diff --git a/.gitignore b/.gitignore index 1a26c62..1f36c1b 100644 --- a/.gitignore +++ b/.gitignore @@ -139,3 +139,4 @@ yarn-error.log # Build directory /build/ /Logos +/Ifnity/Ifnity/vendor/imgui/examples diff --git a/Ifnity/CMakeLists.txt b/Ifnity/CMakeLists.txt index 9f93be7..a36e14f 100644 --- a/Ifnity/CMakeLists.txt +++ b/Ifnity/CMakeLists.txt @@ -1,6 +1,8 @@ cmake_minimum_required(VERSION 3.8) project(IFNITYPROYECT) +# Define la opción y propágala a los subdirectorios +option(BUILD_SHARED_IFNITY "Build Ifnity as a shared library dll" OFF) # Asegurar modulos cmake set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/") diff --git a/Ifnity/CMakeSettings.json b/Ifnity/CMakeSettings.json deleted file mode 100644 index 4e2af56..0000000 --- a/Ifnity/CMakeSettings.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "configurations": [ - { - "name": "x64-Debug", - "generator": "Ninja", - "configurationType": "Debug", - "inheritEnvironments": [ "msvc_x64_x64" ], - "buildRoot": "${projectDir}\\out\\build\\${name}", - "installRoot": "${projectDir}\\out\\install\\${name}", - "cmakeCommandArgs": "", - "buildCommandArgs": "", - "ctestCommandArgs": "" - }, - { - "name": "x64-Release", - "generator": "Ninja", - "configurationType": "RelWithDebInfo", - "buildRoot": "${projectDir}\\out\\build\\${name}", - "installRoot": "${projectDir}\\out\\install\\${name}", - "cmakeCommandArgs": "", - "buildCommandArgs": "", - "ctestCommandArgs": "", - "inheritEnvironments": [ "msvc_x64_x64" ] - }, - { - "name": "x64-Debug-Vs", - "generator": "Visual Studio 17 2022 Win64", - "configurationType": "Debug", - "buildRoot": "${projectDir}\\out\\build\\VisualStudio${name}", - "installRoot": "${projectDir}\\out\\install\\${name}", - "cmakeCommandArgs": "", - "buildCommandArgs": "", - "ctestCommandArgs": "", - "inheritEnvironments": [ "msvc_x64_x64" ], - "variables": [] - } - ] -} \ No newline at end of file diff --git a/Ifnity/Ifnity/CMakeLists.txt b/Ifnity/Ifnity/CMakeLists.txt index e76fb44..681b0d0 100644 --- a/Ifnity/Ifnity/CMakeLists.txt +++ b/Ifnity/Ifnity/CMakeLists.txt @@ -1,6 +1,10 @@ cmake_minimum_required(VERSION 3.8) project(Ifnity) + +#Options + + set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -14,6 +18,7 @@ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE ${CMAKE_BINARY_DIR}/Release) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DIST ${CMAKE_BINARY_DIR}/Dist) + # Buscar nvml.dll en el sistema find_file(NVML_LIBRARY NAMES nvml.dll @@ -28,6 +33,9 @@ else() endif() +#Test if the system has vulkan,d3d11,d3d12,opengl. +include(${PROJECT_SOURCE_DIR}/FindGraphicsAPIs.cmake) + #Rutas nvml.lib set(NVML_LIB_PATH "${PROJECT_SOURCE_DIR}/vendor/nvml/nvml.lib") @@ -37,7 +45,8 @@ add_subdirectory(${PROJECT_SOURCE_DIR}/vendor/glfw) add_subdirectory(${PROJECT_SOURCE_DIR}/vendor) # add D3D12MemoryAllocator add_subdirectory(${PROJECT_SOURCE_DIR}/vendor/D3D12MemoryAllocator) - +# add vulkan bootstrap +add_subdirectory(${PROJECT_SOURCE_DIR}/vendor/vk-bootstrap) # Include directories @@ -56,8 +65,12 @@ include_directories(${PROJECT_SOURCE_DIR}/vendor/imgui) include_directories(${PROJECT_SOURCE_DIR}/vendor/implot) #include stb_image include_directories(${PROJECT_SOURCE_DIR}/vendor/stb_image) -#include d3d12mmemoryallocator +#include d3d12mmemoryallocator and vkmemoryallocator include_directories(${PROJECT_SOURCE_DIR}/vendor/D3D12MemoryAllocator/include) +# Include Vulkan directories +include_directories(${Vulkan_INCLUDE_DIRS}) +# Include VK-Bootstrap +include_directories(${PROJECT_SOURCE_DIR}/vendor/vk-bootstrap) message("Ruta del directorio de origen del proyecto: ${PROJECT_SOURCE_DIR}") @@ -66,6 +79,7 @@ file(GLOB_RECURSE SOURCE_FILES ${PROJECT_SOURCE_DIR}/src/*.h ${PROJECT_SOURCE_DIR}/src/*.hpp ${PROJECT_SOURCE_DIR}/src/*.cpp + ${PROJECT_SOURCE_DIR}/src/*.c ) # Vendor Source Files @@ -78,7 +92,14 @@ set(GLAD_SOURCE ${PROJECT_SOURCE_DIR}/vendor/glad/src/glad.cpp) set(PCH_SOURCES ${PROJECT_SOURCE_DIR}/src/pch.cpp) # Add library -add_library(${PROJECT_NAME} STATIC ${SOURCE_FILES} ${PCH_SOURCES} ${GLAD_SOURCE}) +if(BUILD_SHARED_IFNITY) + add_library(${PROJECT_NAME} SHARED ${SOURCE_FILES} ${PCH_SOURCES} ${GLAD_SOURCE}) + target_compile_definitions(${PROJECT_NAME} PRIVATE IFNITY_PLATFORM_WINDOWS BUILD_SHARED_IFNITY) + message("IFNITY LIKE DLL BUILD SHARED IFNITY = ON ") +else() + add_library(${PROJECT_NAME} STATIC ${SOURCE_FILES} ${PCH_SOURCES} ${GLAD_SOURCE}) +endif() + target_precompile_headers(${PROJECT_NAME} PRIVATE ${PROJECT_SOURCE_DIR}/src/pch.h) @@ -95,7 +116,13 @@ target_link_libraries(${PROJECT_NAME} PUBLIC implot) target_link_libraries(${PROJECT_NAME} INTERFACE glm) target_link_libraries(${PROJECT_NAME} INTERFACE stb_image) target_link_libraries(${PROJECT_NAME} PUBLIC D3D12MemoryAllocator) +# Link Vulkan libraries +target_link_libraries(${PROJECT_NAME} PUBLIC ${Vulkan_LIBRARIES}) +# Link VK-Bootstrap +target_link_libraries(${PROJECT_NAME} PUBLIC vk-bootstrap::vk-bootstrap) +# Include Target Directories +target_include_directories(${PROJECT_NAME} PUBLIC ${PROJECT_SOURCE_DIR}/src/vma) if(NVML_LIBRARY) message(STATUS "Enlazando nvml.lib ya que nvml.dll .") @@ -127,7 +154,7 @@ set_target_properties(${PROJECT_NAME} PROPERTIES # Copiar nvml.lib al directorio de enlace add_custom_command(TARGET ${PROJECT_NAME} PRE_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different + COMMAND ${CMAKE_COMMAND} -E copy_if_different ${PROJECT_SOURCE_DIR}/vendor/nvml/nvml.lib ${CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG} COMMAND ${CMAKE_COMMAND} -E copy_if_different @@ -139,3 +166,5 @@ add_custom_command(TARGET ${PROJECT_NAME} PRE_BUILD ) + + diff --git a/Ifnity/Ifnity/CmakeCheck/CheckD3D11.cpp b/Ifnity/Ifnity/CmakeCheck/CheckD3D11.cpp new file mode 100644 index 0000000..0eba52b --- /dev/null +++ b/Ifnity/Ifnity/CmakeCheck/CheckD3D11.cpp @@ -0,0 +1,6 @@ +#include + +int main() +{ + return 0; +} diff --git a/Ifnity/Ifnity/CmakeCheck/CheckD3D12.cpp b/Ifnity/Ifnity/CmakeCheck/CheckD3D12.cpp new file mode 100644 index 0000000..374a50e --- /dev/null +++ b/Ifnity/Ifnity/CmakeCheck/CheckD3D12.cpp @@ -0,0 +1,6 @@ +#include + +int main() +{ + return 0; +} diff --git a/Ifnity/Ifnity/FindGraphicsAPIs.cmake b/Ifnity/Ifnity/FindGraphicsAPIs.cmake new file mode 100644 index 0000000..b88ed03 --- /dev/null +++ b/Ifnity/Ifnity/FindGraphicsAPIs.cmake @@ -0,0 +1,47 @@ +# FindGraphicsAPIs.cmake + + +#Try compile D3D12 example +if(WIN32) + try_compile(D3D12_COMPILE_SUCCEEDED + "${PROJECT_SOURCE_DIR}/CmakeCheck" + "${PROJECT_SOURCE_DIR}/CmakeCheck/CheckD3D12.cpp" + OUTPUT_VARIABLE D3D12_COMPILE_OUTPUT + ) + try_compile(D3D11_COMPILE_SUCCEEDED + "${PROJECT_SOURCE_DIR}/CmakeCheck" + "${PROJECT_SOURCE_DIR}/CmakeCheck/CheckD3D11.cpp" + OUTPUT_VARIABLE D3D11_COMPILE_OUTPUT + ) + if(D3D12_COMPILE_SUCCEEDED) + message(STATUS "D3D12 is supported.") + else() + message(STATUS "D3D12 IS NOT SUPPORTED. ${D3D12_COMPILE_OUTPUT}") + endif() + + if(D3D11_COMPILE_SUCCEEDED) + message(STATUS "D3D11 is supported") + else() + message(STATUS "D3D11 IS NOT SUPPORTED. ${D3D11_COMPILE_OUTPUT}") + endif() +endif() + +# Find Vulkan +find_package(Vulkan REQUIRED) + +# Find OpenGL +find_package(OpenGL REQUIRED) + + + +if(NOT Vulkan_FOUND) + message(FATAL_ERROR "Vulkan was not found on the system.") +else() + message(STATUS "Vulkan found: ${Vulkan_LIBRARY}") +endif() + +if(NOT OpenGL_FOUND) + message(FATAL_ERROR "OpenGL was not found on the system.") +else() + message(STATUS "OpenGL found: ${OpenGL_LIBRARY}") +endif() diff --git a/Ifnity/Ifnity/src/Ifnity.h b/Ifnity/Ifnity/src/Ifnity.h index 31a7b7f..f62b480 100644 --- a/Ifnity/Ifnity/src/Ifnity.h +++ b/Ifnity/Ifnity/src/Ifnity.h @@ -4,15 +4,12 @@ #include "Ifnity/App.h" #include "Ifnity/Layer.hpp" -#include "Ifnity/Event/WindowEvent.h" #include "Ifnity/Layers/ImguiLayer.h" #include "Ifnity/Layers/NVML_Layer.hpp" #include "Ifnity/Layers/ExampleLayer.h" -#include "Ifnity/Log.h" //wOMDPW -#include "BenchMark/NvmlMonitor.hpp" //Entry Point this include have put at the end of the file. #include "Ifnity/EntryPoint.h" diff --git a/Ifnity/Ifnity/src/Ifnity/App.cpp b/Ifnity/Ifnity/src/Ifnity/App.cpp index a1c7f38..cbe1ed4 100644 --- a/Ifnity/Ifnity/src/Ifnity/App.cpp +++ b/Ifnity/Ifnity/src/Ifnity/App.cpp @@ -1,18 +1,23 @@ #include "pch.h" #include "App.h" -#include "GraphicsDeviceManager.hpp" #include "Ifnity/Layers/ExampleLayer.h" //TODO: BORRAR , your own cpp #include "Ifnity/Layers/NVML_Layer.hpp" #include "Platform/ImguiRender/ImguiOpenglRender.h" #include "Platform/ImguiRender/ImguiD3D11Render.h" #include "Platform/ImguiRender/ImguiD3D12Render.h" +#include "Platform/ImguiRender/ImguiVulkanRender.h" #include #include #include #include + +//#define _MODO_TEST 0 + + + namespace IFNITY { @@ -68,36 +73,37 @@ void main() InitEventBusAndListeners(); - InitConfigurationImGui(); - +#ifndef _MODO_TEST + InitConfigurationImGui(); +#endif } void App::InitEventBusAndListeners() { // Intialize the EventListenerControler - - m_GLFWEventListener = std::make_unique(); - - SetEventBus(m_Window->GetGLFWEventSource()); - - // Connect Differents events. - CONNECT_EVENT(WindowResize); - CONNECT_EVENT(WindowClose); - CONNECT_EVENT(KeyPressed); - CONNECT_EVENT(KeyRelease); - CONNECT_EVENT(MouseMove); - CONNECT_EVENT(ScrollMouseMove); - CONNECT_EVENT(MouseClick); + + m_GLFWEventListener = std::make_unique(); + + SetEventBus(m_Window->GetGLFWEventSource()); + + // Connect Differents events. + CONNECT_EVENT(WindowResize); + CONNECT_EVENT(WindowClose); + CONNECT_EVENT(KeyPressed); + CONNECT_EVENT(KeyRelease); + CONNECT_EVENT(MouseMove); + CONNECT_EVENT(ScrollMouseMove); + CONNECT_EVENT(MouseClick); } - //Example the simple event connect. + //Example the simple event connect. - //events::connect(*m_Window->GetGLFWEventSource(), *m_CameraEventListener); - + //events::connect(*m_Window->GetGLFWEventSource(), *m_CameraEventListener); - // Static member declaration + +// Static member declaration App* App::s_Instance = nullptr; // Default Constructor; App::App(rhi::GraphicsAPI api) : m_graphicsAPI(api) @@ -105,7 +111,7 @@ void main() s_Instance = this; InitApp(m_graphicsAPI); - + } void App::InitConfigurationImGui() @@ -131,24 +137,28 @@ void main() { ImGui_ImplOpenGL3_NewFrame(); ImGui::NewFrame(); - ImPlot::CreateContext(); + }; m_ImguiRenderFunctionMap[rhi::GraphicsAPI::D3D11] = []() { ImGui_ImplDX11_NewFrame(); ImGui::NewFrame(); - ImPlot::CreateContext(); + }; m_ImguiRenderFunctionMap[rhi::GraphicsAPI::D3D12] = []() { - + ImGui_ImplDX12_NewFrame(); ImGui::NewFrame(); - ImPlot::CreateContext(); - + + + }; + m_ImguiRenderFunctionMap[rhi::GraphicsAPI::VULKAN] = []() + { + ImGui_ImplVulkan_NewFrame(); + ImGui::NewFrame(); }; - m_ImguiRenderFunctionMap[rhi::GraphicsAPI::VULKAN] = []() {}; } @@ -169,20 +179,24 @@ void main() //This part its because the initializacion process is in the constructor of the app, then source will be build LAYERS after App constructor. We cant initiate EventBusLayers in App constructor. InitiateEventBusLayers(); +#ifndef _MODO_TEST // TODO: CHange this logic, now is usefull to debug this should be in a layer. bool init = false; if (m_graphicsAPI == rhi::GraphicsAPI::OPENGL && !init) { DeviceOpengl::DemoTriangle(shaderCodeVertex, shaderCodeFragment); - } + } +#endif while (isRunning()) { glfwPollEvents(); m_Window->RenderDemo(m_Window->GetWidth(), m_Window->GetHeight()); // Render ImGui Frame +#ifndef _MODO_TEST RenderImGuiFrame(); +#endif //ImGui::ShowDemoWindow(); //Layer Renders. for (Layer* layer : m_LayerStack) @@ -190,15 +204,16 @@ void main() layer->OnUpdate(); } - m_Window->OnUpdate(); + m_Window->OnUpdate(); +#ifndef _MODO_TEST // Change API if (m_FlagChangeAPI) { //Delete and destroy windows. m_Window->Shutdown(); - + //OnDetach all layers ForceOnDetachLayers(); @@ -207,7 +222,7 @@ void main() ResetAppEvents(); InitApp(m_graphicsAPI); - + ForceOnAttachLayers(); InitiateEventBusLayers(); m_FlagChangeAPI = false; @@ -217,10 +232,11 @@ void main() DeviceOpengl::DemoTriangle(shaderCodeVertex, shaderCodeFragment); } - - } + } +#endif +} m_Window->Shutdown(); } @@ -246,7 +262,7 @@ void main() } } - void App::ForceOnAttachLayers() + void App::ForceOnAttachLayers() { for (Layer* layer : m_LayerStack) { diff --git a/Ifnity/Ifnity/src/Ifnity/App.h b/Ifnity/Ifnity/src/Ifnity/App.h index 6c0fcd1..debcaed 100644 --- a/Ifnity/Ifnity/src/Ifnity/App.h +++ b/Ifnity/Ifnity/src/Ifnity/App.h @@ -1,6 +1,5 @@ #pragma once #include -#include "Core.h" #include "GraphicsDeviceManager.hpp" diff --git a/Ifnity/Ifnity/src/Ifnity/Core.h b/Ifnity/Ifnity/src/Ifnity/Core.h index 47883dd..d7b3dbd 100644 --- a/Ifnity/Ifnity/src/Ifnity/Core.h +++ b/Ifnity/Ifnity/src/Ifnity/Core.h @@ -3,12 +3,23 @@ #pragma warning(disable : 4251) // disable warning for dll interface using in the same interface dll, if you want to use this dll in another dll you should use the same compiler and the same version of the compiler -#ifdef IFNITY_EXPORTS_DLL + + + + +#if defined(_WIN32) || defined(_WIN64) +#if defined(BUILD_SHARED_IFNITY) #define IFNITY_API __declspec(dllexport) -#else +#elif defined(IFNITY_USE_SHARED) #define IFNITY_API __declspec(dllimport) +#else +#define IFNITY_API +#endif +#else +#define IFNITY_API #endif + #if defined(_MSC_VER) // Microsoft Visual Studio #define IFNITY_INLINE __forceinline #elif defined(__GNUC__) // GCC diff --git a/Ifnity/Ifnity/src/Ifnity/EntryPoint.h b/Ifnity/Ifnity/src/Ifnity/EntryPoint.h index effba1e..6c6ea54 100644 --- a/Ifnity/Ifnity/src/Ifnity/EntryPoint.h +++ b/Ifnity/Ifnity/src/Ifnity/EntryPoint.h @@ -10,17 +10,6 @@ int main(int argc, char** argv) { IFNITY::Log::init(); - IFNITY_LOG(LogCore, ERROR, "variable{}"); - - /*NvmlMonitor monitor(100,100); - LoggerDisplayMonitor loggerDisplayMonitor; - monitor.setDisplay(&loggerDisplayMonitor); - - monitor.refresh(); - monitor.refresh(); - monitor.display(); - */ - IFNITY::App* source = IFNITY::CreateApp(); source->run(); diff --git a/Ifnity/Ifnity/src/Ifnity/Event/Event.h b/Ifnity/Ifnity/src/Ifnity/Event/Event.h index 09a9966..5fdb50c 100644 --- a/Ifnity/Ifnity/src/Ifnity/Event/Event.h +++ b/Ifnity/Ifnity/src/Ifnity/Event/Event.h @@ -1,7 +1,7 @@ #pragma once #include "pch.h" -#include "Ifnity/Core.h" + #include "Ifnity/Event/EventMacro.h" namespace IFNITY { diff --git a/Ifnity/Ifnity/src/Ifnity/Event/EventSystem.h b/Ifnity/Ifnity/src/Ifnity/Event/EventSystem.h index e91c4cf..951ed40 100644 --- a/Ifnity/Ifnity/src/Ifnity/Event/EventSystem.h +++ b/Ifnity/Ifnity/src/Ifnity/Event/EventSystem.h @@ -100,7 +100,7 @@ namespace events public: void onEventReceived(const Event& event) { - template.EventSource::dispatchEvent(event); + EventSource::dispatchEvent(event); } }; diff --git a/Ifnity/Ifnity/src/Ifnity/Event/WindowEvent.h b/Ifnity/Ifnity/src/Ifnity/Event/WindowEvent.h index 3bd1468..5e8fcd7 100644 --- a/Ifnity/Ifnity/src/Ifnity/Event/WindowEvent.h +++ b/Ifnity/Ifnity/src/Ifnity/Event/WindowEvent.h @@ -1,7 +1,6 @@ #pragma once #include "pch.h" - #include "Event.h" #include "EventBus.h" diff --git a/Ifnity/Ifnity/src/Ifnity/GraphicsDeviceManager.cpp b/Ifnity/Ifnity/src/Ifnity/GraphicsDeviceManager.cpp index 1f1a787..026d46e 100644 --- a/Ifnity/Ifnity/src/Ifnity/GraphicsDeviceManager.cpp +++ b/Ifnity/Ifnity/src/Ifnity/GraphicsDeviceManager.cpp @@ -3,6 +3,7 @@ #include "Platform\Windows\DeviceOpengl.h" #include "Platform\Windows\DeviceD3D11.h" #include "Platform\Windows\DeviceD3D12.h" +#include "Platform\Windows\DeviceVulkan.h" #define STB_IMAGE_IMPLEMENTATION #include #ifdef _WINDOWS @@ -115,12 +116,14 @@ void GraphicsDeviceManager::Shutdown() // Chek if Shutdown its provide when API is initialized if (m_StateGraphicsDevice == StateGraphicsDevice::INITIALIZED) { - - IFNITY_LOG(LogApp, WARNING, "Shutdown Graphics Device Manager"); - glfwDestroyWindow(m_Window); - m_Window = nullptr; - glfwTerminate(); - + InternalPreDestroy(); + + IFNITY_LOG(LogApp, WARNING, "Shutdown Graphics Device Manager"); + glfwDestroyWindow(m_Window); + m_Window = nullptr; + glfwTerminate(); + + SetGraphicsDeviceState(StateGraphicsDevice::NOT_INITIALIZED); m_InstanceCreated = false; @@ -163,7 +166,7 @@ GraphicsDeviceManager* GraphicsDeviceManager::Create(rhi::GraphicsAPI api) break; case rhi::GraphicsAPI::VULKAN: { - + return BuildWindow(); } break; @@ -273,4 +276,6 @@ void GraphicsDeviceManager::SetWindowIcon() IFNITY_LOG(LogApp, INFO, "Window Icon setted"); } -IFNITY_END_NAMESPACE \ No newline at end of file +IFNITY_END_NAMESPACE + + diff --git a/Ifnity/Ifnity/src/Ifnity/GraphicsDeviceManager.hpp b/Ifnity/Ifnity/src/Ifnity/GraphicsDeviceManager.hpp index af71e62..47feca4 100644 --- a/Ifnity/Ifnity/src/Ifnity/GraphicsDeviceManager.hpp +++ b/Ifnity/Ifnity/src/Ifnity/GraphicsDeviceManager.hpp @@ -1,15 +1,20 @@ #pragma once #include "pch.h" - -#include "Ifnity/Core.h" -#include "Ifnity/Event/Event.h" #include "Ifnity/Event/WindowEvent.h" + +// GRAPHIC API +#define VK_USE_PLATFORM_WIN32_KHR +#include +#define GLFW_INCLUDE_VULKAN #define GLFW_INCLUDE_NONE // Do not include any OpenGL headers #include #ifdef _WIN32 #define GLFW_EXPOSE_NATIVE_WIN32 + + + #endif // _WIN32 #include @@ -106,9 +111,10 @@ class IFNITY_API GraphicsDeviceManager virtual bool IsVSync() const = 0; virtual void ResizeSwapChain() = 0; virtual void InitializeGui() = 0; + virtual void InternalPreDestroy() = 0; + -protected: WindowData m_Props; bool m_IsNvidia = false; GLFWwindow* m_Window = nullptr; @@ -124,7 +130,7 @@ class IFNITY_API GraphicsDeviceManager return new WindowType(std::forward(args)...); } -private: + static rhi::GraphicsAPI g_API; // By default opengl is the api StateGraphicsDevice m_StateGraphicsDevice{ StateGraphicsDevice::NOT_INITIALIZED }; diff --git a/Ifnity/Ifnity/src/Ifnity/Layer.hpp b/Ifnity/Ifnity/src/Ifnity/Layer.hpp index 1d4d6d3..88b575a 100644 --- a/Ifnity/Ifnity/src/Ifnity/Layer.hpp +++ b/Ifnity/Ifnity/src/Ifnity/Layer.hpp @@ -1,8 +1,7 @@ #pragma once #include "pch.h" -#include "Ifnity\Event\EventBus.h" -#include "Ifnity\Event\Event.h" + //This type of layer is based of Hazel Engine Layer. diff --git a/Ifnity/Ifnity/src/Ifnity/LayerStack.hpp b/Ifnity/Ifnity/src/Ifnity/LayerStack.hpp index e77b62a..d10c74f 100644 --- a/Ifnity/Ifnity/src/Ifnity/LayerStack.hpp +++ b/Ifnity/Ifnity/src/Ifnity/LayerStack.hpp @@ -1,5 +1,3 @@ -#pragma once -#include "pch.h" #include "Layer.hpp" diff --git a/Ifnity/Ifnity/src/Ifnity/Layers/ImguiLayer.cpp b/Ifnity/Ifnity/src/Ifnity/Layers/ImguiLayer.cpp index 1c6d5c9..a15452c 100644 --- a/Ifnity/Ifnity/src/Ifnity/Layers/ImguiLayer.cpp +++ b/Ifnity/Ifnity/src/Ifnity/Layers/ImguiLayer.cpp @@ -7,6 +7,7 @@ #include "Platform/ImguiRender/ImguiOpenglRender.h" #include "Platform/ImguiRender/ImguiD3D11Render.h" #include "Platform/ImguiRender/ImguiD3D12Render.h" +#include "Platform/ImguiRender/ImguiVulkanRender.h" #include #include "../App.h" @@ -69,11 +70,15 @@ void ImguiLayer::OnAttach() ImGuiOnDetach = ImGui_ImplDX11_Shutdown; break; case rhi::GraphicsAPI::D3D12: - ImGuiRenderDrawData = [](ImDrawData* drawData) {}; + ImGuiRenderDrawData = [](ImDrawData* drawData) { + ImDrawData* draw_data = ImGui::GetDrawData(); }; //This implement in D3D12Render ImGuiOnDetach = ImGui_ImplDX12_Shutdown; break; case rhi::GraphicsAPI::VULKAN: - IFNITY_LOG(LogApp, ERROR, "Vulkan not implemented"); + ImGuiRenderDrawData = [](ImDrawData* drawData) { // Obtn los datos de dibujo + ImDrawData* draw_data = ImGui::GetDrawData(); + }; // This implement in VulkanRender + ImGuiOnDetach = ImGui_ImplVulkan_Shutdown; break; default: break; diff --git a/Ifnity/Ifnity/src/Ifnity/Layers/NVML_Layer.hpp b/Ifnity/Ifnity/src/Ifnity/Layers/NVML_Layer.hpp index cc0ce03..c2f4101 100644 --- a/Ifnity/Ifnity/src/Ifnity/Layers/NVML_Layer.hpp +++ b/Ifnity/Ifnity/src/Ifnity/Layers/NVML_Layer.hpp @@ -268,7 +268,9 @@ class IFNITY_API NVML_Monitor :public Layer if (m_lastThrottleReason != currentThrottleReason) { - IFNITY_LOG(LogApp, ERROR, (message + "\n").c_str(), deviceIndex); + std::string formattedMessage = fmt::format("{}\n", message); + IFNITY_LOG(LogApp, ERROR, formattedMessage); + } m_lastThrottleReason = currentThrottleReason; m_throttleCooldownTimer.reset(); @@ -418,7 +420,7 @@ class IFNITY_API NVML_Monitor :public Layer { if (ImGui::GetCurrentContext() == nullptr) { - IFNITY_LOG(LogApp, ERROR, "IMGUI CONTEXT NOT INITIALIZED " , __FUNCTION__); + IFNITY_LOG(LogApp, ERROR, "IMGUI CONTEXT NOT INITIALIZED "); return; } ImGuiSettingsHandler iniHandler{}; diff --git a/Ifnity/Ifnity/src/Ifnity/Log.h b/Ifnity/Ifnity/src/Ifnity/Log.h index 2c7e84c..c794d0b 100644 --- a/Ifnity/Ifnity/src/Ifnity/Log.h +++ b/Ifnity/Ifnity/src/Ifnity/Log.h @@ -8,18 +8,18 @@ -#define IFNITY_LOG(logger, level, ...) \ - do { \ +#define IFNITY_LOG(logger, level, fmt, ...) \ + do { \ if (level == WARNING) { \ - logger->warn(__VA_ARGS__); \ + logger->warn(fmt, __VA_ARGS__); \ } else if (level == ERROR) { \ - logger->error(__VA_ARGS__); \ + logger->error(std::string(fmt) + " in function: " + __FUNCTION__, __VA_ARGS__); \ } else if (level == TRACE) { \ - logger->trace(__VA_ARGS__); \ + logger->trace(fmt, __VA_ARGS__); \ } else if (level == INFO) { \ - logger->info(__VA_ARGS__); \ + logger->info(fmt, __VA_ARGS__); \ } else { \ - logger->info(__VA_ARGS__); \ + logger->info(fmt, __VA_ARGS__); \ } \ } while (0) namespace IFNITY diff --git a/Ifnity/Ifnity/src/ImGuiContexManager.cpp b/Ifnity/Ifnity/src/ImGuiContexManager.cpp index fc9ccde..21cc966 100644 --- a/Ifnity/Ifnity/src/ImGuiContexManager.cpp +++ b/Ifnity/Ifnity/src/ImGuiContexManager.cpp @@ -1,12 +1,12 @@ #include "ImGuiContextManager.h" - +#include // Variable esttica para almacenar el contexto de ImGui static ImGuiContext* g_ImGuiContext = nullptr; - +static ImPlotContext* g_ImPlotContext = nullptr; // Funcin para inicializar ImGui IFNITY_API void InitializeImGui() { @@ -16,12 +16,18 @@ IFNITY_API void InitializeImGui() ImGui::SetCurrentContext(g_ImGuiContext); // Configuracin adicional de ImGui si es necesario } + if (g_ImPlotContext == nullptr) + { + g_ImPlotContext = ImPlot::CreateContext(); + ImPlot::SetCurrentContext(g_ImPlotContext); + } } // Funcin para obtener el contexto de ImGui IFNITY_API ImGuiContext* GetImGuiContext() { return g_ImGuiContext; + } // Function to destroy ImGui context. @@ -32,4 +38,9 @@ IFNITY_API void InitializeImGui() ImGui::DestroyContext(g_ImGuiContext); g_ImGuiContext = nullptr; } + if (g_ImPlotContext != nullptr) + { + ImPlot::DestroyContext(g_ImPlotContext); + g_ImPlotContext = nullptr; + } } \ No newline at end of file diff --git a/Ifnity/Ifnity/src/Platform/ImguiRender/ImguiVulkanRender.cpp b/Ifnity/Ifnity/src/Platform/ImguiRender/ImguiVulkanRender.cpp new file mode 100644 index 0000000..851ec2c --- /dev/null +++ b/Ifnity/Ifnity/src/Platform/ImguiRender/ImguiVulkanRender.cpp @@ -0,0 +1,1588 @@ +// dear imgui: Renderer Backend for Vulkan +// This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) + +// Implemented features: +// [!] Renderer: User texture binding. Use 'VkDescriptorSet' as ImTextureID. Read the FAQ about ImTextureID! See https://github.com/ocornut/imgui/pull/914 for discussions. +// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. + +// Important: on 32-bit systems, user texture binding is only supported if your imconfig file has '#define ImTextureID ImU64'. +// This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*. +// To build this on 32-bit systems and support texture changes: +// - [Solution 1] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'ImTextureID=ImU64' (this is what we do in our .vcxproj files) +// - [Solution 2] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'IMGUI_USER_CONFIG="my_imgui_config.h"' and inside 'my_imgui_config.h' add '#define ImTextureID ImU64' and as many other options as you like. +// - [Solution 3] IDE/msbuild: edit imconfig.h and add '#define ImTextureID ImU64' (prefer solution 2 to create your own config file!) +// - [Solution 4] command-line: add '/D ImTextureID=ImU64' to your cl.exe command-line (this is what we do in our batch files) + +// The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification. +// IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/ + +// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +// Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. +// - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. +// You will use those if you want to use this rendering backend in your engine/app. +// - Helper ImGui_ImplVulkanH_XXX functions and structures are only used by this example (main.cpp) and by +// the backend itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code. +// Read comments in imgui_impl_vulkan.h. + +// CHANGELOG +// (minor and older changes stripped away, please see git history for details) +// 2024-04-19: Vulkan: Added convenience support for Volk via IMGUI_IMPL_VULKAN_USE_VOLK define (you can also use IMGUI_IMPL_VULKAN_NO_PROTOTYPES + wrap Volk via ImGui_ImplVulkan_LoadFunctions().) +// 2024-02-14: *BREAKING CHANGE*: Moved RenderPass parameter from ImGui_ImplVulkan_Init() function to ImGui_ImplVulkan_InitInfo structure. Not required when using dynamic rendering. +// 2024-02-12: *BREAKING CHANGE*: Dynamic rendering now require filling PipelineRenderingCreateInfo structure. +// 2024-01-19: Vulkan: Fixed vkAcquireNextImageKHR() validation errors in VulkanSDK 1.3.275 by allocating one extra semaphore than in-flight frames. (#7236) +// 2024-01-11: Vulkan: Fixed vkMapMemory() calls unnecessarily using full buffer size (#3957). Fixed MinAllocationSize handing (#7189). +// 2024-01-03: Vulkan: Added MinAllocationSize field in ImGui_ImplVulkan_InitInfo to workaround zealous "best practice" validation layer. (#7189, #4238) +// 2024-01-03: Vulkan: Stopped creating command pools with VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT as we don't reset them. +// 2023-11-29: Vulkan: Fixed mismatching allocator passed to vkCreateCommandPool() vs vkDestroyCommandPool(). (#7075) +// 2023-11-10: *BREAKING CHANGE*: Removed parameter from ImGui_ImplVulkan_CreateFontsTexture(): backend now creates its own command-buffer to upload fonts. +// *BREAKING CHANGE*: Removed ImGui_ImplVulkan_DestroyFontUploadObjects() which is now unnecessary as we create and destroy those objects in the backend. +// ImGui_ImplVulkan_CreateFontsTexture() is automatically called by NewFrame() the first time. +// You can call ImGui_ImplVulkan_CreateFontsTexture() again to recreate the font atlas texture. +// Added ImGui_ImplVulkan_DestroyFontsTexture() but you probably never need to call this. +// 2023-07-04: Vulkan: Added optional support for VK_KHR_dynamic_rendering. User needs to set init_info->UseDynamicRendering = true and init_info->ColorAttachmentFormat. +// 2023-01-02: Vulkan: Fixed sampler passed to ImGui_ImplVulkan_AddTexture() not being honored + removed a bunch of duplicate code. +// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. +// 2022-10-04: Vulkan: Added experimental ImGui_ImplVulkan_RemoveTexture() for api symmetry. (#914, #5738). +// 2022-01-20: Vulkan: Added support for ImTextureID as VkDescriptorSet. User need to call ImGui_ImplVulkan_AddTexture(). Building for 32-bit targets requires '#define ImTextureID ImU64'. (#914). +// 2021-10-15: Vulkan: Call vkCmdSetScissor() at the end of render a full-viewport to reduce likehood of issues with people using VK_DYNAMIC_STATE_SCISSOR in their app without calling vkCmdSetScissor() explicitly every frame. +// 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). +// 2021-03-22: Vulkan: Fix mapped memory validation error when buffer sizes are not multiple of VkPhysicalDeviceLimits::nonCoherentAtomSize. +// 2021-02-18: Vulkan: Change blending equation to preserve alpha in output buffer. +// 2021-01-27: Vulkan: Added support for custom function load and IMGUI_IMPL_VULKAN_NO_PROTOTYPES by using ImGui_ImplVulkan_LoadFunctions(). +// 2020-11-11: Vulkan: Added support for specifying which subpass to reference during VkPipeline creation. +// 2020-09-07: Vulkan: Added VkPipeline parameter to ImGui_ImplVulkan_RenderDrawData (default to one passed to ImGui_ImplVulkan_Init). +// 2020-05-04: Vulkan: Fixed crash if initial frame has no vertices. +// 2020-04-26: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData didn't have vertices. +// 2019-08-01: Vulkan: Added support for specifying multisample count. Set ImGui_ImplVulkan_InitInfo::MSAASamples to one of the VkSampleCountFlagBits values to use, default is non-multisampled as before. +// 2019-05-29: Vulkan: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. +// 2019-04-30: Vulkan: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. +// 2019-04-04: *BREAKING CHANGE*: Vulkan: Added ImageCount/MinImageCount fields in ImGui_ImplVulkan_InitInfo, required for initialization (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). Added ImGui_ImplVulkan_SetMinImageCount(). +// 2019-04-04: Vulkan: Added VkInstance argument to ImGui_ImplVulkanH_CreateWindow() optional helper. +// 2019-04-04: Vulkan: Avoid passing negative coordinates to vkCmdSetScissor, which debug validation layers do not like. +// 2019-04-01: Vulkan: Support for 32-bit index buffer (#define ImDrawIdx unsigned int). +// 2019-02-16: Vulkan: Viewport and clipping rectangles correctly using draw_data->FramebufferScale to allow retina display. +// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. +// 2018-08-25: Vulkan: Fixed mishandled VkSurfaceCapabilitiesKHR::maxImageCount=0 case. +// 2018-06-22: Inverted the parameters to ImGui_ImplVulkan_RenderDrawData() to be consistent with other backends. +// 2018-06-08: Misc: Extracted imgui_impl_vulkan.cpp/.h away from the old combined GLFW+Vulkan example. +// 2018-06-08: Vulkan: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle. +// 2018-03-03: Vulkan: Various refactor, created a couple of ImGui_ImplVulkanH_XXX helper that the example can use and that viewport support will use. +// 2018-03-01: Vulkan: Renamed ImGui_ImplVulkan_Init_Info to ImGui_ImplVulkan_InitInfo and fields to match more closely Vulkan terminology. +// 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback, ImGui_ImplVulkan_Render() calls ImGui_ImplVulkan_RenderDrawData() itself. +// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. +// 2017-05-15: Vulkan: Fix scissor offset being negative. Fix new Vulkan validation warnings. Set required depth member for buffer image copy. +// 2016-11-13: Vulkan: Fix validation layer warnings and errors and redeclare gl_PerVertex. +// 2016-10-18: Vulkan: Add location decorators & change to use structs as in/out in glsl, update embedded spv (produced with glslangValidator -x). Null the released resources. +// 2016-08-27: Vulkan: Fix Vulkan example for use when a depth buffer is active. + +#include "imgui.h" +#ifndef IMGUI_DISABLE +#include "ImguiVulkanRender.h" +#include +#ifndef IM_MAX +#define IM_MAX(A, B) (((A) >= (B)) ? (A) : (B)) +#endif + +// Visual Studio warnings +#ifdef _MSC_VER +#pragma warning (disable: 4127) // condition expression is constant +#endif + +// Forward Declarations +struct ImGui_ImplVulkan_FrameRenderBuffers; +struct ImGui_ImplVulkan_WindowRenderBuffers; +bool ImGui_ImplVulkan_CreateDeviceObjects(); +void ImGui_ImplVulkan_DestroyDeviceObjects(); +void ImGui_ImplVulkan_DestroyFrameRenderBuffers(VkDevice device, ImGui_ImplVulkan_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator); +void ImGui_ImplVulkan_DestroyWindowRenderBuffers(VkDevice device, ImGui_ImplVulkan_WindowRenderBuffers* buffers, const VkAllocationCallbacks* allocator); +void ImGui_ImplVulkanH_DestroyFrame(VkDevice device, ImGui_ImplVulkanH_Frame* fd, const VkAllocationCallbacks* allocator); +void ImGui_ImplVulkanH_DestroyFrameSemaphores(VkDevice device, ImGui_ImplVulkanH_FrameSemaphores* fsd, const VkAllocationCallbacks* allocator); +void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); +void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator); + +// Vulkan prototypes for use with custom loaders +// (see description of IMGUI_IMPL_VULKAN_NO_PROTOTYPES in imgui_impl_vulkan.h +#if defined(VK_NO_PROTOTYPES) && !defined(VOLK_H_) +#define IMGUI_IMPL_VULKAN_USE_LOADER +static bool g_FunctionsLoaded = false; +#else +static bool g_FunctionsLoaded = true; +#endif +#ifdef IMGUI_IMPL_VULKAN_USE_LOADER +#define IMGUI_VULKAN_FUNC_MAP(IMGUI_VULKAN_FUNC_MAP_MACRO) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkAllocateCommandBuffers) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkAllocateDescriptorSets) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkAllocateMemory) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkBeginCommandBuffer) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkBindBufferMemory) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkBindImageMemory) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdBindDescriptorSets) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdBindIndexBuffer) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdBindPipeline) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdBindVertexBuffers) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdCopyBufferToImage) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdDrawIndexed) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdPipelineBarrier) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdPushConstants) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdSetScissor) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdSetViewport) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateBuffer) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateCommandPool) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateDescriptorSetLayout) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateFence) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateFramebuffer) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateGraphicsPipelines) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateImage) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateImageView) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreatePipelineLayout) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateRenderPass) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateSampler) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateSemaphore) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateShaderModule) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateSwapchainKHR) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyBuffer) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyCommandPool) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyDescriptorSetLayout) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyFence) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyFramebuffer) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyImage) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyImageView) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyPipeline) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyPipelineLayout) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyRenderPass) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroySampler) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroySemaphore) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyShaderModule) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroySurfaceKHR) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroySwapchainKHR) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkDeviceWaitIdle) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkEndCommandBuffer) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkFlushMappedMemoryRanges) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkFreeCommandBuffers) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkFreeDescriptorSets) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkFreeMemory) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetBufferMemoryRequirements) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetImageMemoryRequirements) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetPhysicalDeviceMemoryProperties) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetPhysicalDeviceSurfaceCapabilitiesKHR) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetPhysicalDeviceSurfaceFormatsKHR) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetPhysicalDeviceSurfacePresentModesKHR) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetSwapchainImagesKHR) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkMapMemory) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkQueueSubmit) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkQueueWaitIdle) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkResetCommandPool) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkUnmapMemory) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkUpdateDescriptorSets) + +// Define function pointers +#define IMGUI_VULKAN_FUNC_DEF(func) static PFN_##func func; +IMGUI_VULKAN_FUNC_MAP(IMGUI_VULKAN_FUNC_DEF) +#undef IMGUI_VULKAN_FUNC_DEF +#endif // IMGUI_IMPL_VULKAN_USE_LOADER + +#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING +static PFN_vkCmdBeginRenderingKHR ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR; +static PFN_vkCmdEndRenderingKHR ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR; +#endif + +// Reusable buffers used for rendering 1 current in-flight frame, for ImGui_ImplVulkan_RenderDrawData() +// [Please zero-clear before use!] +struct ImGui_ImplVulkan_FrameRenderBuffers +{ + VkDeviceMemory VertexBufferMemory; + VkDeviceMemory IndexBufferMemory; + VkDeviceSize VertexBufferSize; + VkDeviceSize IndexBufferSize; + VkBuffer VertexBuffer; + VkBuffer IndexBuffer; +}; + +// Each viewport will hold 1 ImGui_ImplVulkanH_WindowRenderBuffers +// [Please zero-clear before use!] +struct ImGui_ImplVulkan_WindowRenderBuffers +{ + uint32_t Index; + uint32_t Count; + ImGui_ImplVulkan_FrameRenderBuffers* FrameRenderBuffers; +}; + +// Vulkan data +struct ImGui_ImplVulkan_Data +{ + ImGui_ImplVulkan_InitInfo VulkanInitInfo; + VkDeviceSize BufferMemoryAlignment; + VkPipelineCreateFlags PipelineCreateFlags; + VkDescriptorSetLayout DescriptorSetLayout; + VkPipelineLayout PipelineLayout; + VkPipeline Pipeline; + VkShaderModule ShaderModuleVert; + VkShaderModule ShaderModuleFrag; + + // Font data + VkSampler FontSampler; + VkDeviceMemory FontMemory; + VkImage FontImage; + VkImageView FontView; + VkDescriptorSet FontDescriptorSet; + VkCommandPool FontCommandPool; + VkCommandBuffer FontCommandBuffer; + + // Render buffers for main window + ImGui_ImplVulkan_WindowRenderBuffers MainWindowRenderBuffers; + + ImGui_ImplVulkan_Data() + { + memset((void*)this, 0, sizeof(*this)); + BufferMemoryAlignment = 256; + } +}; + +//----------------------------------------------------------------------------- +// SHADERS +//----------------------------------------------------------------------------- + +// backends/vulkan/glsl_shader.vert, compiled with: +// # glslangValidator -V -x -o glsl_shader.vert.u32 glsl_shader.vert +/* +#version 450 core +layout(location = 0) in vec2 aPos; +layout(location = 1) in vec2 aUV; +layout(location = 2) in vec4 aColor; +layout(push_constant) uniform uPushConstant { vec2 uScale; vec2 uTranslate; } pc; + +out gl_PerVertex { vec4 gl_Position; }; +layout(location = 0) out struct { vec4 Color; vec2 UV; } Out; + +void main() +{ + Out.Color = aColor; + Out.UV = aUV; + gl_Position = vec4(aPos * pc.uScale + pc.uTranslate, 0, 1); +} +*/ +static uint32_t __glsl_shader_vert_spv[] = +{ + 0x07230203,0x00010000,0x00080001,0x0000002e,0x00000000,0x00020011,0x00000001,0x0006000b, + 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001, + 0x000a000f,0x00000000,0x00000004,0x6e69616d,0x00000000,0x0000000b,0x0000000f,0x00000015, + 0x0000001b,0x0000001c,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d, + 0x00000000,0x00030005,0x00000009,0x00000000,0x00050006,0x00000009,0x00000000,0x6f6c6f43, + 0x00000072,0x00040006,0x00000009,0x00000001,0x00005655,0x00030005,0x0000000b,0x0074754f, + 0x00040005,0x0000000f,0x6c6f4361,0x0000726f,0x00030005,0x00000015,0x00565561,0x00060005, + 0x00000019,0x505f6c67,0x65567265,0x78657472,0x00000000,0x00060006,0x00000019,0x00000000, + 0x505f6c67,0x7469736f,0x006e6f69,0x00030005,0x0000001b,0x00000000,0x00040005,0x0000001c, + 0x736f5061,0x00000000,0x00060005,0x0000001e,0x73755075,0x6e6f4368,0x6e617473,0x00000074, + 0x00050006,0x0000001e,0x00000000,0x61635375,0x0000656c,0x00060006,0x0000001e,0x00000001, + 0x61725475,0x616c736e,0x00006574,0x00030005,0x00000020,0x00006370,0x00040047,0x0000000b, + 0x0000001e,0x00000000,0x00040047,0x0000000f,0x0000001e,0x00000002,0x00040047,0x00000015, + 0x0000001e,0x00000001,0x00050048,0x00000019,0x00000000,0x0000000b,0x00000000,0x00030047, + 0x00000019,0x00000002,0x00040047,0x0000001c,0x0000001e,0x00000000,0x00050048,0x0000001e, + 0x00000000,0x00000023,0x00000000,0x00050048,0x0000001e,0x00000001,0x00000023,0x00000008, + 0x00030047,0x0000001e,0x00000002,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002, + 0x00030016,0x00000006,0x00000020,0x00040017,0x00000007,0x00000006,0x00000004,0x00040017, + 0x00000008,0x00000006,0x00000002,0x0004001e,0x00000009,0x00000007,0x00000008,0x00040020, + 0x0000000a,0x00000003,0x00000009,0x0004003b,0x0000000a,0x0000000b,0x00000003,0x00040015, + 0x0000000c,0x00000020,0x00000001,0x0004002b,0x0000000c,0x0000000d,0x00000000,0x00040020, + 0x0000000e,0x00000001,0x00000007,0x0004003b,0x0000000e,0x0000000f,0x00000001,0x00040020, + 0x00000011,0x00000003,0x00000007,0x0004002b,0x0000000c,0x00000013,0x00000001,0x00040020, + 0x00000014,0x00000001,0x00000008,0x0004003b,0x00000014,0x00000015,0x00000001,0x00040020, + 0x00000017,0x00000003,0x00000008,0x0003001e,0x00000019,0x00000007,0x00040020,0x0000001a, + 0x00000003,0x00000019,0x0004003b,0x0000001a,0x0000001b,0x00000003,0x0004003b,0x00000014, + 0x0000001c,0x00000001,0x0004001e,0x0000001e,0x00000008,0x00000008,0x00040020,0x0000001f, + 0x00000009,0x0000001e,0x0004003b,0x0000001f,0x00000020,0x00000009,0x00040020,0x00000021, + 0x00000009,0x00000008,0x0004002b,0x00000006,0x00000028,0x00000000,0x0004002b,0x00000006, + 0x00000029,0x3f800000,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8, + 0x00000005,0x0004003d,0x00000007,0x00000010,0x0000000f,0x00050041,0x00000011,0x00000012, + 0x0000000b,0x0000000d,0x0003003e,0x00000012,0x00000010,0x0004003d,0x00000008,0x00000016, + 0x00000015,0x00050041,0x00000017,0x00000018,0x0000000b,0x00000013,0x0003003e,0x00000018, + 0x00000016,0x0004003d,0x00000008,0x0000001d,0x0000001c,0x00050041,0x00000021,0x00000022, + 0x00000020,0x0000000d,0x0004003d,0x00000008,0x00000023,0x00000022,0x00050085,0x00000008, + 0x00000024,0x0000001d,0x00000023,0x00050041,0x00000021,0x00000025,0x00000020,0x00000013, + 0x0004003d,0x00000008,0x00000026,0x00000025,0x00050081,0x00000008,0x00000027,0x00000024, + 0x00000026,0x00050051,0x00000006,0x0000002a,0x00000027,0x00000000,0x00050051,0x00000006, + 0x0000002b,0x00000027,0x00000001,0x00070050,0x00000007,0x0000002c,0x0000002a,0x0000002b, + 0x00000028,0x00000029,0x00050041,0x00000011,0x0000002d,0x0000001b,0x0000000d,0x0003003e, + 0x0000002d,0x0000002c,0x000100fd,0x00010038 +}; + +// backends/vulkan/glsl_shader.frag, compiled with: +// # glslangValidator -V -x -o glsl_shader.frag.u32 glsl_shader.frag +/* +#version 450 core +layout(location = 0) out vec4 fColor; +layout(set=0, binding=0) uniform sampler2D sTexture; +layout(location = 0) in struct { vec4 Color; vec2 UV; } In; +void main() +{ + fColor = In.Color * texture(sTexture, In.UV.st); +} +*/ +static uint32_t __glsl_shader_frag_spv[] = +{ + 0x07230203,0x00010000,0x00080001,0x0000001e,0x00000000,0x00020011,0x00000001,0x0006000b, + 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001, + 0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x00000009,0x0000000d,0x00030010, + 0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d, + 0x00000000,0x00040005,0x00000009,0x6c6f4366,0x0000726f,0x00030005,0x0000000b,0x00000000, + 0x00050006,0x0000000b,0x00000000,0x6f6c6f43,0x00000072,0x00040006,0x0000000b,0x00000001, + 0x00005655,0x00030005,0x0000000d,0x00006e49,0x00050005,0x00000016,0x78655473,0x65727574, + 0x00000000,0x00040047,0x00000009,0x0000001e,0x00000000,0x00040047,0x0000000d,0x0000001e, + 0x00000000,0x00040047,0x00000016,0x00000022,0x00000000,0x00040047,0x00000016,0x00000021, + 0x00000000,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,0x00030016,0x00000006, + 0x00000020,0x00040017,0x00000007,0x00000006,0x00000004,0x00040020,0x00000008,0x00000003, + 0x00000007,0x0004003b,0x00000008,0x00000009,0x00000003,0x00040017,0x0000000a,0x00000006, + 0x00000002,0x0004001e,0x0000000b,0x00000007,0x0000000a,0x00040020,0x0000000c,0x00000001, + 0x0000000b,0x0004003b,0x0000000c,0x0000000d,0x00000001,0x00040015,0x0000000e,0x00000020, + 0x00000001,0x0004002b,0x0000000e,0x0000000f,0x00000000,0x00040020,0x00000010,0x00000001, + 0x00000007,0x00090019,0x00000013,0x00000006,0x00000001,0x00000000,0x00000000,0x00000000, + 0x00000001,0x00000000,0x0003001b,0x00000014,0x00000013,0x00040020,0x00000015,0x00000000, + 0x00000014,0x0004003b,0x00000015,0x00000016,0x00000000,0x0004002b,0x0000000e,0x00000018, + 0x00000001,0x00040020,0x00000019,0x00000001,0x0000000a,0x00050036,0x00000002,0x00000004, + 0x00000000,0x00000003,0x000200f8,0x00000005,0x00050041,0x00000010,0x00000011,0x0000000d, + 0x0000000f,0x0004003d,0x00000007,0x00000012,0x00000011,0x0004003d,0x00000014,0x00000017, + 0x00000016,0x00050041,0x00000019,0x0000001a,0x0000000d,0x00000018,0x0004003d,0x0000000a, + 0x0000001b,0x0000001a,0x00050057,0x00000007,0x0000001c,0x00000017,0x0000001b,0x00050085, + 0x00000007,0x0000001d,0x00000012,0x0000001c,0x0003003e,0x00000009,0x0000001d,0x000100fd, + 0x00010038 +}; + +//----------------------------------------------------------------------------- +// FUNCTIONS +//----------------------------------------------------------------------------- + +// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts +// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. +// FIXME: multi-context support is not tested and probably dysfunctional in this backend. +static ImGui_ImplVulkan_Data* ImGui_ImplVulkan_GetBackendData() +{ + return ImGui::GetCurrentContext() ? (ImGui_ImplVulkan_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; +} + +static uint32_t ImGui_ImplVulkan_MemoryType(VkMemoryPropertyFlags properties, uint32_t type_bits) +{ + ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); + ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; + VkPhysicalDeviceMemoryProperties prop; + vkGetPhysicalDeviceMemoryProperties(v->PhysicalDevice, &prop); + for (uint32_t i = 0; i < prop.memoryTypeCount; i++) + if ((prop.memoryTypes[i].propertyFlags & properties) == properties && type_bits & (1 << i)) + return i; + return 0xFFFFFFFF; // Unable to find memoryType +} + +static void check_vk_result(VkResult err) +{ + ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); + if (!bd) + return; + ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; + if (v->CheckVkResultFn) + v->CheckVkResultFn(err); +} + +// Same as IM_MEMALIGN(). 'alignment' must be a power of two. +static inline VkDeviceSize AlignBufferSize(VkDeviceSize size, VkDeviceSize alignment) +{ + return (size + alignment - 1) & ~(alignment - 1); +} + +static void CreateOrResizeBuffer(VkBuffer& buffer, VkDeviceMemory& buffer_memory, VkDeviceSize& buffer_size, size_t new_size, VkBufferUsageFlagBits usage) +{ + ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); + ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; + VkResult err; + if (buffer != VK_NULL_HANDLE) + vkDestroyBuffer(v->Device, buffer, v->Allocator); + if (buffer_memory != VK_NULL_HANDLE) + vkFreeMemory(v->Device, buffer_memory, v->Allocator); + + VkDeviceSize buffer_size_aligned = AlignBufferSize(IM_MAX(v->MinAllocationSize, new_size), bd->BufferMemoryAlignment); + VkBufferCreateInfo buffer_info = {}; + buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + buffer_info.size = buffer_size_aligned; + buffer_info.usage = usage; + buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + err = vkCreateBuffer(v->Device, &buffer_info, v->Allocator, &buffer); + check_vk_result(err); + + VkMemoryRequirements req; + vkGetBufferMemoryRequirements(v->Device, buffer, &req); + bd->BufferMemoryAlignment = (bd->BufferMemoryAlignment > req.alignment) ? bd->BufferMemoryAlignment : req.alignment; + VkMemoryAllocateInfo alloc_info = {}; + alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + alloc_info.allocationSize = req.size; + alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, req.memoryTypeBits); + err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &buffer_memory); + check_vk_result(err); + + err = vkBindBufferMemory(v->Device, buffer, buffer_memory, 0); + check_vk_result(err); + buffer_size = buffer_size_aligned; +} + +static void ImGui_ImplVulkan_SetupRenderState(ImDrawData* draw_data, VkPipeline pipeline, VkCommandBuffer command_buffer, ImGui_ImplVulkan_FrameRenderBuffers* rb, int fb_width, int fb_height) +{ + ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); + + // Bind pipeline: + { + vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); + } + + // Bind Vertex And Index Buffer: + if (draw_data->TotalVtxCount > 0) + { + VkBuffer vertex_buffers[1] = { rb->VertexBuffer }; + VkDeviceSize vertex_offset[1] = { 0 }; + vkCmdBindVertexBuffers(command_buffer, 0, 1, vertex_buffers, vertex_offset); + vkCmdBindIndexBuffer(command_buffer, rb->IndexBuffer, 0, sizeof(ImDrawIdx) == 2 ? VK_INDEX_TYPE_UINT16 : VK_INDEX_TYPE_UINT32); + } + + // Setup viewport: + { + VkViewport viewport; + viewport.x = 0; + viewport.y = 0; + viewport.width = (float)fb_width; + viewport.height = (float)fb_height; + viewport.minDepth = 0.0f; + viewport.maxDepth = 1.0f; + vkCmdSetViewport(command_buffer, 0, 1, &viewport); + } + + // Setup scale and translation: + // Our visible imgui space lies from draw_data->DisplayPps (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. + { + float scale[2]; + scale[0] = 2.0f / draw_data->DisplaySize.x; + scale[1] = 2.0f / draw_data->DisplaySize.y; + float translate[2]; + translate[0] = -1.0f - draw_data->DisplayPos.x * scale[0]; + translate[1] = -1.0f - draw_data->DisplayPos.y * scale[1]; + vkCmdPushConstants(command_buffer, bd->PipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, sizeof(float) * 0, sizeof(float) * 2, scale); + vkCmdPushConstants(command_buffer, bd->PipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, sizeof(float) * 2, sizeof(float) * 2, translate); + } +} + +// Render function +void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer, VkPipeline pipeline) +{ + // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) + int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x); + int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); + if (fb_width <= 0 || fb_height <= 0) + return; + + ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); + ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; + if (pipeline == VK_NULL_HANDLE) + pipeline = bd->Pipeline; + + // Allocate array to store enough vertex/index buffers + ImGui_ImplVulkan_WindowRenderBuffers* wrb = &bd->MainWindowRenderBuffers; + if (wrb->FrameRenderBuffers == nullptr) + { + wrb->Index = 0; + wrb->Count = v->ImageCount; + wrb->FrameRenderBuffers = (ImGui_ImplVulkan_FrameRenderBuffers*)IM_ALLOC(sizeof(ImGui_ImplVulkan_FrameRenderBuffers) * wrb->Count); + memset(wrb->FrameRenderBuffers, 0, sizeof(ImGui_ImplVulkan_FrameRenderBuffers) * wrb->Count); + } + IM_ASSERT(wrb->Count == v->ImageCount); + wrb->Index = (wrb->Index + 1) % wrb->Count; + ImGui_ImplVulkan_FrameRenderBuffers* rb = &wrb->FrameRenderBuffers[wrb->Index]; + + if (draw_data->TotalVtxCount > 0) + { + // Create or resize the vertex/index buffers + size_t vertex_size = AlignBufferSize(draw_data->TotalVtxCount * sizeof(ImDrawVert), bd->BufferMemoryAlignment); + size_t index_size = AlignBufferSize(draw_data->TotalIdxCount * sizeof(ImDrawIdx), bd->BufferMemoryAlignment); + if (rb->VertexBuffer == VK_NULL_HANDLE || rb->VertexBufferSize < vertex_size) + CreateOrResizeBuffer(rb->VertexBuffer, rb->VertexBufferMemory, rb->VertexBufferSize, vertex_size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT); + if (rb->IndexBuffer == VK_NULL_HANDLE || rb->IndexBufferSize < index_size) + CreateOrResizeBuffer(rb->IndexBuffer, rb->IndexBufferMemory, rb->IndexBufferSize, index_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT); + + // Upload vertex/index data into a single contiguous GPU buffer + ImDrawVert* vtx_dst = nullptr; + ImDrawIdx* idx_dst = nullptr; + VkResult err = vkMapMemory(v->Device, rb->VertexBufferMemory, 0, vertex_size, 0, (void**)&vtx_dst); + check_vk_result(err); + err = vkMapMemory(v->Device, rb->IndexBufferMemory, 0, index_size, 0, (void**)&idx_dst); + check_vk_result(err); + for (int n = 0; n < draw_data->CmdListsCount; n++) + { + const ImDrawList* cmd_list = draw_data->CmdLists[n]; + memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert)); + memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx)); + vtx_dst += cmd_list->VtxBuffer.Size; + idx_dst += cmd_list->IdxBuffer.Size; + } + VkMappedMemoryRange range[2] = {}; + range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; + range[0].memory = rb->VertexBufferMemory; + range[0].size = VK_WHOLE_SIZE; + range[1].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; + range[1].memory = rb->IndexBufferMemory; + range[1].size = VK_WHOLE_SIZE; + err = vkFlushMappedMemoryRanges(v->Device, 2, range); + check_vk_result(err); + vkUnmapMemory(v->Device, rb->VertexBufferMemory); + vkUnmapMemory(v->Device, rb->IndexBufferMemory); + } + + // Setup desired Vulkan state + ImGui_ImplVulkan_SetupRenderState(draw_data, pipeline, command_buffer, rb, fb_width, fb_height); + + // Will project scissor/clipping rectangles into framebuffer space + ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports + ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2) + + // Render command lists + // (Because we merged all buffers into a single one, we maintain our own offset into them) + int global_vtx_offset = 0; + int global_idx_offset = 0; + for (int n = 0; n < draw_data->CmdListsCount; n++) + { + const ImDrawList* cmd_list = draw_data->CmdLists[n]; + for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) + { + const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; + if (pcmd->UserCallback != nullptr) + { + // User callback, registered via ImDrawList::AddCallback() + // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) + if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) + ImGui_ImplVulkan_SetupRenderState(draw_data, pipeline, command_buffer, rb, fb_width, fb_height); + else + pcmd->UserCallback(cmd_list, pcmd); + } + else + { + // Project scissor/clipping rectangles into framebuffer space + ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y); + ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y); + + // Clamp to viewport as vkCmdSetScissor() won't accept values that are off bounds + if (clip_min.x < 0.0f) { clip_min.x = 0.0f; } + if (clip_min.y < 0.0f) { clip_min.y = 0.0f; } + if (clip_max.x > fb_width) { clip_max.x = (float)fb_width; } + if (clip_max.y > fb_height) { clip_max.y = (float)fb_height; } + if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) + continue; + + // Apply scissor/clipping rectangle + VkRect2D scissor; + scissor.offset.x = (int32_t)(clip_min.x); + scissor.offset.y = (int32_t)(clip_min.y); + scissor.extent.width = (uint32_t)(clip_max.x - clip_min.x); + scissor.extent.height = (uint32_t)(clip_max.y - clip_min.y); + vkCmdSetScissor(command_buffer, 0, 1, &scissor); + + // Bind DescriptorSet with font or user texture + VkDescriptorSet desc_set[1] = { (VkDescriptorSet)pcmd->TextureId }; + if (sizeof(ImTextureID) < sizeof(ImU64)) + { + // We don't support texture switches if ImTextureID hasn't been redefined to be 64-bit. Do a flaky check that other textures haven't been used. + IM_ASSERT(pcmd->TextureId == (ImTextureID)bd->FontDescriptorSet); + desc_set[0] = bd->FontDescriptorSet; + } + vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, bd->PipelineLayout, 0, 1, desc_set, 0, nullptr); + + // Draw + vkCmdDrawIndexed(command_buffer, pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0); + } + } + global_idx_offset += cmd_list->IdxBuffer.Size; + global_vtx_offset += cmd_list->VtxBuffer.Size; + } + + // Note: at this point both vkCmdSetViewport() and vkCmdSetScissor() have been called. + // Our last values will leak into user/application rendering IF: + // - Your app uses a pipeline with VK_DYNAMIC_STATE_VIEWPORT or VK_DYNAMIC_STATE_SCISSOR dynamic state + // - And you forgot to call vkCmdSetViewport() and vkCmdSetScissor() yourself to explicitly set that state. + // If you use VK_DYNAMIC_STATE_VIEWPORT or VK_DYNAMIC_STATE_SCISSOR you are responsible for setting the values before rendering. + // In theory we should aim to backup/restore those values but I am not sure this is possible. + // We perform a call to vkCmdSetScissor() to set back a full viewport which is likely to fix things for 99% users but technically this is not perfect. (See github #4644) + VkRect2D scissor = { { 0, 0 }, { (uint32_t)fb_width, (uint32_t)fb_height } }; + vkCmdSetScissor(command_buffer, 0, 1, &scissor); +} + +bool ImGui_ImplVulkan_CreateFontsTexture() +{ + ImGuiIO& io = ImGui::GetIO(); + ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); + ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; + VkResult err; + + // Destroy existing texture (if any) + if (bd->FontView || bd->FontImage || bd->FontMemory || bd->FontDescriptorSet) + { + vkQueueWaitIdle(v->Queue); + ImGui_ImplVulkan_DestroyFontsTexture(); + } + + // Create command pool/buffer + if (bd->FontCommandPool == VK_NULL_HANDLE) + { + VkCommandPoolCreateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; + info.flags = 0; + info.queueFamilyIndex = v->QueueFamily; + vkCreateCommandPool(v->Device, &info, v->Allocator, &bd->FontCommandPool); + } + if (bd->FontCommandBuffer == VK_NULL_HANDLE) + { + VkCommandBufferAllocateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + info.commandPool = bd->FontCommandPool; + info.commandBufferCount = 1; + err = vkAllocateCommandBuffers(v->Device, &info, &bd->FontCommandBuffer); + check_vk_result(err); + } + + // Start command buffer + { + err = vkResetCommandPool(v->Device, bd->FontCommandPool, 0); + check_vk_result(err); + VkCommandBufferBeginInfo begin_info = {}; + begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + begin_info.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + err = vkBeginCommandBuffer(bd->FontCommandBuffer, &begin_info); + check_vk_result(err); + } + + unsigned char* pixels; + int width, height; + io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); + size_t upload_size = width * height * 4 * sizeof(char); + + // Create the Image: + { + VkImageCreateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + info.imageType = VK_IMAGE_TYPE_2D; + info.format = VK_FORMAT_R8G8B8A8_UNORM; + info.extent.width = width; + info.extent.height = height; + info.extent.depth = 1; + info.mipLevels = 1; + info.arrayLayers = 1; + info.samples = VK_SAMPLE_COUNT_1_BIT; + info.tiling = VK_IMAGE_TILING_OPTIMAL; + info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; + info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + err = vkCreateImage(v->Device, &info, v->Allocator, &bd->FontImage); + check_vk_result(err); + VkMemoryRequirements req; + vkGetImageMemoryRequirements(v->Device, bd->FontImage, &req); + VkMemoryAllocateInfo alloc_info = {}; + alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + alloc_info.allocationSize = IM_MAX(v->MinAllocationSize, req.size); + alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, req.memoryTypeBits); + err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &bd->FontMemory); + check_vk_result(err); + err = vkBindImageMemory(v->Device, bd->FontImage, bd->FontMemory, 0); + check_vk_result(err); + } + + // Create the Image View: + { + VkImageViewCreateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + info.image = bd->FontImage; + info.viewType = VK_IMAGE_VIEW_TYPE_2D; + info.format = VK_FORMAT_R8G8B8A8_UNORM; + info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + info.subresourceRange.levelCount = 1; + info.subresourceRange.layerCount = 1; + err = vkCreateImageView(v->Device, &info, v->Allocator, &bd->FontView); + check_vk_result(err); + } + + // Create the Descriptor Set: + bd->FontDescriptorSet = (VkDescriptorSet)ImGui_ImplVulkan_AddTexture(bd->FontSampler, bd->FontView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + + // Create the Upload Buffer: + VkDeviceMemory upload_buffer_memory; + VkBuffer upload_buffer; + { + VkBufferCreateInfo buffer_info = {}; + buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + buffer_info.size = upload_size; + buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; + buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + err = vkCreateBuffer(v->Device, &buffer_info, v->Allocator, &upload_buffer); + check_vk_result(err); + VkMemoryRequirements req; + vkGetBufferMemoryRequirements(v->Device, upload_buffer, &req); + bd->BufferMemoryAlignment = (bd->BufferMemoryAlignment > req.alignment) ? bd->BufferMemoryAlignment : req.alignment; + VkMemoryAllocateInfo alloc_info = {}; + alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + alloc_info.allocationSize = IM_MAX(v->MinAllocationSize, req.size); + alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, req.memoryTypeBits); + err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &upload_buffer_memory); + check_vk_result(err); + err = vkBindBufferMemory(v->Device, upload_buffer, upload_buffer_memory, 0); + check_vk_result(err); + } + + // Upload to Buffer: + { + char* map = nullptr; + err = vkMapMemory(v->Device, upload_buffer_memory, 0, upload_size, 0, (void**)(&map)); + check_vk_result(err); + memcpy(map, pixels, upload_size); + VkMappedMemoryRange range[1] = {}; + range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; + range[0].memory = upload_buffer_memory; + range[0].size = upload_size; + err = vkFlushMappedMemoryRanges(v->Device, 1, range); + check_vk_result(err); + vkUnmapMemory(v->Device, upload_buffer_memory); + } + + // Copy to Image: + { + VkImageMemoryBarrier copy_barrier[1] = {}; + copy_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + copy_barrier[0].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + copy_barrier[0].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; + copy_barrier[0].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + copy_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + copy_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + copy_barrier[0].image = bd->FontImage; + copy_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + copy_barrier[0].subresourceRange.levelCount = 1; + copy_barrier[0].subresourceRange.layerCount = 1; + vkCmdPipelineBarrier(bd->FontCommandBuffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, copy_barrier); + + VkBufferImageCopy region = {}; + region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + region.imageSubresource.layerCount = 1; + region.imageExtent.width = width; + region.imageExtent.height = height; + region.imageExtent.depth = 1; + vkCmdCopyBufferToImage(bd->FontCommandBuffer, upload_buffer, bd->FontImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion); + + VkImageMemoryBarrier use_barrier[1] = {}; + use_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + use_barrier[0].srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + use_barrier[0].dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + use_barrier[0].oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + use_barrier[0].newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + use_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + use_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + use_barrier[0].image = bd->FontImage; + use_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + use_barrier[0].subresourceRange.levelCount = 1; + use_barrier[0].subresourceRange.layerCount = 1; + vkCmdPipelineBarrier(bd->FontCommandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, use_barrier); + } + + // Store our identifier + io.Fonts->SetTexID((ImTextureID)bd->FontDescriptorSet); + + // End command buffer + VkSubmitInfo end_info = {}; + end_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + end_info.commandBufferCount = 1; + end_info.pCommandBuffers = &bd->FontCommandBuffer; + err = vkEndCommandBuffer(bd->FontCommandBuffer); + check_vk_result(err); + err = vkQueueSubmit(v->Queue, 1, &end_info, VK_NULL_HANDLE); + check_vk_result(err); + + err = vkQueueWaitIdle(v->Queue); + check_vk_result(err); + + vkDestroyBuffer(v->Device, upload_buffer, v->Allocator); + vkFreeMemory(v->Device, upload_buffer_memory, v->Allocator); + + return true; +} + +// You probably never need to call this, as it is called by ImGui_ImplVulkan_CreateFontsTexture() and ImGui_ImplVulkan_Shutdown(). +void ImGui_ImplVulkan_DestroyFontsTexture() +{ + ImGuiIO& io = ImGui::GetIO(); + ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); + ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; + + if (bd->FontDescriptorSet) + { + ImGui_ImplVulkan_RemoveTexture(bd->FontDescriptorSet); + bd->FontDescriptorSet = VK_NULL_HANDLE; + io.Fonts->SetTexID(0); + } + + if (bd->FontView) { vkDestroyImageView(v->Device, bd->FontView, v->Allocator); bd->FontView = VK_NULL_HANDLE; } + if (bd->FontImage) { vkDestroyImage(v->Device, bd->FontImage, v->Allocator); bd->FontImage = VK_NULL_HANDLE; } + if (bd->FontMemory) { vkFreeMemory(v->Device, bd->FontMemory, v->Allocator); bd->FontMemory = VK_NULL_HANDLE; } +} + +static void ImGui_ImplVulkan_CreateShaderModules(VkDevice device, const VkAllocationCallbacks* allocator) +{ + // Create the shader modules + ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); + if (bd->ShaderModuleVert == VK_NULL_HANDLE) + { + VkShaderModuleCreateInfo vert_info = {}; + vert_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + vert_info.codeSize = sizeof(__glsl_shader_vert_spv); + vert_info.pCode = (uint32_t*)__glsl_shader_vert_spv; + VkResult err = vkCreateShaderModule(device, &vert_info, allocator, &bd->ShaderModuleVert); + check_vk_result(err); + } + if (bd->ShaderModuleFrag == VK_NULL_HANDLE) + { + VkShaderModuleCreateInfo frag_info = {}; + frag_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + frag_info.codeSize = sizeof(__glsl_shader_frag_spv); + frag_info.pCode = (uint32_t*)__glsl_shader_frag_spv; + VkResult err = vkCreateShaderModule(device, &frag_info, allocator, &bd->ShaderModuleFrag); + check_vk_result(err); + } +} + +static void ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAllocationCallbacks* allocator, VkPipelineCache pipelineCache, VkRenderPass renderPass, VkSampleCountFlagBits MSAASamples, VkPipeline* pipeline, uint32_t subpass) +{ + ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); + ImGui_ImplVulkan_CreateShaderModules(device, allocator); + + VkPipelineShaderStageCreateInfo stage[2] = {}; + stage[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + stage[0].stage = VK_SHADER_STAGE_VERTEX_BIT; + stage[0].module = bd->ShaderModuleVert; + stage[0].pName = "main"; + stage[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + stage[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; + stage[1].module = bd->ShaderModuleFrag; + stage[1].pName = "main"; + + VkVertexInputBindingDescription binding_desc[1] = {}; + binding_desc[0].stride = sizeof(ImDrawVert); + binding_desc[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX; + + VkVertexInputAttributeDescription attribute_desc[3] = {}; + attribute_desc[0].location = 0; + attribute_desc[0].binding = binding_desc[0].binding; + attribute_desc[0].format = VK_FORMAT_R32G32_SFLOAT; + attribute_desc[0].offset = offsetof(ImDrawVert, pos); + attribute_desc[1].location = 1; + attribute_desc[1].binding = binding_desc[0].binding; + attribute_desc[1].format = VK_FORMAT_R32G32_SFLOAT; + attribute_desc[1].offset = offsetof(ImDrawVert, uv); + attribute_desc[2].location = 2; + attribute_desc[2].binding = binding_desc[0].binding; + attribute_desc[2].format = VK_FORMAT_R8G8B8A8_UNORM; + attribute_desc[2].offset = offsetof(ImDrawVert, col); + + VkPipelineVertexInputStateCreateInfo vertex_info = {}; + vertex_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; + vertex_info.vertexBindingDescriptionCount = 1; + vertex_info.pVertexBindingDescriptions = binding_desc; + vertex_info.vertexAttributeDescriptionCount = 3; + vertex_info.pVertexAttributeDescriptions = attribute_desc; + + VkPipelineInputAssemblyStateCreateInfo ia_info = {}; + ia_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; + ia_info.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + + VkPipelineViewportStateCreateInfo viewport_info = {}; + viewport_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; + viewport_info.viewportCount = 1; + viewport_info.scissorCount = 1; + + VkPipelineRasterizationStateCreateInfo raster_info = {}; + raster_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; + raster_info.polygonMode = VK_POLYGON_MODE_FILL; + raster_info.cullMode = VK_CULL_MODE_NONE; + raster_info.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + raster_info.lineWidth = 1.0f; + + VkPipelineMultisampleStateCreateInfo ms_info = {}; + ms_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; + ms_info.rasterizationSamples = (MSAASamples != 0) ? MSAASamples : VK_SAMPLE_COUNT_1_BIT; + + VkPipelineColorBlendAttachmentState color_attachment[1] = {}; + color_attachment[0].blendEnable = VK_TRUE; + color_attachment[0].srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; + color_attachment[0].dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; + color_attachment[0].colorBlendOp = VK_BLEND_OP_ADD; + color_attachment[0].srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; + color_attachment[0].dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; + color_attachment[0].alphaBlendOp = VK_BLEND_OP_ADD; + color_attachment[0].colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; + + VkPipelineDepthStencilStateCreateInfo depth_info = {}; + depth_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; + + VkPipelineColorBlendStateCreateInfo blend_info = {}; + blend_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; + blend_info.attachmentCount = 1; + blend_info.pAttachments = color_attachment; + + VkDynamicState dynamic_states[2] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; + VkPipelineDynamicStateCreateInfo dynamic_state = {}; + dynamic_state.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; + dynamic_state.dynamicStateCount = (uint32_t)IM_ARRAYSIZE(dynamic_states); + dynamic_state.pDynamicStates = dynamic_states; + + VkGraphicsPipelineCreateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; + info.flags = bd->PipelineCreateFlags; + info.stageCount = 2; + info.pStages = stage; + info.pVertexInputState = &vertex_info; + info.pInputAssemblyState = &ia_info; + info.pViewportState = &viewport_info; + info.pRasterizationState = &raster_info; + info.pMultisampleState = &ms_info; + info.pDepthStencilState = &depth_info; + info.pColorBlendState = &blend_info; + info.pDynamicState = &dynamic_state; + info.layout = bd->PipelineLayout; + info.renderPass = renderPass; + info.subpass = subpass; + +#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING + if (bd->VulkanInitInfo.UseDynamicRendering) + { + IM_ASSERT(bd->VulkanInitInfo.PipelineRenderingCreateInfo.sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR && "PipelineRenderingCreateInfo sType must be VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR"); + IM_ASSERT(bd->VulkanInitInfo.PipelineRenderingCreateInfo.pNext == nullptr && "PipelineRenderingCreateInfo pNext must be NULL"); + info.pNext = &bd->VulkanInitInfo.PipelineRenderingCreateInfo; + info.renderPass = VK_NULL_HANDLE; // Just make sure it's actually nullptr. + } +#endif + + VkResult err = vkCreateGraphicsPipelines(device, pipelineCache, 1, &info, allocator, pipeline); + check_vk_result(err); +} + +bool ImGui_ImplVulkan_CreateDeviceObjects() +{ + ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); + ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; + VkResult err; + + if (!bd->FontSampler) + { + // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling. + VkSamplerCreateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; + info.magFilter = VK_FILTER_LINEAR; + info.minFilter = VK_FILTER_LINEAR; + info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; + info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; + info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; + info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; + info.minLod = -1000; + info.maxLod = 1000; + info.maxAnisotropy = 1.0f; + err = vkCreateSampler(v->Device, &info, v->Allocator, &bd->FontSampler); + check_vk_result(err); + } + + if (!bd->DescriptorSetLayout) + { + VkDescriptorSetLayoutBinding binding[1] = {}; + binding[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + binding[0].descriptorCount = 1; + binding[0].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; + VkDescriptorSetLayoutCreateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; + info.bindingCount = 1; + info.pBindings = binding; + err = vkCreateDescriptorSetLayout(v->Device, &info, v->Allocator, &bd->DescriptorSetLayout); + check_vk_result(err); + } + + if (!bd->PipelineLayout) + { + // Constants: we are using 'vec2 offset' and 'vec2 scale' instead of a full 3d projection matrix + VkPushConstantRange push_constants[1] = {}; + push_constants[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT; + push_constants[0].offset = sizeof(float) * 0; + push_constants[0].size = sizeof(float) * 4; + VkDescriptorSetLayout set_layout[1] = { bd->DescriptorSetLayout }; + VkPipelineLayoutCreateInfo layout_info = {}; + layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + layout_info.setLayoutCount = 1; + layout_info.pSetLayouts = set_layout; + layout_info.pushConstantRangeCount = 1; + layout_info.pPushConstantRanges = push_constants; + err = vkCreatePipelineLayout(v->Device, &layout_info, v->Allocator, &bd->PipelineLayout); + check_vk_result(err); + } + + ImGui_ImplVulkan_CreatePipeline(v->Device, v->Allocator, v->PipelineCache, v->RenderPass, v->MSAASamples, &bd->Pipeline, v->Subpass); + + return true; +} + +void ImGui_ImplVulkan_DestroyDeviceObjects() +{ + ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); + ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; + ImGui_ImplVulkan_DestroyWindowRenderBuffers(v->Device, &bd->MainWindowRenderBuffers, v->Allocator); + ImGui_ImplVulkan_DestroyFontsTexture(); + + if (bd->FontCommandBuffer) { vkFreeCommandBuffers(v->Device, bd->FontCommandPool, 1, &bd->FontCommandBuffer); bd->FontCommandBuffer = VK_NULL_HANDLE; } + if (bd->FontCommandPool) { vkDestroyCommandPool(v->Device, bd->FontCommandPool, v->Allocator); bd->FontCommandPool = VK_NULL_HANDLE; } + if (bd->ShaderModuleVert) { vkDestroyShaderModule(v->Device, bd->ShaderModuleVert, v->Allocator); bd->ShaderModuleVert = VK_NULL_HANDLE; } + if (bd->ShaderModuleFrag) { vkDestroyShaderModule(v->Device, bd->ShaderModuleFrag, v->Allocator); bd->ShaderModuleFrag = VK_NULL_HANDLE; } + if (bd->FontSampler) { vkDestroySampler(v->Device, bd->FontSampler, v->Allocator); bd->FontSampler = VK_NULL_HANDLE; } + if (bd->DescriptorSetLayout) { vkDestroyDescriptorSetLayout(v->Device, bd->DescriptorSetLayout, v->Allocator); bd->DescriptorSetLayout = VK_NULL_HANDLE; } + if (bd->PipelineLayout) { vkDestroyPipelineLayout(v->Device, bd->PipelineLayout, v->Allocator); bd->PipelineLayout = VK_NULL_HANDLE; } + if (bd->Pipeline) { vkDestroyPipeline(v->Device, bd->Pipeline, v->Allocator); bd->Pipeline = VK_NULL_HANDLE; } +} + +bool ImGui_ImplVulkan_LoadFunctions(PFN_vkVoidFunction(*loader_func)(const char* function_name, void* user_data), void* user_data) +{ + // Load function pointers + // You can use the default Vulkan loader using: + // ImGui_ImplVulkan_LoadFunctions([](const char* function_name, void*) { return vkGetInstanceProcAddr(your_vk_isntance, function_name); }); + // But this would be roughly equivalent to not setting VK_NO_PROTOTYPES. +#ifdef IMGUI_IMPL_VULKAN_USE_LOADER +#define IMGUI_VULKAN_FUNC_LOAD(func) \ + func = reinterpret_cast(loader_func(#func, user_data)); \ + if (func == nullptr) \ + return false; + IMGUI_VULKAN_FUNC_MAP(IMGUI_VULKAN_FUNC_LOAD) +#undef IMGUI_VULKAN_FUNC_LOAD + +#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING + // Manually load those two (see #5446) + ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR = reinterpret_cast(loader_func("vkCmdBeginRenderingKHR", user_data)); + ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR = reinterpret_cast(loader_func("vkCmdEndRenderingKHR", user_data)); +#endif +#else + IM_UNUSED(loader_func); + IM_UNUSED(user_data); +#endif + + g_FunctionsLoaded = true; + return true; +} + +bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info) +{ + IM_ASSERT(g_FunctionsLoaded && "Need to call ImGui_ImplVulkan_LoadFunctions() if IMGUI_IMPL_VULKAN_NO_PROTOTYPES or VK_NO_PROTOTYPES are set!"); + + if (info->UseDynamicRendering) + { +#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING +#ifndef IMGUI_IMPL_VULKAN_USE_LOADER + ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR = reinterpret_cast(vkGetInstanceProcAddr(info->Instance, "vkCmdBeginRenderingKHR")); + ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR = reinterpret_cast(vkGetInstanceProcAddr(info->Instance, "vkCmdEndRenderingKHR")); +#endif + IM_ASSERT(ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR != nullptr); + IM_ASSERT(ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR != nullptr); +#else + IM_ASSERT(0 && "Can't use dynamic rendering when neither VK_VERSION_1_3 or VK_KHR_dynamic_rendering is defined."); +#endif + } + + ImGuiIO& io = ImGui::GetIO(); + IMGUI_CHECKVERSION(); + IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); + + // Setup backend capabilities flags + ImGui_ImplVulkan_Data* bd = IM_NEW(ImGui_ImplVulkan_Data)(); + io.BackendRendererUserData = (void*)bd; + io.BackendRendererName = "imgui_impl_vulkan"; + io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + + IM_ASSERT(info->Instance != VK_NULL_HANDLE); + IM_ASSERT(info->PhysicalDevice != VK_NULL_HANDLE); + IM_ASSERT(info->Device != VK_NULL_HANDLE); + IM_ASSERT(info->Queue != VK_NULL_HANDLE); + IM_ASSERT(info->DescriptorPool != VK_NULL_HANDLE); + IM_ASSERT(info->MinImageCount >= 2); + IM_ASSERT(info->ImageCount >= info->MinImageCount); + if (info->UseDynamicRendering == false) + IM_ASSERT(info->RenderPass != VK_NULL_HANDLE); + + bd->VulkanInitInfo = *info; + + ImGui_ImplVulkan_CreateDeviceObjects(); + + return true; +} + +void ImGui_ImplVulkan_Shutdown() +{ + ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); + IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); + ImGuiIO& io = ImGui::GetIO(); + + ImGui_ImplVulkan_DestroyDeviceObjects(); + io.BackendRendererName = nullptr; + io.BackendRendererUserData = nullptr; + io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; + IM_DELETE(bd); +} + +void ImGui_ImplVulkan_NewFrame() +{ + ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); + IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplVulkan_Init()?"); + + if (!bd->FontDescriptorSet) + ImGui_ImplVulkan_CreateFontsTexture(); +} + +void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count) +{ + ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); + IM_ASSERT(min_image_count >= 2); + if (bd->VulkanInitInfo.MinImageCount == min_image_count) + return; + + ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; + VkResult err = vkDeviceWaitIdle(v->Device); + check_vk_result(err); + ImGui_ImplVulkan_DestroyWindowRenderBuffers(v->Device, &bd->MainWindowRenderBuffers, v->Allocator); + bd->VulkanInitInfo.MinImageCount = min_image_count; +} + +// Register a texture +// FIXME: This is experimental in the sense that we are unsure how to best design/tackle this problem, please post to https://github.com/ocornut/imgui/pull/914 if you have suggestions. +VkDescriptorSet ImGui_ImplVulkan_AddTexture(VkSampler sampler, VkImageView image_view, VkImageLayout image_layout) +{ + ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); + ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; + + // Create Descriptor Set: + VkDescriptorSet descriptor_set; + { + VkDescriptorSetAllocateInfo alloc_info = {}; + alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + alloc_info.descriptorPool = v->DescriptorPool; + alloc_info.descriptorSetCount = 1; + alloc_info.pSetLayouts = &bd->DescriptorSetLayout; + VkResult err = vkAllocateDescriptorSets(v->Device, &alloc_info, &descriptor_set); + check_vk_result(err); + } + + // Update the Descriptor Set: + { + VkDescriptorImageInfo desc_image[1] = {}; + desc_image[0].sampler = sampler; + desc_image[0].imageView = image_view; + desc_image[0].imageLayout = image_layout; + VkWriteDescriptorSet write_desc[1] = {}; + write_desc[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + write_desc[0].dstSet = descriptor_set; + write_desc[0].descriptorCount = 1; + write_desc[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + write_desc[0].pImageInfo = desc_image; + vkUpdateDescriptorSets(v->Device, 1, write_desc, 0, nullptr); + } + return descriptor_set; +} + +void ImGui_ImplVulkan_RemoveTexture(VkDescriptorSet descriptor_set) +{ + ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); + ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; + vkFreeDescriptorSets(v->Device, v->DescriptorPool, 1, &descriptor_set); +} + +void ImGui_ImplVulkan_DestroyFrameRenderBuffers(VkDevice device, ImGui_ImplVulkan_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator) +{ + if (buffers->VertexBuffer) { vkDestroyBuffer(device, buffers->VertexBuffer, allocator); buffers->VertexBuffer = VK_NULL_HANDLE; } + if (buffers->VertexBufferMemory) { vkFreeMemory(device, buffers->VertexBufferMemory, allocator); buffers->VertexBufferMemory = VK_NULL_HANDLE; } + if (buffers->IndexBuffer) { vkDestroyBuffer(device, buffers->IndexBuffer, allocator); buffers->IndexBuffer = VK_NULL_HANDLE; } + if (buffers->IndexBufferMemory) { vkFreeMemory(device, buffers->IndexBufferMemory, allocator); buffers->IndexBufferMemory = VK_NULL_HANDLE; } + buffers->VertexBufferSize = 0; + buffers->IndexBufferSize = 0; +} + +void ImGui_ImplVulkan_DestroyWindowRenderBuffers(VkDevice device, ImGui_ImplVulkan_WindowRenderBuffers* buffers, const VkAllocationCallbacks* allocator) +{ + for (uint32_t n = 0; n < buffers->Count; n++) + ImGui_ImplVulkan_DestroyFrameRenderBuffers(device, &buffers->FrameRenderBuffers[n], allocator); + IM_FREE(buffers->FrameRenderBuffers); + buffers->FrameRenderBuffers = nullptr; + buffers->Index = 0; + buffers->Count = 0; +} + +//------------------------------------------------------------------------- +// Internal / Miscellaneous Vulkan Helpers +// (Used by example's main.cpp. Used by multi-viewport features. PROBABLY NOT used by your own app.) +//------------------------------------------------------------------------- +// You probably do NOT need to use or care about those functions. +// Those functions only exist because: +// 1) they facilitate the readability and maintenance of the multiple main.cpp examples files. +// 2) the upcoming multi-viewport feature will need them internally. +// Generally we avoid exposing any kind of superfluous high-level helpers in the backends, +// but it is too much code to duplicate everywhere so we exceptionally expose them. +// +// Your engine/app will likely _already_ have code to setup all that stuff (swap chain, render pass, frame buffers, etc.). +// You may read this code to learn about Vulkan, but it is recommended you use you own custom tailored code to do equivalent work. +// (The ImGui_ImplVulkanH_XXX functions do not interact with any of the state used by the regular ImGui_ImplVulkan_XXX functions) +//------------------------------------------------------------------------- + +VkSurfaceFormatKHR ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkFormat* request_formats, int request_formats_count, VkColorSpaceKHR request_color_space) +{ + IM_ASSERT(g_FunctionsLoaded && "Need to call ImGui_ImplVulkan_LoadFunctions() if IMGUI_IMPL_VULKAN_NO_PROTOTYPES or VK_NO_PROTOTYPES are set!"); + IM_ASSERT(request_formats != nullptr); + IM_ASSERT(request_formats_count > 0); + + // Per Spec Format and View Format are expected to be the same unless VK_IMAGE_CREATE_MUTABLE_BIT was set at image creation + // Assuming that the default behavior is without setting this bit, there is no need for separate Swapchain image and image view format + // Additionally several new color spaces were introduced with Vulkan Spec v1.0.40, + // hence we must make sure that a format with the mostly available color space, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, is found and used. + uint32_t avail_count; + vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device, surface, &avail_count, nullptr); + ImVector avail_format; + avail_format.resize((int)avail_count); + vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device, surface, &avail_count, avail_format.Data); + + // First check if only one format, VK_FORMAT_UNDEFINED, is available, which would imply that any format is available + if (avail_count == 1) + { + if (avail_format[0].format == VK_FORMAT_UNDEFINED) + { + VkSurfaceFormatKHR ret; + ret.format = request_formats[0]; + ret.colorSpace = request_color_space; + return ret; + } + else + { + // No point in searching another format + return avail_format[0]; + } + } + else + { + // Request several formats, the first found will be used + for (int request_i = 0; request_i < request_formats_count; request_i++) + for (uint32_t avail_i = 0; avail_i < avail_count; avail_i++) + if (avail_format[avail_i].format == request_formats[request_i] && avail_format[avail_i].colorSpace == request_color_space) + return avail_format[avail_i]; + + // If none of the requested image formats could be found, use the first available + return avail_format[0]; + } +} + +VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkPresentModeKHR* request_modes, int request_modes_count) +{ + IM_ASSERT(g_FunctionsLoaded && "Need to call ImGui_ImplVulkan_LoadFunctions() if IMGUI_IMPL_VULKAN_NO_PROTOTYPES or VK_NO_PROTOTYPES are set!"); + IM_ASSERT(request_modes != nullptr); + IM_ASSERT(request_modes_count > 0); + + // Request a certain mode and confirm that it is available. If not use VK_PRESENT_MODE_FIFO_KHR which is mandatory + uint32_t avail_count = 0; + vkGetPhysicalDeviceSurfacePresentModesKHR(physical_device, surface, &avail_count, nullptr); + ImVector avail_modes; + avail_modes.resize((int)avail_count); + vkGetPhysicalDeviceSurfacePresentModesKHR(physical_device, surface, &avail_count, avail_modes.Data); + //for (uint32_t avail_i = 0; avail_i < avail_count; avail_i++) + // printf("[vulkan] avail_modes[%d] = %d\n", avail_i, avail_modes[avail_i]); + + for (int request_i = 0; request_i < request_modes_count; request_i++) + for (uint32_t avail_i = 0; avail_i < avail_count; avail_i++) + if (request_modes[request_i] == avail_modes[avail_i]) + return request_modes[request_i]; + + return VK_PRESENT_MODE_FIFO_KHR; // Always available +} + +void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator) +{ + IM_ASSERT(physical_device != VK_NULL_HANDLE && device != VK_NULL_HANDLE); + IM_UNUSED(physical_device); + + // Create Command Buffers + VkResult err; + for (uint32_t i = 0; i < wd->ImageCount; i++) + { + ImGui_ImplVulkanH_Frame* fd = &wd->Frames[i]; + { + VkCommandPoolCreateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; + info.flags = 0; + info.queueFamilyIndex = queue_family; + err = vkCreateCommandPool(device, &info, allocator, &fd->CommandPool); + check_vk_result(err); + } + { + VkCommandBufferAllocateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + info.commandPool = fd->CommandPool; + info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + info.commandBufferCount = 1; + err = vkAllocateCommandBuffers(device, &info, &fd->CommandBuffer); + check_vk_result(err); + } + { + VkFenceCreateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; + info.flags = VK_FENCE_CREATE_SIGNALED_BIT; + err = vkCreateFence(device, &info, allocator, &fd->Fence); + check_vk_result(err); + } + } + + for (uint32_t i = 0; i < wd->SemaphoreCount; i++) + { + ImGui_ImplVulkanH_FrameSemaphores* fsd = &wd->FrameSemaphores[i]; + { + VkSemaphoreCreateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; + err = vkCreateSemaphore(device, &info, allocator, &fsd->ImageAcquiredSemaphore); + check_vk_result(err); + err = vkCreateSemaphore(device, &info, allocator, &fsd->RenderCompleteSemaphore); + check_vk_result(err); + } + } +} + +int ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_mode) +{ + if (present_mode == VK_PRESENT_MODE_MAILBOX_KHR) + return 3; + if (present_mode == VK_PRESENT_MODE_FIFO_KHR || present_mode == VK_PRESENT_MODE_FIFO_RELAXED_KHR) + return 2; + if (present_mode == VK_PRESENT_MODE_IMMEDIATE_KHR) + return 1; + IM_ASSERT(0); + return 1; +} + +// Also destroy old swap chain and in-flight frames data, if any. +void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count) +{ + VkResult err; + VkSwapchainKHR old_swapchain = wd->Swapchain; + wd->Swapchain = VK_NULL_HANDLE; + err = vkDeviceWaitIdle(device); + check_vk_result(err); + + // We don't use ImGui_ImplVulkanH_DestroyWindow() because we want to preserve the old swapchain to create the new one. + // Destroy old Framebuffer + for (uint32_t i = 0; i < wd->ImageCount; i++) + ImGui_ImplVulkanH_DestroyFrame(device, &wd->Frames[i], allocator); + for (uint32_t i = 0; i < wd->SemaphoreCount; i++) + ImGui_ImplVulkanH_DestroyFrameSemaphores(device, &wd->FrameSemaphores[i], allocator); + IM_FREE(wd->Frames); + IM_FREE(wd->FrameSemaphores); + wd->Frames = nullptr; + wd->FrameSemaphores = nullptr; + wd->ImageCount = 0; + if (wd->RenderPass) + vkDestroyRenderPass(device, wd->RenderPass, allocator); + if (wd->Pipeline) + vkDestroyPipeline(device, wd->Pipeline, allocator); + + // If min image count was not specified, request different count of images dependent on selected present mode + if (min_image_count == 0) + min_image_count = ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(wd->PresentMode); + + // Create Swapchain + { + VkSwapchainCreateInfoKHR info = {}; + info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; + info.surface = wd->Surface; + info.minImageCount = min_image_count; + info.imageFormat = wd->SurfaceFormat.format; + info.imageColorSpace = wd->SurfaceFormat.colorSpace; + info.imageArrayLayers = 1; + info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; // Assume that graphics family == present family + info.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; + info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; + info.presentMode = wd->PresentMode; + info.clipped = VK_TRUE; + info.oldSwapchain = old_swapchain; + VkSurfaceCapabilitiesKHR cap; + err = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physical_device, wd->Surface, &cap); + check_vk_result(err); + if (info.minImageCount < cap.minImageCount) + info.minImageCount = cap.minImageCount; + else if (cap.maxImageCount != 0 && info.minImageCount > cap.maxImageCount) + info.minImageCount = cap.maxImageCount; + + if (cap.currentExtent.width == 0xffffffff) + { + info.imageExtent.width = wd->Width = w; + info.imageExtent.height = wd->Height = h; + } + else + { + info.imageExtent.width = wd->Width = cap.currentExtent.width; + info.imageExtent.height = wd->Height = cap.currentExtent.height; + } + err = vkCreateSwapchainKHR(device, &info, allocator, &wd->Swapchain); + check_vk_result(err); + err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->ImageCount, nullptr); + check_vk_result(err); + VkImage backbuffers[16] = {}; + IM_ASSERT(wd->ImageCount >= min_image_count); + IM_ASSERT(wd->ImageCount < IM_ARRAYSIZE(backbuffers)); + err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->ImageCount, backbuffers); + check_vk_result(err); + + IM_ASSERT(wd->Frames == nullptr && wd->FrameSemaphores == nullptr); + wd->SemaphoreCount = wd->ImageCount + 1; + wd->Frames = (ImGui_ImplVulkanH_Frame*)IM_ALLOC(sizeof(ImGui_ImplVulkanH_Frame) * wd->ImageCount); + wd->FrameSemaphores = (ImGui_ImplVulkanH_FrameSemaphores*)IM_ALLOC(sizeof(ImGui_ImplVulkanH_FrameSemaphores) * wd->SemaphoreCount); + memset(wd->Frames, 0, sizeof(wd->Frames[0]) * wd->ImageCount); + memset(wd->FrameSemaphores, 0, sizeof(wd->FrameSemaphores[0]) * wd->SemaphoreCount); + for (uint32_t i = 0; i < wd->ImageCount; i++) + wd->Frames[i].Backbuffer = backbuffers[i]; + } + if (old_swapchain) + vkDestroySwapchainKHR(device, old_swapchain, allocator); + + // Create the Render Pass + if (wd->UseDynamicRendering == false) + { + VkAttachmentDescription attachment = {}; + attachment.format = wd->SurfaceFormat.format; + attachment.samples = VK_SAMPLE_COUNT_1_BIT; + attachment.loadOp = wd->ClearEnable ? VK_ATTACHMENT_LOAD_OP_CLEAR : VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; + attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + attachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + VkAttachmentReference color_attachment = {}; + color_attachment.attachment = 0; + color_attachment.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + VkSubpassDescription subpass = {}; + subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; + subpass.colorAttachmentCount = 1; + subpass.pColorAttachments = &color_attachment; + VkSubpassDependency dependency = {}; + dependency.srcSubpass = VK_SUBPASS_EXTERNAL; + dependency.dstSubpass = 0; + dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + dependency.srcAccessMask = 0; + dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + VkRenderPassCreateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; + info.attachmentCount = 1; + info.pAttachments = &attachment; + info.subpassCount = 1; + info.pSubpasses = &subpass; + info.dependencyCount = 1; + info.pDependencies = &dependency; + err = vkCreateRenderPass(device, &info, allocator, &wd->RenderPass); + check_vk_result(err); + + // We do not create a pipeline by default as this is also used by examples' main.cpp, + // but secondary viewport in multi-viewport mode may want to create one with: + //ImGui_ImplVulkan_CreatePipeline(device, allocator, VK_NULL_HANDLE, wd->RenderPass, VK_SAMPLE_COUNT_1_BIT, &wd->Pipeline, v->Subpass); + } + + // Create The Image Views + { + VkImageViewCreateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + info.viewType = VK_IMAGE_VIEW_TYPE_2D; + info.format = wd->SurfaceFormat.format; + info.components.r = VK_COMPONENT_SWIZZLE_R; + info.components.g = VK_COMPONENT_SWIZZLE_G; + info.components.b = VK_COMPONENT_SWIZZLE_B; + info.components.a = VK_COMPONENT_SWIZZLE_A; + VkImageSubresourceRange image_range = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }; + info.subresourceRange = image_range; + for (uint32_t i = 0; i < wd->ImageCount; i++) + { + ImGui_ImplVulkanH_Frame* fd = &wd->Frames[i]; + info.image = fd->Backbuffer; + err = vkCreateImageView(device, &info, allocator, &fd->BackbufferView); + check_vk_result(err); + } + } + + // Create Framebuffer + if (wd->UseDynamicRendering == false) + { + VkImageView attachment[1]; + VkFramebufferCreateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; + info.renderPass = wd->RenderPass; + info.attachmentCount = 1; + info.pAttachments = attachment; + info.width = wd->Width; + info.height = wd->Height; + info.layers = 1; + for (uint32_t i = 0; i < wd->ImageCount; i++) + { + ImGui_ImplVulkanH_Frame* fd = &wd->Frames[i]; + attachment[0] = fd->BackbufferView; + err = vkCreateFramebuffer(device, &info, allocator, &fd->Framebuffer); + check_vk_result(err); + } + } +} + +// Create or resize window +void ImGui_ImplVulkanH_CreateOrResizeWindow(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int width, int height, uint32_t min_image_count) +{ + IM_ASSERT(g_FunctionsLoaded && "Need to call ImGui_ImplVulkan_LoadFunctions() if IMGUI_IMPL_VULKAN_NO_PROTOTYPES or VK_NO_PROTOTYPES are set!"); + (void)instance; + ImGui_ImplVulkanH_CreateWindowSwapChain(physical_device, device, wd, allocator, width, height, min_image_count); + ImGui_ImplVulkanH_CreateWindowCommandBuffers(physical_device, device, wd, queue_family, allocator); +} + +void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator) +{ + vkDeviceWaitIdle(device); // FIXME: We could wait on the Queue if we had the queue in wd-> (otherwise VulkanH functions can't use globals) + //vkQueueWaitIdle(bd->Queue); + + for (uint32_t i = 0; i < wd->ImageCount; i++) + ImGui_ImplVulkanH_DestroyFrame(device, &wd->Frames[i], allocator); + for (uint32_t i = 0; i < wd->SemaphoreCount; i++) + ImGui_ImplVulkanH_DestroyFrameSemaphores(device, &wd->FrameSemaphores[i], allocator); + IM_FREE(wd->Frames); + IM_FREE(wd->FrameSemaphores); + wd->Frames = nullptr; + wd->FrameSemaphores = nullptr; + vkDestroyPipeline(device, wd->Pipeline, allocator); + vkDestroyRenderPass(device, wd->RenderPass, allocator); + vkDestroySwapchainKHR(device, wd->Swapchain, allocator); + vkDestroySurfaceKHR(instance, wd->Surface, allocator); + + *wd = ImGui_ImplVulkanH_Window(); +} + +void ImGui_ImplVulkanH_DestroyFrame(VkDevice device, ImGui_ImplVulkanH_Frame* fd, const VkAllocationCallbacks* allocator) +{ + vkDestroyFence(device, fd->Fence, allocator); + vkFreeCommandBuffers(device, fd->CommandPool, 1, &fd->CommandBuffer); + vkDestroyCommandPool(device, fd->CommandPool, allocator); + fd->Fence = VK_NULL_HANDLE; + fd->CommandBuffer = VK_NULL_HANDLE; + fd->CommandPool = VK_NULL_HANDLE; + + vkDestroyImageView(device, fd->BackbufferView, allocator); + vkDestroyFramebuffer(device, fd->Framebuffer, allocator); +} + +void ImGui_ImplVulkanH_DestroyFrameSemaphores(VkDevice device, ImGui_ImplVulkanH_FrameSemaphores* fsd, const VkAllocationCallbacks* allocator) +{ + vkDestroySemaphore(device, fsd->ImageAcquiredSemaphore, allocator); + vkDestroySemaphore(device, fsd->RenderCompleteSemaphore, allocator); + fsd->ImageAcquiredSemaphore = fsd->RenderCompleteSemaphore = VK_NULL_HANDLE; +} + +//----------------------------------------------------------------------------- + +#endif // #ifndef IMGUI_DISABLE diff --git a/Ifnity/Ifnity/src/Platform/ImguiRender/ImguiVulkanRender.h b/Ifnity/Ifnity/src/Platform/ImguiRender/ImguiVulkanRender.h new file mode 100644 index 0000000..1c7f769 --- /dev/null +++ b/Ifnity/Ifnity/src/Platform/ImguiRender/ImguiVulkanRender.h @@ -0,0 +1,195 @@ +// dear imgui: Renderer Backend for Vulkan +// This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) + +// Implemented features: +// [!] Renderer: User texture binding. Use 'VkDescriptorSet' as ImTextureID. Read the FAQ about ImTextureID! See https://github.com/ocornut/imgui/pull/914 for discussions. +// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. + +// Important: on 32-bit systems, user texture binding is only supported if your imconfig file has '#define ImTextureID ImU64'. +// See imgui_impl_vulkan.cpp file for details. + +// The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification. +// IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/ + +// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +// Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. +// - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. +// You will use those if you want to use this rendering backend in your engine/app. +// - Helper ImGui_ImplVulkanH_XXX functions and structures are only used by this example (main.cpp) and by +// the backend itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code. +// Read comments in imgui_impl_vulkan.h. + +#pragma once +#ifndef IMGUI_DISABLE +#include "imgui.h" // IMGUI_IMPL_API + +// [Configuration] in order to use a custom Vulkan function loader: +// (1) You'll need to disable default Vulkan function prototypes. +// We provide a '#define IMGUI_IMPL_VULKAN_NO_PROTOTYPES' convenience configuration flag. +// In order to make sure this is visible from the imgui_impl_vulkan.cpp compilation unit: +// - Add '#define IMGUI_IMPL_VULKAN_NO_PROTOTYPES' in your imconfig.h file +// - Or as a compilation flag in your build system +// - Or uncomment here (not recommended because you'd be modifying imgui sources!) +// - Do not simply add it in a .cpp file! +// (2) Call ImGui_ImplVulkan_LoadFunctions() before ImGui_ImplVulkan_Init() with your custom function. +// If you have no idea what this is, leave it alone! +//#define IMGUI_IMPL_VULKAN_NO_PROTOTYPES + +// Convenience support for Volk +// (you can also technically use IMGUI_IMPL_VULKAN_NO_PROTOTYPES + wrap Volk via ImGui_ImplVulkan_LoadFunctions().) +//#define IMGUI_IMPL_VULKAN_USE_VOLK + +#if defined(IMGUI_IMPL_VULKAN_NO_PROTOTYPES) && !defined(VK_NO_PROTOTYPES) +#define VK_NO_PROTOTYPES +#endif +#if defined(VK_USE_PLATFORM_WIN32_KHR) && !defined(NOMINMAX) +#define NOMINMAX +#endif + +// Vulkan includes +#ifdef IMGUI_IMPL_VULKAN_USE_VOLK +#include +#else +#include +#endif +#if defined(VK_VERSION_1_3) || defined(VK_KHR_dynamic_rendering) +#define IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING +#endif + +// Initialization data, for ImGui_ImplVulkan_Init() +// - VkDescriptorPool should be created with VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, +// and must contain a pool size large enough to hold an ImGui VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER descriptor. +// - When using dynamic rendering, set UseDynamicRendering=true and fill PipelineRenderingCreateInfo structure. +// [Please zero-clear before use!] +struct ImGui_ImplVulkan_InitInfo +{ + VkInstance Instance; + VkPhysicalDevice PhysicalDevice; + VkDevice Device; + uint32_t QueueFamily; + VkQueue Queue; + VkDescriptorPool DescriptorPool; // See requirements in note above + VkRenderPass RenderPass; // Ignored if using dynamic rendering + uint32_t MinImageCount; // >= 2 + uint32_t ImageCount; // >= MinImageCount + VkSampleCountFlagBits MSAASamples; // 0 defaults to VK_SAMPLE_COUNT_1_BIT + + // (Optional) + VkPipelineCache PipelineCache; + uint32_t Subpass; + + // (Optional) Dynamic Rendering + // Need to explicitly enable VK_KHR_dynamic_rendering extension to use this, even for Vulkan 1.3. + bool UseDynamicRendering; +#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING + VkPipelineRenderingCreateInfoKHR PipelineRenderingCreateInfo; +#endif + + // (Optional) Allocation, Debugging + const VkAllocationCallbacks* Allocator; + void (*CheckVkResultFn)(VkResult err); + VkDeviceSize MinAllocationSize; // Minimum allocation size. Set to 1024*1024 to satisfy zealous best practices validation layer and waste a little memory. +}; + +// Follow "Getting Started" link and check examples/ folder to learn about using backends! +IMGUI_IMPL_API bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info); +IMGUI_IMPL_API void ImGui_ImplVulkan_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplVulkan_NewFrame(); +IMGUI_IMPL_API void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer, VkPipeline pipeline = VK_NULL_HANDLE); +IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateFontsTexture(); +IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyFontsTexture(); +IMGUI_IMPL_API void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count); // To override MinImageCount after initialization (e.g. if swap chain is recreated) + +// Register a texture (VkDescriptorSet == ImTextureID) +// FIXME: This is experimental in the sense that we are unsure how to best design/tackle this problem +// Please post to https://github.com/ocornut/imgui/pull/914 if you have suggestions. +IMGUI_IMPL_API VkDescriptorSet ImGui_ImplVulkan_AddTexture(VkSampler sampler, VkImageView image_view, VkImageLayout image_layout); +IMGUI_IMPL_API void ImGui_ImplVulkan_RemoveTexture(VkDescriptorSet descriptor_set); + +// Optional: load Vulkan functions with a custom function loader +// This is only useful with IMGUI_IMPL_VULKAN_NO_PROTOTYPES / VK_NO_PROTOTYPES +IMGUI_IMPL_API bool ImGui_ImplVulkan_LoadFunctions(PFN_vkVoidFunction(*loader_func)(const char* function_name, void* user_data), void* user_data = nullptr); + +//------------------------------------------------------------------------- +// Internal / Miscellaneous Vulkan Helpers +// (Used by example's main.cpp. Used by multi-viewport features. PROBABLY NOT used by your own engine/app.) +//------------------------------------------------------------------------- +// You probably do NOT need to use or care about those functions. +// Those functions only exist because: +// 1) they facilitate the readability and maintenance of the multiple main.cpp examples files. +// 2) the multi-viewport / platform window implementation needs them internally. +// Generally we avoid exposing any kind of superfluous high-level helpers in the bindings, +// but it is too much code to duplicate everywhere so we exceptionally expose them. +// +// Your engine/app will likely _already_ have code to setup all that stuff (swap chain, render pass, frame buffers, etc.). +// You may read this code to learn about Vulkan, but it is recommended you use you own custom tailored code to do equivalent work. +// (The ImGui_ImplVulkanH_XXX functions do not interact with any of the state used by the regular ImGui_ImplVulkan_XXX functions) +//------------------------------------------------------------------------- + +struct ImGui_ImplVulkanH_Frame; +struct ImGui_ImplVulkanH_Window; + +// Helpers +IMGUI_IMPL_API void ImGui_ImplVulkanH_CreateOrResizeWindow(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wnd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); +IMGUI_IMPL_API void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Window* wnd, const VkAllocationCallbacks* allocator); +IMGUI_IMPL_API VkSurfaceFormatKHR ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkFormat* request_formats, int request_formats_count, VkColorSpaceKHR request_color_space); +IMGUI_IMPL_API VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkPresentModeKHR* request_modes, int request_modes_count); +IMGUI_IMPL_API int ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_mode); + +// Helper structure to hold the data needed by one rendering frame +// (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own engine/app.) +// [Please zero-clear before use!] +struct ImGui_ImplVulkanH_Frame +{ + VkCommandPool CommandPool; + VkCommandBuffer CommandBuffer; + VkFence Fence; + VkImage Backbuffer; + VkImageView BackbufferView; + VkFramebuffer Framebuffer; +}; + +struct ImGui_ImplVulkanH_FrameSemaphores +{ + VkSemaphore ImageAcquiredSemaphore; + VkSemaphore RenderCompleteSemaphore; +}; + +// Helper structure to hold the data needed by one rendering context into one OS window +// (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own engine/app.) +struct ImGui_ImplVulkanH_Window +{ + int Width; + int Height; + VkSwapchainKHR Swapchain; + VkSurfaceKHR Surface; + VkSurfaceFormatKHR SurfaceFormat; + VkPresentModeKHR PresentMode; + VkRenderPass RenderPass; + VkPipeline Pipeline; // The window pipeline may uses a different VkRenderPass than the one passed in ImGui_ImplVulkan_InitInfo + bool UseDynamicRendering; + bool ClearEnable; + VkClearValue ClearValue; + uint32_t FrameIndex; // Current frame being rendered to (0 <= FrameIndex < FrameInFlightCount) + uint32_t ImageCount; // Number of simultaneous in-flight frames (returned by vkGetSwapchainImagesKHR, usually derived from min_image_count) + uint32_t SemaphoreCount; // Number of simultaneous in-flight frames + 1, to be able to use it in vkAcquireNextImageKHR + uint32_t SemaphoreIndex; // Current set of swapchain wait semaphores we're using (needs to be distinct from per frame data) + ImGui_ImplVulkanH_Frame* Frames; + ImGui_ImplVulkanH_FrameSemaphores* FrameSemaphores; + + ImGui_ImplVulkanH_Window() + { + memset((void*)this, 0, sizeof(*this)); + PresentMode = (VkPresentModeKHR)~0; // Ensure we get an error if user doesn't set this. + ClearEnable = true; + } +}; + +#endif // #ifndef IMGUI_DISABLE diff --git a/Ifnity/Ifnity/src/Platform/Windows/DeviceD3D11.cpp b/Ifnity/Ifnity/src/Platform/Windows/DeviceD3D11.cpp index ed3c34d..aee5c62 100644 --- a/Ifnity/Ifnity/src/Platform/Windows/DeviceD3D11.cpp +++ b/Ifnity/Ifnity/src/Platform/Windows/DeviceD3D11.cpp @@ -274,6 +274,10 @@ void DeviceD3D11::InitializeGui() IFNITY_LOG(LogApp, TRACE, "Imgui API is set to D3D11"); } +void DeviceD3D11::InternalPreDestroy() +{ +} + void DeviceD3D11::Init() diff --git a/Ifnity/Ifnity/src/Platform/Windows/DeviceD3D11.h b/Ifnity/Ifnity/src/Platform/Windows/DeviceD3D11.h index 974fdcf..b5a5e04 100644 --- a/Ifnity/Ifnity/src/Platform/Windows/DeviceD3D11.h +++ b/Ifnity/Ifnity/src/Platform/Windows/DeviceD3D11.h @@ -62,6 +62,7 @@ class DeviceD3D11 final : public GraphicsDeviceManager bool InitializeDeviceAndContext() override; void ResizeSwapChain() override; void InitializeGui() override; + void InternalPreDestroy() override; private: diff --git a/Ifnity/Ifnity/src/Platform/Windows/DeviceD3D12.cpp b/Ifnity/Ifnity/src/Platform/Windows/DeviceD3D12.cpp index 6121182..8310606 100644 --- a/Ifnity/Ifnity/src/Platform/Windows/DeviceD3D12.cpp +++ b/Ifnity/Ifnity/src/Platform/Windows/DeviceD3D12.cpp @@ -140,7 +140,6 @@ void DeviceD3D12::OnUpdate() m_CommandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(CurrentBackBuffer(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT)); - // Done recording commands. ThrowIfFailed(m_CommandList->Close()); @@ -381,6 +380,9 @@ void DeviceD3D12::InitializeGui() m_CommandList->SetDescriptorHeaps(1, m_CbvSrvUavHeap.GetAddressOf()); +} +void DeviceD3D12::InternalPreDestroy() +{ } void DeviceD3D12::LogAdaptersD3D12() { @@ -981,9 +983,8 @@ void DeviceD3D12::PopulateCommandList() m_CommandList->RSSetViewports(1, &m_ScreenViewport); m_CommandList->RSSetScissorRects(1, &m_ScissorRect); - - // Indicate that the back buffer will be used as a render target. - m_CommandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(CurrentBackBuffer(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET)); + auto barrier = CD3DX12_RESOURCE_BARRIER::Transition(CurrentBackBuffer(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET); + m_CommandList->ResourceBarrier(1, &barrier); // Set necessary state. m_CommandList->SetDescriptorHeaps(1, m_CbvSrvUavHeap.GetAddressOf()); @@ -993,6 +994,9 @@ void DeviceD3D12::PopulateCommandList() m_CommandList->ClearRenderTargetView(CurrentBackBufferView(), Colors::CadetBlue, 0, nullptr); m_CommandList->ClearDepthStencilView(DepthStencilView(), D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 1.0f, 0, 0, nullptr); + D3D12_CPU_DESCRIPTOR_HANDLE backBufferView = CurrentBackBufferView(); + D3D12_CPU_DESCRIPTOR_HANDLE depthStencilView = DepthStencilView(); + m_CommandList->OMSetRenderTargets(1, &backBufferView, true, &depthStencilView); m_CommandList->OMSetRenderTargets(1, &CurrentBackBufferView(), true, &DepthStencilView()); diff --git a/Ifnity/Ifnity/src/Platform/Windows/DeviceD3D12.h b/Ifnity/Ifnity/src/Platform/Windows/DeviceD3D12.h index b68939b..fe07d2d 100644 --- a/Ifnity/Ifnity/src/Platform/Windows/DeviceD3D12.h +++ b/Ifnity/Ifnity/src/Platform/Windows/DeviceD3D12.h @@ -99,6 +99,7 @@ class DeviceD3D12 final : public GraphicsDeviceManager bool InitializeDeviceAndContext() override; void ResizeSwapChain() override; void InitializeGui() override; + void InternalPreDestroy() override; private: void LogAdaptersD3D12(); diff --git a/Ifnity/Ifnity/src/Platform/Windows/DeviceOpengl.cpp b/Ifnity/Ifnity/src/Platform/Windows/DeviceOpengl.cpp index f215fcf..f4a3abc 100644 --- a/Ifnity/Ifnity/src/Platform/Windows/DeviceOpengl.cpp +++ b/Ifnity/Ifnity/src/Platform/Windows/DeviceOpengl.cpp @@ -175,6 +175,10 @@ void DeviceOpengl::Shutdown() } +void DeviceOpengl::InternalPreDestroy() +{ +} + IFNITY_END_NAMESPACE diff --git a/Ifnity/Ifnity/src/Platform/Windows/DeviceOpengl.h b/Ifnity/Ifnity/src/Platform/Windows/DeviceOpengl.h index 52e25a1..4b786e8 100644 --- a/Ifnity/Ifnity/src/Platform/Windows/DeviceOpengl.h +++ b/Ifnity/Ifnity/src/Platform/Windows/DeviceOpengl.h @@ -32,6 +32,7 @@ class DeviceOpengl final : public GraphicsDeviceManager void ResizeSwapChain() override; void InitializeGui() override; void Shutdown() override; + void InternalPreDestroy() override; private: void Init(); void InitializeGLAD(); diff --git a/Ifnity/Ifnity/src/Platform/Windows/DeviceVulkan.cpp b/Ifnity/Ifnity/src/Platform/Windows/DeviceVulkan.cpp index e69de29..41506f3 100644 --- a/Ifnity/Ifnity/src/Platform/Windows/DeviceVulkan.cpp +++ b/Ifnity/Ifnity/src/Platform/Windows/DeviceVulkan.cpp @@ -0,0 +1,930 @@ + + +#include "DeviceVulkan.h" +#define VMA_IMPLEMENTATION +#include "vk_mem_alloc.h" + +//#define IMGUI_DEMO + +IFNITY_NAMESPACE + +static void check_vk_result(VkResult err) +{ + if (err == 0) + return; + fprintf(stderr, "[vulkan] Error: VkResult = %d\n", err); + if (err < 0) + abort(); +} + + +void DeviceVulkan::OnUpdate() +{ + if (vkWaitForFences(m_Device.device, 1, &m_InFlightFences[m_CurrentFrame], VK_TRUE, UINT64_MAX) != VK_SUCCESS) + { + IFNITY_LOG(LogCore, ERROR, "Failed to wait for fences"); + + } + + if (vkResetFences(m_Device.device, 1, &m_InFlightFences[m_CurrentFrame]) != VK_SUCCESS) + { + IFNITY_LOG(LogCore, ERROR, "Failed to reset fences"); + + } + + uint32_t imageIndex = 0; + VkResult result = vkAcquireNextImageKHR(m_Device.device, + m_Swapchain, + UINT64_MAX, + m_ImageAvailableSemaphores[m_CurrentFrame], + VK_NULL_HANDLE, + &imageIndex); + + if (result == VK_ERROR_OUT_OF_DATE_KHR) + { + return ResizeSwapChain(); + } + else + { + if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) + { + IFNITY_LOG(LogCore, ERROR, "Failed to acquire next image"); + } + } + + + if (vkResetCommandBuffer(m_CommandBuffers[m_CurrentFrame], 0) != VK_SUCCESS) + { + IFNITY_LOG(LogCore, ERROR, "Failed to reset command buffer"); + } + + VkCommandBufferBeginInfo cmdBeginInfo{}; + cmdBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + cmdBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + + if (vkBeginCommandBuffer(m_CommandBuffers[m_CurrentFrame], &cmdBeginInfo) != VK_SUCCESS) + { + IFNITY_LOG(LogCore, ERROR, "Failed to begin command buffer"); + } + + + + VkClearValue colorClearValue; + colorClearValue.color = { { 0.1f, 0.1f, 0.1f, 1.0f } }; + + float color[4] = { 1.0f, 0.0f, 0.0f, 1.0f }; // Rojo + + VkClearValue depthValue; + depthValue.depthStencil.depth = 1.0f; + + VkClearValue clearValues[] = { colorClearValue, depthValue }; + + VkRenderPassBeginInfo rpInfo{}; + rpInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; + rpInfo.renderPass = m_RenderPass; + + rpInfo.renderArea.offset.x = 0; + rpInfo.renderArea.offset.y = 0; + rpInfo.renderArea.extent = m_Swapchain.extent; + rpInfo.framebuffer = m_Framebuffers[imageIndex]; + + rpInfo.clearValueCount = 2; + rpInfo.pClearValues = clearValues; + + VkViewport viewport{}; + viewport.x = 0.0f; + viewport.y = 0.0f; + viewport.width = static_cast(m_Swapchain.extent.width); + viewport.height = static_cast(m_Swapchain.extent.height); + viewport.minDepth = 0.0f; + viewport.maxDepth = 1.0f; + + VkRect2D scissor{}; + scissor.offset = { 0, 0 }; + scissor.extent = m_Swapchain.extent; + + BeginRenderDocTrace(m_CommandBuffers[m_CurrentFrame], "Render Pass Begin 11111", color); + vkCmdBeginRenderPass(m_CommandBuffers[m_CurrentFrame], &rpInfo, VK_SUBPASS_CONTENTS_INLINE); + + ///* the rendering itself happens here */ + //if (!mUseChangedShader) { + // vkCmdBindPipeline(mRenderData.rdCommandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, mRenderData.rdBasicPipeline); + //} else { + // vkCmdBindPipeline(mRenderData.rdCommandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, mRenderData.rdChangedPipeline); + //} + + ///* required for dynamic viewport */ + //vkCmdSetViewport(mRenderData.rdCommandBuffer, 0, 1, &viewport); + //vkCmdSetScissor(mRenderData.rdCommandBuffer, 0, 1, &scissor); + + ///* the triangle drawing itself */ + //VkDeviceSize offset = 0; + //vkCmdBindVertexBuffers(mRenderData.rdCommandBuffer, 0, 1, &mVertexBuffer, &offset); + + //vkCmdBindDescriptorSets(mRenderData.rdCommandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, mRenderData.rdPipelineLayout, 0, 1, &mRenderData.rdTextureDescriptorSet, 0, nullptr); + //vkCmdBindDescriptorSets(mRenderData.rdCommandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, mRenderData.rdPipelineLayout, 1, 1, &mRenderData.rdUBODescriptorSet, 0, nullptr); + + //vkCmdDraw(mRenderData.rdCommandBuffer, mRenderData.rdTriangleCount * 3, 1, 0, 0); + + // imgui overlay + + ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), m_CommandBuffers[m_CurrentFrame]); + + vkCmdEndRenderPass(m_CommandBuffers[m_CurrentFrame]); + EndRenderDocTrace(m_CommandBuffers[m_CurrentFrame]); + + if (vkEndCommandBuffer(m_CommandBuffers[m_CurrentFrame]) != VK_SUCCESS) + { + IFNITY_LOG(LogCore, ERROR, "Failed to end command buffer "); + + } + + ///* upload UBO data after commands are created */ + //void* data; + //vmaMapMemory(mRenderData.rdAllocator, mRenderData.rdUboBufferAlloc, &data); + //std::memcpy(data, &mMatrices, static_cast(sizeof(VkUploadMatrices))); + //vmaUnmapMemory(mRenderData.rdAllocator, mRenderData.rdUboBufferAlloc); + + /* submit command buffer */ + VkSubmitInfo submitInfo{}; + submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + + VkPipelineStageFlags waitStage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + submitInfo.pWaitDstStageMask = &waitStage; + + submitInfo.waitSemaphoreCount = 1; + submitInfo.pWaitSemaphores = &m_ImageAvailableSemaphores[m_CurrentFrame]; + + submitInfo.signalSemaphoreCount = 1; + submitInfo.pSignalSemaphores = &m_RenderFinishedSemaphores[m_CurrentFrame]; + + submitInfo.commandBufferCount = 1; + submitInfo.pCommandBuffers = &m_CommandBuffers[m_CurrentFrame]; + + if (vkQueueSubmit(m_GraphicsQueue, 1, &submitInfo, m_InFlightFences[m_CurrentFrame]) != VK_SUCCESS) + { + IFNITY_LOG(LogCore, ERROR, "Failed to submit command buffer"); + + } + + VkPresentInfoKHR presentInfo{}; + presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; + presentInfo.waitSemaphoreCount = 1; + presentInfo.pWaitSemaphores = &m_RenderFinishedSemaphores[m_CurrentFrame]; + + presentInfo.swapchainCount = 1; + presentInfo.pSwapchains = &m_Swapchain.swapchain; + + presentInfo.pImageIndices = &imageIndex; + + result = vkQueuePresentKHR(m_PresentQueue, &presentInfo); + if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR) + { + return ResizeSwapChain(); + } + else + { + if (result != VK_SUCCESS) + { + IFNITY_LOG(LogCore, ERROR, "Failed to present image"); + + } + } + + m_CurrentFrame = (m_CurrentFrame + 1) % 3; + + +} + +unsigned int DeviceVulkan::GetWidth() const +{ + return m_Props.Width; +} + +unsigned int DeviceVulkan::GetHeight() const +{ + return m_Props.Height; +} + +bool DeviceVulkan::InitInternalInstance() +{ + // Create Vulkan instance + + vkb::InstanceBuilder Builder; + + auto inst_ret = + Builder.set_app_name("Example Vulkan Application") + .request_validation_layers() + .use_default_debug_messenger() + .build(); + + if (!inst_ret) + { + //Report Error Log + IFNITY_LOG(LogCore, ERROR, "Failed to create Vulkan instance"); + return false; + } + IFNITY_LOG(LogCore, INFO, "Vulkan instance created"); + + // Store the instance. + m_Instance = inst_ret.value(); + + + return true; +} + +bool DeviceVulkan::InitializeDeviceAndContext() +{ + + + + if (!CreateSurface() || + !CreatePhysicalDevice() || + !CreateDevice() || + !CreateVmaAllocator() || + !GetQueue() || + !CreateSwapChain() || + !CreateCommandPool() || + !CreateRenderPass() || + !CreateFrameBuffer() || + !CreateCommandBuffers() || + !CreateSyncObjects() + + ) + { + IFNITY_LOG(LogCore, ERROR, "Failed Initialization Process "); + return false; + } + + IFNITY_LOG(LogCore, INFO, "Vulkan Device and Context Initialized"); + + + + return true; +} + +bool DeviceVulkan::ConfigureSpecificHintsGLFW() const +{ + //Verify that Vulkan is supported + if (!glfwVulkanSupported()) + { + IFNITY_LOG(LogCore, ERROR, "Vulkan is not supported"); + return false; + } + glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); + return true; +} + +void DeviceVulkan::SetVSync(bool enabled) +{ +} + +bool DeviceVulkan::IsVSync() const +{ + return false; +} + +void DeviceVulkan::ResizeSwapChain() +{ +} + +void DeviceVulkan::InitializeGui() +{ + InitGui(); +} + +void DeviceVulkan::InternalPreDestroy() +{ + //Wait devide to finish and get idle state. + vkDeviceWaitIdle(m_Device.device); +} + + +DeviceVulkan::~DeviceVulkan() +{ + + + //Destroy Descriptor Pool + vkDestroyDescriptorPool(m_Device.device, m_ImGuiDescriptorPool, nullptr); + + //Destroy Sync Objects + DestroySyncObjects(); + DestroyCommandBuffers(); + DestroyCommandPool(); + CleanFrameBuffers(); + DestroyRenderPass(); + + //Destroy Vma Allocator + vmaDestroyAllocator(m_Allocator); + + // Destroy Debug Utils Messenger + if (debugUtilsMessenger != VK_NULL_HANDLE) + { + DestroyDebugUtilsMessengerEXT(m_Instance, debugUtilsMessenger, nullptr); + } + + + // Destroy VkBootStrap + m_Swapchain.destroy_image_views(m_SwapchainImageViews); + + vkb::destroy_swapchain(m_Swapchain); + vkb::destroy_device(m_Device); + vkb::destroy_surface(m_Instance, m_Surface); + vkb::destroy_instance(m_Instance); + + + + IFNITY_LOG(LogCore, INFO, "Delete Device Vulkan Render."); + +} + +bool DeviceVulkan::CreateSurface() +{ + VkResult result = VK_ERROR_UNKNOWN; + result = glfwCreateWindowSurface(m_Instance, m_Window, nullptr, &m_Surface); + + if (result != VK_SUCCESS) + { + IFNITY_LOG(LogCore, ERROR, "Failed to create window surface in Vulkan"); + return false; + } + + return true; +} + +bool DeviceVulkan::CreatePhysicalDevice() +{ + + vkb::PhysicalDeviceSelector physicalDevSel{ m_Instance }; + auto physicalDevSelRet = physicalDevSel.set_surface(m_Surface).select(); + if (!physicalDevSelRet) + { + IFNITY_LOG(LogCore, ERROR, "Failed to select physical device in Vulkan Device"); + return false; + } + + + + + + m_PhysicalDevice = physicalDevSelRet.value(); + + VkPhysicalDeviceFeatures supportedFeatures; + vkGetPhysicalDeviceFeatures(m_PhysicalDevice.physical_device, &supportedFeatures); + + // Enumerar extensiones soportadas por el dispositivo fsico + uint32_t extensionCount = 0; + vkEnumerateDeviceExtensionProperties(m_PhysicalDevice, nullptr, &extensionCount, nullptr); + + std::vector extensions(extensionCount); + vkEnumerateDeviceExtensionProperties(m_PhysicalDevice, nullptr, &extensionCount, extensions.data()); + + for (const auto& ext : extensions) + { + IFNITY_LOG(LogCore, INFO, "Supported extension: {}", ext.extensionName); + } + + // Verificar si VK_EXT_debug_marker est en la lista de extensiones soportadas + bool debugMarkerSupported = false; + for (const auto& ext : extensions) + { + if (strcmp(ext.extensionName, VK_EXT_DEBUG_UTILS_EXTENSION_NAME) == 0) + { + debugMarkerSupported = true; + break; + } + } + + if (debugMarkerSupported) + { + IFNITY_LOG(LogCore, INFO, "VK_EXT_debug_marker is supported"); + } + else + { + IFNITY_LOG(LogCore, WARNING, "VK_EXT_debug_marker is NOT supported"); + } + + //To enable the features that we need available in the physical device. + m_PhysicalDevice.features = supportedFeatures; + + + + return true; +} + +bool DeviceVulkan::CreateDevice() +{ + vkb::DeviceBuilder deviceBuilder{ m_PhysicalDevice }; + + + auto deviceRet = deviceBuilder.build(); + if (!deviceRet) + { + IFNITY_LOG(LogCore, ERROR, "Failed to create device in Vulkan Device"); + return false; + } + m_Device = deviceRet.value(); + +#ifdef _DEBUG + VkDebugUtilsMessengerCreateInfoEXT create_info; + create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT; + create_info.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; + create_info.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; + create_info.pfnUserCallback = debugUtilsMessengerCallback; + create_info.pNext = NULL; + create_info.flags = 0; + + + if (CreateDebugUtilsMessengerEXT(m_Instance, &create_info, nullptr, &debugUtilsMessenger) != VK_SUCCESS) + { + IFNITY_LOG(LogCore, ERROR, "Failed to create debug utils messenger in Vulkan Device"); + return false; + + } + + setupCallbacks(m_Device.device); + +#endif + + + + + + return true; +} + +bool DeviceVulkan::CreateVmaAllocator() +{ + VmaAllocatorCreateInfo allocatorInfo{}; + allocatorInfo.physicalDevice = m_PhysicalDevice.physical_device; + allocatorInfo.device = m_Device.device; + allocatorInfo.instance = m_Instance.instance; + if (vmaCreateAllocator(&allocatorInfo, &m_Allocator) != VK_SUCCESS) + { + IFNITY_LOG(LogCore, ERROR, "Failed to create VMA allocator in Vulkan Device"); + return false; + } + + return true; +} + +bool DeviceVulkan::GetQueue() +{ + auto graphQueueRet = m_Device.get_queue(vkb::QueueType::graphics); + if (!graphQueueRet.has_value()) + { + IFNITY_LOG(LogCore, ERROR, "Failed to get graphics queue in Vulkan Device"); + return false; + } + m_GraphicsQueue = graphQueueRet.value(); + + auto presentQueueRet = m_Device.get_queue(vkb::QueueType::present); + if (!presentQueueRet.has_value()) + { + IFNITY_LOG(LogCore, ERROR, "Failed to get present queue in Vulkan Device"); + return false; + } + m_PresentQueue = presentQueueRet.value(); + + + + return true; +} + +bool DeviceVulkan::CreateSwapChain() +{ + vkb::SwapchainBuilder swapChainBuild{ m_Device }; + + /* VK_PRESENT_MODE_FIFO_KHR enables vsync */ + auto swapChainBuildRet = swapChainBuild.set_old_swapchain(m_Swapchain).set_desired_present_mode(VK_PRESENT_MODE_FIFO_KHR).build(); + if (!swapChainBuildRet) + { + IFNITY_LOG(LogCore, ERROR, "Failed to create swapchain in Vulkan Device"); + return false; + } + + vkb::destroy_swapchain(m_Swapchain); + m_Swapchain = swapChainBuildRet.value(); + + //Get image_count + m_commandBufferCount = m_Swapchain.image_count; + + return true; +} + +bool DeviceVulkan::CreateCommandPool() +{ + VkCommandPoolCreateInfo pool_info{}; + pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; + pool_info.queueFamilyIndex = m_Device.get_queue_index(vkb::QueueType::graphics).value(); + pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; + + if (vkCreateCommandPool(m_Device, &pool_info, nullptr, &m_CommandPool) != VK_SUCCESS) + { + IFNITY_LOG(LogCore, ERROR, "Failed to create command pool in Vulkan Device"); + return false; + } + + return TRUE; +} + +bool DeviceVulkan::DestroyCommandPool() +{ + vkDestroyCommandPool(m_Device, m_CommandPool, nullptr); + return false; +} + +void DeviceVulkan::DestroySyncObjects() +{ + for (size_t i = 0; i < 3; i++) + { + vkDestroySemaphore(m_Device.device, m_ImageAvailableSemaphores[i], nullptr); + vkDestroySemaphore(m_Device.device, m_RenderFinishedSemaphores[i], nullptr); + vkDestroyFence(m_Device.device, m_InFlightFences[i], nullptr); + } + +} + +void DeviceVulkan::DestroyCommandBuffers() +{ + vkFreeCommandBuffers(m_Device.device, + m_CommandPool, + static_cast(m_CommandBuffers.size()), + m_CommandBuffers.data()); + +} + +void DeviceVulkan::CleanFrameBuffers() +{ + for (auto& framebuffer : m_Framebuffers) + { + vkDestroyFramebuffer(m_Device.device, framebuffer, nullptr); + } +} + +void DeviceVulkan::DestroyRenderPass() +{ + vkDestroyRenderPass(m_Device.device, m_RenderPass, nullptr); +} + +bool DeviceVulkan::CreateDepthBuffer() +{ + /*VkExtent3D depthImageExtent = { + m_Swapchain.extent.width, + m_Swapchain.extent.height, + 1 + }; + + mRenderData.rdDepthFormat = VK_FORMAT_D32_SFLOAT; + + VkImageCreateInfo depthImageInfo{}; + depthImageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + depthImageInfo.imageType = VK_IMAGE_TYPE_2D; + depthImageInfo.format = mRenderData.rdDepthFormat; + depthImageInfo.extent = depthImageExtent; + depthImageInfo.mipLevels = 1; + depthImageInfo.arrayLayers = 1; + depthImageInfo.samples = VK_SAMPLE_COUNT_1_BIT; + depthImageInfo.tiling = VK_IMAGE_TILING_OPTIMAL; + depthImageInfo.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; + + VmaAllocationCreateInfo depthAllocInfo{}; + depthAllocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; + depthAllocInfo.requiredFlags = VkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + + if (vmaCreateImage(mRenderData.rdAllocator, &depthImageInfo, &depthAllocInfo, &mRenderData.rdDepthImage, &mRenderData.rdDepthImageAlloc, nullptr) != VK_SUCCESS) + { + Logger::log(1, "%s error: could not allocate depth buffer memory\n", __FUNCTION__); + return false; + } + + VkImageViewCreateInfo depthImageViewinfo{}; + depthImageViewinfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + depthImageViewinfo.viewType = VK_IMAGE_VIEW_TYPE_2D; + depthImageViewinfo.image = mRenderData.rdDepthImage; + depthImageViewinfo.format = mRenderData.rdDepthFormat; + depthImageViewinfo.subresourceRange.baseMipLevel = 0; + depthImageViewinfo.subresourceRange.levelCount = 1; + depthImageViewinfo.subresourceRange.baseArrayLayer = 0; + depthImageViewinfo.subresourceRange.layerCount = 1; + depthImageViewinfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; + + if (vkCreateImageView(m_Device.device, &depthImageViewinfo, nullptr, &mRenderData.rdDepthImageView) != VK_SUCCESS) + { + Logger::log(1, "%s error: could not create depth buffer image view\n", __FUNCTION__); + return false; + }*/ + return true; +} + +bool DeviceVulkan::CreateRenderPass() +{ + //Single RenderPass with one subpass + + std::array attachments = {}; + + // Color attachment + attachments[0].format = m_Swapchain.image_format; // Use the color format selected by the swapchain + attachments[0].samples = VK_SAMPLE_COUNT_1_BIT; // We don't use multi sampling in this example + attachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; // Clear this attachment at the start of the render pass + attachments[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE; // Keep its contents after the render pass is finished (for displaying it) + attachments[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; // Similar to loadOp, but for stenciling (we don't use stencil here) + attachments[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; // Similar to storeOp, but for stenciling (we don't use stencil here) + attachments[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; // Layout at render pass start. Initial doesn't matter, so we use undefined + attachments[0].finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; // Layout to which the attachment is transitioned when the render pass is finished + // As we want to present the color attachment, we transition to PRESENT_KHR +// Setup attachment references + VkAttachmentReference colorReference = {}; + colorReference.attachment = 0; // Attachment 0 is color + colorReference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; // Attachment layout used as color during the subpass + + std::array attachmentref = { colorReference }; + + // Setup a single subpass reference + VkSubpassDescription subpassDescription = {}; + subpassDescription.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; // Pipeline type subpass is to be bound to + subpassDescription.colorAttachmentCount = attachmentref.size(); // Reference to the color attachment in this subpass + subpassDescription.pColorAttachments = attachmentref.data(); // Reference to the color attachment in this subpass + subpassDescription.pDepthStencilAttachment = nullptr; // (Depth attachments not used by this sample) + subpassDescription.inputAttachmentCount = 0; // Input attachments can be used to sample from contents of a previous subpass + subpassDescription.pInputAttachments = nullptr; // (Input attachments not used by this example) + subpassDescription.preserveAttachmentCount = 0; // Preserved attachments can be used to loop (and preserve) attachments through subpasses + subpassDescription.pPreserveAttachments = nullptr; // (Preserve attachments not used by this example) + subpassDescription.pResolveAttachments = nullptr; // Resolve attachments are resolved at the end of a sub pass and can be used for e.g. multi sampling + + // Setup subpass dependencies + std::array dependencies = {}; + + // Setup dependency and add implicit layout transition from final to initial layout for the color attachment. + // (The actual usage layout is preserved through the layout specified in the attachment reference). + dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL; + dependencies[0].dstSubpass = 0; + dependencies[0].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + dependencies[0].srcAccessMask = VK_ACCESS_NONE; + dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT; + + + //Create the render pass + + // Create the render pass object + VkRenderPassCreateInfo renderPassInfo = {}; + renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; + renderPassInfo.attachmentCount = static_cast(attachments.size()); // Number of attachments used by this render pass + renderPassInfo.pAttachments = attachments.data(); // Descriptions of the attachments used by the render pass + renderPassInfo.subpassCount = 1; // We only use one subpass in this example + renderPassInfo.pSubpasses = &subpassDescription; // Description of that subpass + renderPassInfo.dependencyCount = static_cast(dependencies.size()); // Number of subpass dependencies + renderPassInfo.pDependencies = dependencies.data(); // Subpass dependencies used by the render pass + + VK_CHECK(vkCreateRenderPass(m_Device.device, &renderPassInfo, nullptr, &m_RenderPass), "Failed to create render pass"); + + + return true; +} + +bool DeviceVulkan::CreateFrameBuffer() +{ + m_SwapchainImages = m_Swapchain.get_images().value(); + m_SwapchainImageViews = m_Swapchain.get_image_views().value(); + + + VkImageView attachments[1] = {}; + + + VkFramebufferCreateInfo frameBufferCreateInfo = {}; + frameBufferCreateInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; + frameBufferCreateInfo.pNext = NULL; + frameBufferCreateInfo.renderPass = m_RenderPass; + frameBufferCreateInfo.attachmentCount = 1; + frameBufferCreateInfo.pAttachments = attachments; + frameBufferCreateInfo.width = m_Swapchain.extent.width; + frameBufferCreateInfo.height = m_Swapchain.extent.height; + frameBufferCreateInfo.layers = 1; + + //Create Framebuffers for each swapchain image view + m_Framebuffers.resize(m_SwapchainImageViews.size()); + + for (size_t i = 0; i < m_Framebuffers.size(); i++) + { + attachments[0] = m_SwapchainImageViews.at(i); + VK_CHECK(vkCreateFramebuffer(m_Device.device, &frameBufferCreateInfo, nullptr, &m_Framebuffers[i]), "Failed to create framebuffer"); + + } + + return true; +} + +bool DeviceVulkan::CreateCommandBuffers() +{ + m_CommandBuffers.resize(m_Framebuffers.size()); + + VkCommandBufferAllocateInfo bufferAllocInfo{}; + bufferAllocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + bufferAllocInfo.commandPool = m_CommandPool; + bufferAllocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + bufferAllocInfo.commandBufferCount = static_cast(m_CommandBuffers.size()); + + if (vkAllocateCommandBuffers(m_Device.device, &bufferAllocInfo, m_CommandBuffers.data()) != VK_SUCCESS) + { + IFNITY_LOG(LogCore, ERROR, "Failed to allocate command buffers"); + return false; + } + + return true; +} + +bool DeviceVulkan::CreateSyncObjects() +{ + m_ImageAvailableSemaphores.resize(3); + m_RenderFinishedSemaphores.resize(3); + m_InFlightFences.resize(3); + + VkFenceCreateInfo fenceInfo{}; + fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; + fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; + + VkSemaphoreCreateInfo semaphoreInfo{}; + semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; + + for (size_t i = 0; i < 3; i++) + { + if (vkCreateSemaphore(m_Device.device, &semaphoreInfo, nullptr, &m_ImageAvailableSemaphores[i]) != VK_SUCCESS || + vkCreateSemaphore(m_Device.device, &semaphoreInfo, nullptr, &m_RenderFinishedSemaphores[i]) != VK_SUCCESS || + vkCreateFence(m_Device.device, &fenceInfo, nullptr, &m_InFlightFences[i]) != VK_SUCCESS) + { + IFNITY_LOG(LogCore, ERROR, "Failed to create synchronization objects for a frame"); + return false; + } + } + + + return true; +} + +bool DeviceVulkan::AcquireNextImage() +{ + //Get the index of the next available swapchain image + VkResult result = vkAcquireNextImageKHR(m_Device.device, m_Swapchain.swapchain, UINT64_MAX, m_PresentSemaphore, (VkFence)nullptr, &m_imageIndex); + + if (result == VK_ERROR_OUT_OF_DATE_KHR) + { + //Swapchain is out of date (e.g. the window was resized) and + //must be recreated: + ResizeSwapChain(); + return false; + } + else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) + { + IFNITY_LOG(LogCore, ERROR, "Failed to acquire next swapchain image"); + return false; + } + + return true; +} + +bool DeviceVulkan::PopulateCommandBuffer() +{ + return false; +} + +bool DeviceVulkan::SubmitCommandBuffer() +{ + return false; +} + +bool DeviceVulkan::PresentImage() +{ + return false; +} + +bool DeviceVulkan::InitGui() +{ + // Create descriptor pool + if (!CreateImGuiDescriptorPool()) + { + return false; + } + + + ImGui_ImplVulkan_InitInfo init_info = {}; + init_info.Instance = m_Instance; + init_info.PhysicalDevice = m_PhysicalDevice; + init_info.Device = m_Device; + init_info.Queue = m_GraphicsQueue; + init_info.PipelineCache = VK_NULL_HANDLE; + init_info.DescriptorPool = m_ImGuiDescriptorPool; + init_info.RenderPass = m_RenderPass; + init_info.Subpass = 0; + init_info.MinImageCount = 3; + init_info.ImageCount = 3; + init_info.MSAASamples = VK_SAMPLE_COUNT_1_BIT; + init_info.CheckVkResultFn = check_vk_result; + ImGui_ImplVulkan_Init(&init_info); + + //Upload Fonts if this was needed. + + + return true; +} + +bool DeviceVulkan::CreateImGuiDescriptorPool() +{ + VkDescriptorPoolSize pool_sizes[] = + { + { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1 }, + }; + VkDescriptorPoolCreateInfo pool_info = {}; + pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; + pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; + pool_info.maxSets = 1; + pool_info.poolSizeCount = (uint32_t)IM_ARRAYSIZE(pool_sizes); + pool_info.pPoolSizes = pool_sizes; + + if (vkCreateDescriptorPool(m_Device, &pool_info, nullptr, &m_ImGuiDescriptorPool) != VK_SUCCESS) + { + IFNITY_LOG(LogCore, ERROR, "Failed to create descriptor pool for ImGui"); + return false; + } + + return true; +} + + + +void DeviceVulkan::setupCallbacks(VkDevice& i_device) +{ + + // Check if the debug utils extension is present (which is the case if run from a graphics debugger) + bool extensionPresent = false; + uint32_t extensionCount; + vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, nullptr); + std::vector extensions(extensionCount); + vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, extensions.data()); + for (auto& extension : extensions) + { + if (strcmp(extension.extensionName, VK_EXT_DEBUG_UTILS_EXTENSION_NAME) == 0) + { + extensionPresent = true; + break; + } + } + + if (extensionPresent) + { + // As with an other extension, function pointers need to be manually loaded + vkCreateDebugUtilsMessengerEXT = reinterpret_cast(vkGetInstanceProcAddr(m_Instance, "vkCreateDebugUtilsMessengerEXT")); + vkDestroyDebugUtilsMessengerEXT = reinterpret_cast(vkGetInstanceProcAddr(m_Instance, "vkDestroyDebugUtilsMessengerEXT")); + vkCmdBeginDebugUtilsLabelEXT = reinterpret_cast(vkGetInstanceProcAddr(m_Instance, "vkCmdBeginDebugUtilsLabelEXT")); + vkCmdInsertDebugUtilsLabelEXT = reinterpret_cast(vkGetInstanceProcAddr(m_Instance, "vkCmdInsertDebugUtilsLabelEXT")); + vkCmdEndDebugUtilsLabelEXT = reinterpret_cast(vkGetInstanceProcAddr(m_Instance, "vkCmdEndDebugUtilsLabelEXT")); + vkQueueBeginDebugUtilsLabelEXT = reinterpret_cast(vkGetInstanceProcAddr(m_Instance, "vkQueueBeginDebugUtilsLabelEXT")); + vkQueueInsertDebugUtilsLabelEXT = reinterpret_cast(vkGetInstanceProcAddr(m_Instance, "vkQueueInsertDebugUtilsLabelEXT")); + vkQueueEndDebugUtilsLabelEXT = reinterpret_cast(vkGetInstanceProcAddr(m_Instance, "vkQueueEndDebugUtilsLabelEXT")); + vkSetDebugUtilsObjectNameEXT = reinterpret_cast(vkGetInstanceProcAddr(m_Instance, "vkSetDebugUtilsObjectNameEXT")); + + // Set flag if at least one function pointer is present + m_DebugUtilsSupported = (vkCreateDebugUtilsMessengerEXT != VK_NULL_HANDLE); + } + else + { + IFNITY_LOG(LogCore, WARNING, "{} not present, debug utils are disabled.", VK_EXT_DEBUG_UTILS_EXTENSION_NAME); + IFNITY_LOG(LogCore, WARNING, "Try running the sample from inside a Vulkan graphics debugger (e.g. RenderDoc)"); + + } + + +} + +void DeviceVulkan::BeginRenderDocTrace(VkCommandBuffer commandBuffer, const char* markerName, float color[4]) +{ + if (vkCmdBeginDebugUtilsLabelEXT) + { + VkDebugUtilsLabelEXT labelInfo{}; + labelInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT; + labelInfo.pLabelName = markerName; + labelInfo.color[0] = color[0]; + labelInfo.color[1] = color[1]; + labelInfo.color[2] = color[2]; + labelInfo.color[3] = color[3]; + vkCmdBeginDebugUtilsLabelEXT(commandBuffer, &labelInfo); + } + else + { + IFNITY_LOG(LogCore, WARNING, "{} not present, debug utils are disabled.", VK_EXT_DEBUG_UTILS_EXTENSION_NAME); + IFNITY_LOG(LogCore, WARNING, "Try running the sample from inside a Vulkan graphics debugger (e.g. RenderDoc)"); + } +} + +void DeviceVulkan::EndRenderDocTrace(VkCommandBuffer commandBuffer) +{ + if (vkCmdEndDebugUtilsLabelEXT) + { + vkCmdEndDebugUtilsLabelEXT(commandBuffer); + } +} + + +IFNITY_END_NAMESPACE + + diff --git a/Ifnity/Ifnity/src/Platform/Windows/DeviceVulkan.h b/Ifnity/Ifnity/src/Platform/Windows/DeviceVulkan.h index e69de29..6875d43 100644 --- a/Ifnity/Ifnity/src/Platform/Windows/DeviceVulkan.h +++ b/Ifnity/Ifnity/src/Platform/Windows/DeviceVulkan.h @@ -0,0 +1,200 @@ +#pragma once + +#include "UtilsVulkan.h" +#include "Ifnity/GraphicsDeviceManager.hpp" +#include "Platform/ImguiRender/ImguiVulkanRender.h" + +IFNITY_NAMESPACE + +// Data + + + + IFNITY_INLINE VKAPI_ATTR VkBool32 VKAPI_CALL debugUtilsMessengerCallback( + VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, + VkDebugUtilsMessageTypeFlagsEXT messageType, + const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, + void* pUserData) +{ + // Select prefix depending on flags passed to the callback + std::string prefix(""); + + if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) + { + prefix = "VERBOSE: "; + } + else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) + { + prefix = "INFO: "; + } + else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) + { + prefix = "WARNING: "; + } + else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) + { + prefix = "ERROR: "; + } + + std::cerr << prefix << " validation layer: " << pCallbackData->pMessage << std::endl; + + return VK_FALSE; +} + + IFNITY_INLINE VkResult CreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugUtilsMessengerEXT* pDebugMessenger) +{ + auto func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT"); + if (func != nullptr) + { + return func(instance, pCreateInfo, pAllocator, pDebugMessenger); + } + else + { + return VK_ERROR_EXTENSION_NOT_PRESENT; + } +} + +IFNITY_INLINE void DestroyDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerEXT debugMessenger, const VkAllocationCallbacks* pAllocator) + { + auto func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT"); + if (func != nullptr) + { + func(instance, debugMessenger, pAllocator); + } + } + +class DeviceVulkan final : public GraphicsDeviceManager +{ +private: + + + vkb::Instance m_Instance; // Vulkan instance + VmaAllocator m_Allocator; // Vulkan memory allocator + VkSurfaceKHR m_Surface; // Vulkan surface + vkb::Swapchain m_Swapchain; // Vulkan swapchain + vkb::Device m_Device; // Vulkan device bootstrapper + + vkb::PhysicalDevice m_PhysicalDevice; // Vulkan physical device bootstrapper. + + VkCommandPool m_CommandPool = VK_NULL_HANDLE; + VkQueue m_GraphicsQueue = VK_NULL_HANDLE; + VkQueue m_PresentQueue = VK_NULL_HANDLE; + + + // Depth buffer + ImageBlock m_DepthBuffer; + + // Render pass + VkRenderPass m_RenderPass = VK_NULL_HANDLE; + + // Frame buffer and Image, ImageViews + std::vector m_SwapchainImages; + std::vector m_SwapchainImageViews; + std::vector m_Framebuffers; + + // Command buffers + std::vector m_CommandBuffers; + + // Sync objects + std::vector m_ImageAvailableSemaphores; + std::vector m_RenderFinishedSemaphores; + std::vector m_InFlightFences; + + // Sync objects + VkSemaphore m_PresentSemaphore = VK_NULL_HANDLE; + VkSemaphore m_RenderSemaphore = VK_NULL_HANDLE; + VkFence rdRenderFence = VK_NULL_HANDLE; + uint32_t m_CurrentFrame = 0; + + //Auxiliary + uint32_t m_imageIndex = 0; + uint32_t m_commandBufferIndex = 0; + uint32_t m_commandBufferCount = 0; + + //Descritpor Pool Imgui + VkDescriptorPool m_ImGuiDescriptorPool = VK_NULL_HANDLE; + + //DebugUtils + VkDebugUtilsMessengerEXT debugUtilsMessenger; + bool m_DebugUtilsSupported = false; + PFN_vkCreateDebugUtilsMessengerEXT vkCreateDebugUtilsMessengerEXT{ nullptr }; + PFN_vkDestroyDebugUtilsMessengerEXT vkDestroyDebugUtilsMessengerEXT{ nullptr }; + PFN_vkCmdBeginDebugUtilsLabelEXT vkCmdBeginDebugUtilsLabelEXT{ nullptr }; + PFN_vkCmdInsertDebugUtilsLabelEXT vkCmdInsertDebugUtilsLabelEXT{ nullptr }; + PFN_vkCmdEndDebugUtilsLabelEXT vkCmdEndDebugUtilsLabelEXT{ nullptr }; + PFN_vkQueueBeginDebugUtilsLabelEXT vkQueueBeginDebugUtilsLabelEXT{ nullptr }; + PFN_vkQueueInsertDebugUtilsLabelEXT vkQueueInsertDebugUtilsLabelEXT{ nullptr }; + PFN_vkQueueEndDebugUtilsLabelEXT vkQueueEndDebugUtilsLabelEXT{ nullptr }; + PFN_vkSetDebugUtilsObjectNameEXT vkSetDebugUtilsObjectNameEXT{ nullptr }; + +protected: + // Heredado va GraphicsDeviceManager + void OnUpdate() override; + + unsigned int GetWidth() const override; + + unsigned int GetHeight() const override; + + bool InitInternalInstance() override; + + bool InitializeDeviceAndContext() override; + + bool ConfigureSpecificHintsGLFW() const override; + + void SetVSync(bool enabled) override; + + bool IsVSync() const override; + + void ResizeSwapChain() override; + + void InitializeGui() override; + + void InternalPreDestroy() override; + +private: + + ~DeviceVulkan() override; + + // Initialize private methods + bool CreateSurface(); + bool CreatePhysicalDevice(); + bool CreateDevice(); + bool CreateVmaAllocator(); + bool GetQueue(); + bool CreateSwapChain(); + bool CreateCommandPool(); + bool CreateDepthBuffer(); + bool CreateRenderPass(); + bool CreateFrameBuffer(); + bool CreateCommandBuffers(); + bool CreateSyncObjects(); + + //Destroy private methods + bool DestroyCommandPool(); + void DestroySyncObjects(); + void DestroyCommandBuffers(); + void CleanFrameBuffers(); + void DestroyRenderPass(); + + //OnRender private methods + bool AcquireNextImage(); + bool PopulateCommandBuffer(); + bool SubmitCommandBuffer(); + bool PresentImage(); + bool InitGui(); + + //Imgui private methods + bool CreateImGuiDescriptorPool(); + + + void setupCallbacks(VkDevice& i_device); + + void BeginRenderDocTrace(VkCommandBuffer commandBuffer, const char* markerName, float color[4]); + + void EndRenderDocTrace(VkCommandBuffer commandBuffer); + +}; + + + +IFNITY_END_NAMESPACE \ No newline at end of file diff --git a/Ifnity/Ifnity/src/Platform/Windows/UtilsVulkan.h b/Ifnity/Ifnity/src/Platform/Windows/UtilsVulkan.h new file mode 100644 index 0000000..ac9522c --- /dev/null +++ b/Ifnity/Ifnity/src/Platform/Windows/UtilsVulkan.h @@ -0,0 +1,89 @@ + +#pragma once + +#include "pch.h" + +#include +#include +#include + + +#define VK_CHECK(result, errorMessage) \ + if ((result) != VK_SUCCESS) { \ + IFNITY_LOG(LogCore, ERROR, errorMessage); \ + \ + } + + + + +//Forward declaration +struct GLFWwindow; + +struct ImageBlock +{ + VkImage image = VK_NULL_HANDLE; + VkImageView imageView = VK_NULL_HANDLE; + VkFormat format; + VmaAllocation imageAlloc = VK_NULL_HANDLE; + VkDeviceMemory imageMemory = VK_NULL_HANDLE; +}; + +struct VkRenderData +{ + GLFWwindow* rdWindow = nullptr; + + int rdWidth = 0; + int rdHeight = 0; + + unsigned int rdTriangleCount = 0; + + VmaAllocator rdAllocator = nullptr; + + vkb::Instance rdVkbInstance{}; + vkb::PhysicalDevice rdVkbPhysicalDevice{}; + vkb::Device rdVkbDevice{}; + vkb::Swapchain rdVkbSwapchain{}; + + std::vector rdSwapchainImages; + std::vector rdSwapchainImageViews; + std::vector rdFramebuffers; + + VkQueue rdGraphicsQueue = VK_NULL_HANDLE; + VkQueue rdPresentQueue = VK_NULL_HANDLE; + + VkImage rdDepthImage = VK_NULL_HANDLE; + VkImageView rdDepthImageView = VK_NULL_HANDLE; + VkFormat rdDepthFormat; + VmaAllocation rdDepthImageAlloc = VK_NULL_HANDLE; + + VkRenderPass rdRenderpass; + VkPipelineLayout rdPipelineLayout = VK_NULL_HANDLE; + VkPipeline rdBasicPipeline = VK_NULL_HANDLE; + VkPipeline rdChangedPipeline = VK_NULL_HANDLE; + + VkCommandPool rdCommandPool = VK_NULL_HANDLE; + VkCommandBuffer rdCommandBuffer = VK_NULL_HANDLE; + + VkSemaphore rdPresentSemaphore = VK_NULL_HANDLE; + VkSemaphore rdRenderSemaphore = VK_NULL_HANDLE; + VkFence rdRenderFence = VK_NULL_HANDLE; + + VkImage rdTextureImage = VK_NULL_HANDLE; + VkImageView rdTextureImageView = VK_NULL_HANDLE; + VkSampler rdTextureSampler = VK_NULL_HANDLE; + VmaAllocation rdTextureImageAlloc = nullptr; + + VkDescriptorPool rdTextureDescriptorPool = VK_NULL_HANDLE; + VkDescriptorSetLayout rdTextureDescriptorLayout = VK_NULL_HANDLE; + VkDescriptorSet rdTextureDescriptorSet = VK_NULL_HANDLE; + + VkBuffer rdUboBuffer = VK_NULL_HANDLE; + VmaAllocation rdUboBufferAlloc = nullptr; + + VkDescriptorPool rdUBODescriptorPool = VK_NULL_HANDLE; + VkDescriptorSetLayout rdUBODescriptorLayout = VK_NULL_HANDLE; + VkDescriptorSet rdUBODescriptorSet = VK_NULL_HANDLE; + + VkDescriptorPool rdImguiDescriptorPool = VK_NULL_HANDLE; +}; \ No newline at end of file diff --git a/Ifnity/Ifnity/src/vma/vk_mem_alloc.h b/Ifnity/Ifnity/src/vma/vk_mem_alloc.h new file mode 100644 index 0000000..69bb0c1 --- /dev/null +++ b/Ifnity/Ifnity/src/vma/vk_mem_alloc.h @@ -0,0 +1,19108 @@ +// +// Copyright (c) 2017-2024 Advanced Micro Devices, Inc. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#ifndef AMD_VULKAN_MEMORY_ALLOCATOR_H +#define AMD_VULKAN_MEMORY_ALLOCATOR_H + +/** \mainpage Vulkan Memory Allocator + +Version 3.1.0 + +Copyright (c) 2017-2024 Advanced Micro Devices, Inc. All rights reserved. \n +License: MIT \n +See also: [product page on GPUOpen](https://gpuopen.com/gaming-product/vulkan-memory-allocator/), +[repository on GitHub](https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator) + + +API documentation divided into groups: [Topics](topics.html) + +General documentation chapters: + +- User guide + - \subpage quick_start + - [Project setup](@ref quick_start_project_setup) + - [Initialization](@ref quick_start_initialization) + - [Resource allocation](@ref quick_start_resource_allocation) + - \subpage choosing_memory_type + - [Usage](@ref choosing_memory_type_usage) + - [Required and preferred flags](@ref choosing_memory_type_required_preferred_flags) + - [Explicit memory types](@ref choosing_memory_type_explicit_memory_types) + - [Custom memory pools](@ref choosing_memory_type_custom_memory_pools) + - [Dedicated allocations](@ref choosing_memory_type_dedicated_allocations) + - \subpage memory_mapping + - [Copy functions](@ref memory_mapping_copy_functions) + - [Mapping functions](@ref memory_mapping_mapping_functions) + - [Persistently mapped memory](@ref memory_mapping_persistently_mapped_memory) + - [Cache flush and invalidate](@ref memory_mapping_cache_control) + - \subpage staying_within_budget + - [Querying for budget](@ref staying_within_budget_querying_for_budget) + - [Controlling memory usage](@ref staying_within_budget_controlling_memory_usage) + - \subpage resource_aliasing + - \subpage custom_memory_pools + - [Choosing memory type index](@ref custom_memory_pools_MemTypeIndex) + - [When not to use custom pools](@ref custom_memory_pools_when_not_use) + - [Linear allocation algorithm](@ref linear_algorithm) + - [Free-at-once](@ref linear_algorithm_free_at_once) + - [Stack](@ref linear_algorithm_stack) + - [Double stack](@ref linear_algorithm_double_stack) + - [Ring buffer](@ref linear_algorithm_ring_buffer) + - \subpage defragmentation + - \subpage statistics + - [Numeric statistics](@ref statistics_numeric_statistics) + - [JSON dump](@ref statistics_json_dump) + - \subpage allocation_annotation + - [Allocation user data](@ref allocation_user_data) + - [Allocation names](@ref allocation_names) + - \subpage virtual_allocator + - \subpage debugging_memory_usage + - [Memory initialization](@ref debugging_memory_usage_initialization) + - [Margins](@ref debugging_memory_usage_margins) + - [Corruption detection](@ref debugging_memory_usage_corruption_detection) + - [Leak detection features](@ref debugging_memory_usage_leak_detection) + - \subpage other_api_interop +- \subpage usage_patterns + - [GPU-only resource](@ref usage_patterns_gpu_only) + - [Staging copy for upload](@ref usage_patterns_staging_copy_upload) + - [Readback](@ref usage_patterns_readback) + - [Advanced data uploading](@ref usage_patterns_advanced_data_uploading) + - [Other use cases](@ref usage_patterns_other_use_cases) +- \subpage configuration + - [Pointers to Vulkan functions](@ref config_Vulkan_functions) + - [Custom host memory allocator](@ref custom_memory_allocator) + - [Device memory allocation callbacks](@ref allocation_callbacks) + - [Device heap memory limit](@ref heap_memory_limit) +- Extension support + - \subpage vk_khr_dedicated_allocation + - \subpage enabling_buffer_device_address + - \subpage vk_ext_memory_priority + - \subpage vk_amd_device_coherent_memory + - \subpage vk_khr_external_memory_win32 +- \subpage general_considerations + - [Thread safety](@ref general_considerations_thread_safety) + - [Versioning and compatibility](@ref general_considerations_versioning_and_compatibility) + - [Validation layer warnings](@ref general_considerations_validation_layer_warnings) + - [Allocation algorithm](@ref general_considerations_allocation_algorithm) + - [Features not supported](@ref general_considerations_features_not_supported) + +\defgroup group_init Library initialization + +\brief API elements related to the initialization and management of the entire library, especially #VmaAllocator object. + +\defgroup group_alloc Memory allocation + +\brief API elements related to the allocation, deallocation, and management of Vulkan memory, buffers, images. +Most basic ones being: vmaCreateBuffer(), vmaCreateImage(). + +\defgroup group_virtual Virtual allocator + +\brief API elements related to the mechanism of \ref virtual_allocator - using the core allocation algorithm +for user-defined purpose without allocating any real GPU memory. + +\defgroup group_stats Statistics + +\brief API elements that query current status of the allocator, from memory usage, budget, to full dump of the internal state in JSON format. +See documentation chapter: \ref statistics. +*/ + + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(VULKAN_H_) +#include +#endif + +#if !defined(VMA_VULKAN_VERSION) + #if defined(VK_VERSION_1_3) + #define VMA_VULKAN_VERSION 1003000 + #elif defined(VK_VERSION_1_2) + #define VMA_VULKAN_VERSION 1002000 + #elif defined(VK_VERSION_1_1) + #define VMA_VULKAN_VERSION 1001000 + #else + #define VMA_VULKAN_VERSION 1000000 + #endif +#endif + +#if defined(__ANDROID__) && defined(VK_NO_PROTOTYPES) && VMA_STATIC_VULKAN_FUNCTIONS + extern PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr; + extern PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr; + extern PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties; + extern PFN_vkGetPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties; + extern PFN_vkAllocateMemory vkAllocateMemory; + extern PFN_vkFreeMemory vkFreeMemory; + extern PFN_vkMapMemory vkMapMemory; + extern PFN_vkUnmapMemory vkUnmapMemory; + extern PFN_vkFlushMappedMemoryRanges vkFlushMappedMemoryRanges; + extern PFN_vkInvalidateMappedMemoryRanges vkInvalidateMappedMemoryRanges; + extern PFN_vkBindBufferMemory vkBindBufferMemory; + extern PFN_vkBindImageMemory vkBindImageMemory; + extern PFN_vkGetBufferMemoryRequirements vkGetBufferMemoryRequirements; + extern PFN_vkGetImageMemoryRequirements vkGetImageMemoryRequirements; + extern PFN_vkCreateBuffer vkCreateBuffer; + extern PFN_vkDestroyBuffer vkDestroyBuffer; + extern PFN_vkCreateImage vkCreateImage; + extern PFN_vkDestroyImage vkDestroyImage; + extern PFN_vkCmdCopyBuffer vkCmdCopyBuffer; + #if VMA_VULKAN_VERSION >= 1001000 + extern PFN_vkGetBufferMemoryRequirements2 vkGetBufferMemoryRequirements2; + extern PFN_vkGetImageMemoryRequirements2 vkGetImageMemoryRequirements2; + extern PFN_vkBindBufferMemory2 vkBindBufferMemory2; + extern PFN_vkBindImageMemory2 vkBindImageMemory2; + extern PFN_vkGetPhysicalDeviceMemoryProperties2 vkGetPhysicalDeviceMemoryProperties2; + #endif // #if VMA_VULKAN_VERSION >= 1001000 +#endif // #if defined(__ANDROID__) && VMA_STATIC_VULKAN_FUNCTIONS && VK_NO_PROTOTYPES + +#if !defined(VMA_DEDICATED_ALLOCATION) + #if VK_KHR_get_memory_requirements2 && VK_KHR_dedicated_allocation + #define VMA_DEDICATED_ALLOCATION 1 + #else + #define VMA_DEDICATED_ALLOCATION 0 + #endif +#endif + +#if !defined(VMA_BIND_MEMORY2) + #if VK_KHR_bind_memory2 + #define VMA_BIND_MEMORY2 1 + #else + #define VMA_BIND_MEMORY2 0 + #endif +#endif + +#if !defined(VMA_MEMORY_BUDGET) + #if VK_EXT_memory_budget && (VK_KHR_get_physical_device_properties2 || VMA_VULKAN_VERSION >= 1001000) + #define VMA_MEMORY_BUDGET 1 + #else + #define VMA_MEMORY_BUDGET 0 + #endif +#endif + +// Defined to 1 when VK_KHR_buffer_device_address device extension or equivalent core Vulkan 1.2 feature is defined in its headers. +#if !defined(VMA_BUFFER_DEVICE_ADDRESS) + #if VK_KHR_buffer_device_address || VMA_VULKAN_VERSION >= 1002000 + #define VMA_BUFFER_DEVICE_ADDRESS 1 + #else + #define VMA_BUFFER_DEVICE_ADDRESS 0 + #endif +#endif + +// Defined to 1 when VK_EXT_memory_priority device extension is defined in Vulkan headers. +#if !defined(VMA_MEMORY_PRIORITY) + #if VK_EXT_memory_priority + #define VMA_MEMORY_PRIORITY 1 + #else + #define VMA_MEMORY_PRIORITY 0 + #endif +#endif + +// Defined to 1 when VK_KHR_maintenance4 device extension is defined in Vulkan headers. +#if !defined(VMA_KHR_MAINTENANCE4) + #if VK_KHR_maintenance4 + #define VMA_KHR_MAINTENANCE4 1 + #else + #define VMA_KHR_MAINTENANCE4 0 + #endif +#endif + +// Defined to 1 when VK_KHR_maintenance5 device extension is defined in Vulkan headers. +#if !defined(VMA_KHR_MAINTENANCE5) + #if VK_KHR_maintenance5 + #define VMA_KHR_MAINTENANCE5 1 + #else + #define VMA_KHR_MAINTENANCE5 0 + #endif +#endif + + +// Defined to 1 when VK_KHR_external_memory device extension is defined in Vulkan headers. +#if !defined(VMA_EXTERNAL_MEMORY) + #if VK_KHR_external_memory + #define VMA_EXTERNAL_MEMORY 1 + #else + #define VMA_EXTERNAL_MEMORY 0 + #endif +#endif + +// Defined to 1 when VK_KHR_external_memory_win32 device extension is defined in Vulkan headers. +#if !defined(VMA_EXTERNAL_MEMORY_WIN32) + #if VK_KHR_external_memory_win32 + #define VMA_EXTERNAL_MEMORY_WIN32 1 + #else + #define VMA_EXTERNAL_MEMORY_WIN32 0 + #endif +#endif + +// Define these macros to decorate all public functions with additional code, +// before and after returned type, appropriately. This may be useful for +// exporting the functions when compiling VMA as a separate library. Example: +// #define VMA_CALL_PRE __declspec(dllexport) +// #define VMA_CALL_POST __cdecl +#ifndef VMA_CALL_PRE + #define VMA_CALL_PRE +#endif +#ifndef VMA_CALL_POST + #define VMA_CALL_POST +#endif + +// Define this macro to decorate pNext pointers with an attribute specifying the Vulkan +// structure that will be extended via the pNext chain. +#ifndef VMA_EXTENDS_VK_STRUCT + #define VMA_EXTENDS_VK_STRUCT(vkStruct) +#endif + +// Define this macro to decorate pointers with an attribute specifying the +// length of the array they point to if they are not null. +// +// The length may be one of +// - The name of another parameter in the argument list where the pointer is declared +// - The name of another member in the struct where the pointer is declared +// - The name of a member of a struct type, meaning the value of that member in +// the context of the call. For example +// VMA_LEN_IF_NOT_NULL("VkPhysicalDeviceMemoryProperties::memoryHeapCount"), +// this means the number of memory heaps available in the device associated +// with the VmaAllocator being dealt with. +#ifndef VMA_LEN_IF_NOT_NULL + #define VMA_LEN_IF_NOT_NULL(len) +#endif + +// The VMA_NULLABLE macro is defined to be _Nullable when compiling with Clang. +// see: https://clang.llvm.org/docs/AttributeReference.html#nullable +#ifndef VMA_NULLABLE + #ifdef __clang__ + #define VMA_NULLABLE _Nullable + #else + #define VMA_NULLABLE + #endif +#endif + +// The VMA_NOT_NULL macro is defined to be _Nonnull when compiling with Clang. +// see: https://clang.llvm.org/docs/AttributeReference.html#nonnull +#ifndef VMA_NOT_NULL + #ifdef __clang__ + #define VMA_NOT_NULL _Nonnull + #else + #define VMA_NOT_NULL + #endif +#endif + +// If non-dispatchable handles are represented as pointers then we can give +// then nullability annotations +#ifndef VMA_NOT_NULL_NON_DISPATCHABLE + #if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__) ) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__) + #define VMA_NOT_NULL_NON_DISPATCHABLE VMA_NOT_NULL + #else + #define VMA_NOT_NULL_NON_DISPATCHABLE + #endif +#endif + +#ifndef VMA_NULLABLE_NON_DISPATCHABLE + #if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__) ) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__) + #define VMA_NULLABLE_NON_DISPATCHABLE VMA_NULLABLE + #else + #define VMA_NULLABLE_NON_DISPATCHABLE + #endif +#endif + +#ifndef VMA_STATS_STRING_ENABLED + #define VMA_STATS_STRING_ENABLED 1 +#endif + +//////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// +// +// INTERFACE +// +//////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// + +// Sections for managing code placement in file, only for development purposes e.g. for convenient folding inside an IDE. +#ifndef _VMA_ENUM_DECLARATIONS + +/** +\addtogroup group_init +@{ +*/ + +/// Flags for created #VmaAllocator. +typedef enum VmaAllocatorCreateFlagBits +{ + /** \brief Allocator and all objects created from it will not be synchronized internally, so you must guarantee they are used from only one thread at a time or synchronized externally by you. + + Using this flag may increase performance because internal mutexes are not used. + */ + VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT = 0x00000001, + /** \brief Enables usage of VK_KHR_dedicated_allocation extension. + + The flag works only if VmaAllocatorCreateInfo::vulkanApiVersion `== VK_API_VERSION_1_0`. + When it is `VK_API_VERSION_1_1`, the flag is ignored because the extension has been promoted to Vulkan 1.1. + + Using this extension will automatically allocate dedicated blocks of memory for + some buffers and images instead of suballocating place for them out of bigger + memory blocks (as if you explicitly used #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT + flag) when it is recommended by the driver. It may improve performance on some + GPUs. + + You may set this flag only if you found out that following device extensions are + supported, you enabled them while creating Vulkan device passed as + VmaAllocatorCreateInfo::device, and you want them to be used internally by this + library: + + - VK_KHR_get_memory_requirements2 (device extension) + - VK_KHR_dedicated_allocation (device extension) + + When this flag is set, you can experience following warnings reported by Vulkan + validation layer. You can ignore them. + + > vkBindBufferMemory(): Binding memory to buffer 0x2d but vkGetBufferMemoryRequirements() has not been called on that buffer. + */ + VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT = 0x00000002, + /** + Enables usage of VK_KHR_bind_memory2 extension. + + The flag works only if VmaAllocatorCreateInfo::vulkanApiVersion `== VK_API_VERSION_1_0`. + When it is `VK_API_VERSION_1_1`, the flag is ignored because the extension has been promoted to Vulkan 1.1. + + You may set this flag only if you found out that this device extension is supported, + you enabled it while creating Vulkan device passed as VmaAllocatorCreateInfo::device, + and you want it to be used internally by this library. + + The extension provides functions `vkBindBufferMemory2KHR` and `vkBindImageMemory2KHR`, + which allow to pass a chain of `pNext` structures while binding. + This flag is required if you use `pNext` parameter in vmaBindBufferMemory2() or vmaBindImageMemory2(). + */ + VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT = 0x00000004, + /** + Enables usage of VK_EXT_memory_budget extension. + + You may set this flag only if you found out that this device extension is supported, + you enabled it while creating Vulkan device passed as VmaAllocatorCreateInfo::device, + and you want it to be used internally by this library, along with another instance extension + VK_KHR_get_physical_device_properties2, which is required by it (or Vulkan 1.1, where this extension is promoted). + + The extension provides query for current memory usage and budget, which will probably + be more accurate than an estimation used by the library otherwise. + */ + VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT = 0x00000008, + /** + Enables usage of VK_AMD_device_coherent_memory extension. + + You may set this flag only if you: + + - found out that this device extension is supported and enabled it while creating Vulkan device passed as VmaAllocatorCreateInfo::device, + - checked that `VkPhysicalDeviceCoherentMemoryFeaturesAMD::deviceCoherentMemory` is true and set it while creating the Vulkan device, + - want it to be used internally by this library. + + The extension and accompanying device feature provide access to memory types with + `VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD` and `VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD` flags. + They are useful mostly for writing breadcrumb markers - a common method for debugging GPU crash/hang/TDR. + + When the extension is not enabled, such memory types are still enumerated, but their usage is illegal. + To protect from this error, if you don't create the allocator with this flag, it will refuse to allocate any memory or create a custom pool in such memory type, + returning `VK_ERROR_FEATURE_NOT_PRESENT`. + */ + VMA_ALLOCATOR_CREATE_AMD_DEVICE_COHERENT_MEMORY_BIT = 0x00000010, + /** + Enables usage of "buffer device address" feature, which allows you to use function + `vkGetBufferDeviceAddress*` to get raw GPU pointer to a buffer and pass it for usage inside a shader. + + You may set this flag only if you: + + 1. (For Vulkan version < 1.2) Found as available and enabled device extension + VK_KHR_buffer_device_address. + This extension is promoted to core Vulkan 1.2. + 2. Found as available and enabled device feature `VkPhysicalDeviceBufferDeviceAddressFeatures::bufferDeviceAddress`. + + When this flag is set, you can create buffers with `VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT` using VMA. + The library automatically adds `VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT` to + allocated memory blocks wherever it might be needed. + + For more information, see documentation chapter \ref enabling_buffer_device_address. + */ + VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT = 0x00000020, + /** + Enables usage of VK_EXT_memory_priority extension in the library. + + You may set this flag only if you found available and enabled this device extension, + along with `VkPhysicalDeviceMemoryPriorityFeaturesEXT::memoryPriority == VK_TRUE`, + while creating Vulkan device passed as VmaAllocatorCreateInfo::device. + + When this flag is used, VmaAllocationCreateInfo::priority and VmaPoolCreateInfo::priority + are used to set priorities of allocated Vulkan memory. Without it, these variables are ignored. + + A priority must be a floating-point value between 0 and 1, indicating the priority of the allocation relative to other memory allocations. + Larger values are higher priority. The granularity of the priorities is implementation-dependent. + It is automatically passed to every call to `vkAllocateMemory` done by the library using structure `VkMemoryPriorityAllocateInfoEXT`. + The value to be used for default priority is 0.5. + For more details, see the documentation of the VK_EXT_memory_priority extension. + */ + VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT = 0x00000040, + /** + Enables usage of VK_KHR_maintenance4 extension in the library. + + You may set this flag only if you found available and enabled this device extension, + while creating Vulkan device passed as VmaAllocatorCreateInfo::device. + */ + VMA_ALLOCATOR_CREATE_KHR_MAINTENANCE4_BIT = 0x00000080, + /** + Enables usage of VK_KHR_maintenance5 extension in the library. + + You should set this flag if you found available and enabled this device extension, + while creating Vulkan device passed as VmaAllocatorCreateInfo::device. + */ + VMA_ALLOCATOR_CREATE_KHR_MAINTENANCE5_BIT = 0x00000100, + + /** + Enables usage of VK_KHR_external_memory_win32 extension in the library. + + You should set this flag if you found available and enabled this device extension, + while creating Vulkan device passed as VmaAllocatorCreateInfo::device. + For more information, see \ref vk_khr_external_memory_win32. + */ + VMA_ALLOCATOR_CREATE_KHR_EXTERNAL_MEMORY_WIN32_BIT = 0x00000200, + + VMA_ALLOCATOR_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF +} VmaAllocatorCreateFlagBits; +/// See #VmaAllocatorCreateFlagBits. +typedef VkFlags VmaAllocatorCreateFlags; + +/** @} */ + +/** +\addtogroup group_alloc +@{ +*/ + +/// \brief Intended usage of the allocated memory. +typedef enum VmaMemoryUsage +{ + /** No intended memory usage specified. + Use other members of VmaAllocationCreateInfo to specify your requirements. + */ + VMA_MEMORY_USAGE_UNKNOWN = 0, + /** + \deprecated Obsolete, preserved for backward compatibility. + Prefers `VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT`. + */ + VMA_MEMORY_USAGE_GPU_ONLY = 1, + /** + \deprecated Obsolete, preserved for backward compatibility. + Guarantees `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` and `VK_MEMORY_PROPERTY_HOST_COHERENT_BIT`. + */ + VMA_MEMORY_USAGE_CPU_ONLY = 2, + /** + \deprecated Obsolete, preserved for backward compatibility. + Guarantees `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT`, prefers `VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT`. + */ + VMA_MEMORY_USAGE_CPU_TO_GPU = 3, + /** + \deprecated Obsolete, preserved for backward compatibility. + Guarantees `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT`, prefers `VK_MEMORY_PROPERTY_HOST_CACHED_BIT`. + */ + VMA_MEMORY_USAGE_GPU_TO_CPU = 4, + /** + \deprecated Obsolete, preserved for backward compatibility. + Prefers not `VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT`. + */ + VMA_MEMORY_USAGE_CPU_COPY = 5, + /** + Lazily allocated GPU memory having `VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT`. + Exists mostly on mobile platforms. Using it on desktop PC or other GPUs with no such memory type present will fail the allocation. + + Usage: Memory for transient attachment images (color attachments, depth attachments etc.), created with `VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT`. + + Allocations with this usage are always created as dedicated - it implies #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT. + */ + VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED = 6, + /** + Selects best memory type automatically. + This flag is recommended for most common use cases. + + When using this flag, if you want to map the allocation (using vmaMapMemory() or #VMA_ALLOCATION_CREATE_MAPPED_BIT), + you must pass one of the flags: #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT + in VmaAllocationCreateInfo::flags. + + It can be used only with functions that let the library know `VkBufferCreateInfo` or `VkImageCreateInfo`, e.g. + vmaCreateBuffer(), vmaCreateImage(), vmaFindMemoryTypeIndexForBufferInfo(), vmaFindMemoryTypeIndexForImageInfo() + and not with generic memory allocation functions. + */ + VMA_MEMORY_USAGE_AUTO = 7, + /** + Selects best memory type automatically with preference for GPU (device) memory. + + When using this flag, if you want to map the allocation (using vmaMapMemory() or #VMA_ALLOCATION_CREATE_MAPPED_BIT), + you must pass one of the flags: #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT + in VmaAllocationCreateInfo::flags. + + It can be used only with functions that let the library know `VkBufferCreateInfo` or `VkImageCreateInfo`, e.g. + vmaCreateBuffer(), vmaCreateImage(), vmaFindMemoryTypeIndexForBufferInfo(), vmaFindMemoryTypeIndexForImageInfo() + and not with generic memory allocation functions. + */ + VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE = 8, + /** + Selects best memory type automatically with preference for CPU (host) memory. + + When using this flag, if you want to map the allocation (using vmaMapMemory() or #VMA_ALLOCATION_CREATE_MAPPED_BIT), + you must pass one of the flags: #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT + in VmaAllocationCreateInfo::flags. + + It can be used only with functions that let the library know `VkBufferCreateInfo` or `VkImageCreateInfo`, e.g. + vmaCreateBuffer(), vmaCreateImage(), vmaFindMemoryTypeIndexForBufferInfo(), vmaFindMemoryTypeIndexForImageInfo() + and not with generic memory allocation functions. + */ + VMA_MEMORY_USAGE_AUTO_PREFER_HOST = 9, + + VMA_MEMORY_USAGE_MAX_ENUM = 0x7FFFFFFF +} VmaMemoryUsage; + +/// Flags to be passed as VmaAllocationCreateInfo::flags. +typedef enum VmaAllocationCreateFlagBits +{ + /** \brief Set this flag if the allocation should have its own memory block. + + Use it for special, big resources, like fullscreen images used as attachments. + + If you use this flag while creating a buffer or an image, `VkMemoryDedicatedAllocateInfo` + structure is applied if possible. + */ + VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT = 0x00000001, + + /** \brief Set this flag to only try to allocate from existing `VkDeviceMemory` blocks and never create new such block. + + If new allocation cannot be placed in any of the existing blocks, allocation + fails with `VK_ERROR_OUT_OF_DEVICE_MEMORY` error. + + You should not use #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT and + #VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT at the same time. It makes no sense. + */ + VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT = 0x00000002, + /** \brief Set this flag to use a memory that will be persistently mapped and retrieve pointer to it. + + Pointer to mapped memory will be returned through VmaAllocationInfo::pMappedData. + + It is valid to use this flag for allocation made from memory type that is not + `HOST_VISIBLE`. This flag is then ignored and memory is not mapped. This is + useful if you need an allocation that is efficient to use on GPU + (`DEVICE_LOCAL`) and still want to map it directly if possible on platforms that + support it (e.g. Intel GPU). + */ + VMA_ALLOCATION_CREATE_MAPPED_BIT = 0x00000004, + /** \deprecated Preserved for backward compatibility. Consider using vmaSetAllocationName() instead. + + Set this flag to treat VmaAllocationCreateInfo::pUserData as pointer to a + null-terminated string. Instead of copying pointer value, a local copy of the + string is made and stored in allocation's `pName`. The string is automatically + freed together with the allocation. It is also used in vmaBuildStatsString(). + */ + VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT = 0x00000020, + /** Allocation will be created from upper stack in a double stack pool. + + This flag is only allowed for custom pools created with #VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT flag. + */ + VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT = 0x00000040, + /** Create both buffer/image and allocation, but don't bind them together. + It is useful when you want to bind yourself to do some more advanced binding, e.g. using some extensions. + The flag is meaningful only with functions that bind by default: vmaCreateBuffer(), vmaCreateImage(). + Otherwise it is ignored. + + If you want to make sure the new buffer/image is not tied to the new memory allocation + through `VkMemoryDedicatedAllocateInfoKHR` structure in case the allocation ends up in its own memory block, + use also flag #VMA_ALLOCATION_CREATE_CAN_ALIAS_BIT. + */ + VMA_ALLOCATION_CREATE_DONT_BIND_BIT = 0x00000080, + /** Create allocation only if additional device memory required for it, if any, won't exceed + memory budget. Otherwise return `VK_ERROR_OUT_OF_DEVICE_MEMORY`. + */ + VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT = 0x00000100, + /** \brief Set this flag if the allocated memory will have aliasing resources. + + Usage of this flag prevents supplying `VkMemoryDedicatedAllocateInfoKHR` when #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT is specified. + Otherwise created dedicated memory will not be suitable for aliasing resources, resulting in Vulkan Validation Layer errors. + */ + VMA_ALLOCATION_CREATE_CAN_ALIAS_BIT = 0x00000200, + /** + Requests possibility to map the allocation (using vmaMapMemory() or #VMA_ALLOCATION_CREATE_MAPPED_BIT). + + - If you use #VMA_MEMORY_USAGE_AUTO or other `VMA_MEMORY_USAGE_AUTO*` value, + you must use this flag to be able to map the allocation. Otherwise, mapping is incorrect. + - If you use other value of #VmaMemoryUsage, this flag is ignored and mapping is always possible in memory types that are `HOST_VISIBLE`. + This includes allocations created in \ref custom_memory_pools. + + Declares that mapped memory will only be written sequentially, e.g. using `memcpy()` or a loop writing number-by-number, + never read or accessed randomly, so a memory type can be selected that is uncached and write-combined. + + \warning Violating this declaration may work correctly, but will likely be very slow. + Watch out for implicit reads introduced by doing e.g. `pMappedData[i] += x;` + Better prepare your data in a local variable and `memcpy()` it to the mapped pointer all at once. + */ + VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT = 0x00000400, + /** + Requests possibility to map the allocation (using vmaMapMemory() or #VMA_ALLOCATION_CREATE_MAPPED_BIT). + + - If you use #VMA_MEMORY_USAGE_AUTO or other `VMA_MEMORY_USAGE_AUTO*` value, + you must use this flag to be able to map the allocation. Otherwise, mapping is incorrect. + - If you use other value of #VmaMemoryUsage, this flag is ignored and mapping is always possible in memory types that are `HOST_VISIBLE`. + This includes allocations created in \ref custom_memory_pools. + + Declares that mapped memory can be read, written, and accessed in random order, + so a `HOST_CACHED` memory type is preferred. + */ + VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT = 0x00000800, + /** + Together with #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT, + it says that despite request for host access, a not-`HOST_VISIBLE` memory type can be selected + if it may improve performance. + + By using this flag, you declare that you will check if the allocation ended up in a `HOST_VISIBLE` memory type + (e.g. using vmaGetAllocationMemoryProperties()) and if not, you will create some "staging" buffer and + issue an explicit transfer to write/read your data. + To prepare for this possibility, don't forget to add appropriate flags like + `VK_BUFFER_USAGE_TRANSFER_DST_BIT`, `VK_BUFFER_USAGE_TRANSFER_SRC_BIT` to the parameters of created buffer or image. + */ + VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT = 0x00001000, + /** Allocation strategy that chooses smallest possible free range for the allocation + to minimize memory usage and fragmentation, possibly at the expense of allocation time. + */ + VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT = 0x00010000, + /** Allocation strategy that chooses first suitable free range for the allocation - + not necessarily in terms of the smallest offset but the one that is easiest and fastest to find + to minimize allocation time, possibly at the expense of allocation quality. + */ + VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT = 0x00020000, + /** Allocation strategy that chooses always the lowest offset in available space. + This is not the most efficient strategy but achieves highly packed data. + Used internally by defragmentation, not recommended in typical usage. + */ + VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT = 0x00040000, + /** Alias to #VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT. + */ + VMA_ALLOCATION_CREATE_STRATEGY_BEST_FIT_BIT = VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT, + /** Alias to #VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT. + */ + VMA_ALLOCATION_CREATE_STRATEGY_FIRST_FIT_BIT = VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT, + /** A bit mask to extract only `STRATEGY` bits from entire set of flags. + */ + VMA_ALLOCATION_CREATE_STRATEGY_MASK = + VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT | + VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT | + VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT, + + VMA_ALLOCATION_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF +} VmaAllocationCreateFlagBits; +/// See #VmaAllocationCreateFlagBits. +typedef VkFlags VmaAllocationCreateFlags; + +/// Flags to be passed as VmaPoolCreateInfo::flags. +typedef enum VmaPoolCreateFlagBits +{ + /** \brief Use this flag if you always allocate only buffers and linear images or only optimal images out of this pool and so Buffer-Image Granularity can be ignored. + + This is an optional optimization flag. + + If you always allocate using vmaCreateBuffer(), vmaCreateImage(), + vmaAllocateMemoryForBuffer(), then you don't need to use it because allocator + knows exact type of your allocations so it can handle Buffer-Image Granularity + in the optimal way. + + If you also allocate using vmaAllocateMemoryForImage() or vmaAllocateMemory(), + exact type of such allocations is not known, so allocator must be conservative + in handling Buffer-Image Granularity, which can lead to suboptimal allocation + (wasted memory). In that case, if you can make sure you always allocate only + buffers and linear images or only optimal images out of this pool, use this flag + to make allocator disregard Buffer-Image Granularity and so make allocations + faster and more optimal. + */ + VMA_POOL_CREATE_IGNORE_BUFFER_IMAGE_GRANULARITY_BIT = 0x00000002, + + /** \brief Enables alternative, linear allocation algorithm in this pool. + + Specify this flag to enable linear allocation algorithm, which always creates + new allocations after last one and doesn't reuse space from allocations freed in + between. It trades memory consumption for simplified algorithm and data + structure, which has better performance and uses less memory for metadata. + + By using this flag, you can achieve behavior of free-at-once, stack, + ring buffer, and double stack. + For details, see documentation chapter \ref linear_algorithm. + */ + VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT = 0x00000004, + + /** Bit mask to extract only `ALGORITHM` bits from entire set of flags. + */ + VMA_POOL_CREATE_ALGORITHM_MASK = + VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT, + + VMA_POOL_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF +} VmaPoolCreateFlagBits; +/// Flags to be passed as VmaPoolCreateInfo::flags. See #VmaPoolCreateFlagBits. +typedef VkFlags VmaPoolCreateFlags; + +/// Flags to be passed as VmaDefragmentationInfo::flags. +typedef enum VmaDefragmentationFlagBits +{ + /* \brief Use simple but fast algorithm for defragmentation. + May not achieve best results but will require least time to compute and least allocations to copy. + */ + VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FAST_BIT = 0x1, + /* \brief Default defragmentation algorithm, applied also when no `ALGORITHM` flag is specified. + Offers a balance between defragmentation quality and the amount of allocations and bytes that need to be moved. + */ + VMA_DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED_BIT = 0x2, + /* \brief Perform full defragmentation of memory. + Can result in notably more time to compute and allocations to copy, but will achieve best memory packing. + */ + VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FULL_BIT = 0x4, + /** \brief Use the most roboust algorithm at the cost of time to compute and number of copies to make. + Only available when bufferImageGranularity is greater than 1, since it aims to reduce + alignment issues between different types of resources. + Otherwise falls back to same behavior as #VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FULL_BIT. + */ + VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT = 0x8, + + /// A bit mask to extract only `ALGORITHM` bits from entire set of flags. + VMA_DEFRAGMENTATION_FLAG_ALGORITHM_MASK = + VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FAST_BIT | + VMA_DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED_BIT | + VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FULL_BIT | + VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT, + + VMA_DEFRAGMENTATION_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF +} VmaDefragmentationFlagBits; +/// See #VmaDefragmentationFlagBits. +typedef VkFlags VmaDefragmentationFlags; + +/// Operation performed on single defragmentation move. See structure #VmaDefragmentationMove. +typedef enum VmaDefragmentationMoveOperation +{ + /// Buffer/image has been recreated at `dstTmpAllocation`, data has been copied, old buffer/image has been destroyed. `srcAllocation` should be changed to point to the new place. This is the default value set by vmaBeginDefragmentationPass(). + VMA_DEFRAGMENTATION_MOVE_OPERATION_COPY = 0, + /// Set this value if you cannot move the allocation. New place reserved at `dstTmpAllocation` will be freed. `srcAllocation` will remain unchanged. + VMA_DEFRAGMENTATION_MOVE_OPERATION_IGNORE = 1, + /// Set this value if you decide to abandon the allocation and you destroyed the buffer/image. New place reserved at `dstTmpAllocation` will be freed, along with `srcAllocation`, which will be destroyed. + VMA_DEFRAGMENTATION_MOVE_OPERATION_DESTROY = 2, +} VmaDefragmentationMoveOperation; + +/** @} */ + +/** +\addtogroup group_virtual +@{ +*/ + +/// Flags to be passed as VmaVirtualBlockCreateInfo::flags. +typedef enum VmaVirtualBlockCreateFlagBits +{ + /** \brief Enables alternative, linear allocation algorithm in this virtual block. + + Specify this flag to enable linear allocation algorithm, which always creates + new allocations after last one and doesn't reuse space from allocations freed in + between. It trades memory consumption for simplified algorithm and data + structure, which has better performance and uses less memory for metadata. + + By using this flag, you can achieve behavior of free-at-once, stack, + ring buffer, and double stack. + For details, see documentation chapter \ref linear_algorithm. + */ + VMA_VIRTUAL_BLOCK_CREATE_LINEAR_ALGORITHM_BIT = 0x00000001, + + /** \brief Bit mask to extract only `ALGORITHM` bits from entire set of flags. + */ + VMA_VIRTUAL_BLOCK_CREATE_ALGORITHM_MASK = + VMA_VIRTUAL_BLOCK_CREATE_LINEAR_ALGORITHM_BIT, + + VMA_VIRTUAL_BLOCK_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF +} VmaVirtualBlockCreateFlagBits; +/// Flags to be passed as VmaVirtualBlockCreateInfo::flags. See #VmaVirtualBlockCreateFlagBits. +typedef VkFlags VmaVirtualBlockCreateFlags; + +/// Flags to be passed as VmaVirtualAllocationCreateInfo::flags. +typedef enum VmaVirtualAllocationCreateFlagBits +{ + /** \brief Allocation will be created from upper stack in a double stack pool. + + This flag is only allowed for virtual blocks created with #VMA_VIRTUAL_BLOCK_CREATE_LINEAR_ALGORITHM_BIT flag. + */ + VMA_VIRTUAL_ALLOCATION_CREATE_UPPER_ADDRESS_BIT = VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT, + /** \brief Allocation strategy that tries to minimize memory usage. + */ + VMA_VIRTUAL_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT = VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT, + /** \brief Allocation strategy that tries to minimize allocation time. + */ + VMA_VIRTUAL_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT = VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT, + /** Allocation strategy that chooses always the lowest offset in available space. + This is not the most efficient strategy but achieves highly packed data. + */ + VMA_VIRTUAL_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT = VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT, + /** \brief A bit mask to extract only `STRATEGY` bits from entire set of flags. + + These strategy flags are binary compatible with equivalent flags in #VmaAllocationCreateFlagBits. + */ + VMA_VIRTUAL_ALLOCATION_CREATE_STRATEGY_MASK = VMA_ALLOCATION_CREATE_STRATEGY_MASK, + + VMA_VIRTUAL_ALLOCATION_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF +} VmaVirtualAllocationCreateFlagBits; +/// Flags to be passed as VmaVirtualAllocationCreateInfo::flags. See #VmaVirtualAllocationCreateFlagBits. +typedef VkFlags VmaVirtualAllocationCreateFlags; + +/** @} */ + +#endif // _VMA_ENUM_DECLARATIONS + +#ifndef _VMA_DATA_TYPES_DECLARATIONS + +/** +\addtogroup group_init +@{ */ + +/** \struct VmaAllocator +\brief Represents main object of this library initialized. + +Fill structure #VmaAllocatorCreateInfo and call function vmaCreateAllocator() to create it. +Call function vmaDestroyAllocator() to destroy it. + +It is recommended to create just one object of this type per `VkDevice` object, +right after Vulkan is initialized and keep it alive until before Vulkan device is destroyed. +*/ +VK_DEFINE_HANDLE(VmaAllocator) + +/** @} */ + +/** +\addtogroup group_alloc +@{ +*/ + +/** \struct VmaPool +\brief Represents custom memory pool + +Fill structure VmaPoolCreateInfo and call function vmaCreatePool() to create it. +Call function vmaDestroyPool() to destroy it. + +For more information see [Custom memory pools](@ref choosing_memory_type_custom_memory_pools). +*/ +VK_DEFINE_HANDLE(VmaPool) + +/** \struct VmaAllocation +\brief Represents single memory allocation. + +It may be either dedicated block of `VkDeviceMemory` or a specific region of a bigger block of this type +plus unique offset. + +There are multiple ways to create such object. +You need to fill structure VmaAllocationCreateInfo. +For more information see [Choosing memory type](@ref choosing_memory_type). + +Although the library provides convenience functions that create Vulkan buffer or image, +allocate memory for it and bind them together, +binding of the allocation to a buffer or an image is out of scope of the allocation itself. +Allocation object can exist without buffer/image bound, +binding can be done manually by the user, and destruction of it can be done +independently of destruction of the allocation. + +The object also remembers its size and some other information. +To retrieve this information, use function vmaGetAllocationInfo() and inspect +returned structure VmaAllocationInfo. +*/ +VK_DEFINE_HANDLE(VmaAllocation) + +/** \struct VmaDefragmentationContext +\brief An opaque object that represents started defragmentation process. + +Fill structure #VmaDefragmentationInfo and call function vmaBeginDefragmentation() to create it. +Call function vmaEndDefragmentation() to destroy it. +*/ +VK_DEFINE_HANDLE(VmaDefragmentationContext) + +/** @} */ + +/** +\addtogroup group_virtual +@{ +*/ + +/** \struct VmaVirtualAllocation +\brief Represents single memory allocation done inside VmaVirtualBlock. + +Use it as a unique identifier to virtual allocation within the single block. + +Use value `VK_NULL_HANDLE` to represent a null/invalid allocation. +*/ +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VmaVirtualAllocation) + +/** @} */ + +/** +\addtogroup group_virtual +@{ +*/ + +/** \struct VmaVirtualBlock +\brief Handle to a virtual block object that allows to use core allocation algorithm without allocating any real GPU memory. + +Fill in #VmaVirtualBlockCreateInfo structure and use vmaCreateVirtualBlock() to create it. Use vmaDestroyVirtualBlock() to destroy it. +For more information, see documentation chapter \ref virtual_allocator. + +This object is not thread-safe - should not be used from multiple threads simultaneously, must be synchronized externally. +*/ +VK_DEFINE_HANDLE(VmaVirtualBlock) + +/** @} */ + +/** +\addtogroup group_init +@{ +*/ + +/// Callback function called after successful vkAllocateMemory. +typedef void (VKAPI_PTR* PFN_vmaAllocateDeviceMemoryFunction)( + VmaAllocator VMA_NOT_NULL allocator, + uint32_t memoryType, + VkDeviceMemory VMA_NOT_NULL_NON_DISPATCHABLE memory, + VkDeviceSize size, + void* VMA_NULLABLE pUserData); + +/// Callback function called before vkFreeMemory. +typedef void (VKAPI_PTR* PFN_vmaFreeDeviceMemoryFunction)( + VmaAllocator VMA_NOT_NULL allocator, + uint32_t memoryType, + VkDeviceMemory VMA_NOT_NULL_NON_DISPATCHABLE memory, + VkDeviceSize size, + void* VMA_NULLABLE pUserData); + +/** \brief Set of callbacks that the library will call for `vkAllocateMemory` and `vkFreeMemory`. + +Provided for informative purpose, e.g. to gather statistics about number of +allocations or total amount of memory allocated in Vulkan. + +Used in VmaAllocatorCreateInfo::pDeviceMemoryCallbacks. +*/ +typedef struct VmaDeviceMemoryCallbacks +{ + /// Optional, can be null. + PFN_vmaAllocateDeviceMemoryFunction VMA_NULLABLE pfnAllocate; + /// Optional, can be null. + PFN_vmaFreeDeviceMemoryFunction VMA_NULLABLE pfnFree; + /// Optional, can be null. + void* VMA_NULLABLE pUserData; +} VmaDeviceMemoryCallbacks; + +/** \brief Pointers to some Vulkan functions - a subset used by the library. + +Used in VmaAllocatorCreateInfo::pVulkanFunctions. +*/ +typedef struct VmaVulkanFunctions +{ + /// Required when using VMA_DYNAMIC_VULKAN_FUNCTIONS. + PFN_vkGetInstanceProcAddr VMA_NULLABLE vkGetInstanceProcAddr; + /// Required when using VMA_DYNAMIC_VULKAN_FUNCTIONS. + PFN_vkGetDeviceProcAddr VMA_NULLABLE vkGetDeviceProcAddr; + PFN_vkGetPhysicalDeviceProperties VMA_NULLABLE vkGetPhysicalDeviceProperties; + PFN_vkGetPhysicalDeviceMemoryProperties VMA_NULLABLE vkGetPhysicalDeviceMemoryProperties; + PFN_vkAllocateMemory VMA_NULLABLE vkAllocateMemory; + PFN_vkFreeMemory VMA_NULLABLE vkFreeMemory; + PFN_vkMapMemory VMA_NULLABLE vkMapMemory; + PFN_vkUnmapMemory VMA_NULLABLE vkUnmapMemory; + PFN_vkFlushMappedMemoryRanges VMA_NULLABLE vkFlushMappedMemoryRanges; + PFN_vkInvalidateMappedMemoryRanges VMA_NULLABLE vkInvalidateMappedMemoryRanges; + PFN_vkBindBufferMemory VMA_NULLABLE vkBindBufferMemory; + PFN_vkBindImageMemory VMA_NULLABLE vkBindImageMemory; + PFN_vkGetBufferMemoryRequirements VMA_NULLABLE vkGetBufferMemoryRequirements; + PFN_vkGetImageMemoryRequirements VMA_NULLABLE vkGetImageMemoryRequirements; + PFN_vkCreateBuffer VMA_NULLABLE vkCreateBuffer; + PFN_vkDestroyBuffer VMA_NULLABLE vkDestroyBuffer; + PFN_vkCreateImage VMA_NULLABLE vkCreateImage; + PFN_vkDestroyImage VMA_NULLABLE vkDestroyImage; + PFN_vkCmdCopyBuffer VMA_NULLABLE vkCmdCopyBuffer; +#if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000 + /// Fetch "vkGetBufferMemoryRequirements2" on Vulkan >= 1.1, fetch "vkGetBufferMemoryRequirements2KHR" when using VK_KHR_dedicated_allocation extension. + PFN_vkGetBufferMemoryRequirements2KHR VMA_NULLABLE vkGetBufferMemoryRequirements2KHR; + /// Fetch "vkGetImageMemoryRequirements2" on Vulkan >= 1.1, fetch "vkGetImageMemoryRequirements2KHR" when using VK_KHR_dedicated_allocation extension. + PFN_vkGetImageMemoryRequirements2KHR VMA_NULLABLE vkGetImageMemoryRequirements2KHR; +#endif +#if VMA_BIND_MEMORY2 || VMA_VULKAN_VERSION >= 1001000 + /// Fetch "vkBindBufferMemory2" on Vulkan >= 1.1, fetch "vkBindBufferMemory2KHR" when using VK_KHR_bind_memory2 extension. + PFN_vkBindBufferMemory2KHR VMA_NULLABLE vkBindBufferMemory2KHR; + /// Fetch "vkBindImageMemory2" on Vulkan >= 1.1, fetch "vkBindImageMemory2KHR" when using VK_KHR_bind_memory2 extension. + PFN_vkBindImageMemory2KHR VMA_NULLABLE vkBindImageMemory2KHR; +#endif +#if VMA_MEMORY_BUDGET || VMA_VULKAN_VERSION >= 1001000 + /// Fetch from "vkGetPhysicalDeviceMemoryProperties2" on Vulkan >= 1.1, but you can also fetch it from "vkGetPhysicalDeviceMemoryProperties2KHR" if you enabled extension VK_KHR_get_physical_device_properties2. + PFN_vkGetPhysicalDeviceMemoryProperties2KHR VMA_NULLABLE vkGetPhysicalDeviceMemoryProperties2KHR; +#endif +#if VMA_KHR_MAINTENANCE4 || VMA_VULKAN_VERSION >= 1003000 + /// Fetch from "vkGetDeviceBufferMemoryRequirements" on Vulkan >= 1.3, but you can also fetch it from "vkGetDeviceBufferMemoryRequirementsKHR" if you enabled extension VK_KHR_maintenance4. + PFN_vkGetDeviceBufferMemoryRequirementsKHR VMA_NULLABLE vkGetDeviceBufferMemoryRequirements; + /// Fetch from "vkGetDeviceImageMemoryRequirements" on Vulkan >= 1.3, but you can also fetch it from "vkGetDeviceImageMemoryRequirementsKHR" if you enabled extension VK_KHR_maintenance4. + PFN_vkGetDeviceImageMemoryRequirementsKHR VMA_NULLABLE vkGetDeviceImageMemoryRequirements; +#endif +#if VMA_EXTERNAL_MEMORY_WIN32 + PFN_vkGetMemoryWin32HandleKHR VMA_NULLABLE vkGetMemoryWin32HandleKHR; +#else + void* VMA_NULLABLE vkGetMemoryWin32HandleKHR; +#endif +} VmaVulkanFunctions; + +/// Description of a Allocator to be created. +typedef struct VmaAllocatorCreateInfo +{ + /// Flags for created allocator. Use #VmaAllocatorCreateFlagBits enum. + VmaAllocatorCreateFlags flags; + /// Vulkan physical device. + /** It must be valid throughout whole lifetime of created allocator. */ + VkPhysicalDevice VMA_NOT_NULL physicalDevice; + /// Vulkan device. + /** It must be valid throughout whole lifetime of created allocator. */ + VkDevice VMA_NOT_NULL device; + /// Preferred size of a single `VkDeviceMemory` block to be allocated from large heaps > 1 GiB. Optional. + /** Set to 0 to use default, which is currently 256 MiB. */ + VkDeviceSize preferredLargeHeapBlockSize; + /// Custom CPU memory allocation callbacks. Optional. + /** Optional, can be null. When specified, will also be used for all CPU-side memory allocations. */ + const VkAllocationCallbacks* VMA_NULLABLE pAllocationCallbacks; + /// Informative callbacks for `vkAllocateMemory`, `vkFreeMemory`. Optional. + /** Optional, can be null. */ + const VmaDeviceMemoryCallbacks* VMA_NULLABLE pDeviceMemoryCallbacks; + /** \brief Either null or a pointer to an array of limits on maximum number of bytes that can be allocated out of particular Vulkan memory heap. + + If not NULL, it must be a pointer to an array of + `VkPhysicalDeviceMemoryProperties::memoryHeapCount` elements, defining limit on + maximum number of bytes that can be allocated out of particular Vulkan memory + heap. + + Any of the elements may be equal to `VK_WHOLE_SIZE`, which means no limit on that + heap. This is also the default in case of `pHeapSizeLimit` = NULL. + + If there is a limit defined for a heap: + + - If user tries to allocate more memory from that heap using this allocator, + the allocation fails with `VK_ERROR_OUT_OF_DEVICE_MEMORY`. + - If the limit is smaller than heap size reported in `VkMemoryHeap::size`, the + value of this limit will be reported instead when using vmaGetMemoryProperties(). + + Warning! Using this feature may not be equivalent to installing a GPU with + smaller amount of memory, because graphics driver doesn't necessary fail new + allocations with `VK_ERROR_OUT_OF_DEVICE_MEMORY` result when memory capacity is + exceeded. It may return success and just silently migrate some device memory + blocks to system RAM. This driver behavior can also be controlled using + VK_AMD_memory_overallocation_behavior extension. + */ + const VkDeviceSize* VMA_NULLABLE VMA_LEN_IF_NOT_NULL("VkPhysicalDeviceMemoryProperties::memoryHeapCount") pHeapSizeLimit; + + /** \brief Pointers to Vulkan functions. Can be null. + + For details see [Pointers to Vulkan functions](@ref config_Vulkan_functions). + */ + const VmaVulkanFunctions* VMA_NULLABLE pVulkanFunctions; + /** \brief Handle to Vulkan instance object. + + Starting from version 3.0.0 this member is no longer optional, it must be set! + */ + VkInstance VMA_NOT_NULL instance; + /** \brief Optional. Vulkan version that the application uses. + + It must be a value in the format as created by macro `VK_MAKE_VERSION` or a constant like: `VK_API_VERSION_1_1`, `VK_API_VERSION_1_0`. + The patch version number specified is ignored. Only the major and minor versions are considered. + Only versions 1.0, 1.1, 1.2, 1.3 are supported by the current implementation. + Leaving it initialized to zero is equivalent to `VK_API_VERSION_1_0`. + It must match the Vulkan version used by the application and supported on the selected physical device, + so it must be no higher than `VkApplicationInfo::apiVersion` passed to `vkCreateInstance` + and no higher than `VkPhysicalDeviceProperties::apiVersion` found on the physical device used. + */ + uint32_t vulkanApiVersion; +#if VMA_EXTERNAL_MEMORY + /** \brief Either null or a pointer to an array of external memory handle types for each Vulkan memory type. + + If not NULL, it must be a pointer to an array of `VkPhysicalDeviceMemoryProperties::memoryTypeCount` + elements, defining external memory handle types of particular Vulkan memory type, + to be passed using `VkExportMemoryAllocateInfoKHR`. + + Any of the elements may be equal to 0, which means not to use `VkExportMemoryAllocateInfoKHR` on this memory type. + This is also the default in case of `pTypeExternalMemoryHandleTypes` = NULL. + */ + const VkExternalMemoryHandleTypeFlagsKHR* VMA_NULLABLE VMA_LEN_IF_NOT_NULL("VkPhysicalDeviceMemoryProperties::memoryTypeCount") pTypeExternalMemoryHandleTypes; +#endif // #if VMA_EXTERNAL_MEMORY +} VmaAllocatorCreateInfo; + +/// Information about existing #VmaAllocator object. +typedef struct VmaAllocatorInfo +{ + /** \brief Handle to Vulkan instance object. + + This is the same value as has been passed through VmaAllocatorCreateInfo::instance. + */ + VkInstance VMA_NOT_NULL instance; + /** \brief Handle to Vulkan physical device object. + + This is the same value as has been passed through VmaAllocatorCreateInfo::physicalDevice. + */ + VkPhysicalDevice VMA_NOT_NULL physicalDevice; + /** \brief Handle to Vulkan device object. + + This is the same value as has been passed through VmaAllocatorCreateInfo::device. + */ + VkDevice VMA_NOT_NULL device; +} VmaAllocatorInfo; + +/** @} */ + +/** +\addtogroup group_stats +@{ +*/ + +/** \brief Calculated statistics of memory usage e.g. in a specific memory type, heap, custom pool, or total. + +These are fast to calculate. +See functions: vmaGetHeapBudgets(), vmaGetPoolStatistics(). +*/ +typedef struct VmaStatistics +{ + /** \brief Number of `VkDeviceMemory` objects - Vulkan memory blocks allocated. + */ + uint32_t blockCount; + /** \brief Number of #VmaAllocation objects allocated. + + Dedicated allocations have their own blocks, so each one adds 1 to `allocationCount` as well as `blockCount`. + */ + uint32_t allocationCount; + /** \brief Number of bytes allocated in `VkDeviceMemory` blocks. + + \note To avoid confusion, please be aware that what Vulkan calls an "allocation" - a whole `VkDeviceMemory` object + (e.g. as in `VkPhysicalDeviceLimits::maxMemoryAllocationCount`) is called a "block" in VMA, while VMA calls + "allocation" a #VmaAllocation object that represents a memory region sub-allocated from such block, usually for a single buffer or image. + */ + VkDeviceSize blockBytes; + /** \brief Total number of bytes occupied by all #VmaAllocation objects. + + Always less or equal than `blockBytes`. + Difference `(blockBytes - allocationBytes)` is the amount of memory allocated from Vulkan + but unused by any #VmaAllocation. + */ + VkDeviceSize allocationBytes; +} VmaStatistics; + +/** \brief More detailed statistics than #VmaStatistics. + +These are slower to calculate. Use for debugging purposes. +See functions: vmaCalculateStatistics(), vmaCalculatePoolStatistics(). + +Previous version of the statistics API provided averages, but they have been removed +because they can be easily calculated as: + +\code +VkDeviceSize allocationSizeAvg = detailedStats.statistics.allocationBytes / detailedStats.statistics.allocationCount; +VkDeviceSize unusedBytes = detailedStats.statistics.blockBytes - detailedStats.statistics.allocationBytes; +VkDeviceSize unusedRangeSizeAvg = unusedBytes / detailedStats.unusedRangeCount; +\endcode +*/ +typedef struct VmaDetailedStatistics +{ + /// Basic statistics. + VmaStatistics statistics; + /// Number of free ranges of memory between allocations. + uint32_t unusedRangeCount; + /// Smallest allocation size. `VK_WHOLE_SIZE` if there are 0 allocations. + VkDeviceSize allocationSizeMin; + /// Largest allocation size. 0 if there are 0 allocations. + VkDeviceSize allocationSizeMax; + /// Smallest empty range size. `VK_WHOLE_SIZE` if there are 0 empty ranges. + VkDeviceSize unusedRangeSizeMin; + /// Largest empty range size. 0 if there are 0 empty ranges. + VkDeviceSize unusedRangeSizeMax; +} VmaDetailedStatistics; + +/** \brief General statistics from current state of the Allocator - +total memory usage across all memory heaps and types. + +These are slower to calculate. Use for debugging purposes. +See function vmaCalculateStatistics(). +*/ +typedef struct VmaTotalStatistics +{ + VmaDetailedStatistics memoryType[VK_MAX_MEMORY_TYPES]; + VmaDetailedStatistics memoryHeap[VK_MAX_MEMORY_HEAPS]; + VmaDetailedStatistics total; +} VmaTotalStatistics; + +/** \brief Statistics of current memory usage and available budget for a specific memory heap. + +These are fast to calculate. +See function vmaGetHeapBudgets(). +*/ +typedef struct VmaBudget +{ + /** \brief Statistics fetched from the library. + */ + VmaStatistics statistics; + /** \brief Estimated current memory usage of the program, in bytes. + + Fetched from system using VK_EXT_memory_budget extension if enabled. + + It might be different than `statistics.blockBytes` (usually higher) due to additional implicit objects + also occupying the memory, like swapchain, pipelines, descriptor heaps, command buffers, or + `VkDeviceMemory` blocks allocated outside of this library, if any. + */ + VkDeviceSize usage; + /** \brief Estimated amount of memory available to the program, in bytes. + + Fetched from system using VK_EXT_memory_budget extension if enabled. + + It might be different (most probably smaller) than `VkMemoryHeap::size[heapIndex]` due to factors + external to the program, decided by the operating system. + Difference `budget - usage` is the amount of additional memory that can probably + be allocated without problems. Exceeding the budget may result in various problems. + */ + VkDeviceSize budget; +} VmaBudget; + +/** @} */ + +/** +\addtogroup group_alloc +@{ +*/ + +/** \brief Parameters of new #VmaAllocation. + +To be used with functions like vmaCreateBuffer(), vmaCreateImage(), and many others. +*/ +typedef struct VmaAllocationCreateInfo +{ + /// Use #VmaAllocationCreateFlagBits enum. + VmaAllocationCreateFlags flags; + /** \brief Intended usage of memory. + + You can leave #VMA_MEMORY_USAGE_UNKNOWN if you specify memory requirements in other way. \n + If `pool` is not null, this member is ignored. + */ + VmaMemoryUsage usage; + /** \brief Flags that must be set in a Memory Type chosen for an allocation. + + Leave 0 if you specify memory requirements in other way. \n + If `pool` is not null, this member is ignored.*/ + VkMemoryPropertyFlags requiredFlags; + /** \brief Flags that preferably should be set in a memory type chosen for an allocation. + + Set to 0 if no additional flags are preferred. \n + If `pool` is not null, this member is ignored. */ + VkMemoryPropertyFlags preferredFlags; + /** \brief Bitmask containing one bit set for every memory type acceptable for this allocation. + + Value 0 is equivalent to `UINT32_MAX` - it means any memory type is accepted if + it meets other requirements specified by this structure, with no further + restrictions on memory type index. \n + If `pool` is not null, this member is ignored. + */ + uint32_t memoryTypeBits; + /** \brief Pool that this allocation should be created in. + + Leave `VK_NULL_HANDLE` to allocate from default pool. If not null, members: + `usage`, `requiredFlags`, `preferredFlags`, `memoryTypeBits` are ignored. + */ + VmaPool VMA_NULLABLE pool; + /** \brief Custom general-purpose pointer that will be stored in #VmaAllocation, can be read as VmaAllocationInfo::pUserData and changed using vmaSetAllocationUserData(). + + If #VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT is used, it must be either + null or pointer to a null-terminated string. The string will be then copied to + internal buffer, so it doesn't need to be valid after allocation call. + */ + void* VMA_NULLABLE pUserData; + /** \brief A floating-point value between 0 and 1, indicating the priority of the allocation relative to other memory allocations. + + It is used only when #VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT flag was used during creation of the #VmaAllocator object + and this allocation ends up as dedicated or is explicitly forced as dedicated using #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT. + Otherwise, it has the priority of a memory block where it is placed and this variable is ignored. + */ + float priority; +} VmaAllocationCreateInfo; + +/// Describes parameter of created #VmaPool. +typedef struct VmaPoolCreateInfo +{ + /** \brief Vulkan memory type index to allocate this pool from. + */ + uint32_t memoryTypeIndex; + /** \brief Use combination of #VmaPoolCreateFlagBits. + */ + VmaPoolCreateFlags flags; + /** \brief Size of a single `VkDeviceMemory` block to be allocated as part of this pool, in bytes. Optional. + + Specify nonzero to set explicit, constant size of memory blocks used by this + pool. + + Leave 0 to use default and let the library manage block sizes automatically. + Sizes of particular blocks may vary. + In this case, the pool will also support dedicated allocations. + */ + VkDeviceSize blockSize; + /** \brief Minimum number of blocks to be always allocated in this pool, even if they stay empty. + + Set to 0 to have no preallocated blocks and allow the pool be completely empty. + */ + size_t minBlockCount; + /** \brief Maximum number of blocks that can be allocated in this pool. Optional. + + Set to 0 to use default, which is `SIZE_MAX`, which means no limit. + + Set to same value as VmaPoolCreateInfo::minBlockCount to have fixed amount of memory allocated + throughout whole lifetime of this pool. + */ + size_t maxBlockCount; + /** \brief A floating-point value between 0 and 1, indicating the priority of the allocations in this pool relative to other memory allocations. + + It is used only when #VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT flag was used during creation of the #VmaAllocator object. + Otherwise, this variable is ignored. + */ + float priority; + /** \brief Additional minimum alignment to be used for all allocations created from this pool. Can be 0. + + Leave 0 (default) not to impose any additional alignment. If not 0, it must be a power of two. + It can be useful in cases where alignment returned by Vulkan by functions like `vkGetBufferMemoryRequirements` is not enough, + e.g. when doing interop with OpenGL. + */ + VkDeviceSize minAllocationAlignment; + /** \brief Additional `pNext` chain to be attached to `VkMemoryAllocateInfo` used for every allocation made by this pool. Optional. + + Optional, can be null. If not null, it must point to a `pNext` chain of structures that can be attached to `VkMemoryAllocateInfo`. + It can be useful for special needs such as adding `VkExportMemoryAllocateInfoKHR`. + Structures pointed by this member must remain alive and unchanged for the whole lifetime of the custom pool. + + Please note that some structures, e.g. `VkMemoryPriorityAllocateInfoEXT`, `VkMemoryDedicatedAllocateInfoKHR`, + can be attached automatically by this library when using other, more convenient of its features. + */ + void* VMA_NULLABLE VMA_EXTENDS_VK_STRUCT(VkMemoryAllocateInfo) pMemoryAllocateNext; +} VmaPoolCreateInfo; + +/** @} */ + +/** +\addtogroup group_alloc +@{ +*/ + +/** +Parameters of #VmaAllocation objects, that can be retrieved using function vmaGetAllocationInfo(). + +There is also an extended version of this structure that carries additional parameters: #VmaAllocationInfo2. +*/ +typedef struct VmaAllocationInfo +{ + /** \brief Memory type index that this allocation was allocated from. + + It never changes. + */ + uint32_t memoryType; + /** \brief Handle to Vulkan memory object. + + Same memory object can be shared by multiple allocations. + + It can change after the allocation is moved during \ref defragmentation. + */ + VkDeviceMemory VMA_NULLABLE_NON_DISPATCHABLE deviceMemory; + /** \brief Offset in `VkDeviceMemory` object to the beginning of this allocation, in bytes. `(deviceMemory, offset)` pair is unique to this allocation. + + You usually don't need to use this offset. If you create a buffer or an image together with the allocation using e.g. function + vmaCreateBuffer(), vmaCreateImage(), functions that operate on these resources refer to the beginning of the buffer or image, + not entire device memory block. Functions like vmaMapMemory(), vmaBindBufferMemory() also refer to the beginning of the allocation + and apply this offset automatically. + + It can change after the allocation is moved during \ref defragmentation. + */ + VkDeviceSize offset; + /** \brief Size of this allocation, in bytes. + + It never changes. + + \note Allocation size returned in this variable may be greater than the size + requested for the resource e.g. as `VkBufferCreateInfo::size`. Whole size of the + allocation is accessible for operations on memory e.g. using a pointer after + mapping with vmaMapMemory(), but operations on the resource e.g. using + `vkCmdCopyBuffer` must be limited to the size of the resource. + */ + VkDeviceSize size; + /** \brief Pointer to the beginning of this allocation as mapped data. + + If the allocation hasn't been mapped using vmaMapMemory() and hasn't been + created with #VMA_ALLOCATION_CREATE_MAPPED_BIT flag, this value is null. + + It can change after call to vmaMapMemory(), vmaUnmapMemory(). + It can also change after the allocation is moved during \ref defragmentation. + */ + void* VMA_NULLABLE pMappedData; + /** \brief Custom general-purpose pointer that was passed as VmaAllocationCreateInfo::pUserData or set using vmaSetAllocationUserData(). + + It can change after call to vmaSetAllocationUserData() for this allocation. + */ + void* VMA_NULLABLE pUserData; + /** \brief Custom allocation name that was set with vmaSetAllocationName(). + + It can change after call to vmaSetAllocationName() for this allocation. + + Another way to set custom name is to pass it in VmaAllocationCreateInfo::pUserData with + additional flag #VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT set [DEPRECATED]. + */ + const char* VMA_NULLABLE pName; +} VmaAllocationInfo; + +/// Extended parameters of a #VmaAllocation object that can be retrieved using function vmaGetAllocationInfo2(). +typedef struct VmaAllocationInfo2 +{ + /** \brief Basic parameters of the allocation. + + If you need only these, you can use function vmaGetAllocationInfo() and structure #VmaAllocationInfo instead. + */ + VmaAllocationInfo allocationInfo; + /** \brief Size of the `VkDeviceMemory` block that the allocation belongs to. + + In case of an allocation with dedicated memory, it will be equal to `allocationInfo.size`. + */ + VkDeviceSize blockSize; + /** \brief `VK_TRUE` if the allocation has dedicated memory, `VK_FALSE` if it was placed as part of a larger memory block. + + When `VK_TRUE`, it also means `VkMemoryDedicatedAllocateInfo` was used when creating the allocation + (if VK_KHR_dedicated_allocation extension or Vulkan version >= 1.1 is enabled). + */ + VkBool32 dedicatedMemory; +} VmaAllocationInfo2; + +/** Callback function called during vmaBeginDefragmentation() to check custom criterion about ending current defragmentation pass. + +Should return true if the defragmentation needs to stop current pass. +*/ +typedef VkBool32 (VKAPI_PTR* PFN_vmaCheckDefragmentationBreakFunction)(void* VMA_NULLABLE pUserData); + +/** \brief Parameters for defragmentation. + +To be used with function vmaBeginDefragmentation(). +*/ +typedef struct VmaDefragmentationInfo +{ + /// \brief Use combination of #VmaDefragmentationFlagBits. + VmaDefragmentationFlags flags; + /** \brief Custom pool to be defragmented. + + If null then default pools will undergo defragmentation process. + */ + VmaPool VMA_NULLABLE pool; + /** \brief Maximum numbers of bytes that can be copied during single pass, while moving allocations to different places. + + `0` means no limit. + */ + VkDeviceSize maxBytesPerPass; + /** \brief Maximum number of allocations that can be moved during single pass to a different place. + + `0` means no limit. + */ + uint32_t maxAllocationsPerPass; + /** \brief Optional custom callback for stopping vmaBeginDefragmentation(). + + Have to return true for breaking current defragmentation pass. + */ + PFN_vmaCheckDefragmentationBreakFunction VMA_NULLABLE pfnBreakCallback; + /// \brief Optional data to pass to custom callback for stopping pass of defragmentation. + void* VMA_NULLABLE pBreakCallbackUserData; +} VmaDefragmentationInfo; + +/// Single move of an allocation to be done for defragmentation. +typedef struct VmaDefragmentationMove +{ + /// Operation to be performed on the allocation by vmaEndDefragmentationPass(). Default value is #VMA_DEFRAGMENTATION_MOVE_OPERATION_COPY. You can modify it. + VmaDefragmentationMoveOperation operation; + /// Allocation that should be moved. + VmaAllocation VMA_NOT_NULL srcAllocation; + /** \brief Temporary allocation pointing to destination memory that will replace `srcAllocation`. + + \warning Do not store this allocation in your data structures! It exists only temporarily, for the duration of the defragmentation pass, + to be used for binding new buffer/image to the destination memory using e.g. vmaBindBufferMemory(). + vmaEndDefragmentationPass() will destroy it and make `srcAllocation` point to this memory. + */ + VmaAllocation VMA_NOT_NULL dstTmpAllocation; +} VmaDefragmentationMove; + +/** \brief Parameters for incremental defragmentation steps. + +To be used with function vmaBeginDefragmentationPass(). +*/ +typedef struct VmaDefragmentationPassMoveInfo +{ + /// Number of elements in the `pMoves` array. + uint32_t moveCount; + /** \brief Array of moves to be performed by the user in the current defragmentation pass. + + Pointer to an array of `moveCount` elements, owned by VMA, created in vmaBeginDefragmentationPass(), destroyed in vmaEndDefragmentationPass(). + + For each element, you should: + + 1. Create a new buffer/image in the place pointed by VmaDefragmentationMove::dstMemory + VmaDefragmentationMove::dstOffset. + 2. Copy data from the VmaDefragmentationMove::srcAllocation e.g. using `vkCmdCopyBuffer`, `vkCmdCopyImage`. + 3. Make sure these commands finished executing on the GPU. + 4. Destroy the old buffer/image. + + Only then you can finish defragmentation pass by calling vmaEndDefragmentationPass(). + After this call, the allocation will point to the new place in memory. + + Alternatively, if you cannot move specific allocation, you can set VmaDefragmentationMove::operation to #VMA_DEFRAGMENTATION_MOVE_OPERATION_IGNORE. + + Alternatively, if you decide you want to completely remove the allocation: + + 1. Destroy its buffer/image. + 2. Set VmaDefragmentationMove::operation to #VMA_DEFRAGMENTATION_MOVE_OPERATION_DESTROY. + + Then, after vmaEndDefragmentationPass() the allocation will be freed. + */ + VmaDefragmentationMove* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(moveCount) pMoves; +} VmaDefragmentationPassMoveInfo; + +/// Statistics returned for defragmentation process in function vmaEndDefragmentation(). +typedef struct VmaDefragmentationStats +{ + /// Total number of bytes that have been copied while moving allocations to different places. + VkDeviceSize bytesMoved; + /// Total number of bytes that have been released to the system by freeing empty `VkDeviceMemory` objects. + VkDeviceSize bytesFreed; + /// Number of allocations that have been moved to different places. + uint32_t allocationsMoved; + /// Number of empty `VkDeviceMemory` objects that have been released to the system. + uint32_t deviceMemoryBlocksFreed; +} VmaDefragmentationStats; + +/** @} */ + +/** +\addtogroup group_virtual +@{ +*/ + +/// Parameters of created #VmaVirtualBlock object to be passed to vmaCreateVirtualBlock(). +typedef struct VmaVirtualBlockCreateInfo +{ + /** \brief Total size of the virtual block. + + Sizes can be expressed in bytes or any units you want as long as you are consistent in using them. + For example, if you allocate from some array of structures, 1 can mean single instance of entire structure. + */ + VkDeviceSize size; + + /** \brief Use combination of #VmaVirtualBlockCreateFlagBits. + */ + VmaVirtualBlockCreateFlags flags; + + /** \brief Custom CPU memory allocation callbacks. Optional. + + Optional, can be null. When specified, they will be used for all CPU-side memory allocations. + */ + const VkAllocationCallbacks* VMA_NULLABLE pAllocationCallbacks; +} VmaVirtualBlockCreateInfo; + +/// Parameters of created virtual allocation to be passed to vmaVirtualAllocate(). +typedef struct VmaVirtualAllocationCreateInfo +{ + /** \brief Size of the allocation. + + Cannot be zero. + */ + VkDeviceSize size; + /** \brief Required alignment of the allocation. Optional. + + Must be power of two. Special value 0 has the same meaning as 1 - means no special alignment is required, so allocation can start at any offset. + */ + VkDeviceSize alignment; + /** \brief Use combination of #VmaVirtualAllocationCreateFlagBits. + */ + VmaVirtualAllocationCreateFlags flags; + /** \brief Custom pointer to be associated with the allocation. Optional. + + It can be any value and can be used for user-defined purposes. It can be fetched or changed later. + */ + void* VMA_NULLABLE pUserData; +} VmaVirtualAllocationCreateInfo; + +/// Parameters of an existing virtual allocation, returned by vmaGetVirtualAllocationInfo(). +typedef struct VmaVirtualAllocationInfo +{ + /** \brief Offset of the allocation. + + Offset at which the allocation was made. + */ + VkDeviceSize offset; + /** \brief Size of the allocation. + + Same value as passed in VmaVirtualAllocationCreateInfo::size. + */ + VkDeviceSize size; + /** \brief Custom pointer associated with the allocation. + + Same value as passed in VmaVirtualAllocationCreateInfo::pUserData or to vmaSetVirtualAllocationUserData(). + */ + void* VMA_NULLABLE pUserData; +} VmaVirtualAllocationInfo; + +/** @} */ + +#endif // _VMA_DATA_TYPES_DECLARATIONS + +#ifndef _VMA_FUNCTION_HEADERS + +/** +\addtogroup group_init +@{ +*/ + +/// Creates #VmaAllocator object. +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAllocator( + const VmaAllocatorCreateInfo* VMA_NOT_NULL pCreateInfo, + VmaAllocator VMA_NULLABLE* VMA_NOT_NULL pAllocator); + +/// Destroys allocator object. +VMA_CALL_PRE void VMA_CALL_POST vmaDestroyAllocator( + VmaAllocator VMA_NULLABLE allocator); + +/** \brief Returns information about existing #VmaAllocator object - handle to Vulkan device etc. + +It might be useful if you want to keep just the #VmaAllocator handle and fetch other required handles to +`VkPhysicalDevice`, `VkDevice` etc. every time using this function. +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocatorInfo( + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocatorInfo* VMA_NOT_NULL pAllocatorInfo); + +/** +PhysicalDeviceProperties are fetched from physicalDevice by the allocator. +You can access it here, without fetching it again on your own. +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaGetPhysicalDeviceProperties( + VmaAllocator VMA_NOT_NULL allocator, + const VkPhysicalDeviceProperties* VMA_NULLABLE* VMA_NOT_NULL ppPhysicalDeviceProperties); + +/** +PhysicalDeviceMemoryProperties are fetched from physicalDevice by the allocator. +You can access it here, without fetching it again on your own. +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryProperties( + VmaAllocator VMA_NOT_NULL allocator, + const VkPhysicalDeviceMemoryProperties* VMA_NULLABLE* VMA_NOT_NULL ppPhysicalDeviceMemoryProperties); + +/** +\brief Given Memory Type Index, returns Property Flags of this memory type. + +This is just a convenience function. Same information can be obtained using +vmaGetMemoryProperties(). +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryTypeProperties( + VmaAllocator VMA_NOT_NULL allocator, + uint32_t memoryTypeIndex, + VkMemoryPropertyFlags* VMA_NOT_NULL pFlags); + +/** \brief Sets index of the current frame. +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaSetCurrentFrameIndex( + VmaAllocator VMA_NOT_NULL allocator, + uint32_t frameIndex); + +/** @} */ + +/** +\addtogroup group_stats +@{ +*/ + +/** \brief Retrieves statistics from current state of the Allocator. + +This function is called "calculate" not "get" because it has to traverse all +internal data structures, so it may be quite slow. Use it for debugging purposes. +For faster but more brief statistics suitable to be called every frame or every allocation, +use vmaGetHeapBudgets(). + +Note that when using allocator from multiple threads, returned information may immediately +become outdated. +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaCalculateStatistics( + VmaAllocator VMA_NOT_NULL allocator, + VmaTotalStatistics* VMA_NOT_NULL pStats); + +/** \brief Retrieves information about current memory usage and budget for all memory heaps. + +\param allocator +\param[out] pBudgets Must point to array with number of elements at least equal to number of memory heaps in physical device used. + +This function is called "get" not "calculate" because it is very fast, suitable to be called +every frame or every allocation. For more detailed statistics use vmaCalculateStatistics(). + +Note that when using allocator from multiple threads, returned information may immediately +become outdated. +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaGetHeapBudgets( + VmaAllocator VMA_NOT_NULL allocator, + VmaBudget* VMA_NOT_NULL VMA_LEN_IF_NOT_NULL("VkPhysicalDeviceMemoryProperties::memoryHeapCount") pBudgets); + +/** @} */ + +/** +\addtogroup group_alloc +@{ +*/ + +/** +\brief Helps to find memoryTypeIndex, given memoryTypeBits and VmaAllocationCreateInfo. + +This algorithm tries to find a memory type that: + +- Is allowed by memoryTypeBits. +- Contains all the flags from pAllocationCreateInfo->requiredFlags. +- Matches intended usage. +- Has as many flags from pAllocationCreateInfo->preferredFlags as possible. + +\return Returns VK_ERROR_FEATURE_NOT_PRESENT if not found. Receiving such result +from this function or any other allocating function probably means that your +device doesn't support any memory type with requested features for the specific +type of resource you want to use it for. Please check parameters of your +resource, like image layout (OPTIMAL versus LINEAR) or mip level count. +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndex( + VmaAllocator VMA_NOT_NULL allocator, + uint32_t memoryTypeBits, + const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo, + uint32_t* VMA_NOT_NULL pMemoryTypeIndex); + +/** +\brief Helps to find memoryTypeIndex, given VkBufferCreateInfo and VmaAllocationCreateInfo. + +It can be useful e.g. to determine value to be used as VmaPoolCreateInfo::memoryTypeIndex. +It internally creates a temporary, dummy buffer that never has memory bound. +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForBufferInfo( + VmaAllocator VMA_NOT_NULL allocator, + const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo, + const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo, + uint32_t* VMA_NOT_NULL pMemoryTypeIndex); + +/** +\brief Helps to find memoryTypeIndex, given VkImageCreateInfo and VmaAllocationCreateInfo. + +It can be useful e.g. to determine value to be used as VmaPoolCreateInfo::memoryTypeIndex. +It internally creates a temporary, dummy image that never has memory bound. +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForImageInfo( + VmaAllocator VMA_NOT_NULL allocator, + const VkImageCreateInfo* VMA_NOT_NULL pImageCreateInfo, + const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo, + uint32_t* VMA_NOT_NULL pMemoryTypeIndex); + +/** \brief Allocates Vulkan device memory and creates #VmaPool object. + +\param allocator Allocator object. +\param pCreateInfo Parameters of pool to create. +\param[out] pPool Handle to created pool. +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreatePool( + VmaAllocator VMA_NOT_NULL allocator, + const VmaPoolCreateInfo* VMA_NOT_NULL pCreateInfo, + VmaPool VMA_NULLABLE* VMA_NOT_NULL pPool); + +/** \brief Destroys #VmaPool object and frees Vulkan device memory. +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaDestroyPool( + VmaAllocator VMA_NOT_NULL allocator, + VmaPool VMA_NULLABLE pool); + +/** @} */ + +/** +\addtogroup group_stats +@{ +*/ + +/** \brief Retrieves statistics of existing #VmaPool object. + +\param allocator Allocator object. +\param pool Pool object. +\param[out] pPoolStats Statistics of specified pool. +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolStatistics( + VmaAllocator VMA_NOT_NULL allocator, + VmaPool VMA_NOT_NULL pool, + VmaStatistics* VMA_NOT_NULL pPoolStats); + +/** \brief Retrieves detailed statistics of existing #VmaPool object. + +\param allocator Allocator object. +\param pool Pool object. +\param[out] pPoolStats Statistics of specified pool. +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaCalculatePoolStatistics( + VmaAllocator VMA_NOT_NULL allocator, + VmaPool VMA_NOT_NULL pool, + VmaDetailedStatistics* VMA_NOT_NULL pPoolStats); + +/** @} */ + +/** +\addtogroup group_alloc +@{ +*/ + +/** \brief Checks magic number in margins around all allocations in given memory pool in search for corruptions. + +Corruption detection is enabled only when `VMA_DEBUG_DETECT_CORRUPTION` macro is defined to nonzero, +`VMA_DEBUG_MARGIN` is defined to nonzero and the pool is created in memory type that is +`HOST_VISIBLE` and `HOST_COHERENT`. For more information, see [Corruption detection](@ref debugging_memory_usage_corruption_detection). + +Possible return values: + +- `VK_ERROR_FEATURE_NOT_PRESENT` - corruption detection is not enabled for specified pool. +- `VK_SUCCESS` - corruption detection has been performed and succeeded. +- `VK_ERROR_UNKNOWN` - corruption detection has been performed and found memory corruptions around one of the allocations. + `VMA_ASSERT` is also fired in that case. +- Other value: Error returned by Vulkan, e.g. memory mapping failure. +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCheckPoolCorruption( + VmaAllocator VMA_NOT_NULL allocator, + VmaPool VMA_NOT_NULL pool); + +/** \brief Retrieves name of a custom pool. + +After the call `ppName` is either null or points to an internally-owned null-terminated string +containing name of the pool that was previously set. The pointer becomes invalid when the pool is +destroyed or its name is changed using vmaSetPoolName(). +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolName( + VmaAllocator VMA_NOT_NULL allocator, + VmaPool VMA_NOT_NULL pool, + const char* VMA_NULLABLE* VMA_NOT_NULL ppName); + +/** \brief Sets name of a custom pool. + +`pName` can be either null or pointer to a null-terminated string with new name for the pool. +Function makes internal copy of the string, so it can be changed or freed immediately after this call. +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaSetPoolName( + VmaAllocator VMA_NOT_NULL allocator, + VmaPool VMA_NOT_NULL pool, + const char* VMA_NULLABLE pName); + +/** \brief General purpose memory allocation. + +\param allocator +\param pVkMemoryRequirements +\param pCreateInfo +\param[out] pAllocation Handle to allocated memory. +\param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo(). + +You should free the memory using vmaFreeMemory() or vmaFreeMemoryPages(). + +It is recommended to use vmaAllocateMemoryForBuffer(), vmaAllocateMemoryForImage(), +vmaCreateBuffer(), vmaCreateImage() instead whenever possible. +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemory( + VmaAllocator VMA_NOT_NULL allocator, + const VkMemoryRequirements* VMA_NOT_NULL pVkMemoryRequirements, + const VmaAllocationCreateInfo* VMA_NOT_NULL pCreateInfo, + VmaAllocation VMA_NULLABLE* VMA_NOT_NULL pAllocation, + VmaAllocationInfo* VMA_NULLABLE pAllocationInfo); + +/** \brief General purpose memory allocation for multiple allocation objects at once. + +\param allocator Allocator object. +\param pVkMemoryRequirements Memory requirements for each allocation. +\param pCreateInfo Creation parameters for each allocation. +\param allocationCount Number of allocations to make. +\param[out] pAllocations Pointer to array that will be filled with handles to created allocations. +\param[out] pAllocationInfo Optional. Pointer to array that will be filled with parameters of created allocations. + +You should free the memory using vmaFreeMemory() or vmaFreeMemoryPages(). + +Word "pages" is just a suggestion to use this function to allocate pieces of memory needed for sparse binding. +It is just a general purpose allocation function able to make multiple allocations at once. +It may be internally optimized to be more efficient than calling vmaAllocateMemory() `allocationCount` times. + +All allocations are made using same parameters. All of them are created out of the same memory pool and type. +If any allocation fails, all allocations already made within this function call are also freed, so that when +returned result is not `VK_SUCCESS`, `pAllocation` array is always entirely filled with `VK_NULL_HANDLE`. +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryPages( + VmaAllocator VMA_NOT_NULL allocator, + const VkMemoryRequirements* VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(allocationCount) pVkMemoryRequirements, + const VmaAllocationCreateInfo* VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(allocationCount) pCreateInfo, + size_t allocationCount, + VmaAllocation VMA_NULLABLE* VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(allocationCount) pAllocations, + VmaAllocationInfo* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) pAllocationInfo); + +/** \brief Allocates memory suitable for given `VkBuffer`. + +\param allocator +\param buffer +\param pCreateInfo +\param[out] pAllocation Handle to allocated memory. +\param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo(). + +It only creates #VmaAllocation. To bind the memory to the buffer, use vmaBindBufferMemory(). + +This is a special-purpose function. In most cases you should use vmaCreateBuffer(). + +You must free the allocation using vmaFreeMemory() when no longer needed. +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForBuffer( + VmaAllocator VMA_NOT_NULL allocator, + VkBuffer VMA_NOT_NULL_NON_DISPATCHABLE buffer, + const VmaAllocationCreateInfo* VMA_NOT_NULL pCreateInfo, + VmaAllocation VMA_NULLABLE* VMA_NOT_NULL pAllocation, + VmaAllocationInfo* VMA_NULLABLE pAllocationInfo); + +/** \brief Allocates memory suitable for given `VkImage`. + +\param allocator +\param image +\param pCreateInfo +\param[out] pAllocation Handle to allocated memory. +\param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo(). + +It only creates #VmaAllocation. To bind the memory to the buffer, use vmaBindImageMemory(). + +This is a special-purpose function. In most cases you should use vmaCreateImage(). + +You must free the allocation using vmaFreeMemory() when no longer needed. +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForImage( + VmaAllocator VMA_NOT_NULL allocator, + VkImage VMA_NOT_NULL_NON_DISPATCHABLE image, + const VmaAllocationCreateInfo* VMA_NOT_NULL pCreateInfo, + VmaAllocation VMA_NULLABLE* VMA_NOT_NULL pAllocation, + VmaAllocationInfo* VMA_NULLABLE pAllocationInfo); + +/** \brief Frees memory previously allocated using vmaAllocateMemory(), vmaAllocateMemoryForBuffer(), or vmaAllocateMemoryForImage(). + +Passing `VK_NULL_HANDLE` as `allocation` is valid. Such function call is just skipped. +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemory( + VmaAllocator VMA_NOT_NULL allocator, + const VmaAllocation VMA_NULLABLE allocation); + +/** \brief Frees memory and destroys multiple allocations. + +Word "pages" is just a suggestion to use this function to free pieces of memory used for sparse binding. +It is just a general purpose function to free memory and destroy allocations made using e.g. vmaAllocateMemory(), +vmaAllocateMemoryPages() and other functions. +It may be internally optimized to be more efficient than calling vmaFreeMemory() `allocationCount` times. + +Allocations in `pAllocations` array can come from any memory pools and types. +Passing `VK_NULL_HANDLE` as elements of `pAllocations` array is valid. Such entries are just skipped. +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemoryPages( + VmaAllocator VMA_NOT_NULL allocator, + size_t allocationCount, + const VmaAllocation VMA_NULLABLE* VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(allocationCount) pAllocations); + +/** \brief Returns current information about specified allocation. + +Current parameters of given allocation are returned in `pAllocationInfo`. + +Although this function doesn't lock any mutex, so it should be quite efficient, +you should avoid calling it too often. +You can retrieve same VmaAllocationInfo structure while creating your resource, from function +vmaCreateBuffer(), vmaCreateImage(). You can remember it if you are sure parameters don't change +(e.g. due to defragmentation). + +There is also a new function vmaGetAllocationInfo2() that offers extended information +about the allocation, returned using new structure #VmaAllocationInfo2. +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocationInfo( + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, + VmaAllocationInfo* VMA_NOT_NULL pAllocationInfo); + +/** \brief Returns extended information about specified allocation. + +Current parameters of given allocation are returned in `pAllocationInfo`. +Extended parameters in structure #VmaAllocationInfo2 include memory block size +and a flag telling whether the allocation has dedicated memory. +It can be useful e.g. for interop with OpenGL. +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocationInfo2( + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, + VmaAllocationInfo2* VMA_NOT_NULL pAllocationInfo); + +/** \brief Sets pUserData in given allocation to new value. + +The value of pointer `pUserData` is copied to allocation's `pUserData`. +It is opaque, so you can use it however you want - e.g. +as a pointer, ordinal number or some handle to you own data. +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaSetAllocationUserData( + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, + void* VMA_NULLABLE pUserData); + +/** \brief Sets pName in given allocation to new value. + +`pName` must be either null, or pointer to a null-terminated string. The function +makes local copy of the string and sets it as allocation's `pName`. String +passed as pName doesn't need to be valid for whole lifetime of the allocation - +you can free it after this call. String previously pointed by allocation's +`pName` is freed from memory. +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaSetAllocationName( + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, + const char* VMA_NULLABLE pName); + +/** +\brief Given an allocation, returns Property Flags of its memory type. + +This is just a convenience function. Same information can be obtained using +vmaGetAllocationInfo() + vmaGetMemoryProperties(). +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocationMemoryProperties( + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, + VkMemoryPropertyFlags* VMA_NOT_NULL pFlags); + + +#if VMA_EXTERNAL_MEMORY_WIN32 +/** +\brief Given an allocation, returns Win32 handle that may be imported by other processes or APIs. + +\param hTargetProcess Must be a valid handle to target process or null. If it's null, the function returns + handle for the current process. +\param[out] pHandle Output parameter that returns the handle. + +The function fills `pHandle` with handle that can be used in target process. +The handle is fetched using function `vkGetMemoryWin32HandleKHR`. +When no longer needed, you must close it using: + +\code +CloseHandle(handle); +\endcode + +You can close it any time, before or after destroying the allocation object. +It is reference-counted internally by Windows. + +Note the handle is returned for the entire `VkDeviceMemory` block that the allocation belongs to. +If the allocation is sub-allocated from a larger block, you may need to consider the offset of the allocation +(VmaAllocationInfo::offset). + +If the function fails with `VK_ERROR_FEATURE_NOT_PRESENT` error code, please double-check +that VmaVulkanFunctions::vkGetMemoryWin32HandleKHR function pointer is set, e.g. either by using `VMA_DYNAMIC_VULKAN_FUNCTIONS` +or by manually passing it through VmaAllocatorCreateInfo::pVulkanFunctions. + +For more information, see chapter \ref vk_khr_external_memory_win32. +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaGetMemoryWin32Handle(VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, HANDLE hTargetProcess, HANDLE* VMA_NOT_NULL pHandle); +#endif // VMA_EXTERNAL_MEMORY_WIN32 + +/** \brief Maps memory represented by given allocation and returns pointer to it. + +Maps memory represented by given allocation to make it accessible to CPU code. +When succeeded, `*ppData` contains pointer to first byte of this memory. + +\warning +If the allocation is part of a bigger `VkDeviceMemory` block, returned pointer is +correctly offsetted to the beginning of region assigned to this particular allocation. +Unlike the result of `vkMapMemory`, it points to the allocation, not to the beginning of the whole block. +You should not add VmaAllocationInfo::offset to it! + +Mapping is internally reference-counted and synchronized, so despite raw Vulkan +function `vkMapMemory()` cannot be used to map same block of `VkDeviceMemory` +multiple times simultaneously, it is safe to call this function on allocations +assigned to the same memory block. Actual Vulkan memory will be mapped on first +mapping and unmapped on last unmapping. + +If the function succeeded, you must call vmaUnmapMemory() to unmap the +allocation when mapping is no longer needed or before freeing the allocation, at +the latest. + +It also safe to call this function multiple times on the same allocation. You +must call vmaUnmapMemory() same number of times as you called vmaMapMemory(). + +It is also safe to call this function on allocation created with +#VMA_ALLOCATION_CREATE_MAPPED_BIT flag. Its memory stays mapped all the time. +You must still call vmaUnmapMemory() same number of times as you called +vmaMapMemory(). You must not call vmaUnmapMemory() additional time to free the +"0-th" mapping made automatically due to #VMA_ALLOCATION_CREATE_MAPPED_BIT flag. + +This function fails when used on allocation made in memory type that is not +`HOST_VISIBLE`. + +This function doesn't automatically flush or invalidate caches. +If the allocation is made from a memory types that is not `HOST_COHERENT`, +you also need to use vmaInvalidateAllocation() / vmaFlushAllocation(), as required by Vulkan specification. +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaMapMemory( + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, + void* VMA_NULLABLE* VMA_NOT_NULL ppData); + +/** \brief Unmaps memory represented by given allocation, mapped previously using vmaMapMemory(). + +For details, see description of vmaMapMemory(). + +This function doesn't automatically flush or invalidate caches. +If the allocation is made from a memory types that is not `HOST_COHERENT`, +you also need to use vmaInvalidateAllocation() / vmaFlushAllocation(), as required by Vulkan specification. +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaUnmapMemory( + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation); + +/** \brief Flushes memory of given allocation. + +Calls `vkFlushMappedMemoryRanges()` for memory associated with given range of given allocation. +It needs to be called after writing to a mapped memory for memory types that are not `HOST_COHERENT`. +Unmap operation doesn't do that automatically. + +- `offset` must be relative to the beginning of allocation. +- `size` can be `VK_WHOLE_SIZE`. It means all memory from `offset` the the end of given allocation. +- `offset` and `size` don't have to be aligned. + They are internally rounded down/up to multiply of `nonCoherentAtomSize`. +- If `size` is 0, this call is ignored. +- If memory type that the `allocation` belongs to is not `HOST_VISIBLE` or it is `HOST_COHERENT`, + this call is ignored. + +Warning! `offset` and `size` are relative to the contents of given `allocation`. +If you mean whole allocation, you can pass 0 and `VK_WHOLE_SIZE`, respectively. +Do not pass allocation's offset as `offset`!!! + +This function returns the `VkResult` from `vkFlushMappedMemoryRanges` if it is +called, otherwise `VK_SUCCESS`. +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaFlushAllocation( + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, + VkDeviceSize offset, + VkDeviceSize size); + +/** \brief Invalidates memory of given allocation. + +Calls `vkInvalidateMappedMemoryRanges()` for memory associated with given range of given allocation. +It needs to be called before reading from a mapped memory for memory types that are not `HOST_COHERENT`. +Map operation doesn't do that automatically. + +- `offset` must be relative to the beginning of allocation. +- `size` can be `VK_WHOLE_SIZE`. It means all memory from `offset` the the end of given allocation. +- `offset` and `size` don't have to be aligned. + They are internally rounded down/up to multiply of `nonCoherentAtomSize`. +- If `size` is 0, this call is ignored. +- If memory type that the `allocation` belongs to is not `HOST_VISIBLE` or it is `HOST_COHERENT`, + this call is ignored. + +Warning! `offset` and `size` are relative to the contents of given `allocation`. +If you mean whole allocation, you can pass 0 and `VK_WHOLE_SIZE`, respectively. +Do not pass allocation's offset as `offset`!!! + +This function returns the `VkResult` from `vkInvalidateMappedMemoryRanges` if +it is called, otherwise `VK_SUCCESS`. +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaInvalidateAllocation( + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, + VkDeviceSize offset, + VkDeviceSize size); + +/** \brief Flushes memory of given set of allocations. + +Calls `vkFlushMappedMemoryRanges()` for memory associated with given ranges of given allocations. +For more information, see documentation of vmaFlushAllocation(). + +\param allocator +\param allocationCount +\param allocations +\param offsets If not null, it must point to an array of offsets of regions to flush, relative to the beginning of respective allocations. Null means all offsets are zero. +\param sizes If not null, it must point to an array of sizes of regions to flush in respective allocations. Null means `VK_WHOLE_SIZE` for all allocations. + +This function returns the `VkResult` from `vkFlushMappedMemoryRanges` if it is +called, otherwise `VK_SUCCESS`. +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaFlushAllocations( + VmaAllocator VMA_NOT_NULL allocator, + uint32_t allocationCount, + const VmaAllocation VMA_NOT_NULL* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) allocations, + const VkDeviceSize* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) offsets, + const VkDeviceSize* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) sizes); + +/** \brief Invalidates memory of given set of allocations. + +Calls `vkInvalidateMappedMemoryRanges()` for memory associated with given ranges of given allocations. +For more information, see documentation of vmaInvalidateAllocation(). + +\param allocator +\param allocationCount +\param allocations +\param offsets If not null, it must point to an array of offsets of regions to flush, relative to the beginning of respective allocations. Null means all offsets are zero. +\param sizes If not null, it must point to an array of sizes of regions to flush in respective allocations. Null means `VK_WHOLE_SIZE` for all allocations. + +This function returns the `VkResult` from `vkInvalidateMappedMemoryRanges` if it is +called, otherwise `VK_SUCCESS`. +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaInvalidateAllocations( + VmaAllocator VMA_NOT_NULL allocator, + uint32_t allocationCount, + const VmaAllocation VMA_NOT_NULL* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) allocations, + const VkDeviceSize* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) offsets, + const VkDeviceSize* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) sizes); + +/** \brief Maps the allocation temporarily if needed, copies data from specified host pointer to it, and flushes the memory from the host caches if needed. + +\param allocator +\param pSrcHostPointer Pointer to the host data that become source of the copy. +\param dstAllocation Handle to the allocation that becomes destination of the copy. +\param dstAllocationLocalOffset Offset within `dstAllocation` where to write copied data, in bytes. +\param size Number of bytes to copy. + +This is a convenience function that allows to copy data from a host pointer to an allocation easily. +Same behavior can be achieved by calling vmaMapMemory(), `memcpy()`, vmaUnmapMemory(), vmaFlushAllocation(). + +This function can be called only for allocations created in a memory type that has `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` flag. +It can be ensured e.g. by using #VMA_MEMORY_USAGE_AUTO and #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or +#VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT. +Otherwise, the function will fail and generate a Validation Layers error. + +`dstAllocationLocalOffset` is relative to the contents of given `dstAllocation`. +If you mean whole allocation, you should pass 0. +Do not pass allocation's offset within device memory block this parameter! +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCopyMemoryToAllocation( + VmaAllocator VMA_NOT_NULL allocator, + const void* VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(size) pSrcHostPointer, + VmaAllocation VMA_NOT_NULL dstAllocation, + VkDeviceSize dstAllocationLocalOffset, + VkDeviceSize size); + +/** \brief Invalidates memory in the host caches if needed, maps the allocation temporarily if needed, and copies data from it to a specified host pointer. + +\param allocator +\param srcAllocation Handle to the allocation that becomes source of the copy. +\param srcAllocationLocalOffset Offset within `srcAllocation` where to read copied data, in bytes. +\param pDstHostPointer Pointer to the host memory that become destination of the copy. +\param size Number of bytes to copy. + +This is a convenience function that allows to copy data from an allocation to a host pointer easily. +Same behavior can be achieved by calling vmaInvalidateAllocation(), vmaMapMemory(), `memcpy()`, vmaUnmapMemory(). + +This function should be called only for allocations created in a memory type that has `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` +and `VK_MEMORY_PROPERTY_HOST_CACHED_BIT` flag. +It can be ensured e.g. by using #VMA_MEMORY_USAGE_AUTO and #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT. +Otherwise, the function may fail and generate a Validation Layers error. +It may also work very slowly when reading from an uncached memory. + +`srcAllocationLocalOffset` is relative to the contents of given `srcAllocation`. +If you mean whole allocation, you should pass 0. +Do not pass allocation's offset within device memory block as this parameter! +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCopyAllocationToMemory( + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL srcAllocation, + VkDeviceSize srcAllocationLocalOffset, + void* VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(size) pDstHostPointer, + VkDeviceSize size); + +/** \brief Checks magic number in margins around all allocations in given memory types (in both default and custom pools) in search for corruptions. + +\param allocator +\param memoryTypeBits Bit mask, where each bit set means that a memory type with that index should be checked. + +Corruption detection is enabled only when `VMA_DEBUG_DETECT_CORRUPTION` macro is defined to nonzero, +`VMA_DEBUG_MARGIN` is defined to nonzero and only for memory types that are +`HOST_VISIBLE` and `HOST_COHERENT`. For more information, see [Corruption detection](@ref debugging_memory_usage_corruption_detection). + +Possible return values: + +- `VK_ERROR_FEATURE_NOT_PRESENT` - corruption detection is not enabled for any of specified memory types. +- `VK_SUCCESS` - corruption detection has been performed and succeeded. +- `VK_ERROR_UNKNOWN` - corruption detection has been performed and found memory corruptions around one of the allocations. + `VMA_ASSERT` is also fired in that case. +- Other value: Error returned by Vulkan, e.g. memory mapping failure. +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCheckCorruption( + VmaAllocator VMA_NOT_NULL allocator, + uint32_t memoryTypeBits); + +/** \brief Begins defragmentation process. + +\param allocator Allocator object. +\param pInfo Structure filled with parameters of defragmentation. +\param[out] pContext Context object that must be passed to vmaEndDefragmentation() to finish defragmentation. +\returns +- `VK_SUCCESS` if defragmentation can begin. +- `VK_ERROR_FEATURE_NOT_PRESENT` if defragmentation is not supported. + +For more information about defragmentation, see documentation chapter: +[Defragmentation](@ref defragmentation). +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaBeginDefragmentation( + VmaAllocator VMA_NOT_NULL allocator, + const VmaDefragmentationInfo* VMA_NOT_NULL pInfo, + VmaDefragmentationContext VMA_NULLABLE* VMA_NOT_NULL pContext); + +/** \brief Ends defragmentation process. + +\param allocator Allocator object. +\param context Context object that has been created by vmaBeginDefragmentation(). +\param[out] pStats Optional stats for the defragmentation. Can be null. + +Use this function to finish defragmentation started by vmaBeginDefragmentation(). +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaEndDefragmentation( + VmaAllocator VMA_NOT_NULL allocator, + VmaDefragmentationContext VMA_NOT_NULL context, + VmaDefragmentationStats* VMA_NULLABLE pStats); + +/** \brief Starts single defragmentation pass. + +\param allocator Allocator object. +\param context Context object that has been created by vmaBeginDefragmentation(). +\param[out] pPassInfo Computed information for current pass. +\returns +- `VK_SUCCESS` if no more moves are possible. Then you can omit call to vmaEndDefragmentationPass() and simply end whole defragmentation. +- `VK_INCOMPLETE` if there are pending moves returned in `pPassInfo`. You need to perform them, call vmaEndDefragmentationPass(), + and then preferably try another pass with vmaBeginDefragmentationPass(). +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaBeginDefragmentationPass( + VmaAllocator VMA_NOT_NULL allocator, + VmaDefragmentationContext VMA_NOT_NULL context, + VmaDefragmentationPassMoveInfo* VMA_NOT_NULL pPassInfo); + +/** \brief Ends single defragmentation pass. + +\param allocator Allocator object. +\param context Context object that has been created by vmaBeginDefragmentation(). +\param pPassInfo Computed information for current pass filled by vmaBeginDefragmentationPass() and possibly modified by you. + +Returns `VK_SUCCESS` if no more moves are possible or `VK_INCOMPLETE` if more defragmentations are possible. + +Ends incremental defragmentation pass and commits all defragmentation moves from `pPassInfo`. +After this call: + +- Allocations at `pPassInfo[i].srcAllocation` that had `pPassInfo[i].operation ==` #VMA_DEFRAGMENTATION_MOVE_OPERATION_COPY + (which is the default) will be pointing to the new destination place. +- Allocation at `pPassInfo[i].srcAllocation` that had `pPassInfo[i].operation ==` #VMA_DEFRAGMENTATION_MOVE_OPERATION_DESTROY + will be freed. + +If no more moves are possible you can end whole defragmentation. +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaEndDefragmentationPass( + VmaAllocator VMA_NOT_NULL allocator, + VmaDefragmentationContext VMA_NOT_NULL context, + VmaDefragmentationPassMoveInfo* VMA_NOT_NULL pPassInfo); + +/** \brief Binds buffer to allocation. + +Binds specified buffer to region of memory represented by specified allocation. +Gets `VkDeviceMemory` handle and offset from the allocation. +If you want to create a buffer, allocate memory for it and bind them together separately, +you should use this function for binding instead of standard `vkBindBufferMemory()`, +because it ensures proper synchronization so that when a `VkDeviceMemory` object is used by multiple +allocations, calls to `vkBind*Memory()` or `vkMapMemory()` won't happen from multiple threads simultaneously +(which is illegal in Vulkan). + +It is recommended to use function vmaCreateBuffer() instead of this one. +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory( + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, + VkBuffer VMA_NOT_NULL_NON_DISPATCHABLE buffer); + +/** \brief Binds buffer to allocation with additional parameters. + +\param allocator +\param allocation +\param allocationLocalOffset Additional offset to be added while binding, relative to the beginning of the `allocation`. Normally it should be 0. +\param buffer +\param pNext A chain of structures to be attached to `VkBindBufferMemoryInfoKHR` structure used internally. Normally it should be null. + +This function is similar to vmaBindBufferMemory(), but it provides additional parameters. + +If `pNext` is not null, #VmaAllocator object must have been created with #VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT flag +or with VmaAllocatorCreateInfo::vulkanApiVersion `>= VK_API_VERSION_1_1`. Otherwise the call fails. +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory2( + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, + VkDeviceSize allocationLocalOffset, + VkBuffer VMA_NOT_NULL_NON_DISPATCHABLE buffer, + const void* VMA_NULLABLE VMA_EXTENDS_VK_STRUCT(VkBindBufferMemoryInfoKHR) pNext); + +/** \brief Binds image to allocation. + +Binds specified image to region of memory represented by specified allocation. +Gets `VkDeviceMemory` handle and offset from the allocation. +If you want to create an image, allocate memory for it and bind them together separately, +you should use this function for binding instead of standard `vkBindImageMemory()`, +because it ensures proper synchronization so that when a `VkDeviceMemory` object is used by multiple +allocations, calls to `vkBind*Memory()` or `vkMapMemory()` won't happen from multiple threads simultaneously +(which is illegal in Vulkan). + +It is recommended to use function vmaCreateImage() instead of this one. +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory( + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, + VkImage VMA_NOT_NULL_NON_DISPATCHABLE image); + +/** \brief Binds image to allocation with additional parameters. + +\param allocator +\param allocation +\param allocationLocalOffset Additional offset to be added while binding, relative to the beginning of the `allocation`. Normally it should be 0. +\param image +\param pNext A chain of structures to be attached to `VkBindImageMemoryInfoKHR` structure used internally. Normally it should be null. + +This function is similar to vmaBindImageMemory(), but it provides additional parameters. + +If `pNext` is not null, #VmaAllocator object must have been created with #VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT flag +or with VmaAllocatorCreateInfo::vulkanApiVersion `>= VK_API_VERSION_1_1`. Otherwise the call fails. +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory2( + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, + VkDeviceSize allocationLocalOffset, + VkImage VMA_NOT_NULL_NON_DISPATCHABLE image, + const void* VMA_NULLABLE VMA_EXTENDS_VK_STRUCT(VkBindImageMemoryInfoKHR) pNext); + +/** \brief Creates a new `VkBuffer`, allocates and binds memory for it. + +\param allocator +\param pBufferCreateInfo +\param pAllocationCreateInfo +\param[out] pBuffer Buffer that was created. +\param[out] pAllocation Allocation that was created. +\param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo(). + +This function automatically: + +-# Creates buffer. +-# Allocates appropriate memory for it. +-# Binds the buffer with the memory. + +If any of these operations fail, buffer and allocation are not created, +returned value is negative error code, `*pBuffer` and `*pAllocation` are null. + +If the function succeeded, you must destroy both buffer and allocation when you +no longer need them using either convenience function vmaDestroyBuffer() or +separately, using `vkDestroyBuffer()` and vmaFreeMemory(). + +If #VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT flag was used, +VK_KHR_dedicated_allocation extension is used internally to query driver whether +it requires or prefers the new buffer to have dedicated allocation. If yes, +and if dedicated allocation is possible +(#VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT is not used), it creates dedicated +allocation for this buffer, just like when using +#VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT. + +\note This function creates a new `VkBuffer`. Sub-allocation of parts of one large buffer, +although recommended as a good practice, is out of scope of this library and could be implemented +by the user as a higher-level logic on top of VMA. +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateBuffer( + VmaAllocator VMA_NOT_NULL allocator, + const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo, + const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo, + VkBuffer VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pBuffer, + VmaAllocation VMA_NULLABLE* VMA_NOT_NULL pAllocation, + VmaAllocationInfo* VMA_NULLABLE pAllocationInfo); + +/** \brief Creates a buffer with additional minimum alignment. + +Similar to vmaCreateBuffer() but provides additional parameter `minAlignment` which allows to specify custom, +minimum alignment to be used when placing the buffer inside a larger memory block, which may be needed e.g. +for interop with OpenGL. +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateBufferWithAlignment( + VmaAllocator VMA_NOT_NULL allocator, + const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo, + const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo, + VkDeviceSize minAlignment, + VkBuffer VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pBuffer, + VmaAllocation VMA_NULLABLE* VMA_NOT_NULL pAllocation, + VmaAllocationInfo* VMA_NULLABLE pAllocationInfo); + +/** \brief Creates a new `VkBuffer`, binds already created memory for it. + +\param allocator +\param allocation Allocation that provides memory to be used for binding new buffer to it. +\param pBufferCreateInfo +\param[out] pBuffer Buffer that was created. + +This function automatically: + +-# Creates buffer. +-# Binds the buffer with the supplied memory. + +If any of these operations fail, buffer is not created, +returned value is negative error code and `*pBuffer` is null. + +If the function succeeded, you must destroy the buffer when you +no longer need it using `vkDestroyBuffer()`. If you want to also destroy the corresponding +allocation you can use convenience function vmaDestroyBuffer(). + +\note There is a new version of this function augmented with parameter `allocationLocalOffset` - see vmaCreateAliasingBuffer2(). +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingBuffer( + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, + const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo, + VkBuffer VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pBuffer); + +/** \brief Creates a new `VkBuffer`, binds already created memory for it. + +\param allocator +\param allocation Allocation that provides memory to be used for binding new buffer to it. +\param allocationLocalOffset Additional offset to be added while binding, relative to the beginning of the allocation. Normally it should be 0. +\param pBufferCreateInfo +\param[out] pBuffer Buffer that was created. + +This function automatically: + +-# Creates buffer. +-# Binds the buffer with the supplied memory. + +If any of these operations fail, buffer is not created, +returned value is negative error code and `*pBuffer` is null. + +If the function succeeded, you must destroy the buffer when you +no longer need it using `vkDestroyBuffer()`. If you want to also destroy the corresponding +allocation you can use convenience function vmaDestroyBuffer(). + +\note This is a new version of the function augmented with parameter `allocationLocalOffset`. +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingBuffer2( + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, + VkDeviceSize allocationLocalOffset, + const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo, + VkBuffer VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pBuffer); + +/** \brief Destroys Vulkan buffer and frees allocated memory. + +This is just a convenience function equivalent to: + +\code +vkDestroyBuffer(device, buffer, allocationCallbacks); +vmaFreeMemory(allocator, allocation); +\endcode + +It is safe to pass null as buffer and/or allocation. +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaDestroyBuffer( + VmaAllocator VMA_NOT_NULL allocator, + VkBuffer VMA_NULLABLE_NON_DISPATCHABLE buffer, + VmaAllocation VMA_NULLABLE allocation); + +/// Function similar to vmaCreateBuffer(). +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateImage( + VmaAllocator VMA_NOT_NULL allocator, + const VkImageCreateInfo* VMA_NOT_NULL pImageCreateInfo, + const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo, + VkImage VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pImage, + VmaAllocation VMA_NULLABLE* VMA_NOT_NULL pAllocation, + VmaAllocationInfo* VMA_NULLABLE pAllocationInfo); + +/// Function similar to vmaCreateAliasingBuffer() but for images. +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingImage( + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, + const VkImageCreateInfo* VMA_NOT_NULL pImageCreateInfo, + VkImage VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pImage); + +/// Function similar to vmaCreateAliasingBuffer2() but for images. +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingImage2( + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, + VkDeviceSize allocationLocalOffset, + const VkImageCreateInfo* VMA_NOT_NULL pImageCreateInfo, + VkImage VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pImage); + +/** \brief Destroys Vulkan image and frees allocated memory. + +This is just a convenience function equivalent to: + +\code +vkDestroyImage(device, image, allocationCallbacks); +vmaFreeMemory(allocator, allocation); +\endcode + +It is safe to pass null as image and/or allocation. +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaDestroyImage( + VmaAllocator VMA_NOT_NULL allocator, + VkImage VMA_NULLABLE_NON_DISPATCHABLE image, + VmaAllocation VMA_NULLABLE allocation); + +/** @} */ + +/** +\addtogroup group_virtual +@{ +*/ + +/** \brief Creates new #VmaVirtualBlock object. + +\param pCreateInfo Parameters for creation. +\param[out] pVirtualBlock Returned virtual block object or `VMA_NULL` if creation failed. +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateVirtualBlock( + const VmaVirtualBlockCreateInfo* VMA_NOT_NULL pCreateInfo, + VmaVirtualBlock VMA_NULLABLE* VMA_NOT_NULL pVirtualBlock); + +/** \brief Destroys #VmaVirtualBlock object. + +Please note that you should consciously handle virtual allocations that could remain unfreed in the block. +You should either free them individually using vmaVirtualFree() or call vmaClearVirtualBlock() +if you are sure this is what you want. If you do neither, an assert is called. + +If you keep pointers to some additional metadata associated with your virtual allocations in their `pUserData`, +don't forget to free them. +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaDestroyVirtualBlock( + VmaVirtualBlock VMA_NULLABLE virtualBlock); + +/** \brief Returns true of the #VmaVirtualBlock is empty - contains 0 virtual allocations and has all its space available for new allocations. +*/ +VMA_CALL_PRE VkBool32 VMA_CALL_POST vmaIsVirtualBlockEmpty( + VmaVirtualBlock VMA_NOT_NULL virtualBlock); + +/** \brief Returns information about a specific virtual allocation within a virtual block, like its size and `pUserData` pointer. +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaGetVirtualAllocationInfo( + VmaVirtualBlock VMA_NOT_NULL virtualBlock, + VmaVirtualAllocation VMA_NOT_NULL_NON_DISPATCHABLE allocation, VmaVirtualAllocationInfo* VMA_NOT_NULL pVirtualAllocInfo); + +/** \brief Allocates new virtual allocation inside given #VmaVirtualBlock. + +If the allocation fails due to not enough free space available, `VK_ERROR_OUT_OF_DEVICE_MEMORY` is returned +(despite the function doesn't ever allocate actual GPU memory). +`pAllocation` is then set to `VK_NULL_HANDLE` and `pOffset`, if not null, it set to `UINT64_MAX`. + +\param virtualBlock Virtual block +\param pCreateInfo Parameters for the allocation +\param[out] pAllocation Returned handle of the new allocation +\param[out] pOffset Returned offset of the new allocation. Optional, can be null. +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaVirtualAllocate( + VmaVirtualBlock VMA_NOT_NULL virtualBlock, + const VmaVirtualAllocationCreateInfo* VMA_NOT_NULL pCreateInfo, + VmaVirtualAllocation VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pAllocation, + VkDeviceSize* VMA_NULLABLE pOffset); + +/** \brief Frees virtual allocation inside given #VmaVirtualBlock. + +It is correct to call this function with `allocation == VK_NULL_HANDLE` - it does nothing. +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaVirtualFree( + VmaVirtualBlock VMA_NOT_NULL virtualBlock, + VmaVirtualAllocation VMA_NULLABLE_NON_DISPATCHABLE allocation); + +/** \brief Frees all virtual allocations inside given #VmaVirtualBlock. + +You must either call this function or free each virtual allocation individually with vmaVirtualFree() +before destroying a virtual block. Otherwise, an assert is called. + +If you keep pointer to some additional metadata associated with your virtual allocation in its `pUserData`, +don't forget to free it as well. +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaClearVirtualBlock( + VmaVirtualBlock VMA_NOT_NULL virtualBlock); + +/** \brief Changes custom pointer associated with given virtual allocation. +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaSetVirtualAllocationUserData( + VmaVirtualBlock VMA_NOT_NULL virtualBlock, + VmaVirtualAllocation VMA_NOT_NULL_NON_DISPATCHABLE allocation, + void* VMA_NULLABLE pUserData); + +/** \brief Calculates and returns statistics about virtual allocations and memory usage in given #VmaVirtualBlock. + +This function is fast to call. For more detailed statistics, see vmaCalculateVirtualBlockStatistics(). +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaGetVirtualBlockStatistics( + VmaVirtualBlock VMA_NOT_NULL virtualBlock, + VmaStatistics* VMA_NOT_NULL pStats); + +/** \brief Calculates and returns detailed statistics about virtual allocations and memory usage in given #VmaVirtualBlock. + +This function is slow to call. Use for debugging purposes. +For less detailed statistics, see vmaGetVirtualBlockStatistics(). +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaCalculateVirtualBlockStatistics( + VmaVirtualBlock VMA_NOT_NULL virtualBlock, + VmaDetailedStatistics* VMA_NOT_NULL pStats); + +/** @} */ + +#if VMA_STATS_STRING_ENABLED +/** +\addtogroup group_stats +@{ +*/ + +/** \brief Builds and returns a null-terminated string in JSON format with information about given #VmaVirtualBlock. +\param virtualBlock Virtual block. +\param[out] ppStatsString Returned string. +\param detailedMap Pass `VK_FALSE` to only obtain statistics as returned by vmaCalculateVirtualBlockStatistics(). Pass `VK_TRUE` to also obtain full list of allocations and free spaces. + +Returned string must be freed using vmaFreeVirtualBlockStatsString(). +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaBuildVirtualBlockStatsString( + VmaVirtualBlock VMA_NOT_NULL virtualBlock, + char* VMA_NULLABLE* VMA_NOT_NULL ppStatsString, + VkBool32 detailedMap); + +/// Frees a string returned by vmaBuildVirtualBlockStatsString(). +VMA_CALL_PRE void VMA_CALL_POST vmaFreeVirtualBlockStatsString( + VmaVirtualBlock VMA_NOT_NULL virtualBlock, + char* VMA_NULLABLE pStatsString); + +/** \brief Builds and returns statistics as a null-terminated string in JSON format. +\param allocator +\param[out] ppStatsString Must be freed using vmaFreeStatsString() function. +\param detailedMap +*/ +VMA_CALL_PRE void VMA_CALL_POST vmaBuildStatsString( + VmaAllocator VMA_NOT_NULL allocator, + char* VMA_NULLABLE* VMA_NOT_NULL ppStatsString, + VkBool32 detailedMap); + +VMA_CALL_PRE void VMA_CALL_POST vmaFreeStatsString( + VmaAllocator VMA_NOT_NULL allocator, + char* VMA_NULLABLE pStatsString); + +/** @} */ + +#endif // VMA_STATS_STRING_ENABLED + +#endif // _VMA_FUNCTION_HEADERS + +#ifdef __cplusplus +} +#endif + +#endif // AMD_VULKAN_MEMORY_ALLOCATOR_H + +//////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// +// +// IMPLEMENTATION +// +//////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// + +// For Visual Studio IntelliSense. +#if defined(__cplusplus) && defined(__INTELLISENSE__) +#define VMA_IMPLEMENTATION +#endif + +#ifdef VMA_IMPLEMENTATION +#undef VMA_IMPLEMENTATION + +#include +#include +#include +#include +#include +#include + +#if !defined(VMA_CPP20) + #if __cplusplus >= 202002L || _MSVC_LANG >= 202002L // C++20 + #define VMA_CPP20 1 + #else + #define VMA_CPP20 0 + #endif +#endif + +#ifdef _MSC_VER + #include // For functions like __popcnt, _BitScanForward etc. +#endif +#if VMA_CPP20 + #include +#endif + +#if VMA_STATS_STRING_ENABLED + #include // For snprintf +#endif + +/******************************************************************************* +CONFIGURATION SECTION + +Define some of these macros before each #include of this header or change them +here if you need other then default behavior depending on your environment. +*/ +#ifndef _VMA_CONFIGURATION + +/* +Define this macro to 1 to make the library fetch pointers to Vulkan functions +internally, like: + + vulkanFunctions.vkAllocateMemory = &vkAllocateMemory; +*/ +#if !defined(VMA_STATIC_VULKAN_FUNCTIONS) && !defined(VK_NO_PROTOTYPES) + #define VMA_STATIC_VULKAN_FUNCTIONS 1 +#endif + +/* +Define this macro to 1 to make the library fetch pointers to Vulkan functions +internally, like: + + vulkanFunctions.vkAllocateMemory = (PFN_vkAllocateMemory)vkGetDeviceProcAddr(device, "vkAllocateMemory"); + +To use this feature in new versions of VMA you now have to pass +VmaVulkanFunctions::vkGetInstanceProcAddr and vkGetDeviceProcAddr as +VmaAllocatorCreateInfo::pVulkanFunctions. Other members can be null. +*/ +#if !defined(VMA_DYNAMIC_VULKAN_FUNCTIONS) + #define VMA_DYNAMIC_VULKAN_FUNCTIONS 1 +#endif + +#ifndef VMA_USE_STL_SHARED_MUTEX + #if __cplusplus >= 201703L || _MSVC_LANG >= 201703L // C++17 + #define VMA_USE_STL_SHARED_MUTEX 1 + // Visual studio defines __cplusplus properly only when passed additional parameter: /Zc:__cplusplus + // Otherwise it is always 199711L, despite shared_mutex works since Visual Studio 2015 Update 2. + #elif defined(_MSC_FULL_VER) && _MSC_FULL_VER >= 190023918 && __cplusplus == 199711L && _MSVC_LANG >= 201703L + #define VMA_USE_STL_SHARED_MUTEX 1 + #else + #define VMA_USE_STL_SHARED_MUTEX 0 + #endif +#endif + +/* +Define this macro to include custom header files without having to edit this file directly, e.g.: + + // Inside of "my_vma_configuration_user_includes.h": + + #include "my_custom_assert.h" // for MY_CUSTOM_ASSERT + #include "my_custom_min.h" // for my_custom_min + #include + #include + + // Inside a different file, which includes "vk_mem_alloc.h": + + #define VMA_CONFIGURATION_USER_INCLUDES_H "my_vma_configuration_user_includes.h" + #define VMA_ASSERT(expr) MY_CUSTOM_ASSERT(expr) + #define VMA_MIN(v1, v2) (my_custom_min(v1, v2)) + #include "vk_mem_alloc.h" + ... + +The following headers are used in this CONFIGURATION section only, so feel free to +remove them if not needed. +*/ +#if !defined(VMA_CONFIGURATION_USER_INCLUDES_H) + #include // for assert + #include // for min, max, swap + #include +#else + #include VMA_CONFIGURATION_USER_INCLUDES_H +#endif + +#ifndef VMA_NULL + // Value used as null pointer. Define it to e.g.: nullptr, NULL, 0, (void*)0. + #define VMA_NULL nullptr +#endif + +#ifndef VMA_FALLTHROUGH + #if __cplusplus >= 201703L || _MSVC_LANG >= 201703L // C++17 + #define VMA_FALLTHROUGH [[fallthrough]] + #else + #define VMA_FALLTHROUGH + #endif +#endif + +// Normal assert to check for programmer's errors, especially in Debug configuration. +#ifndef VMA_ASSERT + #ifdef NDEBUG + #define VMA_ASSERT(expr) + #else + #define VMA_ASSERT(expr) assert(expr) + #endif +#endif + +// Assert that will be called very often, like inside data structures e.g. operator[]. +// Making it non-empty can make program slow. +#ifndef VMA_HEAVY_ASSERT + #ifdef NDEBUG + #define VMA_HEAVY_ASSERT(expr) + #else + #define VMA_HEAVY_ASSERT(expr) //VMA_ASSERT(expr) + #endif +#endif + +// Assert used for reporting memory leaks - unfreed allocations. +#ifndef VMA_ASSERT_LEAK + #define VMA_ASSERT_LEAK(expr) VMA_ASSERT(expr) +#endif + +// If your compiler is not compatible with C++17 and definition of +// aligned_alloc() function is missing, uncommenting following line may help: + +//#include + +#if defined(__ANDROID_API__) && (__ANDROID_API__ < 16) +#include +static void* vma_aligned_alloc(size_t alignment, size_t size) +{ + // alignment must be >= sizeof(void*) + if(alignment < sizeof(void*)) + { + alignment = sizeof(void*); + } + + return memalign(alignment, size); +} +#elif defined(__APPLE__) || defined(__ANDROID__) || (defined(__linux__) && defined(__GLIBCXX__) && !defined(_GLIBCXX_HAVE_ALIGNED_ALLOC)) +#include + +#if defined(__APPLE__) +#include +#endif + +static void* vma_aligned_alloc(size_t alignment, size_t size) +{ + // Unfortunately, aligned_alloc causes VMA to crash due to it returning null pointers. (At least under 11.4) + // Therefore, for now disable this specific exception until a proper solution is found. + //#if defined(__APPLE__) && (defined(MAC_OS_X_VERSION_10_16) || defined(__IPHONE_14_0)) + //#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_16 || __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_14_0 + // // For C++14, usr/include/malloc/_malloc.h declares aligned_alloc()) only + // // with the MacOSX11.0 SDK in Xcode 12 (which is what adds + // // MAC_OS_X_VERSION_10_16), even though the function is marked + // // available for 10.15. That is why the preprocessor checks for 10.16 but + // // the __builtin_available checks for 10.15. + // // People who use C++17 could call aligned_alloc with the 10.15 SDK already. + // if (__builtin_available(macOS 10.15, iOS 13, *)) + // return aligned_alloc(alignment, size); + //#endif + //#endif + + // alignment must be >= sizeof(void*) + if(alignment < sizeof(void*)) + { + alignment = sizeof(void*); + } + + void *pointer; + if(posix_memalign(&pointer, alignment, size) == 0) + return pointer; + return VMA_NULL; +} +#elif defined(_WIN32) +static void* vma_aligned_alloc(size_t alignment, size_t size) +{ + return _aligned_malloc(size, alignment); +} +#elif __cplusplus >= 201703L || _MSVC_LANG >= 201703L // C++17 +static void* vma_aligned_alloc(size_t alignment, size_t size) +{ + return aligned_alloc(alignment, size); +} +#else +static void* vma_aligned_alloc(size_t alignment, size_t size) +{ + VMA_ASSERT(0 && "Could not implement aligned_alloc automatically. Please enable C++17 or later in your compiler or provide custom implementation of macro VMA_SYSTEM_ALIGNED_MALLOC (and VMA_SYSTEM_ALIGNED_FREE if needed) using the API of your system."); + return VMA_NULL; +} +#endif + +#if defined(_WIN32) +static void vma_aligned_free(void* ptr) +{ + _aligned_free(ptr); +} +#else +static void vma_aligned_free(void* VMA_NULLABLE ptr) +{ + free(ptr); +} +#endif + +#ifndef VMA_ALIGN_OF + #define VMA_ALIGN_OF(type) (alignof(type)) +#endif + +#ifndef VMA_SYSTEM_ALIGNED_MALLOC + #define VMA_SYSTEM_ALIGNED_MALLOC(size, alignment) vma_aligned_alloc((alignment), (size)) +#endif + +#ifndef VMA_SYSTEM_ALIGNED_FREE + // VMA_SYSTEM_FREE is the old name, but might have been defined by the user + #if defined(VMA_SYSTEM_FREE) + #define VMA_SYSTEM_ALIGNED_FREE(ptr) VMA_SYSTEM_FREE(ptr) + #else + #define VMA_SYSTEM_ALIGNED_FREE(ptr) vma_aligned_free(ptr) + #endif +#endif + +#ifndef VMA_COUNT_BITS_SET + // Returns number of bits set to 1 in (v) + #define VMA_COUNT_BITS_SET(v) VmaCountBitsSet(v) +#endif + +#ifndef VMA_BITSCAN_LSB + // Scans integer for index of first nonzero value from the Least Significant Bit (LSB). If mask is 0 then returns UINT8_MAX + #define VMA_BITSCAN_LSB(mask) VmaBitScanLSB(mask) +#endif + +#ifndef VMA_BITSCAN_MSB + // Scans integer for index of first nonzero value from the Most Significant Bit (MSB). If mask is 0 then returns UINT8_MAX + #define VMA_BITSCAN_MSB(mask) VmaBitScanMSB(mask) +#endif + +#ifndef VMA_MIN + #define VMA_MIN(v1, v2) ((std::min)((v1), (v2))) +#endif + +#ifndef VMA_MAX + #define VMA_MAX(v1, v2) ((std::max)((v1), (v2))) +#endif + +#ifndef VMA_SORT + #define VMA_SORT(beg, end, cmp) std::sort(beg, end, cmp) +#endif + +#ifndef VMA_DEBUG_LOG_FORMAT + #define VMA_DEBUG_LOG_FORMAT(format, ...) + /* + #define VMA_DEBUG_LOG_FORMAT(format, ...) do { \ + printf((format), __VA_ARGS__); \ + printf("\n"); \ + } while(false) + */ +#endif + +#ifndef VMA_DEBUG_LOG + #define VMA_DEBUG_LOG(str) VMA_DEBUG_LOG_FORMAT("%s", (str)) +#endif + +#ifndef VMA_LEAK_LOG_FORMAT + #define VMA_LEAK_LOG_FORMAT(format, ...) VMA_DEBUG_LOG_FORMAT(format, __VA_ARGS__) +#endif + +#ifndef VMA_CLASS_NO_COPY + #define VMA_CLASS_NO_COPY(className) \ + private: \ + className(const className&) = delete; \ + className& operator=(const className&) = delete; +#endif +#ifndef VMA_CLASS_NO_COPY_NO_MOVE + #define VMA_CLASS_NO_COPY_NO_MOVE(className) \ + private: \ + className(const className&) = delete; \ + className(className&&) = delete; \ + className& operator=(const className&) = delete; \ + className& operator=(className&&) = delete; +#endif + +// Define this macro to 1 to enable functions: vmaBuildStatsString, vmaFreeStatsString. +#if VMA_STATS_STRING_ENABLED + static inline void VmaUint32ToStr(char* VMA_NOT_NULL outStr, size_t strLen, uint32_t num) + { + snprintf(outStr, strLen, "%" PRIu32, num); + } + static inline void VmaUint64ToStr(char* VMA_NOT_NULL outStr, size_t strLen, uint64_t num) + { + snprintf(outStr, strLen, "%" PRIu64, num); + } + static inline void VmaPtrToStr(char* VMA_NOT_NULL outStr, size_t strLen, const void* ptr) + { + snprintf(outStr, strLen, "%p", ptr); + } +#endif + +#ifndef VMA_MUTEX + class VmaMutex + { + VMA_CLASS_NO_COPY_NO_MOVE(VmaMutex) + public: + VmaMutex() { } + void Lock() { m_Mutex.lock(); } + void Unlock() { m_Mutex.unlock(); } + bool TryLock() { return m_Mutex.try_lock(); } + private: + std::mutex m_Mutex; + }; + #define VMA_MUTEX VmaMutex +#endif + +// Read-write mutex, where "read" is shared access, "write" is exclusive access. +#ifndef VMA_RW_MUTEX + #if VMA_USE_STL_SHARED_MUTEX + // Use std::shared_mutex from C++17. + #include + class VmaRWMutex + { + public: + void LockRead() { m_Mutex.lock_shared(); } + void UnlockRead() { m_Mutex.unlock_shared(); } + bool TryLockRead() { return m_Mutex.try_lock_shared(); } + void LockWrite() { m_Mutex.lock(); } + void UnlockWrite() { m_Mutex.unlock(); } + bool TryLockWrite() { return m_Mutex.try_lock(); } + private: + std::shared_mutex m_Mutex; + }; + #define VMA_RW_MUTEX VmaRWMutex + #elif defined(_WIN32) && defined(WINVER) && defined(SRWLOCK_INIT) && WINVER >= 0x0600 + // Use SRWLOCK from WinAPI. + // Minimum supported client = Windows Vista, server = Windows Server 2008. + class VmaRWMutex + { + public: + VmaRWMutex() { InitializeSRWLock(&m_Lock); } + void LockRead() { AcquireSRWLockShared(&m_Lock); } + void UnlockRead() { ReleaseSRWLockShared(&m_Lock); } + bool TryLockRead() { return TryAcquireSRWLockShared(&m_Lock) != FALSE; } + void LockWrite() { AcquireSRWLockExclusive(&m_Lock); } + void UnlockWrite() { ReleaseSRWLockExclusive(&m_Lock); } + bool TryLockWrite() { return TryAcquireSRWLockExclusive(&m_Lock) != FALSE; } + private: + SRWLOCK m_Lock; + }; + #define VMA_RW_MUTEX VmaRWMutex + #else + // Less efficient fallback: Use normal mutex. + class VmaRWMutex + { + public: + void LockRead() { m_Mutex.Lock(); } + void UnlockRead() { m_Mutex.Unlock(); } + bool TryLockRead() { return m_Mutex.TryLock(); } + void LockWrite() { m_Mutex.Lock(); } + void UnlockWrite() { m_Mutex.Unlock(); } + bool TryLockWrite() { return m_Mutex.TryLock(); } + private: + VMA_MUTEX m_Mutex; + }; + #define VMA_RW_MUTEX VmaRWMutex + #endif // #if VMA_USE_STL_SHARED_MUTEX +#endif // #ifndef VMA_RW_MUTEX + +/* +If providing your own implementation, you need to implement a subset of std::atomic. +*/ +#ifndef VMA_ATOMIC_UINT32 + #include + #define VMA_ATOMIC_UINT32 std::atomic +#endif + +#ifndef VMA_ATOMIC_UINT64 + #include + #define VMA_ATOMIC_UINT64 std::atomic +#endif + +#ifndef VMA_DEBUG_ALWAYS_DEDICATED_MEMORY + /** + Every allocation will have its own memory block. + Define to 1 for debugging purposes only. + */ + #define VMA_DEBUG_ALWAYS_DEDICATED_MEMORY (0) +#endif + +#ifndef VMA_MIN_ALIGNMENT + /** + Minimum alignment of all allocations, in bytes. + Set to more than 1 for debugging purposes. Must be power of two. + */ + #ifdef VMA_DEBUG_ALIGNMENT // Old name + #define VMA_MIN_ALIGNMENT VMA_DEBUG_ALIGNMENT + #else + #define VMA_MIN_ALIGNMENT (1) + #endif +#endif + +#ifndef VMA_DEBUG_MARGIN + /** + Minimum margin after every allocation, in bytes. + Set nonzero for debugging purposes only. + */ + #define VMA_DEBUG_MARGIN (0) +#endif + +#ifndef VMA_DEBUG_INITIALIZE_ALLOCATIONS + /** + Define this macro to 1 to automatically fill new allocations and destroyed + allocations with some bit pattern. + */ + #define VMA_DEBUG_INITIALIZE_ALLOCATIONS (0) +#endif + +#ifndef VMA_DEBUG_DETECT_CORRUPTION + /** + Define this macro to 1 together with non-zero value of VMA_DEBUG_MARGIN to + enable writing magic value to the margin after every allocation and + validating it, so that memory corruptions (out-of-bounds writes) are detected. + */ + #define VMA_DEBUG_DETECT_CORRUPTION (0) +#endif + +#ifndef VMA_DEBUG_GLOBAL_MUTEX + /** + Set this to 1 for debugging purposes only, to enable single mutex protecting all + entry calls to the library. Can be useful for debugging multithreading issues. + */ + #define VMA_DEBUG_GLOBAL_MUTEX (0) +#endif + +#ifndef VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY + /** + Minimum value for VkPhysicalDeviceLimits::bufferImageGranularity. + Set to more than 1 for debugging purposes only. Must be power of two. + */ + #define VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY (1) +#endif + +#ifndef VMA_DEBUG_DONT_EXCEED_MAX_MEMORY_ALLOCATION_COUNT + /* + Set this to 1 to make VMA never exceed VkPhysicalDeviceLimits::maxMemoryAllocationCount + and return error instead of leaving up to Vulkan implementation what to do in such cases. + */ + #define VMA_DEBUG_DONT_EXCEED_MAX_MEMORY_ALLOCATION_COUNT (0) +#endif + +#ifndef VMA_SMALL_HEAP_MAX_SIZE + /// Maximum size of a memory heap in Vulkan to consider it "small". + #define VMA_SMALL_HEAP_MAX_SIZE (1024ull * 1024 * 1024) +#endif + +#ifndef VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE + /// Default size of a block allocated as single VkDeviceMemory from a "large" heap. + #define VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE (256ull * 1024 * 1024) +#endif + +/* +Mapping hysteresis is a logic that launches when vmaMapMemory/vmaUnmapMemory is called +or a persistently mapped allocation is created and destroyed several times in a row. +It keeps additional +1 mapping of a device memory block to prevent calling actual +vkMapMemory/vkUnmapMemory too many times, which may improve performance and help +tools like RenderDoc. +*/ +#ifndef VMA_MAPPING_HYSTERESIS_ENABLED + #define VMA_MAPPING_HYSTERESIS_ENABLED 1 +#endif + +#define VMA_VALIDATE(cond) do { if(!(cond)) { \ + VMA_ASSERT(0 && "Validation failed: " #cond); \ + return false; \ + } } while(false) + +/******************************************************************************* +END OF CONFIGURATION +*/ +#endif // _VMA_CONFIGURATION + + +static const uint8_t VMA_ALLOCATION_FILL_PATTERN_CREATED = 0xDC; +static const uint8_t VMA_ALLOCATION_FILL_PATTERN_DESTROYED = 0xEF; +// Decimal 2139416166, float NaN, little-endian binary 66 E6 84 7F. +static const uint32_t VMA_CORRUPTION_DETECTION_MAGIC_VALUE = 0x7F84E666; + +// Copy of some Vulkan definitions so we don't need to check their existence just to handle few constants. +static const uint32_t VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD_COPY = 0x00000040; +static const uint32_t VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD_COPY = 0x00000080; +static const uint32_t VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_COPY = 0x00020000; +static const uint32_t VK_IMAGE_CREATE_DISJOINT_BIT_COPY = 0x00000200; +static const int32_t VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT_COPY = 1000158000; +static const uint32_t VMA_ALLOCATION_INTERNAL_STRATEGY_MIN_OFFSET = 0x10000000u; +static const uint32_t VMA_ALLOCATION_TRY_COUNT = 32; +static const uint32_t VMA_VENDOR_ID_AMD = 4098; + +// This one is tricky. Vulkan specification defines this code as available since +// Vulkan 1.0, but doesn't actually define it in Vulkan SDK earlier than 1.2.131. +// See pull request #207. +#define VK_ERROR_UNKNOWN_COPY ((VkResult)-13) + + +#if VMA_STATS_STRING_ENABLED +// Correspond to values of enum VmaSuballocationType. +static const char* VMA_SUBALLOCATION_TYPE_NAMES[] = +{ + "FREE", + "UNKNOWN", + "BUFFER", + "IMAGE_UNKNOWN", + "IMAGE_LINEAR", + "IMAGE_OPTIMAL", +}; +#endif + +static VkAllocationCallbacks VmaEmptyAllocationCallbacks = + { VMA_NULL, VMA_NULL, VMA_NULL, VMA_NULL, VMA_NULL, VMA_NULL }; + + +#ifndef _VMA_ENUM_DECLARATIONS + +enum VmaSuballocationType +{ + VMA_SUBALLOCATION_TYPE_FREE = 0, + VMA_SUBALLOCATION_TYPE_UNKNOWN = 1, + VMA_SUBALLOCATION_TYPE_BUFFER = 2, + VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN = 3, + VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR = 4, + VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL = 5, + VMA_SUBALLOCATION_TYPE_MAX_ENUM = 0x7FFFFFFF +}; + +enum VMA_CACHE_OPERATION +{ + VMA_CACHE_FLUSH, + VMA_CACHE_INVALIDATE +}; + +enum class VmaAllocationRequestType +{ + Normal, + TLSF, + // Used by "Linear" algorithm. + UpperAddress, + EndOf1st, + EndOf2nd, +}; + +#endif // _VMA_ENUM_DECLARATIONS + +#ifndef _VMA_FORWARD_DECLARATIONS +// Opaque handle used by allocation algorithms to identify single allocation in any conforming way. +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VmaAllocHandle); + +struct VmaMutexLock; +struct VmaMutexLockRead; +struct VmaMutexLockWrite; + +template +struct AtomicTransactionalIncrement; + +template +struct VmaStlAllocator; + +template +class VmaVector; + +template +class VmaSmallVector; + +template +class VmaPoolAllocator; + +template +struct VmaListItem; + +template +class VmaRawList; + +template +class VmaList; + +template +class VmaIntrusiveLinkedList; + +#if VMA_STATS_STRING_ENABLED +class VmaStringBuilder; +class VmaJsonWriter; +#endif + +class VmaDeviceMemoryBlock; + +struct VmaDedicatedAllocationListItemTraits; +class VmaDedicatedAllocationList; + +struct VmaSuballocation; +struct VmaSuballocationOffsetLess; +struct VmaSuballocationOffsetGreater; +struct VmaSuballocationItemSizeLess; + +typedef VmaList> VmaSuballocationList; + +struct VmaAllocationRequest; + +class VmaBlockMetadata; +class VmaBlockMetadata_Linear; +class VmaBlockMetadata_TLSF; + +class VmaBlockVector; + +struct VmaPoolListItemTraits; + +struct VmaCurrentBudgetData; + +class VmaAllocationObjectAllocator; + +#endif // _VMA_FORWARD_DECLARATIONS + + +#ifndef _VMA_FUNCTIONS + +/* +Returns number of bits set to 1 in (v). + +On specific platforms and compilers you can use intrinsics like: + +Visual Studio: + return __popcnt(v); +GCC, Clang: + return static_cast(__builtin_popcount(v)); + +Define macro VMA_COUNT_BITS_SET to provide your optimized implementation. +But you need to check in runtime whether user's CPU supports these, as some old processors don't. +*/ +static inline uint32_t VmaCountBitsSet(uint32_t v) +{ +#if VMA_CPP20 + return std::popcount(v); +#else + uint32_t c = v - ((v >> 1) & 0x55555555); + c = ((c >> 2) & 0x33333333) + (c & 0x33333333); + c = ((c >> 4) + c) & 0x0F0F0F0F; + c = ((c >> 8) + c) & 0x00FF00FF; + c = ((c >> 16) + c) & 0x0000FFFF; + return c; +#endif +} + +static inline uint8_t VmaBitScanLSB(uint64_t mask) +{ +#if defined(_MSC_VER) && defined(_WIN64) + unsigned long pos; + if (_BitScanForward64(&pos, mask)) + return static_cast(pos); + return UINT8_MAX; +#elif VMA_CPP20 + if(mask) + return static_cast(std::countr_zero(mask)); + return UINT8_MAX; +#elif defined __GNUC__ || defined __clang__ + return static_cast(__builtin_ffsll(mask)) - 1U; +#else + uint8_t pos = 0; + uint64_t bit = 1; + do + { + if (mask & bit) + return pos; + bit <<= 1; + } while (pos++ < 63); + return UINT8_MAX; +#endif +} + +static inline uint8_t VmaBitScanLSB(uint32_t mask) +{ +#ifdef _MSC_VER + unsigned long pos; + if (_BitScanForward(&pos, mask)) + return static_cast(pos); + return UINT8_MAX; +#elif VMA_CPP20 + if(mask) + return static_cast(std::countr_zero(mask)); + return UINT8_MAX; +#elif defined __GNUC__ || defined __clang__ + return static_cast(__builtin_ffs(mask)) - 1U; +#else + uint8_t pos = 0; + uint32_t bit = 1; + do + { + if (mask & bit) + return pos; + bit <<= 1; + } while (pos++ < 31); + return UINT8_MAX; +#endif +} + +static inline uint8_t VmaBitScanMSB(uint64_t mask) +{ +#if defined(_MSC_VER) && defined(_WIN64) + unsigned long pos; + if (_BitScanReverse64(&pos, mask)) + return static_cast(pos); +#elif VMA_CPP20 + if(mask) + return 63 - static_cast(std::countl_zero(mask)); +#elif defined __GNUC__ || defined __clang__ + if (mask) + return 63 - static_cast(__builtin_clzll(mask)); +#else + uint8_t pos = 63; + uint64_t bit = 1ULL << 63; + do + { + if (mask & bit) + return pos; + bit >>= 1; + } while (pos-- > 0); +#endif + return UINT8_MAX; +} + +static inline uint8_t VmaBitScanMSB(uint32_t mask) +{ +#ifdef _MSC_VER + unsigned long pos; + if (_BitScanReverse(&pos, mask)) + return static_cast(pos); +#elif VMA_CPP20 + if(mask) + return 31 - static_cast(std::countl_zero(mask)); +#elif defined __GNUC__ || defined __clang__ + if (mask) + return 31 - static_cast(__builtin_clz(mask)); +#else + uint8_t pos = 31; + uint32_t bit = 1UL << 31; + do + { + if (mask & bit) + return pos; + bit >>= 1; + } while (pos-- > 0); +#endif + return UINT8_MAX; +} + +/* +Returns true if given number is a power of two. +T must be unsigned integer number or signed integer but always nonnegative. +For 0 returns true. +*/ +template +inline bool VmaIsPow2(T x) +{ + return (x & (x - 1)) == 0; +} + +// Aligns given value up to nearest multiply of align value. For example: VmaAlignUp(11, 8) = 16. +// Use types like uint32_t, uint64_t as T. +template +static inline T VmaAlignUp(T val, T alignment) +{ + VMA_HEAVY_ASSERT(VmaIsPow2(alignment)); + return (val + alignment - 1) & ~(alignment - 1); +} + +// Aligns given value down to nearest multiply of align value. For example: VmaAlignDown(11, 8) = 8. +// Use types like uint32_t, uint64_t as T. +template +static inline T VmaAlignDown(T val, T alignment) +{ + VMA_HEAVY_ASSERT(VmaIsPow2(alignment)); + return val & ~(alignment - 1); +} + +// Division with mathematical rounding to nearest number. +template +static inline T VmaRoundDiv(T x, T y) +{ + return (x + (y / (T)2)) / y; +} + +// Divide by 'y' and round up to nearest integer. +template +static inline T VmaDivideRoundingUp(T x, T y) +{ + return (x + y - (T)1) / y; +} + +// Returns smallest power of 2 greater or equal to v. +static inline uint32_t VmaNextPow2(uint32_t v) +{ + v--; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + v++; + return v; +} + +static inline uint64_t VmaNextPow2(uint64_t v) +{ + v--; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + v |= v >> 32; + v++; + return v; +} + +// Returns largest power of 2 less or equal to v. +static inline uint32_t VmaPrevPow2(uint32_t v) +{ + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + v = v ^ (v >> 1); + return v; +} + +static inline uint64_t VmaPrevPow2(uint64_t v) +{ + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + v |= v >> 32; + v = v ^ (v >> 1); + return v; +} + +static inline bool VmaStrIsEmpty(const char* pStr) +{ + return pStr == VMA_NULL || *pStr == '\0'; +} + +/* +Returns true if two memory blocks occupy overlapping pages. +ResourceA must be in less memory offset than ResourceB. + +Algorithm is based on "Vulkan 1.0.39 - A Specification (with all registered Vulkan extensions)" +chapter 11.6 "Resource Memory Association", paragraph "Buffer-Image Granularity". +*/ +static inline bool VmaBlocksOnSamePage( + VkDeviceSize resourceAOffset, + VkDeviceSize resourceASize, + VkDeviceSize resourceBOffset, + VkDeviceSize pageSize) +{ + VMA_ASSERT(resourceAOffset + resourceASize <= resourceBOffset && resourceASize > 0 && pageSize > 0); + VkDeviceSize resourceAEnd = resourceAOffset + resourceASize - 1; + VkDeviceSize resourceAEndPage = resourceAEnd & ~(pageSize - 1); + VkDeviceSize resourceBStart = resourceBOffset; + VkDeviceSize resourceBStartPage = resourceBStart & ~(pageSize - 1); + return resourceAEndPage == resourceBStartPage; +} + +/* +Returns true if given suballocation types could conflict and must respect +VkPhysicalDeviceLimits::bufferImageGranularity. They conflict if one is buffer +or linear image and another one is optimal image. If type is unknown, behave +conservatively. +*/ +static inline bool VmaIsBufferImageGranularityConflict( + VmaSuballocationType suballocType1, + VmaSuballocationType suballocType2) +{ + if (suballocType1 > suballocType2) + { + std::swap(suballocType1, suballocType2); + } + + switch (suballocType1) + { + case VMA_SUBALLOCATION_TYPE_FREE: + return false; + case VMA_SUBALLOCATION_TYPE_UNKNOWN: + return true; + case VMA_SUBALLOCATION_TYPE_BUFFER: + return + suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN || + suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL; + case VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN: + return + suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN || + suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR || + suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL; + case VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR: + return + suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL; + case VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL: + return false; + default: + VMA_ASSERT(0); + return true; + } +} + +static void VmaWriteMagicValue(void* pData, VkDeviceSize offset) +{ +#if VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_DETECT_CORRUPTION + uint32_t* pDst = (uint32_t*)((char*)pData + offset); + const size_t numberCount = VMA_DEBUG_MARGIN / sizeof(uint32_t); + for (size_t i = 0; i < numberCount; ++i, ++pDst) + { + *pDst = VMA_CORRUPTION_DETECTION_MAGIC_VALUE; + } +#else + // no-op +#endif +} + +static bool VmaValidateMagicValue(const void* pData, VkDeviceSize offset) +{ +#if VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_DETECT_CORRUPTION + const uint32_t* pSrc = (const uint32_t*)((const char*)pData + offset); + const size_t numberCount = VMA_DEBUG_MARGIN / sizeof(uint32_t); + for (size_t i = 0; i < numberCount; ++i, ++pSrc) + { + if (*pSrc != VMA_CORRUPTION_DETECTION_MAGIC_VALUE) + { + return false; + } + } +#endif + return true; +} + +/* +Fills structure with parameters of an example buffer to be used for transfers +during GPU memory defragmentation. +*/ +static void VmaFillGpuDefragmentationBufferCreateInfo(VkBufferCreateInfo& outBufCreateInfo) +{ + memset(&outBufCreateInfo, 0, sizeof(outBufCreateInfo)); + outBufCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + outBufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + outBufCreateInfo.size = (VkDeviceSize)VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE; // Example size. +} + + +/* +Performs binary search and returns iterator to first element that is greater or +equal to (key), according to comparison (cmp). + +Cmp should return true if first argument is less than second argument. + +Returned value is the found element, if present in the collection or place where +new element with value (key) should be inserted. +*/ +template +static IterT VmaBinaryFindFirstNotLess(IterT beg, IterT end, const KeyT& key, const CmpLess& cmp) +{ + size_t down = 0, up = size_t(end - beg); + while (down < up) + { + const size_t mid = down + (up - down) / 2; // Overflow-safe midpoint calculation + if (cmp(*(beg + mid), key)) + { + down = mid + 1; + } + else + { + up = mid; + } + } + return beg + down; +} + +template +IterT VmaBinaryFindSorted(const IterT& beg, const IterT& end, const KeyT& value, const CmpLess& cmp) +{ + IterT it = VmaBinaryFindFirstNotLess( + beg, end, value, cmp); + if (it == end || + (!cmp(*it, value) && !cmp(value, *it))) + { + return it; + } + return end; +} + +/* +Returns true if all pointers in the array are not-null and unique. +Warning! O(n^2) complexity. Use only inside VMA_HEAVY_ASSERT. +T must be pointer type, e.g. VmaAllocation, VmaPool. +*/ +template +static bool VmaValidatePointerArray(uint32_t count, const T* arr) +{ + for (uint32_t i = 0; i < count; ++i) + { + const T iPtr = arr[i]; + if (iPtr == VMA_NULL) + { + return false; + } + for (uint32_t j = i + 1; j < count; ++j) + { + if (iPtr == arr[j]) + { + return false; + } + } + } + return true; +} + +template +static inline void VmaPnextChainPushFront(MainT* mainStruct, NewT* newStruct) +{ + newStruct->pNext = mainStruct->pNext; + mainStruct->pNext = newStruct; +} +// Finds structure with s->sType == sType in mainStruct->pNext chain. +// Returns pointer to it. If not found, returns null. +template +static inline const FindT* VmaPnextChainFind(const MainT* mainStruct, VkStructureType sType) +{ + for(const VkBaseInStructure* s = (const VkBaseInStructure*)mainStruct->pNext; + s != VMA_NULL; s = s->pNext) + { + if(s->sType == sType) + { + return (const FindT*)s; + } + } + return VMA_NULL; +} + +// An abstraction over buffer or image `usage` flags, depending on available extensions. +struct VmaBufferImageUsage +{ +#if VMA_KHR_MAINTENANCE5 + typedef uint64_t BaseType; // VkFlags64 +#else + typedef uint32_t BaseType; // VkFlags32 +#endif + + static const VmaBufferImageUsage UNKNOWN; + + BaseType Value; + + VmaBufferImageUsage() { *this = UNKNOWN; } + explicit VmaBufferImageUsage(BaseType usage) : Value(usage) { } + VmaBufferImageUsage(const VkBufferCreateInfo &createInfo, bool useKhrMaintenance5); + explicit VmaBufferImageUsage(const VkImageCreateInfo &createInfo); + + bool operator==(const VmaBufferImageUsage& rhs) const { return Value == rhs.Value; } + bool operator!=(const VmaBufferImageUsage& rhs) const { return Value != rhs.Value; } + + bool Contains(BaseType flag) const { return (Value & flag) != 0; } + bool ContainsDeviceAccess() const + { + // This relies on values of VK_IMAGE_USAGE_TRANSFER* being the same as VK_BUFFER_IMAGE_TRANSFER*. + return (Value & ~BaseType(VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT)) != 0; + } +}; + +const VmaBufferImageUsage VmaBufferImageUsage::UNKNOWN = VmaBufferImageUsage(0); + +VmaBufferImageUsage::VmaBufferImageUsage(const VkBufferCreateInfo &createInfo, + bool useKhrMaintenance5) +{ +#if VMA_KHR_MAINTENANCE5 + if(useKhrMaintenance5) + { + // If VkBufferCreateInfo::pNext chain contains VkBufferUsageFlags2CreateInfoKHR, + // take usage from it and ignore VkBufferCreateInfo::usage, per specification + // of the VK_KHR_maintenance5 extension. + const VkBufferUsageFlags2CreateInfoKHR* const usageFlags2 = + VmaPnextChainFind(&createInfo, VK_STRUCTURE_TYPE_BUFFER_USAGE_FLAGS_2_CREATE_INFO_KHR); + if(usageFlags2) + { + this->Value = usageFlags2->usage; + return; + } + } +#endif + + this->Value = (BaseType)createInfo.usage; +} + +VmaBufferImageUsage::VmaBufferImageUsage(const VkImageCreateInfo &createInfo) +{ + // Maybe in the future there will be VK_KHR_maintenanceN extension with structure + // VkImageUsageFlags2CreateInfoKHR, like the one for buffers... + + this->Value = (BaseType)createInfo.usage; +} + +// This is the main algorithm that guides the selection of a memory type best for an allocation - +// converts usage to required/preferred/not preferred flags. +static bool FindMemoryPreferences( + bool isIntegratedGPU, + const VmaAllocationCreateInfo& allocCreateInfo, + VmaBufferImageUsage bufImgUsage, + VkMemoryPropertyFlags& outRequiredFlags, + VkMemoryPropertyFlags& outPreferredFlags, + VkMemoryPropertyFlags& outNotPreferredFlags) +{ + outRequiredFlags = allocCreateInfo.requiredFlags; + outPreferredFlags = allocCreateInfo.preferredFlags; + outNotPreferredFlags = 0; + + switch(allocCreateInfo.usage) + { + case VMA_MEMORY_USAGE_UNKNOWN: + break; + case VMA_MEMORY_USAGE_GPU_ONLY: + if(!isIntegratedGPU || (outPreferredFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0) + { + outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + } + break; + case VMA_MEMORY_USAGE_CPU_ONLY: + outRequiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; + break; + case VMA_MEMORY_USAGE_CPU_TO_GPU: + outRequiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; + if(!isIntegratedGPU || (outPreferredFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0) + { + outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + } + break; + case VMA_MEMORY_USAGE_GPU_TO_CPU: + outRequiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; + outPreferredFlags |= VK_MEMORY_PROPERTY_HOST_CACHED_BIT; + break; + case VMA_MEMORY_USAGE_CPU_COPY: + outNotPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + break; + case VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED: + outRequiredFlags |= VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT; + break; + case VMA_MEMORY_USAGE_AUTO: + case VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE: + case VMA_MEMORY_USAGE_AUTO_PREFER_HOST: + { + if(bufImgUsage == VmaBufferImageUsage::UNKNOWN) + { + VMA_ASSERT(0 && "VMA_MEMORY_USAGE_AUTO* values can only be used with functions like vmaCreateBuffer, vmaCreateImage so that the details of the created resource are known." + " Maybe you use VkBufferUsageFlags2CreateInfoKHR but forgot to use VMA_ALLOCATOR_CREATE_KHR_MAINTENANCE5_BIT?" ); + return false; + } + + const bool deviceAccess = bufImgUsage.ContainsDeviceAccess(); + const bool hostAccessSequentialWrite = (allocCreateInfo.flags & VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT) != 0; + const bool hostAccessRandom = (allocCreateInfo.flags & VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT) != 0; + const bool hostAccessAllowTransferInstead = (allocCreateInfo.flags & VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT) != 0; + const bool preferDevice = allocCreateInfo.usage == VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE; + const bool preferHost = allocCreateInfo.usage == VMA_MEMORY_USAGE_AUTO_PREFER_HOST; + + // CPU random access - e.g. a buffer written to or transferred from GPU to read back on CPU. + if(hostAccessRandom) + { + // Prefer cached. Cannot require it, because some platforms don't have it (e.g. Raspberry Pi - see #362)! + outPreferredFlags |= VK_MEMORY_PROPERTY_HOST_CACHED_BIT; + + if (!isIntegratedGPU && deviceAccess && hostAccessAllowTransferInstead && !preferHost) + { + // Nice if it will end up in HOST_VISIBLE, but more importantly prefer DEVICE_LOCAL. + // Omitting HOST_VISIBLE here is intentional. + // In case there is DEVICE_LOCAL | HOST_VISIBLE | HOST_CACHED, it will pick that one. + // Otherwise, this will give same weight to DEVICE_LOCAL as HOST_VISIBLE | HOST_CACHED and select the former if occurs first on the list. + outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + } + else + { + // Always CPU memory. + outRequiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; + } + } + // CPU sequential write - may be CPU or host-visible GPU memory, uncached and write-combined. + else if(hostAccessSequentialWrite) + { + // Want uncached and write-combined. + outNotPreferredFlags |= VK_MEMORY_PROPERTY_HOST_CACHED_BIT; + + if(!isIntegratedGPU && deviceAccess && hostAccessAllowTransferInstead && !preferHost) + { + outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; + } + else + { + outRequiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; + // Direct GPU access, CPU sequential write (e.g. a dynamic uniform buffer updated every frame) + if(deviceAccess) + { + // Could go to CPU memory or GPU BAR/unified. Up to the user to decide. If no preference, choose GPU memory. + if(preferHost) + outNotPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + else + outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + } + // GPU no direct access, CPU sequential write (e.g. an upload buffer to be transferred to the GPU) + else + { + // Could go to CPU memory or GPU BAR/unified. Up to the user to decide. If no preference, choose CPU memory. + if(preferDevice) + outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + else + outNotPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + } + } + } + // No CPU access + else + { + // if(deviceAccess) + // + // GPU access, no CPU access (e.g. a color attachment image) - prefer GPU memory, + // unless there is a clear preference from the user not to do so. + // + // else: + // + // No direct GPU access, no CPU access, just transfers. + // It may be staging copy intended for e.g. preserving image for next frame (then better GPU memory) or + // a "swap file" copy to free some GPU memory (then better CPU memory). + // Up to the user to decide. If no preferece, assume the former and choose GPU memory. + + if(preferHost) + outNotPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + else + outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + } + break; + } + default: + VMA_ASSERT(0); + } + + // Avoid DEVICE_COHERENT unless explicitly requested. + if(((allocCreateInfo.requiredFlags | allocCreateInfo.preferredFlags) & + (VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD_COPY | VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD_COPY)) == 0) + { + outNotPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD_COPY; + } + + return true; +} + +//////////////////////////////////////////////////////////////////////////////// +// Memory allocation + +static void* VmaMalloc(const VkAllocationCallbacks* pAllocationCallbacks, size_t size, size_t alignment) +{ + void* result = VMA_NULL; + if ((pAllocationCallbacks != VMA_NULL) && + (pAllocationCallbacks->pfnAllocation != VMA_NULL)) + { + result = (*pAllocationCallbacks->pfnAllocation)( + pAllocationCallbacks->pUserData, + size, + alignment, + VK_SYSTEM_ALLOCATION_SCOPE_OBJECT); + } + else + { + result = VMA_SYSTEM_ALIGNED_MALLOC(size, alignment); + } + VMA_ASSERT(result != VMA_NULL && "CPU memory allocation failed."); + return result; +} + +static void VmaFree(const VkAllocationCallbacks* pAllocationCallbacks, void* ptr) +{ + if ((pAllocationCallbacks != VMA_NULL) && + (pAllocationCallbacks->pfnFree != VMA_NULL)) + { + (*pAllocationCallbacks->pfnFree)(pAllocationCallbacks->pUserData, ptr); + } + else + { + VMA_SYSTEM_ALIGNED_FREE(ptr); + } +} + +template +static T* VmaAllocate(const VkAllocationCallbacks* pAllocationCallbacks) +{ + return (T*)VmaMalloc(pAllocationCallbacks, sizeof(T), VMA_ALIGN_OF(T)); +} + +template +static T* VmaAllocateArray(const VkAllocationCallbacks* pAllocationCallbacks, size_t count) +{ + return (T*)VmaMalloc(pAllocationCallbacks, sizeof(T) * count, VMA_ALIGN_OF(T)); +} + +#define vma_new(allocator, type) new(VmaAllocate(allocator))(type) + +#define vma_new_array(allocator, type, count) new(VmaAllocateArray((allocator), (count)))(type) + +template +static void vma_delete(const VkAllocationCallbacks* pAllocationCallbacks, T* ptr) +{ + ptr->~T(); + VmaFree(pAllocationCallbacks, ptr); +} + +template +static void vma_delete_array(const VkAllocationCallbacks* pAllocationCallbacks, T* ptr, size_t count) +{ + if (ptr != VMA_NULL) + { + for (size_t i = count; i--; ) + { + ptr[i].~T(); + } + VmaFree(pAllocationCallbacks, ptr); + } +} + +static char* VmaCreateStringCopy(const VkAllocationCallbacks* allocs, const char* srcStr) +{ + if (srcStr != VMA_NULL) + { + const size_t len = strlen(srcStr); + char* const result = vma_new_array(allocs, char, len + 1); + memcpy(result, srcStr, len + 1); + return result; + } + return VMA_NULL; +} + +#if VMA_STATS_STRING_ENABLED +static char* VmaCreateStringCopy(const VkAllocationCallbacks* allocs, const char* srcStr, size_t strLen) +{ + if (srcStr != VMA_NULL) + { + char* const result = vma_new_array(allocs, char, strLen + 1); + memcpy(result, srcStr, strLen); + result[strLen] = '\0'; + return result; + } + return VMA_NULL; +} +#endif // VMA_STATS_STRING_ENABLED + +static void VmaFreeString(const VkAllocationCallbacks* allocs, char* str) +{ + if (str != VMA_NULL) + { + const size_t len = strlen(str); + vma_delete_array(allocs, str, len + 1); + } +} + +template +size_t VmaVectorInsertSorted(VectorT& vector, const typename VectorT::value_type& value) +{ + const size_t indexToInsert = VmaBinaryFindFirstNotLess( + vector.data(), + vector.data() + vector.size(), + value, + CmpLess()) - vector.data(); + VmaVectorInsert(vector, indexToInsert, value); + return indexToInsert; +} + +template +bool VmaVectorRemoveSorted(VectorT& vector, const typename VectorT::value_type& value) +{ + CmpLess comparator; + typename VectorT::iterator it = VmaBinaryFindFirstNotLess( + vector.begin(), + vector.end(), + value, + comparator); + if ((it != vector.end()) && !comparator(*it, value) && !comparator(value, *it)) + { + size_t indexToRemove = it - vector.begin(); + VmaVectorRemove(vector, indexToRemove); + return true; + } + return false; +} +#endif // _VMA_FUNCTIONS + +#ifndef _VMA_STATISTICS_FUNCTIONS + +static void VmaClearStatistics(VmaStatistics& outStats) +{ + outStats.blockCount = 0; + outStats.allocationCount = 0; + outStats.blockBytes = 0; + outStats.allocationBytes = 0; +} + +static void VmaAddStatistics(VmaStatistics& inoutStats, const VmaStatistics& src) +{ + inoutStats.blockCount += src.blockCount; + inoutStats.allocationCount += src.allocationCount; + inoutStats.blockBytes += src.blockBytes; + inoutStats.allocationBytes += src.allocationBytes; +} + +static void VmaClearDetailedStatistics(VmaDetailedStatistics& outStats) +{ + VmaClearStatistics(outStats.statistics); + outStats.unusedRangeCount = 0; + outStats.allocationSizeMin = VK_WHOLE_SIZE; + outStats.allocationSizeMax = 0; + outStats.unusedRangeSizeMin = VK_WHOLE_SIZE; + outStats.unusedRangeSizeMax = 0; +} + +static void VmaAddDetailedStatisticsAllocation(VmaDetailedStatistics& inoutStats, VkDeviceSize size) +{ + inoutStats.statistics.allocationCount++; + inoutStats.statistics.allocationBytes += size; + inoutStats.allocationSizeMin = VMA_MIN(inoutStats.allocationSizeMin, size); + inoutStats.allocationSizeMax = VMA_MAX(inoutStats.allocationSizeMax, size); +} + +static void VmaAddDetailedStatisticsUnusedRange(VmaDetailedStatistics& inoutStats, VkDeviceSize size) +{ + inoutStats.unusedRangeCount++; + inoutStats.unusedRangeSizeMin = VMA_MIN(inoutStats.unusedRangeSizeMin, size); + inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, size); +} + +static void VmaAddDetailedStatistics(VmaDetailedStatistics& inoutStats, const VmaDetailedStatistics& src) +{ + VmaAddStatistics(inoutStats.statistics, src.statistics); + inoutStats.unusedRangeCount += src.unusedRangeCount; + inoutStats.allocationSizeMin = VMA_MIN(inoutStats.allocationSizeMin, src.allocationSizeMin); + inoutStats.allocationSizeMax = VMA_MAX(inoutStats.allocationSizeMax, src.allocationSizeMax); + inoutStats.unusedRangeSizeMin = VMA_MIN(inoutStats.unusedRangeSizeMin, src.unusedRangeSizeMin); + inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, src.unusedRangeSizeMax); +} + +#endif // _VMA_STATISTICS_FUNCTIONS + +#ifndef _VMA_MUTEX_LOCK +// Helper RAII class to lock a mutex in constructor and unlock it in destructor (at the end of scope). +struct VmaMutexLock +{ + VMA_CLASS_NO_COPY_NO_MOVE(VmaMutexLock) +public: + VmaMutexLock(VMA_MUTEX& mutex, bool useMutex = true) : + m_pMutex(useMutex ? &mutex : VMA_NULL) + { + if (m_pMutex) { m_pMutex->Lock(); } + } + ~VmaMutexLock() { if (m_pMutex) { m_pMutex->Unlock(); } } + +private: + VMA_MUTEX* m_pMutex; +}; + +// Helper RAII class to lock a RW mutex in constructor and unlock it in destructor (at the end of scope), for reading. +struct VmaMutexLockRead +{ + VMA_CLASS_NO_COPY_NO_MOVE(VmaMutexLockRead) +public: + VmaMutexLockRead(VMA_RW_MUTEX& mutex, bool useMutex) : + m_pMutex(useMutex ? &mutex : VMA_NULL) + { + if (m_pMutex) { m_pMutex->LockRead(); } + } + ~VmaMutexLockRead() { if (m_pMutex) { m_pMutex->UnlockRead(); } } + +private: + VMA_RW_MUTEX* m_pMutex; +}; + +// Helper RAII class to lock a RW mutex in constructor and unlock it in destructor (at the end of scope), for writing. +struct VmaMutexLockWrite +{ + VMA_CLASS_NO_COPY_NO_MOVE(VmaMutexLockWrite) +public: + VmaMutexLockWrite(VMA_RW_MUTEX& mutex, bool useMutex) + : m_pMutex(useMutex ? &mutex : VMA_NULL) + { + if (m_pMutex) { m_pMutex->LockWrite(); } + } + ~VmaMutexLockWrite() { if (m_pMutex) { m_pMutex->UnlockWrite(); } } + +private: + VMA_RW_MUTEX* m_pMutex; +}; + +#if VMA_DEBUG_GLOBAL_MUTEX + static VMA_MUTEX gDebugGlobalMutex; + #define VMA_DEBUG_GLOBAL_MUTEX_LOCK VmaMutexLock debugGlobalMutexLock(gDebugGlobalMutex, true); +#else + #define VMA_DEBUG_GLOBAL_MUTEX_LOCK +#endif +#endif // _VMA_MUTEX_LOCK + +#ifndef _VMA_ATOMIC_TRANSACTIONAL_INCREMENT +// An object that increments given atomic but decrements it back in the destructor unless Commit() is called. +template +struct AtomicTransactionalIncrement +{ +public: + using T = decltype(AtomicT().load()); + + ~AtomicTransactionalIncrement() + { + if(m_Atomic) + --(*m_Atomic); + } + + void Commit() { m_Atomic = VMA_NULL; } + T Increment(AtomicT* atomic) + { + m_Atomic = atomic; + return m_Atomic->fetch_add(1); + } + +private: + AtomicT* m_Atomic = VMA_NULL; +}; +#endif // _VMA_ATOMIC_TRANSACTIONAL_INCREMENT + +#ifndef _VMA_STL_ALLOCATOR +// STL-compatible allocator. +template +struct VmaStlAllocator +{ + const VkAllocationCallbacks* const m_pCallbacks; + typedef T value_type; + + VmaStlAllocator(const VkAllocationCallbacks* pCallbacks) : m_pCallbacks(pCallbacks) {} + template + VmaStlAllocator(const VmaStlAllocator& src) : m_pCallbacks(src.m_pCallbacks) {} + VmaStlAllocator(const VmaStlAllocator&) = default; + VmaStlAllocator& operator=(const VmaStlAllocator&) = delete; + + T* allocate(size_t n) { return VmaAllocateArray(m_pCallbacks, n); } + void deallocate(T* p, size_t n) { VmaFree(m_pCallbacks, p); } + + template + bool operator==(const VmaStlAllocator& rhs) const + { + return m_pCallbacks == rhs.m_pCallbacks; + } + template + bool operator!=(const VmaStlAllocator& rhs) const + { + return m_pCallbacks != rhs.m_pCallbacks; + } +}; +#endif // _VMA_STL_ALLOCATOR + +#ifndef _VMA_VECTOR +/* Class with interface compatible with subset of std::vector. +T must be POD because constructors and destructors are not called and memcpy is +used for these objects. */ +template +class VmaVector +{ +public: + typedef T value_type; + typedef T* iterator; + typedef const T* const_iterator; + + VmaVector(const AllocatorT& allocator); + VmaVector(size_t count, const AllocatorT& allocator); + // This version of the constructor is here for compatibility with pre-C++14 std::vector. + // value is unused. + VmaVector(size_t count, const T& value, const AllocatorT& allocator) : VmaVector(count, allocator) {} + VmaVector(const VmaVector& src); + VmaVector& operator=(const VmaVector& rhs); + ~VmaVector() { VmaFree(m_Allocator.m_pCallbacks, m_pArray); } + + bool empty() const { return m_Count == 0; } + size_t size() const { return m_Count; } + T* data() { return m_pArray; } + T& front() { VMA_HEAVY_ASSERT(m_Count > 0); return m_pArray[0]; } + T& back() { VMA_HEAVY_ASSERT(m_Count > 0); return m_pArray[m_Count - 1]; } + const T* data() const { return m_pArray; } + const T& front() const { VMA_HEAVY_ASSERT(m_Count > 0); return m_pArray[0]; } + const T& back() const { VMA_HEAVY_ASSERT(m_Count > 0); return m_pArray[m_Count - 1]; } + + iterator begin() { return m_pArray; } + iterator end() { return m_pArray + m_Count; } + const_iterator cbegin() const { return m_pArray; } + const_iterator cend() const { return m_pArray + m_Count; } + const_iterator begin() const { return cbegin(); } + const_iterator end() const { return cend(); } + + void pop_front() { VMA_HEAVY_ASSERT(m_Count > 0); remove(0); } + void pop_back() { VMA_HEAVY_ASSERT(m_Count > 0); resize(size() - 1); } + void push_front(const T& src) { insert(0, src); } + + void push_back(const T& src); + void reserve(size_t newCapacity, bool freeMemory = false); + void resize(size_t newCount); + void clear() { resize(0); } + void shrink_to_fit(); + void insert(size_t index, const T& src); + void remove(size_t index); + + T& operator[](size_t index) { VMA_HEAVY_ASSERT(index < m_Count); return m_pArray[index]; } + const T& operator[](size_t index) const { VMA_HEAVY_ASSERT(index < m_Count); return m_pArray[index]; } + +private: + AllocatorT m_Allocator; + T* m_pArray; + size_t m_Count; + size_t m_Capacity; +}; + +#ifndef _VMA_VECTOR_FUNCTIONS +template +VmaVector::VmaVector(const AllocatorT& allocator) + : m_Allocator(allocator), + m_pArray(VMA_NULL), + m_Count(0), + m_Capacity(0) {} + +template +VmaVector::VmaVector(size_t count, const AllocatorT& allocator) + : m_Allocator(allocator), + m_pArray(count ? (T*)VmaAllocateArray(allocator.m_pCallbacks, count) : VMA_NULL), + m_Count(count), + m_Capacity(count) {} + +template +VmaVector::VmaVector(const VmaVector& src) + : m_Allocator(src.m_Allocator), + m_pArray(src.m_Count ? (T*)VmaAllocateArray(src.m_Allocator.m_pCallbacks, src.m_Count) : VMA_NULL), + m_Count(src.m_Count), + m_Capacity(src.m_Count) +{ + if (m_Count != 0) + { + memcpy(m_pArray, src.m_pArray, m_Count * sizeof(T)); + } +} + +template +VmaVector& VmaVector::operator=(const VmaVector& rhs) +{ + if (&rhs != this) + { + resize(rhs.m_Count); + if (m_Count != 0) + { + memcpy(m_pArray, rhs.m_pArray, m_Count * sizeof(T)); + } + } + return *this; +} + +template +void VmaVector::push_back(const T& src) +{ + const size_t newIndex = size(); + resize(newIndex + 1); + m_pArray[newIndex] = src; +} + +template +void VmaVector::reserve(size_t newCapacity, bool freeMemory) +{ + newCapacity = VMA_MAX(newCapacity, m_Count); + + if ((newCapacity < m_Capacity) && !freeMemory) + { + newCapacity = m_Capacity; + } + + if (newCapacity != m_Capacity) + { + T* const newArray = newCapacity ? VmaAllocateArray(m_Allocator, newCapacity) : VMA_NULL; + if (m_Count != 0) + { + memcpy(newArray, m_pArray, m_Count * sizeof(T)); + } + VmaFree(m_Allocator.m_pCallbacks, m_pArray); + m_Capacity = newCapacity; + m_pArray = newArray; + } +} + +template +void VmaVector::resize(size_t newCount) +{ + size_t newCapacity = m_Capacity; + if (newCount > m_Capacity) + { + newCapacity = VMA_MAX(newCount, VMA_MAX(m_Capacity * 3 / 2, (size_t)8)); + } + + if (newCapacity != m_Capacity) + { + T* const newArray = newCapacity ? VmaAllocateArray(m_Allocator.m_pCallbacks, newCapacity) : VMA_NULL; + const size_t elementsToCopy = VMA_MIN(m_Count, newCount); + if (elementsToCopy != 0) + { + memcpy(newArray, m_pArray, elementsToCopy * sizeof(T)); + } + VmaFree(m_Allocator.m_pCallbacks, m_pArray); + m_Capacity = newCapacity; + m_pArray = newArray; + } + + m_Count = newCount; +} + +template +void VmaVector::shrink_to_fit() +{ + if (m_Capacity > m_Count) + { + T* newArray = VMA_NULL; + if (m_Count > 0) + { + newArray = VmaAllocateArray(m_Allocator.m_pCallbacks, m_Count); + memcpy(newArray, m_pArray, m_Count * sizeof(T)); + } + VmaFree(m_Allocator.m_pCallbacks, m_pArray); + m_Capacity = m_Count; + m_pArray = newArray; + } +} + +template +void VmaVector::insert(size_t index, const T& src) +{ + VMA_HEAVY_ASSERT(index <= m_Count); + const size_t oldCount = size(); + resize(oldCount + 1); + if (index < oldCount) + { + memmove(m_pArray + (index + 1), m_pArray + index, (oldCount - index) * sizeof(T)); + } + m_pArray[index] = src; +} + +template +void VmaVector::remove(size_t index) +{ + VMA_HEAVY_ASSERT(index < m_Count); + const size_t oldCount = size(); + if (index < oldCount - 1) + { + memmove(m_pArray + index, m_pArray + (index + 1), (oldCount - index - 1) * sizeof(T)); + } + resize(oldCount - 1); +} +#endif // _VMA_VECTOR_FUNCTIONS + +template +static void VmaVectorInsert(VmaVector& vec, size_t index, const T& item) +{ + vec.insert(index, item); +} + +template +static void VmaVectorRemove(VmaVector& vec, size_t index) +{ + vec.remove(index); +} +#endif // _VMA_VECTOR + +#ifndef _VMA_SMALL_VECTOR +/* +This is a vector (a variable-sized array), optimized for the case when the array is small. + +It contains some number of elements in-place, which allows it to avoid heap allocation +when the actual number of elements is below that threshold. This allows normal "small" +cases to be fast without losing generality for large inputs. +*/ +template +class VmaSmallVector +{ +public: + typedef T value_type; + typedef T* iterator; + + VmaSmallVector(const AllocatorT& allocator); + VmaSmallVector(size_t count, const AllocatorT& allocator); + template + VmaSmallVector(const VmaSmallVector&) = delete; + template + VmaSmallVector& operator=(const VmaSmallVector&) = delete; + ~VmaSmallVector() = default; + + bool empty() const { return m_Count == 0; } + size_t size() const { return m_Count; } + T* data() { return m_Count > N ? m_DynamicArray.data() : m_StaticArray; } + T& front() { VMA_HEAVY_ASSERT(m_Count > 0); return data()[0]; } + T& back() { VMA_HEAVY_ASSERT(m_Count > 0); return data()[m_Count - 1]; } + const T* data() const { return m_Count > N ? m_DynamicArray.data() : m_StaticArray; } + const T& front() const { VMA_HEAVY_ASSERT(m_Count > 0); return data()[0]; } + const T& back() const { VMA_HEAVY_ASSERT(m_Count > 0); return data()[m_Count - 1]; } + + iterator begin() { return data(); } + iterator end() { return data() + m_Count; } + + void pop_front() { VMA_HEAVY_ASSERT(m_Count > 0); remove(0); } + void pop_back() { VMA_HEAVY_ASSERT(m_Count > 0); resize(size() - 1); } + void push_front(const T& src) { insert(0, src); } + + void push_back(const T& src); + void resize(size_t newCount, bool freeMemory = false); + void clear(bool freeMemory = false); + void insert(size_t index, const T& src); + void remove(size_t index); + + T& operator[](size_t index) { VMA_HEAVY_ASSERT(index < m_Count); return data()[index]; } + const T& operator[](size_t index) const { VMA_HEAVY_ASSERT(index < m_Count); return data()[index]; } + +private: + size_t m_Count; + T m_StaticArray[N]; // Used when m_Size <= N + VmaVector m_DynamicArray; // Used when m_Size > N +}; + +#ifndef _VMA_SMALL_VECTOR_FUNCTIONS +template +VmaSmallVector::VmaSmallVector(const AllocatorT& allocator) + : m_Count(0), + m_DynamicArray(allocator) {} + +template +VmaSmallVector::VmaSmallVector(size_t count, const AllocatorT& allocator) + : m_Count(count), + m_DynamicArray(count > N ? count : 0, allocator) {} + +template +void VmaSmallVector::push_back(const T& src) +{ + const size_t newIndex = size(); + resize(newIndex + 1); + data()[newIndex] = src; +} + +template +void VmaSmallVector::resize(size_t newCount, bool freeMemory) +{ + if (newCount > N && m_Count > N) + { + // Any direction, staying in m_DynamicArray + m_DynamicArray.resize(newCount); + if (freeMemory) + { + m_DynamicArray.shrink_to_fit(); + } + } + else if (newCount > N && m_Count <= N) + { + // Growing, moving from m_StaticArray to m_DynamicArray + m_DynamicArray.resize(newCount); + if (m_Count > 0) + { + memcpy(m_DynamicArray.data(), m_StaticArray, m_Count * sizeof(T)); + } + } + else if (newCount <= N && m_Count > N) + { + // Shrinking, moving from m_DynamicArray to m_StaticArray + if (newCount > 0) + { + memcpy(m_StaticArray, m_DynamicArray.data(), newCount * sizeof(T)); + } + m_DynamicArray.resize(0); + if (freeMemory) + { + m_DynamicArray.shrink_to_fit(); + } + } + else + { + // Any direction, staying in m_StaticArray - nothing to do here + } + m_Count = newCount; +} + +template +void VmaSmallVector::clear(bool freeMemory) +{ + m_DynamicArray.clear(); + if (freeMemory) + { + m_DynamicArray.shrink_to_fit(); + } + m_Count = 0; +} + +template +void VmaSmallVector::insert(size_t index, const T& src) +{ + VMA_HEAVY_ASSERT(index <= m_Count); + const size_t oldCount = size(); + resize(oldCount + 1); + T* const dataPtr = data(); + if (index < oldCount) + { + // I know, this could be more optimal for case where memmove can be memcpy directly from m_StaticArray to m_DynamicArray. + memmove(dataPtr + (index + 1), dataPtr + index, (oldCount - index) * sizeof(T)); + } + dataPtr[index] = src; +} + +template +void VmaSmallVector::remove(size_t index) +{ + VMA_HEAVY_ASSERT(index < m_Count); + const size_t oldCount = size(); + if (index < oldCount - 1) + { + // I know, this could be more optimal for case where memmove can be memcpy directly from m_DynamicArray to m_StaticArray. + T* const dataPtr = data(); + memmove(dataPtr + index, dataPtr + (index + 1), (oldCount - index - 1) * sizeof(T)); + } + resize(oldCount - 1); +} +#endif // _VMA_SMALL_VECTOR_FUNCTIONS +#endif // _VMA_SMALL_VECTOR + +#ifndef _VMA_POOL_ALLOCATOR +/* +Allocator for objects of type T using a list of arrays (pools) to speed up +allocation. Number of elements that can be allocated is not bounded because +allocator can create multiple blocks. +*/ +template +class VmaPoolAllocator +{ + VMA_CLASS_NO_COPY_NO_MOVE(VmaPoolAllocator) +public: + VmaPoolAllocator(const VkAllocationCallbacks* pAllocationCallbacks, uint32_t firstBlockCapacity); + ~VmaPoolAllocator(); + template T* Alloc(Types&&... args); + void Free(T* ptr); + +private: + union Item + { + uint32_t NextFreeIndex; + alignas(T) char Value[sizeof(T)]; + }; + struct ItemBlock + { + Item* pItems; + uint32_t Capacity; + uint32_t FirstFreeIndex; + }; + + const VkAllocationCallbacks* m_pAllocationCallbacks; + const uint32_t m_FirstBlockCapacity; + VmaVector> m_ItemBlocks; + + ItemBlock& CreateNewBlock(); +}; + +#ifndef _VMA_POOL_ALLOCATOR_FUNCTIONS +template +VmaPoolAllocator::VmaPoolAllocator(const VkAllocationCallbacks* pAllocationCallbacks, uint32_t firstBlockCapacity) + : m_pAllocationCallbacks(pAllocationCallbacks), + m_FirstBlockCapacity(firstBlockCapacity), + m_ItemBlocks(VmaStlAllocator(pAllocationCallbacks)) +{ + VMA_ASSERT(m_FirstBlockCapacity > 1); +} + +template +VmaPoolAllocator::~VmaPoolAllocator() +{ + for (size_t i = m_ItemBlocks.size(); i--;) + vma_delete_array(m_pAllocationCallbacks, m_ItemBlocks[i].pItems, m_ItemBlocks[i].Capacity); + m_ItemBlocks.clear(); +} + +template +template T* VmaPoolAllocator::Alloc(Types&&... args) +{ + for (size_t i = m_ItemBlocks.size(); i--; ) + { + ItemBlock& block = m_ItemBlocks[i]; + // This block has some free items: Use first one. + if (block.FirstFreeIndex != UINT32_MAX) + { + Item* const pItem = &block.pItems[block.FirstFreeIndex]; + block.FirstFreeIndex = pItem->NextFreeIndex; + T* result = (T*)&pItem->Value; + new(result)T(std::forward(args)...); // Explicit constructor call. + return result; + } + } + + // No block has free item: Create new one and use it. + ItemBlock& newBlock = CreateNewBlock(); + Item* const pItem = &newBlock.pItems[0]; + newBlock.FirstFreeIndex = pItem->NextFreeIndex; + T* result = (T*)&pItem->Value; + new(result) T(std::forward(args)...); // Explicit constructor call. + return result; +} + +template +void VmaPoolAllocator::Free(T* ptr) +{ + // Search all memory blocks to find ptr. + for (size_t i = m_ItemBlocks.size(); i--; ) + { + ItemBlock& block = m_ItemBlocks[i]; + + // Casting to union. + Item* pItemPtr; + memcpy(&pItemPtr, &ptr, sizeof(pItemPtr)); + + // Check if pItemPtr is in address range of this block. + if ((pItemPtr >= block.pItems) && (pItemPtr < block.pItems + block.Capacity)) + { + ptr->~T(); // Explicit destructor call. + const uint32_t index = static_cast(pItemPtr - block.pItems); + pItemPtr->NextFreeIndex = block.FirstFreeIndex; + block.FirstFreeIndex = index; + return; + } + } + VMA_ASSERT(0 && "Pointer doesn't belong to this memory pool."); +} + +template +typename VmaPoolAllocator::ItemBlock& VmaPoolAllocator::CreateNewBlock() +{ + const uint32_t newBlockCapacity = m_ItemBlocks.empty() ? + m_FirstBlockCapacity : m_ItemBlocks.back().Capacity * 3 / 2; + + const ItemBlock newBlock = + { + vma_new_array(m_pAllocationCallbacks, Item, newBlockCapacity), + newBlockCapacity, + 0 + }; + + m_ItemBlocks.push_back(newBlock); + + // Setup singly-linked list of all free items in this block. + for (uint32_t i = 0; i < newBlockCapacity - 1; ++i) + newBlock.pItems[i].NextFreeIndex = i + 1; + newBlock.pItems[newBlockCapacity - 1].NextFreeIndex = UINT32_MAX; + return m_ItemBlocks.back(); +} +#endif // _VMA_POOL_ALLOCATOR_FUNCTIONS +#endif // _VMA_POOL_ALLOCATOR + +#ifndef _VMA_RAW_LIST +template +struct VmaListItem +{ + VmaListItem* pPrev; + VmaListItem* pNext; + T Value; +}; + +// Doubly linked list. +template +class VmaRawList +{ + VMA_CLASS_NO_COPY_NO_MOVE(VmaRawList) +public: + typedef VmaListItem ItemType; + + VmaRawList(const VkAllocationCallbacks* pAllocationCallbacks); + // Intentionally not calling Clear, because that would be unnecessary + // computations to return all items to m_ItemAllocator as free. + ~VmaRawList() = default; + + size_t GetCount() const { return m_Count; } + bool IsEmpty() const { return m_Count == 0; } + + ItemType* Front() { return m_pFront; } + ItemType* Back() { return m_pBack; } + const ItemType* Front() const { return m_pFront; } + const ItemType* Back() const { return m_pBack; } + + ItemType* PushFront(); + ItemType* PushBack(); + ItemType* PushFront(const T& value); + ItemType* PushBack(const T& value); + void PopFront(); + void PopBack(); + + // Item can be null - it means PushBack. + ItemType* InsertBefore(ItemType* pItem); + // Item can be null - it means PushFront. + ItemType* InsertAfter(ItemType* pItem); + ItemType* InsertBefore(ItemType* pItem, const T& value); + ItemType* InsertAfter(ItemType* pItem, const T& value); + + void Clear(); + void Remove(ItemType* pItem); + +private: + const VkAllocationCallbacks* const m_pAllocationCallbacks; + VmaPoolAllocator m_ItemAllocator; + ItemType* m_pFront; + ItemType* m_pBack; + size_t m_Count; +}; + +#ifndef _VMA_RAW_LIST_FUNCTIONS +template +VmaRawList::VmaRawList(const VkAllocationCallbacks* pAllocationCallbacks) + : m_pAllocationCallbacks(pAllocationCallbacks), + m_ItemAllocator(pAllocationCallbacks, 128), + m_pFront(VMA_NULL), + m_pBack(VMA_NULL), + m_Count(0) {} + +template +VmaListItem* VmaRawList::PushFront() +{ + ItemType* const pNewItem = m_ItemAllocator.Alloc(); + pNewItem->pPrev = VMA_NULL; + if (IsEmpty()) + { + pNewItem->pNext = VMA_NULL; + m_pFront = pNewItem; + m_pBack = pNewItem; + m_Count = 1; + } + else + { + pNewItem->pNext = m_pFront; + m_pFront->pPrev = pNewItem; + m_pFront = pNewItem; + ++m_Count; + } + return pNewItem; +} + +template +VmaListItem* VmaRawList::PushBack() +{ + ItemType* const pNewItem = m_ItemAllocator.Alloc(); + pNewItem->pNext = VMA_NULL; + if(IsEmpty()) + { + pNewItem->pPrev = VMA_NULL; + m_pFront = pNewItem; + m_pBack = pNewItem; + m_Count = 1; + } + else + { + pNewItem->pPrev = m_pBack; + m_pBack->pNext = pNewItem; + m_pBack = pNewItem; + ++m_Count; + } + return pNewItem; +} + +template +VmaListItem* VmaRawList::PushFront(const T& value) +{ + ItemType* const pNewItem = PushFront(); + pNewItem->Value = value; + return pNewItem; +} + +template +VmaListItem* VmaRawList::PushBack(const T& value) +{ + ItemType* const pNewItem = PushBack(); + pNewItem->Value = value; + return pNewItem; +} + +template +void VmaRawList::PopFront() +{ + VMA_HEAVY_ASSERT(m_Count > 0); + ItemType* const pFrontItem = m_pFront; + ItemType* const pNextItem = pFrontItem->pNext; + if (pNextItem != VMA_NULL) + { + pNextItem->pPrev = VMA_NULL; + } + m_pFront = pNextItem; + m_ItemAllocator.Free(pFrontItem); + --m_Count; +} + +template +void VmaRawList::PopBack() +{ + VMA_HEAVY_ASSERT(m_Count > 0); + ItemType* const pBackItem = m_pBack; + ItemType* const pPrevItem = pBackItem->pPrev; + if(pPrevItem != VMA_NULL) + { + pPrevItem->pNext = VMA_NULL; + } + m_pBack = pPrevItem; + m_ItemAllocator.Free(pBackItem); + --m_Count; +} + +template +void VmaRawList::Clear() +{ + if (IsEmpty() == false) + { + ItemType* pItem = m_pBack; + while (pItem != VMA_NULL) + { + ItemType* const pPrevItem = pItem->pPrev; + m_ItemAllocator.Free(pItem); + pItem = pPrevItem; + } + m_pFront = VMA_NULL; + m_pBack = VMA_NULL; + m_Count = 0; + } +} + +template +void VmaRawList::Remove(ItemType* pItem) +{ + VMA_HEAVY_ASSERT(pItem != VMA_NULL); + VMA_HEAVY_ASSERT(m_Count > 0); + + if(pItem->pPrev != VMA_NULL) + { + pItem->pPrev->pNext = pItem->pNext; + } + else + { + VMA_HEAVY_ASSERT(m_pFront == pItem); + m_pFront = pItem->pNext; + } + + if(pItem->pNext != VMA_NULL) + { + pItem->pNext->pPrev = pItem->pPrev; + } + else + { + VMA_HEAVY_ASSERT(m_pBack == pItem); + m_pBack = pItem->pPrev; + } + + m_ItemAllocator.Free(pItem); + --m_Count; +} + +template +VmaListItem* VmaRawList::InsertBefore(ItemType* pItem) +{ + if(pItem != VMA_NULL) + { + ItemType* const prevItem = pItem->pPrev; + ItemType* const newItem = m_ItemAllocator.Alloc(); + newItem->pPrev = prevItem; + newItem->pNext = pItem; + pItem->pPrev = newItem; + if(prevItem != VMA_NULL) + { + prevItem->pNext = newItem; + } + else + { + VMA_HEAVY_ASSERT(m_pFront == pItem); + m_pFront = newItem; + } + ++m_Count; + return newItem; + } + else + return PushBack(); +} + +template +VmaListItem* VmaRawList::InsertAfter(ItemType* pItem) +{ + if(pItem != VMA_NULL) + { + ItemType* const nextItem = pItem->pNext; + ItemType* const newItem = m_ItemAllocator.Alloc(); + newItem->pNext = nextItem; + newItem->pPrev = pItem; + pItem->pNext = newItem; + if(nextItem != VMA_NULL) + { + nextItem->pPrev = newItem; + } + else + { + VMA_HEAVY_ASSERT(m_pBack == pItem); + m_pBack = newItem; + } + ++m_Count; + return newItem; + } + else + return PushFront(); +} + +template +VmaListItem* VmaRawList::InsertBefore(ItemType* pItem, const T& value) +{ + ItemType* const newItem = InsertBefore(pItem); + newItem->Value = value; + return newItem; +} + +template +VmaListItem* VmaRawList::InsertAfter(ItemType* pItem, const T& value) +{ + ItemType* const newItem = InsertAfter(pItem); + newItem->Value = value; + return newItem; +} +#endif // _VMA_RAW_LIST_FUNCTIONS +#endif // _VMA_RAW_LIST + +#ifndef _VMA_LIST +template +class VmaList +{ + VMA_CLASS_NO_COPY_NO_MOVE(VmaList) +public: + class reverse_iterator; + class const_iterator; + class const_reverse_iterator; + + class iterator + { + friend class const_iterator; + friend class VmaList; + public: + iterator() : m_pList(VMA_NULL), m_pItem(VMA_NULL) {} + iterator(const reverse_iterator& src) : m_pList(src.m_pList), m_pItem(src.m_pItem) {} + + T& operator*() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return m_pItem->Value; } + T* operator->() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return &m_pItem->Value; } + + bool operator==(const iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem == rhs.m_pItem; } + bool operator!=(const iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem != rhs.m_pItem; } + + iterator operator++(int) { iterator result = *this; ++*this; return result; } + iterator operator--(int) { iterator result = *this; --*this; return result; } + + iterator& operator++() { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); m_pItem = m_pItem->pNext; return *this; } + iterator& operator--(); + + private: + VmaRawList* m_pList; + VmaListItem* m_pItem; + + iterator(VmaRawList* pList, VmaListItem* pItem) : m_pList(pList), m_pItem(pItem) {} + }; + class reverse_iterator + { + friend class const_reverse_iterator; + friend class VmaList; + public: + reverse_iterator() : m_pList(VMA_NULL), m_pItem(VMA_NULL) {} + reverse_iterator(const iterator& src) : m_pList(src.m_pList), m_pItem(src.m_pItem) {} + + T& operator*() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return m_pItem->Value; } + T* operator->() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return &m_pItem->Value; } + + bool operator==(const reverse_iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem == rhs.m_pItem; } + bool operator!=(const reverse_iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem != rhs.m_pItem; } + + reverse_iterator operator++(int) { reverse_iterator result = *this; ++* this; return result; } + reverse_iterator operator--(int) { reverse_iterator result = *this; --* this; return result; } + + reverse_iterator& operator++() { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); m_pItem = m_pItem->pPrev; return *this; } + reverse_iterator& operator--(); + + private: + VmaRawList* m_pList; + VmaListItem* m_pItem; + + reverse_iterator(VmaRawList* pList, VmaListItem* pItem) : m_pList(pList), m_pItem(pItem) {} + }; + class const_iterator + { + friend class VmaList; + public: + const_iterator() : m_pList(VMA_NULL), m_pItem(VMA_NULL) {} + const_iterator(const iterator& src) : m_pList(src.m_pList), m_pItem(src.m_pItem) {} + const_iterator(const reverse_iterator& src) : m_pList(src.m_pList), m_pItem(src.m_pItem) {} + + iterator drop_const() { return { const_cast*>(m_pList), const_cast*>(m_pItem) }; } + + const T& operator*() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return m_pItem->Value; } + const T* operator->() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return &m_pItem->Value; } + + bool operator==(const const_iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem == rhs.m_pItem; } + bool operator!=(const const_iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem != rhs.m_pItem; } + + const_iterator operator++(int) { const_iterator result = *this; ++* this; return result; } + const_iterator operator--(int) { const_iterator result = *this; --* this; return result; } + + const_iterator& operator++() { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); m_pItem = m_pItem->pNext; return *this; } + const_iterator& operator--(); + + private: + const VmaRawList* m_pList; + const VmaListItem* m_pItem; + + const_iterator(const VmaRawList* pList, const VmaListItem* pItem) : m_pList(pList), m_pItem(pItem) {} + }; + class const_reverse_iterator + { + friend class VmaList; + public: + const_reverse_iterator() : m_pList(VMA_NULL), m_pItem(VMA_NULL) {} + const_reverse_iterator(const reverse_iterator& src) : m_pList(src.m_pList), m_pItem(src.m_pItem) {} + const_reverse_iterator(const iterator& src) : m_pList(src.m_pList), m_pItem(src.m_pItem) {} + + reverse_iterator drop_const() { return { const_cast*>(m_pList), const_cast*>(m_pItem) }; } + + const T& operator*() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return m_pItem->Value; } + const T* operator->() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return &m_pItem->Value; } + + bool operator==(const const_reverse_iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem == rhs.m_pItem; } + bool operator!=(const const_reverse_iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem != rhs.m_pItem; } + + const_reverse_iterator operator++(int) { const_reverse_iterator result = *this; ++* this; return result; } + const_reverse_iterator operator--(int) { const_reverse_iterator result = *this; --* this; return result; } + + const_reverse_iterator& operator++() { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); m_pItem = m_pItem->pPrev; return *this; } + const_reverse_iterator& operator--(); + + private: + const VmaRawList* m_pList; + const VmaListItem* m_pItem; + + const_reverse_iterator(const VmaRawList* pList, const VmaListItem* pItem) : m_pList(pList), m_pItem(pItem) {} + }; + + VmaList(const AllocatorT& allocator) : m_RawList(allocator.m_pCallbacks) {} + + bool empty() const { return m_RawList.IsEmpty(); } + size_t size() const { return m_RawList.GetCount(); } + + iterator begin() { return iterator(&m_RawList, m_RawList.Front()); } + iterator end() { return iterator(&m_RawList, VMA_NULL); } + + const_iterator cbegin() const { return const_iterator(&m_RawList, m_RawList.Front()); } + const_iterator cend() const { return const_iterator(&m_RawList, VMA_NULL); } + + const_iterator begin() const { return cbegin(); } + const_iterator end() const { return cend(); } + + reverse_iterator rbegin() { return reverse_iterator(&m_RawList, m_RawList.Back()); } + reverse_iterator rend() { return reverse_iterator(&m_RawList, VMA_NULL); } + + const_reverse_iterator crbegin() const { return const_reverse_iterator(&m_RawList, m_RawList.Back()); } + const_reverse_iterator crend() const { return const_reverse_iterator(&m_RawList, VMA_NULL); } + + const_reverse_iterator rbegin() const { return crbegin(); } + const_reverse_iterator rend() const { return crend(); } + + void push_back(const T& value) { m_RawList.PushBack(value); } + iterator insert(iterator it, const T& value) { return iterator(&m_RawList, m_RawList.InsertBefore(it.m_pItem, value)); } + + void clear() { m_RawList.Clear(); } + void erase(iterator it) { m_RawList.Remove(it.m_pItem); } + +private: + VmaRawList m_RawList; +}; + +#ifndef _VMA_LIST_FUNCTIONS +template +typename VmaList::iterator& VmaList::iterator::operator--() +{ + if (m_pItem != VMA_NULL) + { + m_pItem = m_pItem->pPrev; + } + else + { + VMA_HEAVY_ASSERT(!m_pList->IsEmpty()); + m_pItem = m_pList->Back(); + } + return *this; +} + +template +typename VmaList::reverse_iterator& VmaList::reverse_iterator::operator--() +{ + if (m_pItem != VMA_NULL) + { + m_pItem = m_pItem->pNext; + } + else + { + VMA_HEAVY_ASSERT(!m_pList->IsEmpty()); + m_pItem = m_pList->Front(); + } + return *this; +} + +template +typename VmaList::const_iterator& VmaList::const_iterator::operator--() +{ + if (m_pItem != VMA_NULL) + { + m_pItem = m_pItem->pPrev; + } + else + { + VMA_HEAVY_ASSERT(!m_pList->IsEmpty()); + m_pItem = m_pList->Back(); + } + return *this; +} + +template +typename VmaList::const_reverse_iterator& VmaList::const_reverse_iterator::operator--() +{ + if (m_pItem != VMA_NULL) + { + m_pItem = m_pItem->pNext; + } + else + { + VMA_HEAVY_ASSERT(!m_pList->IsEmpty()); + m_pItem = m_pList->Back(); + } + return *this; +} +#endif // _VMA_LIST_FUNCTIONS +#endif // _VMA_LIST + +#ifndef _VMA_INTRUSIVE_LINKED_LIST +/* +Expected interface of ItemTypeTraits: +struct MyItemTypeTraits +{ + typedef MyItem ItemType; + static ItemType* GetPrev(const ItemType* item) { return item->myPrevPtr; } + static ItemType* GetNext(const ItemType* item) { return item->myNextPtr; } + static ItemType*& AccessPrev(ItemType* item) { return item->myPrevPtr; } + static ItemType*& AccessNext(ItemType* item) { return item->myNextPtr; } +}; +*/ +template +class VmaIntrusiveLinkedList +{ +public: + typedef typename ItemTypeTraits::ItemType ItemType; + static ItemType* GetPrev(const ItemType* item) { return ItemTypeTraits::GetPrev(item); } + static ItemType* GetNext(const ItemType* item) { return ItemTypeTraits::GetNext(item); } + + // Movable, not copyable. + VmaIntrusiveLinkedList() = default; + VmaIntrusiveLinkedList(VmaIntrusiveLinkedList && src); + VmaIntrusiveLinkedList(const VmaIntrusiveLinkedList&) = delete; + VmaIntrusiveLinkedList& operator=(VmaIntrusiveLinkedList&& src); + VmaIntrusiveLinkedList& operator=(const VmaIntrusiveLinkedList&) = delete; + ~VmaIntrusiveLinkedList() { VMA_HEAVY_ASSERT(IsEmpty()); } + + size_t GetCount() const { return m_Count; } + bool IsEmpty() const { return m_Count == 0; } + ItemType* Front() { return m_Front; } + ItemType* Back() { return m_Back; } + const ItemType* Front() const { return m_Front; } + const ItemType* Back() const { return m_Back; } + + void PushBack(ItemType* item); + void PushFront(ItemType* item); + ItemType* PopBack(); + ItemType* PopFront(); + + // MyItem can be null - it means PushBack. + void InsertBefore(ItemType* existingItem, ItemType* newItem); + // MyItem can be null - it means PushFront. + void InsertAfter(ItemType* existingItem, ItemType* newItem); + void Remove(ItemType* item); + void RemoveAll(); + +private: + ItemType* m_Front = VMA_NULL; + ItemType* m_Back = VMA_NULL; + size_t m_Count = 0; +}; + +#ifndef _VMA_INTRUSIVE_LINKED_LIST_FUNCTIONS +template +VmaIntrusiveLinkedList::VmaIntrusiveLinkedList(VmaIntrusiveLinkedList&& src) + : m_Front(src.m_Front), m_Back(src.m_Back), m_Count(src.m_Count) +{ + src.m_Front = src.m_Back = VMA_NULL; + src.m_Count = 0; +} + +template +VmaIntrusiveLinkedList& VmaIntrusiveLinkedList::operator=(VmaIntrusiveLinkedList&& src) +{ + if (&src != this) + { + VMA_HEAVY_ASSERT(IsEmpty()); + m_Front = src.m_Front; + m_Back = src.m_Back; + m_Count = src.m_Count; + src.m_Front = src.m_Back = VMA_NULL; + src.m_Count = 0; + } + return *this; +} + +template +void VmaIntrusiveLinkedList::PushBack(ItemType* item) +{ + VMA_HEAVY_ASSERT(ItemTypeTraits::GetPrev(item) == VMA_NULL && ItemTypeTraits::GetNext(item) == VMA_NULL); + if (IsEmpty()) + { + m_Front = item; + m_Back = item; + m_Count = 1; + } + else + { + ItemTypeTraits::AccessPrev(item) = m_Back; + ItemTypeTraits::AccessNext(m_Back) = item; + m_Back = item; + ++m_Count; + } +} + +template +void VmaIntrusiveLinkedList::PushFront(ItemType* item) +{ + VMA_HEAVY_ASSERT(ItemTypeTraits::GetPrev(item) == VMA_NULL && ItemTypeTraits::GetNext(item) == VMA_NULL); + if (IsEmpty()) + { + m_Front = item; + m_Back = item; + m_Count = 1; + } + else + { + ItemTypeTraits::AccessNext(item) = m_Front; + ItemTypeTraits::AccessPrev(m_Front) = item; + m_Front = item; + ++m_Count; + } +} + +template +typename VmaIntrusiveLinkedList::ItemType* VmaIntrusiveLinkedList::PopBack() +{ + VMA_HEAVY_ASSERT(m_Count > 0); + ItemType* const backItem = m_Back; + ItemType* const prevItem = ItemTypeTraits::GetPrev(backItem); + if (prevItem != VMA_NULL) + { + ItemTypeTraits::AccessNext(prevItem) = VMA_NULL; + } + m_Back = prevItem; + --m_Count; + ItemTypeTraits::AccessPrev(backItem) = VMA_NULL; + ItemTypeTraits::AccessNext(backItem) = VMA_NULL; + return backItem; +} + +template +typename VmaIntrusiveLinkedList::ItemType* VmaIntrusiveLinkedList::PopFront() +{ + VMA_HEAVY_ASSERT(m_Count > 0); + ItemType* const frontItem = m_Front; + ItemType* const nextItem = ItemTypeTraits::GetNext(frontItem); + if (nextItem != VMA_NULL) + { + ItemTypeTraits::AccessPrev(nextItem) = VMA_NULL; + } + m_Front = nextItem; + --m_Count; + ItemTypeTraits::AccessPrev(frontItem) = VMA_NULL; + ItemTypeTraits::AccessNext(frontItem) = VMA_NULL; + return frontItem; +} + +template +void VmaIntrusiveLinkedList::InsertBefore(ItemType* existingItem, ItemType* newItem) +{ + VMA_HEAVY_ASSERT(newItem != VMA_NULL && ItemTypeTraits::GetPrev(newItem) == VMA_NULL && ItemTypeTraits::GetNext(newItem) == VMA_NULL); + if (existingItem != VMA_NULL) + { + ItemType* const prevItem = ItemTypeTraits::GetPrev(existingItem); + ItemTypeTraits::AccessPrev(newItem) = prevItem; + ItemTypeTraits::AccessNext(newItem) = existingItem; + ItemTypeTraits::AccessPrev(existingItem) = newItem; + if (prevItem != VMA_NULL) + { + ItemTypeTraits::AccessNext(prevItem) = newItem; + } + else + { + VMA_HEAVY_ASSERT(m_Front == existingItem); + m_Front = newItem; + } + ++m_Count; + } + else + PushBack(newItem); +} + +template +void VmaIntrusiveLinkedList::InsertAfter(ItemType* existingItem, ItemType* newItem) +{ + VMA_HEAVY_ASSERT(newItem != VMA_NULL && ItemTypeTraits::GetPrev(newItem) == VMA_NULL && ItemTypeTraits::GetNext(newItem) == VMA_NULL); + if (existingItem != VMA_NULL) + { + ItemType* const nextItem = ItemTypeTraits::GetNext(existingItem); + ItemTypeTraits::AccessNext(newItem) = nextItem; + ItemTypeTraits::AccessPrev(newItem) = existingItem; + ItemTypeTraits::AccessNext(existingItem) = newItem; + if (nextItem != VMA_NULL) + { + ItemTypeTraits::AccessPrev(nextItem) = newItem; + } + else + { + VMA_HEAVY_ASSERT(m_Back == existingItem); + m_Back = newItem; + } + ++m_Count; + } + else + return PushFront(newItem); +} + +template +void VmaIntrusiveLinkedList::Remove(ItemType* item) +{ + VMA_HEAVY_ASSERT(item != VMA_NULL && m_Count > 0); + if (ItemTypeTraits::GetPrev(item) != VMA_NULL) + { + ItemTypeTraits::AccessNext(ItemTypeTraits::AccessPrev(item)) = ItemTypeTraits::GetNext(item); + } + else + { + VMA_HEAVY_ASSERT(m_Front == item); + m_Front = ItemTypeTraits::GetNext(item); + } + + if (ItemTypeTraits::GetNext(item) != VMA_NULL) + { + ItemTypeTraits::AccessPrev(ItemTypeTraits::AccessNext(item)) = ItemTypeTraits::GetPrev(item); + } + else + { + VMA_HEAVY_ASSERT(m_Back == item); + m_Back = ItemTypeTraits::GetPrev(item); + } + ItemTypeTraits::AccessPrev(item) = VMA_NULL; + ItemTypeTraits::AccessNext(item) = VMA_NULL; + --m_Count; +} + +template +void VmaIntrusiveLinkedList::RemoveAll() +{ + if (!IsEmpty()) + { + ItemType* item = m_Back; + while (item != VMA_NULL) + { + ItemType* const prevItem = ItemTypeTraits::AccessPrev(item); + ItemTypeTraits::AccessPrev(item) = VMA_NULL; + ItemTypeTraits::AccessNext(item) = VMA_NULL; + item = prevItem; + } + m_Front = VMA_NULL; + m_Back = VMA_NULL; + m_Count = 0; + } +} +#endif // _VMA_INTRUSIVE_LINKED_LIST_FUNCTIONS +#endif // _VMA_INTRUSIVE_LINKED_LIST + +#if !defined(_VMA_STRING_BUILDER) && VMA_STATS_STRING_ENABLED +class VmaStringBuilder +{ +public: + VmaStringBuilder(const VkAllocationCallbacks* allocationCallbacks) : m_Data(VmaStlAllocator(allocationCallbacks)) {} + ~VmaStringBuilder() = default; + + size_t GetLength() const { return m_Data.size(); } + const char* GetData() const { return m_Data.data(); } + void AddNewLine() { Add('\n'); } + void Add(char ch) { m_Data.push_back(ch); } + + void Add(const char* pStr); + void AddNumber(uint32_t num); + void AddNumber(uint64_t num); + void AddPointer(const void* ptr); + +private: + VmaVector> m_Data; +}; + +#ifndef _VMA_STRING_BUILDER_FUNCTIONS +void VmaStringBuilder::Add(const char* pStr) +{ + const size_t strLen = strlen(pStr); + if (strLen > 0) + { + const size_t oldCount = m_Data.size(); + m_Data.resize(oldCount + strLen); + memcpy(m_Data.data() + oldCount, pStr, strLen); + } +} + +void VmaStringBuilder::AddNumber(uint32_t num) +{ + char buf[11]; + buf[10] = '\0'; + char* p = &buf[10]; + do + { + *--p = '0' + (char)(num % 10); + num /= 10; + } while (num); + Add(p); +} + +void VmaStringBuilder::AddNumber(uint64_t num) +{ + char buf[21]; + buf[20] = '\0'; + char* p = &buf[20]; + do + { + *--p = '0' + (char)(num % 10); + num /= 10; + } while (num); + Add(p); +} + +void VmaStringBuilder::AddPointer(const void* ptr) +{ + char buf[21]; + VmaPtrToStr(buf, sizeof(buf), ptr); + Add(buf); +} +#endif //_VMA_STRING_BUILDER_FUNCTIONS +#endif // _VMA_STRING_BUILDER + +#if !defined(_VMA_JSON_WRITER) && VMA_STATS_STRING_ENABLED +/* +Allows to conveniently build a correct JSON document to be written to the +VmaStringBuilder passed to the constructor. +*/ +class VmaJsonWriter +{ + VMA_CLASS_NO_COPY_NO_MOVE(VmaJsonWriter) +public: + // sb - string builder to write the document to. Must remain alive for the whole lifetime of this object. + VmaJsonWriter(const VkAllocationCallbacks* pAllocationCallbacks, VmaStringBuilder& sb); + ~VmaJsonWriter(); + + // Begins object by writing "{". + // Inside an object, you must call pairs of WriteString and a value, e.g.: + // j.BeginObject(true); j.WriteString("A"); j.WriteNumber(1); j.WriteString("B"); j.WriteNumber(2); j.EndObject(); + // Will write: { "A": 1, "B": 2 } + void BeginObject(bool singleLine = false); + // Ends object by writing "}". + void EndObject(); + + // Begins array by writing "[". + // Inside an array, you can write a sequence of any values. + void BeginArray(bool singleLine = false); + // Ends array by writing "[". + void EndArray(); + + // Writes a string value inside "". + // pStr can contain any ANSI characters, including '"', new line etc. - they will be properly escaped. + void WriteString(const char* pStr); + + // Begins writing a string value. + // Call BeginString, ContinueString, ContinueString, ..., EndString instead of + // WriteString to conveniently build the string content incrementally, made of + // parts including numbers. + void BeginString(const char* pStr = VMA_NULL); + // Posts next part of an open string. + void ContinueString(const char* pStr); + // Posts next part of an open string. The number is converted to decimal characters. + void ContinueString(uint32_t n); + void ContinueString(uint64_t n); + // Posts next part of an open string. Pointer value is converted to characters + // using "%p" formatting - shown as hexadecimal number, e.g.: 000000081276Ad00 + void ContinueString_Pointer(const void* ptr); + // Ends writing a string value by writing '"'. + void EndString(const char* pStr = VMA_NULL); + + // Writes a number value. + void WriteNumber(uint32_t n); + void WriteNumber(uint64_t n); + // Writes a boolean value - false or true. + void WriteBool(bool b); + // Writes a null value. + void WriteNull(); + +private: + enum COLLECTION_TYPE + { + COLLECTION_TYPE_OBJECT, + COLLECTION_TYPE_ARRAY, + }; + struct StackItem + { + COLLECTION_TYPE type; + uint32_t valueCount; + bool singleLineMode; + }; + + static const char* const INDENT; + + VmaStringBuilder& m_SB; + VmaVector< StackItem, VmaStlAllocator > m_Stack; + bool m_InsideString; + + void BeginValue(bool isString); + void WriteIndent(bool oneLess = false); +}; +const char* const VmaJsonWriter::INDENT = " "; + +#ifndef _VMA_JSON_WRITER_FUNCTIONS +VmaJsonWriter::VmaJsonWriter(const VkAllocationCallbacks* pAllocationCallbacks, VmaStringBuilder& sb) + : m_SB(sb), + m_Stack(VmaStlAllocator(pAllocationCallbacks)), + m_InsideString(false) {} + +VmaJsonWriter::~VmaJsonWriter() +{ + VMA_ASSERT(!m_InsideString); + VMA_ASSERT(m_Stack.empty()); +} + +void VmaJsonWriter::BeginObject(bool singleLine) +{ + VMA_ASSERT(!m_InsideString); + + BeginValue(false); + m_SB.Add('{'); + + StackItem item; + item.type = COLLECTION_TYPE_OBJECT; + item.valueCount = 0; + item.singleLineMode = singleLine; + m_Stack.push_back(item); +} + +void VmaJsonWriter::EndObject() +{ + VMA_ASSERT(!m_InsideString); + + WriteIndent(true); + m_SB.Add('}'); + + VMA_ASSERT(!m_Stack.empty() && m_Stack.back().type == COLLECTION_TYPE_OBJECT); + m_Stack.pop_back(); +} + +void VmaJsonWriter::BeginArray(bool singleLine) +{ + VMA_ASSERT(!m_InsideString); + + BeginValue(false); + m_SB.Add('['); + + StackItem item; + item.type = COLLECTION_TYPE_ARRAY; + item.valueCount = 0; + item.singleLineMode = singleLine; + m_Stack.push_back(item); +} + +void VmaJsonWriter::EndArray() +{ + VMA_ASSERT(!m_InsideString); + + WriteIndent(true); + m_SB.Add(']'); + + VMA_ASSERT(!m_Stack.empty() && m_Stack.back().type == COLLECTION_TYPE_ARRAY); + m_Stack.pop_back(); +} + +void VmaJsonWriter::WriteString(const char* pStr) +{ + BeginString(pStr); + EndString(); +} + +void VmaJsonWriter::BeginString(const char* pStr) +{ + VMA_ASSERT(!m_InsideString); + + BeginValue(true); + m_SB.Add('"'); + m_InsideString = true; + if (pStr != VMA_NULL && pStr[0] != '\0') + { + ContinueString(pStr); + } +} + +void VmaJsonWriter::ContinueString(const char* pStr) +{ + VMA_ASSERT(m_InsideString); + + const size_t strLen = strlen(pStr); + for (size_t i = 0; i < strLen; ++i) + { + char ch = pStr[i]; + if (ch == '\\') + { + m_SB.Add("\\\\"); + } + else if (ch == '"') + { + m_SB.Add("\\\""); + } + else if ((uint8_t)ch >= 32) + { + m_SB.Add(ch); + } + else switch (ch) + { + case '\b': + m_SB.Add("\\b"); + break; + case '\f': + m_SB.Add("\\f"); + break; + case '\n': + m_SB.Add("\\n"); + break; + case '\r': + m_SB.Add("\\r"); + break; + case '\t': + m_SB.Add("\\t"); + break; + default: + VMA_ASSERT(0 && "Character not currently supported."); + } + } +} + +void VmaJsonWriter::ContinueString(uint32_t n) +{ + VMA_ASSERT(m_InsideString); + m_SB.AddNumber(n); +} + +void VmaJsonWriter::ContinueString(uint64_t n) +{ + VMA_ASSERT(m_InsideString); + m_SB.AddNumber(n); +} + +void VmaJsonWriter::ContinueString_Pointer(const void* ptr) +{ + VMA_ASSERT(m_InsideString); + m_SB.AddPointer(ptr); +} + +void VmaJsonWriter::EndString(const char* pStr) +{ + VMA_ASSERT(m_InsideString); + if (pStr != VMA_NULL && pStr[0] != '\0') + { + ContinueString(pStr); + } + m_SB.Add('"'); + m_InsideString = false; +} + +void VmaJsonWriter::WriteNumber(uint32_t n) +{ + VMA_ASSERT(!m_InsideString); + BeginValue(false); + m_SB.AddNumber(n); +} + +void VmaJsonWriter::WriteNumber(uint64_t n) +{ + VMA_ASSERT(!m_InsideString); + BeginValue(false); + m_SB.AddNumber(n); +} + +void VmaJsonWriter::WriteBool(bool b) +{ + VMA_ASSERT(!m_InsideString); + BeginValue(false); + m_SB.Add(b ? "true" : "false"); +} + +void VmaJsonWriter::WriteNull() +{ + VMA_ASSERT(!m_InsideString); + BeginValue(false); + m_SB.Add("null"); +} + +void VmaJsonWriter::BeginValue(bool isString) +{ + if (!m_Stack.empty()) + { + StackItem& currItem = m_Stack.back(); + if (currItem.type == COLLECTION_TYPE_OBJECT && + currItem.valueCount % 2 == 0) + { + VMA_ASSERT(isString); + } + + if (currItem.type == COLLECTION_TYPE_OBJECT && + currItem.valueCount % 2 != 0) + { + m_SB.Add(": "); + } + else if (currItem.valueCount > 0) + { + m_SB.Add(", "); + WriteIndent(); + } + else + { + WriteIndent(); + } + ++currItem.valueCount; + } +} + +void VmaJsonWriter::WriteIndent(bool oneLess) +{ + if (!m_Stack.empty() && !m_Stack.back().singleLineMode) + { + m_SB.AddNewLine(); + + size_t count = m_Stack.size(); + if (count > 0 && oneLess) + { + --count; + } + for (size_t i = 0; i < count; ++i) + { + m_SB.Add(INDENT); + } + } +} +#endif // _VMA_JSON_WRITER_FUNCTIONS + +static void VmaPrintDetailedStatistics(VmaJsonWriter& json, const VmaDetailedStatistics& stat) +{ + json.BeginObject(); + + json.WriteString("BlockCount"); + json.WriteNumber(stat.statistics.blockCount); + json.WriteString("BlockBytes"); + json.WriteNumber(stat.statistics.blockBytes); + json.WriteString("AllocationCount"); + json.WriteNumber(stat.statistics.allocationCount); + json.WriteString("AllocationBytes"); + json.WriteNumber(stat.statistics.allocationBytes); + json.WriteString("UnusedRangeCount"); + json.WriteNumber(stat.unusedRangeCount); + + if (stat.statistics.allocationCount > 1) + { + json.WriteString("AllocationSizeMin"); + json.WriteNumber(stat.allocationSizeMin); + json.WriteString("AllocationSizeMax"); + json.WriteNumber(stat.allocationSizeMax); + } + if (stat.unusedRangeCount > 1) + { + json.WriteString("UnusedRangeSizeMin"); + json.WriteNumber(stat.unusedRangeSizeMin); + json.WriteString("UnusedRangeSizeMax"); + json.WriteNumber(stat.unusedRangeSizeMax); + } + json.EndObject(); +} +#endif // _VMA_JSON_WRITER + +#ifndef _VMA_MAPPING_HYSTERESIS + +class VmaMappingHysteresis +{ + VMA_CLASS_NO_COPY_NO_MOVE(VmaMappingHysteresis) +public: + VmaMappingHysteresis() = default; + + uint32_t GetExtraMapping() const { return m_ExtraMapping; } + + // Call when Map was called. + // Returns true if switched to extra +1 mapping reference count. + bool PostMap() + { +#if VMA_MAPPING_HYSTERESIS_ENABLED + if(m_ExtraMapping == 0) + { + ++m_MajorCounter; + if(m_MajorCounter >= COUNTER_MIN_EXTRA_MAPPING) + { + m_ExtraMapping = 1; + m_MajorCounter = 0; + m_MinorCounter = 0; + return true; + } + } + else // m_ExtraMapping == 1 + PostMinorCounter(); +#endif // #if VMA_MAPPING_HYSTERESIS_ENABLED + return false; + } + + // Call when Unmap was called. + void PostUnmap() + { +#if VMA_MAPPING_HYSTERESIS_ENABLED + if(m_ExtraMapping == 0) + ++m_MajorCounter; + else // m_ExtraMapping == 1 + PostMinorCounter(); +#endif // #if VMA_MAPPING_HYSTERESIS_ENABLED + } + + // Call when allocation was made from the memory block. + void PostAlloc() + { +#if VMA_MAPPING_HYSTERESIS_ENABLED + if(m_ExtraMapping == 1) + ++m_MajorCounter; + else // m_ExtraMapping == 0 + PostMinorCounter(); +#endif // #if VMA_MAPPING_HYSTERESIS_ENABLED + } + + // Call when allocation was freed from the memory block. + // Returns true if switched to extra -1 mapping reference count. + bool PostFree() + { +#if VMA_MAPPING_HYSTERESIS_ENABLED + if(m_ExtraMapping == 1) + { + ++m_MajorCounter; + if(m_MajorCounter >= COUNTER_MIN_EXTRA_MAPPING && + m_MajorCounter > m_MinorCounter + 1) + { + m_ExtraMapping = 0; + m_MajorCounter = 0; + m_MinorCounter = 0; + return true; + } + } + else // m_ExtraMapping == 0 + PostMinorCounter(); +#endif // #if VMA_MAPPING_HYSTERESIS_ENABLED + return false; + } + +private: + static const int32_t COUNTER_MIN_EXTRA_MAPPING = 7; + + uint32_t m_MinorCounter = 0; + uint32_t m_MajorCounter = 0; + uint32_t m_ExtraMapping = 0; // 0 or 1. + + void PostMinorCounter() + { + if(m_MinorCounter < m_MajorCounter) + { + ++m_MinorCounter; + } + else if(m_MajorCounter > 0) + { + --m_MajorCounter; + --m_MinorCounter; + } + } +}; + +#endif // _VMA_MAPPING_HYSTERESIS + +#if VMA_EXTERNAL_MEMORY_WIN32 +class VmaWin32Handle +{ +public: + VmaWin32Handle() noexcept : m_hHandle(VMA_NULL) { } + explicit VmaWin32Handle(HANDLE hHandle) noexcept : m_hHandle(hHandle) { } + ~VmaWin32Handle() noexcept { if (m_hHandle != VMA_NULL) { ::CloseHandle(m_hHandle); } } + VMA_CLASS_NO_COPY_NO_MOVE(VmaWin32Handle) + +public: + // Strengthened + VkResult GetHandle(VkDevice device, VkDeviceMemory memory, PFN_vkGetMemoryWin32HandleKHR pvkGetMemoryWin32HandleKHR, HANDLE hTargetProcess, bool useMutex, HANDLE* pHandle) noexcept + { + *pHandle = VMA_NULL; + // Try to get handle first. + if (m_hHandle != VMA_NULL) + { + *pHandle = Duplicate(hTargetProcess); + return VK_SUCCESS; + } + + VkResult res = VK_SUCCESS; + // If failed, try to create it. + { + VmaMutexLockWrite lock(m_Mutex, useMutex); + if (m_hHandle == VMA_NULL) + { + res = Create(device, memory, pvkGetMemoryWin32HandleKHR, &m_hHandle); + } + } + + *pHandle = Duplicate(hTargetProcess); + return res; + } + + operator bool() const noexcept { return m_hHandle != VMA_NULL; } +private: + // Not atomic + static VkResult Create(VkDevice device, VkDeviceMemory memory, PFN_vkGetMemoryWin32HandleKHR pvkGetMemoryWin32HandleKHR, HANDLE* pHandle) noexcept + { + VkResult res = VK_ERROR_FEATURE_NOT_PRESENT; + if (pvkGetMemoryWin32HandleKHR != VMA_NULL) + { + VkMemoryGetWin32HandleInfoKHR handleInfo{ }; + handleInfo.sType = VK_STRUCTURE_TYPE_MEMORY_GET_WIN32_HANDLE_INFO_KHR; + handleInfo.memory = memory; + handleInfo.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT_KHR; + res = pvkGetMemoryWin32HandleKHR(device, &handleInfo, pHandle); + } + return res; + } + HANDLE Duplicate(HANDLE hTargetProcess = VMA_NULL) const noexcept + { + if (!m_hHandle) + return m_hHandle; + + HANDLE hCurrentProcess = ::GetCurrentProcess(); + HANDLE hDupHandle = VMA_NULL; + if (!::DuplicateHandle(hCurrentProcess, m_hHandle, hTargetProcess ? hTargetProcess : hCurrentProcess, &hDupHandle, 0, FALSE, DUPLICATE_SAME_ACCESS)) + { + VMA_ASSERT(0 && "Failed to duplicate handle."); + } + return hDupHandle; + } +private: + HANDLE m_hHandle; + VMA_RW_MUTEX m_Mutex; // Protects access m_Handle +}; +#else +class VmaWin32Handle +{ + // ABI compatibility + void* placeholder = VMA_NULL; + VMA_RW_MUTEX placeholder2; +}; +#endif // VMA_EXTERNAL_MEMORY_WIN32 + + +#ifndef _VMA_DEVICE_MEMORY_BLOCK +/* +Represents a single block of device memory (`VkDeviceMemory`) with all the +data about its regions (aka suballocations, #VmaAllocation), assigned and free. + +Thread-safety: +- Access to m_pMetadata must be externally synchronized. +- Map, Unmap, Bind* are synchronized internally. +*/ +class VmaDeviceMemoryBlock +{ + VMA_CLASS_NO_COPY_NO_MOVE(VmaDeviceMemoryBlock) +public: + VmaBlockMetadata* m_pMetadata; + + VmaDeviceMemoryBlock(VmaAllocator hAllocator); + ~VmaDeviceMemoryBlock(); + + // Always call after construction. + void Init( + VmaAllocator hAllocator, + VmaPool hParentPool, + uint32_t newMemoryTypeIndex, + VkDeviceMemory newMemory, + VkDeviceSize newSize, + uint32_t id, + uint32_t algorithm, + VkDeviceSize bufferImageGranularity); + // Always call before destruction. + void Destroy(VmaAllocator allocator); + + VmaPool GetParentPool() const { return m_hParentPool; } + VkDeviceMemory GetDeviceMemory() const { return m_hMemory; } + uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; } + uint32_t GetId() const { return m_Id; } + void* GetMappedData() const { return m_pMappedData; } + uint32_t GetMapRefCount() const { return m_MapCount; } + + // Call when allocation/free was made from m_pMetadata. + // Used for m_MappingHysteresis. + void PostAlloc(VmaAllocator hAllocator); + void PostFree(VmaAllocator hAllocator); + + // Validates all data structures inside this object. If not valid, returns false. + bool Validate() const; + VkResult CheckCorruption(VmaAllocator hAllocator); + + // ppData can be null. + VkResult Map(VmaAllocator hAllocator, uint32_t count, void** ppData); + void Unmap(VmaAllocator hAllocator, uint32_t count); + + VkResult WriteMagicValueAfterAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize); + VkResult ValidateMagicValueAfterAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize); + + VkResult BindBufferMemory( + const VmaAllocator hAllocator, + const VmaAllocation hAllocation, + VkDeviceSize allocationLocalOffset, + VkBuffer hBuffer, + const void* pNext); + VkResult BindImageMemory( + const VmaAllocator hAllocator, + const VmaAllocation hAllocation, + VkDeviceSize allocationLocalOffset, + VkImage hImage, + const void* pNext); +#if VMA_EXTERNAL_MEMORY_WIN32 + VkResult CreateWin32Handle( + const VmaAllocator hAllocator, + PFN_vkGetMemoryWin32HandleKHR pvkGetMemoryWin32HandleKHR, + HANDLE hTargetProcess, + HANDLE* pHandle)noexcept; +#endif // VMA_EXTERNAL_MEMORY_WIN32 +private: + VmaPool m_hParentPool; // VK_NULL_HANDLE if not belongs to custom pool. + uint32_t m_MemoryTypeIndex; + uint32_t m_Id; + VkDeviceMemory m_hMemory; + + /* + Protects access to m_hMemory so it is not used by multiple threads simultaneously, e.g. vkMapMemory, vkBindBufferMemory. + Also protects m_MapCount, m_pMappedData. + Allocations, deallocations, any change in m_pMetadata is protected by parent's VmaBlockVector::m_Mutex. + */ + VMA_MUTEX m_MapAndBindMutex; + VmaMappingHysteresis m_MappingHysteresis; + uint32_t m_MapCount; + void* m_pMappedData; + + VmaWin32Handle m_Handle; +}; +#endif // _VMA_DEVICE_MEMORY_BLOCK + +#ifndef _VMA_ALLOCATION_T +struct VmaAllocationExtraData +{ + void* m_pMappedData = VMA_NULL; // Not null means memory is mapped. + VmaWin32Handle m_Handle; +}; + +struct VmaAllocation_T +{ + friend struct VmaDedicatedAllocationListItemTraits; + + enum FLAGS + { + FLAG_PERSISTENT_MAP = 0x01, + FLAG_MAPPING_ALLOWED = 0x02, + }; + +public: + enum ALLOCATION_TYPE + { + ALLOCATION_TYPE_NONE, + ALLOCATION_TYPE_BLOCK, + ALLOCATION_TYPE_DEDICATED, + }; + + // This struct is allocated using VmaPoolAllocator. + VmaAllocation_T(bool mappingAllowed); + ~VmaAllocation_T(); + + void InitBlockAllocation( + VmaDeviceMemoryBlock* block, + VmaAllocHandle allocHandle, + VkDeviceSize alignment, + VkDeviceSize size, + uint32_t memoryTypeIndex, + VmaSuballocationType suballocationType, + bool mapped); + // pMappedData not null means allocation is created with MAPPED flag. + void InitDedicatedAllocation( + VmaAllocator allocator, + VmaPool hParentPool, + uint32_t memoryTypeIndex, + VkDeviceMemory hMemory, + VmaSuballocationType suballocationType, + void* pMappedData, + VkDeviceSize size); + void Destroy(VmaAllocator allocator); + + ALLOCATION_TYPE GetType() const { return (ALLOCATION_TYPE)m_Type; } + VkDeviceSize GetAlignment() const { return m_Alignment; } + VkDeviceSize GetSize() const { return m_Size; } + void* GetUserData() const { return m_pUserData; } + const char* GetName() const { return m_pName; } + VmaSuballocationType GetSuballocationType() const { return (VmaSuballocationType)m_SuballocationType; } + + VmaDeviceMemoryBlock* GetBlock() const { VMA_ASSERT(m_Type == ALLOCATION_TYPE_BLOCK); return m_BlockAllocation.m_Block; } + uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; } + bool IsPersistentMap() const { return (m_Flags & FLAG_PERSISTENT_MAP) != 0; } + bool IsMappingAllowed() const { return (m_Flags & FLAG_MAPPING_ALLOWED) != 0; } + + void SetUserData(VmaAllocator hAllocator, void* pUserData) { m_pUserData = pUserData; } + void SetName(VmaAllocator hAllocator, const char* pName); + void FreeName(VmaAllocator hAllocator); + uint8_t SwapBlockAllocation(VmaAllocator hAllocator, VmaAllocation allocation); + VmaAllocHandle GetAllocHandle() const; + VkDeviceSize GetOffset() const; + VmaPool GetParentPool() const; + VkDeviceMemory GetMemory() const; + void* GetMappedData() const; + + void BlockAllocMap(); + void BlockAllocUnmap(); + VkResult DedicatedAllocMap(VmaAllocator hAllocator, void** ppData); + void DedicatedAllocUnmap(VmaAllocator hAllocator); + +#if VMA_STATS_STRING_ENABLED + VmaBufferImageUsage GetBufferImageUsage() const { return m_BufferImageUsage; } + void InitBufferUsage(const VkBufferCreateInfo &createInfo, bool useKhrMaintenance5) + { + VMA_ASSERT(m_BufferImageUsage == VmaBufferImageUsage::UNKNOWN); + m_BufferImageUsage = VmaBufferImageUsage(createInfo, useKhrMaintenance5); + } + void InitImageUsage(const VkImageCreateInfo &createInfo) + { + VMA_ASSERT(m_BufferImageUsage == VmaBufferImageUsage::UNKNOWN); + m_BufferImageUsage = VmaBufferImageUsage(createInfo); + } + void PrintParameters(class VmaJsonWriter& json) const; +#endif + +#if VMA_EXTERNAL_MEMORY_WIN32 + VkResult GetWin32Handle(VmaAllocator hAllocator, HANDLE hTargetProcess, HANDLE* hHandle) noexcept; +#endif // VMA_EXTERNAL_MEMORY_WIN32 + +private: + // Allocation out of VmaDeviceMemoryBlock. + struct BlockAllocation + { + VmaDeviceMemoryBlock* m_Block; + VmaAllocHandle m_AllocHandle; + }; + // Allocation for an object that has its own private VkDeviceMemory. + struct DedicatedAllocation + { + VmaPool m_hParentPool; // VK_NULL_HANDLE if not belongs to custom pool. + VkDeviceMemory m_hMemory; + VmaAllocationExtraData* m_ExtraData; + VmaAllocation_T* m_Prev; + VmaAllocation_T* m_Next; + }; + union + { + // Allocation out of VmaDeviceMemoryBlock. + BlockAllocation m_BlockAllocation; + // Allocation for an object that has its own private VkDeviceMemory. + DedicatedAllocation m_DedicatedAllocation; + }; + + VkDeviceSize m_Alignment; + VkDeviceSize m_Size; + void* m_pUserData; + char* m_pName; + uint32_t m_MemoryTypeIndex; + uint8_t m_Type; // ALLOCATION_TYPE + uint8_t m_SuballocationType; // VmaSuballocationType + // Reference counter for vmaMapMemory()/vmaUnmapMemory(). + uint8_t m_MapCount; + uint8_t m_Flags; // enum FLAGS +#if VMA_STATS_STRING_ENABLED + VmaBufferImageUsage m_BufferImageUsage; // 0 if unknown. +#endif + + void EnsureExtraData(VmaAllocator hAllocator); +}; +#endif // _VMA_ALLOCATION_T + +#ifndef _VMA_DEDICATED_ALLOCATION_LIST_ITEM_TRAITS +struct VmaDedicatedAllocationListItemTraits +{ + typedef VmaAllocation_T ItemType; + + static ItemType* GetPrev(const ItemType* item) + { + VMA_HEAVY_ASSERT(item->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED); + return item->m_DedicatedAllocation.m_Prev; + } + static ItemType* GetNext(const ItemType* item) + { + VMA_HEAVY_ASSERT(item->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED); + return item->m_DedicatedAllocation.m_Next; + } + static ItemType*& AccessPrev(ItemType* item) + { + VMA_HEAVY_ASSERT(item->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED); + return item->m_DedicatedAllocation.m_Prev; + } + static ItemType*& AccessNext(ItemType* item) + { + VMA_HEAVY_ASSERT(item->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED); + return item->m_DedicatedAllocation.m_Next; + } +}; +#endif // _VMA_DEDICATED_ALLOCATION_LIST_ITEM_TRAITS + +#ifndef _VMA_DEDICATED_ALLOCATION_LIST +/* +Stores linked list of VmaAllocation_T objects. +Thread-safe, synchronized internally. +*/ +class VmaDedicatedAllocationList +{ + VMA_CLASS_NO_COPY_NO_MOVE(VmaDedicatedAllocationList) +public: + VmaDedicatedAllocationList() {} + ~VmaDedicatedAllocationList(); + + void Init(bool useMutex) { m_UseMutex = useMutex; } + bool Validate(); + + void AddDetailedStatistics(VmaDetailedStatistics& inoutStats); + void AddStatistics(VmaStatistics& inoutStats); +#if VMA_STATS_STRING_ENABLED + // Writes JSON array with the list of allocations. + void BuildStatsString(VmaJsonWriter& json); +#endif + + bool IsEmpty(); + void Register(VmaAllocation alloc); + void Unregister(VmaAllocation alloc); + +private: + typedef VmaIntrusiveLinkedList DedicatedAllocationLinkedList; + + bool m_UseMutex = true; + VMA_RW_MUTEX m_Mutex; + DedicatedAllocationLinkedList m_AllocationList; +}; + +#ifndef _VMA_DEDICATED_ALLOCATION_LIST_FUNCTIONS + +VmaDedicatedAllocationList::~VmaDedicatedAllocationList() +{ + VMA_HEAVY_ASSERT(Validate()); + + if (!m_AllocationList.IsEmpty()) + { + VMA_ASSERT_LEAK(false && "Unfreed dedicated allocations found!"); + } +} + +bool VmaDedicatedAllocationList::Validate() +{ + const size_t declaredCount = m_AllocationList.GetCount(); + size_t actualCount = 0; + VmaMutexLockRead lock(m_Mutex, m_UseMutex); + for (VmaAllocation alloc = m_AllocationList.Front(); + alloc != VMA_NULL; alloc = m_AllocationList.GetNext(alloc)) + { + ++actualCount; + } + VMA_VALIDATE(actualCount == declaredCount); + + return true; +} + +void VmaDedicatedAllocationList::AddDetailedStatistics(VmaDetailedStatistics& inoutStats) +{ + for(auto* item = m_AllocationList.Front(); item != VMA_NULL; item = DedicatedAllocationLinkedList::GetNext(item)) + { + const VkDeviceSize size = item->GetSize(); + inoutStats.statistics.blockCount++; + inoutStats.statistics.blockBytes += size; + VmaAddDetailedStatisticsAllocation(inoutStats, item->GetSize()); + } +} + +void VmaDedicatedAllocationList::AddStatistics(VmaStatistics& inoutStats) +{ + VmaMutexLockRead lock(m_Mutex, m_UseMutex); + + const uint32_t allocCount = (uint32_t)m_AllocationList.GetCount(); + inoutStats.blockCount += allocCount; + inoutStats.allocationCount += allocCount; + + for(auto* item = m_AllocationList.Front(); item != VMA_NULL; item = DedicatedAllocationLinkedList::GetNext(item)) + { + const VkDeviceSize size = item->GetSize(); + inoutStats.blockBytes += size; + inoutStats.allocationBytes += size; + } +} + +#if VMA_STATS_STRING_ENABLED +void VmaDedicatedAllocationList::BuildStatsString(VmaJsonWriter& json) +{ + VmaMutexLockRead lock(m_Mutex, m_UseMutex); + json.BeginArray(); + for (VmaAllocation alloc = m_AllocationList.Front(); + alloc != VMA_NULL; alloc = m_AllocationList.GetNext(alloc)) + { + json.BeginObject(true); + alloc->PrintParameters(json); + json.EndObject(); + } + json.EndArray(); +} +#endif // VMA_STATS_STRING_ENABLED + +bool VmaDedicatedAllocationList::IsEmpty() +{ + VmaMutexLockRead lock(m_Mutex, m_UseMutex); + return m_AllocationList.IsEmpty(); +} + +void VmaDedicatedAllocationList::Register(VmaAllocation alloc) +{ + VmaMutexLockWrite lock(m_Mutex, m_UseMutex); + m_AllocationList.PushBack(alloc); +} + +void VmaDedicatedAllocationList::Unregister(VmaAllocation alloc) +{ + VmaMutexLockWrite lock(m_Mutex, m_UseMutex); + m_AllocationList.Remove(alloc); +} +#endif // _VMA_DEDICATED_ALLOCATION_LIST_FUNCTIONS +#endif // _VMA_DEDICATED_ALLOCATION_LIST + +#ifndef _VMA_SUBALLOCATION +/* +Represents a region of VmaDeviceMemoryBlock that is either assigned and returned as +allocated memory block or free. +*/ +struct VmaSuballocation +{ + VkDeviceSize offset; + VkDeviceSize size; + void* userData; + VmaSuballocationType type; +}; + +// Comparator for offsets. +struct VmaSuballocationOffsetLess +{ + bool operator()(const VmaSuballocation& lhs, const VmaSuballocation& rhs) const + { + return lhs.offset < rhs.offset; + } +}; + +struct VmaSuballocationOffsetGreater +{ + bool operator()(const VmaSuballocation& lhs, const VmaSuballocation& rhs) const + { + return lhs.offset > rhs.offset; + } +}; + +struct VmaSuballocationItemSizeLess +{ + bool operator()(const VmaSuballocationList::iterator lhs, + const VmaSuballocationList::iterator rhs) const + { + return lhs->size < rhs->size; + } + + bool operator()(const VmaSuballocationList::iterator lhs, + VkDeviceSize rhsSize) const + { + return lhs->size < rhsSize; + } +}; +#endif // _VMA_SUBALLOCATION + +#ifndef _VMA_ALLOCATION_REQUEST +/* +Parameters of planned allocation inside a VmaDeviceMemoryBlock. +item points to a FREE suballocation. +*/ +struct VmaAllocationRequest +{ + VmaAllocHandle allocHandle; + VkDeviceSize size; + VmaSuballocationList::iterator item; + void* customData; + uint64_t algorithmData; + VmaAllocationRequestType type; +}; +#endif // _VMA_ALLOCATION_REQUEST + +#ifndef _VMA_BLOCK_METADATA +/* +Data structure used for bookkeeping of allocations and unused ranges of memory +in a single VkDeviceMemory block. +*/ +class VmaBlockMetadata +{ + VMA_CLASS_NO_COPY_NO_MOVE(VmaBlockMetadata) +public: + // pAllocationCallbacks, if not null, must be owned externally - alive and unchanged for the whole lifetime of this object. + VmaBlockMetadata(const VkAllocationCallbacks* pAllocationCallbacks, + VkDeviceSize bufferImageGranularity, bool isVirtual); + virtual ~VmaBlockMetadata() = default; + + virtual void Init(VkDeviceSize size) { m_Size = size; } + bool IsVirtual() const { return m_IsVirtual; } + VkDeviceSize GetSize() const { return m_Size; } + + // Validates all data structures inside this object. If not valid, returns false. + virtual bool Validate() const = 0; + virtual size_t GetAllocationCount() const = 0; + virtual size_t GetFreeRegionsCount() const = 0; + virtual VkDeviceSize GetSumFreeSize() const = 0; + // Returns true if this block is empty - contains only single free suballocation. + virtual bool IsEmpty() const = 0; + virtual void GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo) = 0; + virtual VkDeviceSize GetAllocationOffset(VmaAllocHandle allocHandle) const = 0; + virtual void* GetAllocationUserData(VmaAllocHandle allocHandle) const = 0; + + virtual VmaAllocHandle GetAllocationListBegin() const = 0; + virtual VmaAllocHandle GetNextAllocation(VmaAllocHandle prevAlloc) const = 0; + virtual VkDeviceSize GetNextFreeRegionSize(VmaAllocHandle alloc) const = 0; + + // Shouldn't modify blockCount. + virtual void AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const = 0; + virtual void AddStatistics(VmaStatistics& inoutStats) const = 0; + +#if VMA_STATS_STRING_ENABLED + virtual void PrintDetailedMap(class VmaJsonWriter& json) const = 0; +#endif + + // Tries to find a place for suballocation with given parameters inside this block. + // If succeeded, fills pAllocationRequest and returns true. + // If failed, returns false. + virtual bool CreateAllocationRequest( + VkDeviceSize allocSize, + VkDeviceSize allocAlignment, + bool upperAddress, + VmaSuballocationType allocType, + // Always one of VMA_ALLOCATION_CREATE_STRATEGY_* or VMA_ALLOCATION_INTERNAL_STRATEGY_* flags. + uint32_t strategy, + VmaAllocationRequest* pAllocationRequest) = 0; + + virtual VkResult CheckCorruption(const void* pBlockData) = 0; + + // Makes actual allocation based on request. Request must already be checked and valid. + virtual void Alloc( + const VmaAllocationRequest& request, + VmaSuballocationType type, + void* userData) = 0; + + // Frees suballocation assigned to given memory region. + virtual void Free(VmaAllocHandle allocHandle) = 0; + + // Frees all allocations. + // Careful! Don't call it if there are VmaAllocation objects owned by userData of cleared allocations! + virtual void Clear() = 0; + + virtual void SetAllocationUserData(VmaAllocHandle allocHandle, void* userData) = 0; + virtual void DebugLogAllAllocations() const = 0; + +protected: + const VkAllocationCallbacks* GetAllocationCallbacks() const { return m_pAllocationCallbacks; } + VkDeviceSize GetBufferImageGranularity() const { return m_BufferImageGranularity; } + VkDeviceSize GetDebugMargin() const { return VkDeviceSize(IsVirtual() ? 0 : VMA_DEBUG_MARGIN); } + + void DebugLogAllocation(VkDeviceSize offset, VkDeviceSize size, void* userData) const; +#if VMA_STATS_STRING_ENABLED + // mapRefCount == UINT32_MAX means unspecified. + void PrintDetailedMap_Begin(class VmaJsonWriter& json, + VkDeviceSize unusedBytes, + size_t allocationCount, + size_t unusedRangeCount) const; + void PrintDetailedMap_Allocation(class VmaJsonWriter& json, + VkDeviceSize offset, VkDeviceSize size, void* userData) const; + void PrintDetailedMap_UnusedRange(class VmaJsonWriter& json, + VkDeviceSize offset, + VkDeviceSize size) const; + void PrintDetailedMap_End(class VmaJsonWriter& json) const; +#endif + +private: + VkDeviceSize m_Size; + const VkAllocationCallbacks* m_pAllocationCallbacks; + const VkDeviceSize m_BufferImageGranularity; + const bool m_IsVirtual; +}; + +#ifndef _VMA_BLOCK_METADATA_FUNCTIONS +VmaBlockMetadata::VmaBlockMetadata(const VkAllocationCallbacks* pAllocationCallbacks, + VkDeviceSize bufferImageGranularity, bool isVirtual) + : m_Size(0), + m_pAllocationCallbacks(pAllocationCallbacks), + m_BufferImageGranularity(bufferImageGranularity), + m_IsVirtual(isVirtual) {} + +void VmaBlockMetadata::DebugLogAllocation(VkDeviceSize offset, VkDeviceSize size, void* userData) const +{ + if (IsVirtual()) + { + VMA_LEAK_LOG_FORMAT("UNFREED VIRTUAL ALLOCATION; Offset: %" PRIu64 "; Size: %" PRIu64 "; UserData: %p", offset, size, userData); + } + else + { + VMA_ASSERT(userData != VMA_NULL); + VmaAllocation allocation = reinterpret_cast(userData); + + userData = allocation->GetUserData(); + const char* name = allocation->GetName(); + +#if VMA_STATS_STRING_ENABLED + VMA_LEAK_LOG_FORMAT("UNFREED ALLOCATION; Offset: %" PRIu64 "; Size: %" PRIu64 "; UserData: %p; Name: %s; Type: %s; Usage: %" PRIu64, + offset, size, userData, name ? name : "vma_empty", + VMA_SUBALLOCATION_TYPE_NAMES[allocation->GetSuballocationType()], + (uint64_t)allocation->GetBufferImageUsage().Value); +#else + VMA_LEAK_LOG_FORMAT("UNFREED ALLOCATION; Offset: %" PRIu64 "; Size: %" PRIu64 "; UserData: %p; Name: %s; Type: %u", + offset, size, userData, name ? name : "vma_empty", + (unsigned)allocation->GetSuballocationType()); +#endif // VMA_STATS_STRING_ENABLED + } + +} + +#if VMA_STATS_STRING_ENABLED +void VmaBlockMetadata::PrintDetailedMap_Begin(class VmaJsonWriter& json, + VkDeviceSize unusedBytes, size_t allocationCount, size_t unusedRangeCount) const +{ + json.WriteString("TotalBytes"); + json.WriteNumber(GetSize()); + + json.WriteString("UnusedBytes"); + json.WriteNumber(unusedBytes); + + json.WriteString("Allocations"); + json.WriteNumber((uint64_t)allocationCount); + + json.WriteString("UnusedRanges"); + json.WriteNumber((uint64_t)unusedRangeCount); + + json.WriteString("Suballocations"); + json.BeginArray(); +} + +void VmaBlockMetadata::PrintDetailedMap_Allocation(class VmaJsonWriter& json, + VkDeviceSize offset, VkDeviceSize size, void* userData) const +{ + json.BeginObject(true); + + json.WriteString("Offset"); + json.WriteNumber(offset); + + if (IsVirtual()) + { + json.WriteString("Size"); + json.WriteNumber(size); + if (userData) + { + json.WriteString("CustomData"); + json.BeginString(); + json.ContinueString_Pointer(userData); + json.EndString(); + } + } + else + { + ((VmaAllocation)userData)->PrintParameters(json); + } + + json.EndObject(); +} + +void VmaBlockMetadata::PrintDetailedMap_UnusedRange(class VmaJsonWriter& json, + VkDeviceSize offset, VkDeviceSize size) const +{ + json.BeginObject(true); + + json.WriteString("Offset"); + json.WriteNumber(offset); + + json.WriteString("Type"); + json.WriteString(VMA_SUBALLOCATION_TYPE_NAMES[VMA_SUBALLOCATION_TYPE_FREE]); + + json.WriteString("Size"); + json.WriteNumber(size); + + json.EndObject(); +} + +void VmaBlockMetadata::PrintDetailedMap_End(class VmaJsonWriter& json) const +{ + json.EndArray(); +} +#endif // VMA_STATS_STRING_ENABLED +#endif // _VMA_BLOCK_METADATA_FUNCTIONS +#endif // _VMA_BLOCK_METADATA + +#ifndef _VMA_BLOCK_BUFFER_IMAGE_GRANULARITY +// Before deleting object of this class remember to call 'Destroy()' +class VmaBlockBufferImageGranularity final +{ +public: + struct ValidationContext + { + const VkAllocationCallbacks* allocCallbacks; + uint16_t* pageAllocs; + }; + + VmaBlockBufferImageGranularity(VkDeviceSize bufferImageGranularity); + ~VmaBlockBufferImageGranularity(); + + bool IsEnabled() const { return m_BufferImageGranularity > MAX_LOW_BUFFER_IMAGE_GRANULARITY; } + + void Init(const VkAllocationCallbacks* pAllocationCallbacks, VkDeviceSize size); + // Before destroying object you must call free it's memory + void Destroy(const VkAllocationCallbacks* pAllocationCallbacks); + + void RoundupAllocRequest(VmaSuballocationType allocType, + VkDeviceSize& inOutAllocSize, + VkDeviceSize& inOutAllocAlignment) const; + + bool CheckConflictAndAlignUp(VkDeviceSize& inOutAllocOffset, + VkDeviceSize allocSize, + VkDeviceSize blockOffset, + VkDeviceSize blockSize, + VmaSuballocationType allocType) const; + + void AllocPages(uint8_t allocType, VkDeviceSize offset, VkDeviceSize size); + void FreePages(VkDeviceSize offset, VkDeviceSize size); + void Clear(); + + ValidationContext StartValidation(const VkAllocationCallbacks* pAllocationCallbacks, + bool isVirutal) const; + bool Validate(ValidationContext& ctx, VkDeviceSize offset, VkDeviceSize size) const; + bool FinishValidation(ValidationContext& ctx) const; + +private: + static const uint16_t MAX_LOW_BUFFER_IMAGE_GRANULARITY = 256; + + struct RegionInfo + { + uint8_t allocType; + uint16_t allocCount; + }; + + VkDeviceSize m_BufferImageGranularity; + uint32_t m_RegionCount; + RegionInfo* m_RegionInfo; + + uint32_t GetStartPage(VkDeviceSize offset) const { return OffsetToPageIndex(offset & ~(m_BufferImageGranularity - 1)); } + uint32_t GetEndPage(VkDeviceSize offset, VkDeviceSize size) const { return OffsetToPageIndex((offset + size - 1) & ~(m_BufferImageGranularity - 1)); } + + uint32_t OffsetToPageIndex(VkDeviceSize offset) const; + void AllocPage(RegionInfo& page, uint8_t allocType); +}; + +#ifndef _VMA_BLOCK_BUFFER_IMAGE_GRANULARITY_FUNCTIONS +VmaBlockBufferImageGranularity::VmaBlockBufferImageGranularity(VkDeviceSize bufferImageGranularity) + : m_BufferImageGranularity(bufferImageGranularity), + m_RegionCount(0), + m_RegionInfo(VMA_NULL) {} + +VmaBlockBufferImageGranularity::~VmaBlockBufferImageGranularity() +{ + VMA_ASSERT(m_RegionInfo == VMA_NULL && "Free not called before destroying object!"); +} + +void VmaBlockBufferImageGranularity::Init(const VkAllocationCallbacks* pAllocationCallbacks, VkDeviceSize size) +{ + if (IsEnabled()) + { + m_RegionCount = static_cast(VmaDivideRoundingUp(size, m_BufferImageGranularity)); + m_RegionInfo = vma_new_array(pAllocationCallbacks, RegionInfo, m_RegionCount); + memset(m_RegionInfo, 0, m_RegionCount * sizeof(RegionInfo)); + } +} + +void VmaBlockBufferImageGranularity::Destroy(const VkAllocationCallbacks* pAllocationCallbacks) +{ + if (m_RegionInfo) + { + vma_delete_array(pAllocationCallbacks, m_RegionInfo, m_RegionCount); + m_RegionInfo = VMA_NULL; + } +} + +void VmaBlockBufferImageGranularity::RoundupAllocRequest(VmaSuballocationType allocType, + VkDeviceSize& inOutAllocSize, + VkDeviceSize& inOutAllocAlignment) const +{ + if (m_BufferImageGranularity > 1 && + m_BufferImageGranularity <= MAX_LOW_BUFFER_IMAGE_GRANULARITY) + { + if (allocType == VMA_SUBALLOCATION_TYPE_UNKNOWN || + allocType == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN || + allocType == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL) + { + inOutAllocAlignment = VMA_MAX(inOutAllocAlignment, m_BufferImageGranularity); + inOutAllocSize = VmaAlignUp(inOutAllocSize, m_BufferImageGranularity); + } + } +} + +bool VmaBlockBufferImageGranularity::CheckConflictAndAlignUp(VkDeviceSize& inOutAllocOffset, + VkDeviceSize allocSize, + VkDeviceSize blockOffset, + VkDeviceSize blockSize, + VmaSuballocationType allocType) const +{ + if (IsEnabled()) + { + uint32_t startPage = GetStartPage(inOutAllocOffset); + if (m_RegionInfo[startPage].allocCount > 0 && + VmaIsBufferImageGranularityConflict(static_cast(m_RegionInfo[startPage].allocType), allocType)) + { + inOutAllocOffset = VmaAlignUp(inOutAllocOffset, m_BufferImageGranularity); + if (blockSize < allocSize + inOutAllocOffset - blockOffset) + return true; + ++startPage; + } + uint32_t endPage = GetEndPage(inOutAllocOffset, allocSize); + if (endPage != startPage && + m_RegionInfo[endPage].allocCount > 0 && + VmaIsBufferImageGranularityConflict(static_cast(m_RegionInfo[endPage].allocType), allocType)) + { + return true; + } + } + return false; +} + +void VmaBlockBufferImageGranularity::AllocPages(uint8_t allocType, VkDeviceSize offset, VkDeviceSize size) +{ + if (IsEnabled()) + { + uint32_t startPage = GetStartPage(offset); + AllocPage(m_RegionInfo[startPage], allocType); + + uint32_t endPage = GetEndPage(offset, size); + if (startPage != endPage) + AllocPage(m_RegionInfo[endPage], allocType); + } +} + +void VmaBlockBufferImageGranularity::FreePages(VkDeviceSize offset, VkDeviceSize size) +{ + if (IsEnabled()) + { + uint32_t startPage = GetStartPage(offset); + --m_RegionInfo[startPage].allocCount; + if (m_RegionInfo[startPage].allocCount == 0) + m_RegionInfo[startPage].allocType = VMA_SUBALLOCATION_TYPE_FREE; + uint32_t endPage = GetEndPage(offset, size); + if (startPage != endPage) + { + --m_RegionInfo[endPage].allocCount; + if (m_RegionInfo[endPage].allocCount == 0) + m_RegionInfo[endPage].allocType = VMA_SUBALLOCATION_TYPE_FREE; + } + } +} + +void VmaBlockBufferImageGranularity::Clear() +{ + if (m_RegionInfo) + memset(m_RegionInfo, 0, m_RegionCount * sizeof(RegionInfo)); +} + +VmaBlockBufferImageGranularity::ValidationContext VmaBlockBufferImageGranularity::StartValidation( + const VkAllocationCallbacks* pAllocationCallbacks, bool isVirutal) const +{ + ValidationContext ctx{ pAllocationCallbacks, VMA_NULL }; + if (!isVirutal && IsEnabled()) + { + ctx.pageAllocs = vma_new_array(pAllocationCallbacks, uint16_t, m_RegionCount); + memset(ctx.pageAllocs, 0, m_RegionCount * sizeof(uint16_t)); + } + return ctx; +} + +bool VmaBlockBufferImageGranularity::Validate(ValidationContext& ctx, + VkDeviceSize offset, VkDeviceSize size) const +{ + if (IsEnabled()) + { + uint32_t start = GetStartPage(offset); + ++ctx.pageAllocs[start]; + VMA_VALIDATE(m_RegionInfo[start].allocCount > 0); + + uint32_t end = GetEndPage(offset, size); + if (start != end) + { + ++ctx.pageAllocs[end]; + VMA_VALIDATE(m_RegionInfo[end].allocCount > 0); + } + } + return true; +} + +bool VmaBlockBufferImageGranularity::FinishValidation(ValidationContext& ctx) const +{ + // Check proper page structure + if (IsEnabled()) + { + VMA_ASSERT(ctx.pageAllocs != VMA_NULL && "Validation context not initialized!"); + + for (uint32_t page = 0; page < m_RegionCount; ++page) + { + VMA_VALIDATE(ctx.pageAllocs[page] == m_RegionInfo[page].allocCount); + } + vma_delete_array(ctx.allocCallbacks, ctx.pageAllocs, m_RegionCount); + ctx.pageAllocs = VMA_NULL; + } + return true; +} + +uint32_t VmaBlockBufferImageGranularity::OffsetToPageIndex(VkDeviceSize offset) const +{ + return static_cast(offset >> VMA_BITSCAN_MSB(m_BufferImageGranularity)); +} + +void VmaBlockBufferImageGranularity::AllocPage(RegionInfo& page, uint8_t allocType) +{ + // When current alloc type is free then it can be overridden by new type + if (page.allocCount == 0 || (page.allocCount > 0 && page.allocType == VMA_SUBALLOCATION_TYPE_FREE)) + page.allocType = allocType; + + ++page.allocCount; +} +#endif // _VMA_BLOCK_BUFFER_IMAGE_GRANULARITY_FUNCTIONS +#endif // _VMA_BLOCK_BUFFER_IMAGE_GRANULARITY + +#ifndef _VMA_BLOCK_METADATA_LINEAR +/* +Allocations and their references in internal data structure look like this: + +if(m_2ndVectorMode == SECOND_VECTOR_EMPTY): + + 0 +-------+ + | | + | | + | | + +-------+ + | Alloc | 1st[m_1stNullItemsBeginCount] + +-------+ + | Alloc | 1st[m_1stNullItemsBeginCount + 1] + +-------+ + | ... | + +-------+ + | Alloc | 1st[1st.size() - 1] + +-------+ + | | + | | + | | +GetSize() +-------+ + +if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER): + + 0 +-------+ + | Alloc | 2nd[0] + +-------+ + | Alloc | 2nd[1] + +-------+ + | ... | + +-------+ + | Alloc | 2nd[2nd.size() - 1] + +-------+ + | | + | | + | | + +-------+ + | Alloc | 1st[m_1stNullItemsBeginCount] + +-------+ + | Alloc | 1st[m_1stNullItemsBeginCount + 1] + +-------+ + | ... | + +-------+ + | Alloc | 1st[1st.size() - 1] + +-------+ + | | +GetSize() +-------+ + +if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK): + + 0 +-------+ + | | + | | + | | + +-------+ + | Alloc | 1st[m_1stNullItemsBeginCount] + +-------+ + | Alloc | 1st[m_1stNullItemsBeginCount + 1] + +-------+ + | ... | + +-------+ + | Alloc | 1st[1st.size() - 1] + +-------+ + | | + | | + | | + +-------+ + | Alloc | 2nd[2nd.size() - 1] + +-------+ + | ... | + +-------+ + | Alloc | 2nd[1] + +-------+ + | Alloc | 2nd[0] +GetSize() +-------+ + +*/ +class VmaBlockMetadata_Linear : public VmaBlockMetadata +{ + VMA_CLASS_NO_COPY_NO_MOVE(VmaBlockMetadata_Linear) +public: + VmaBlockMetadata_Linear(const VkAllocationCallbacks* pAllocationCallbacks, + VkDeviceSize bufferImageGranularity, bool isVirtual); + virtual ~VmaBlockMetadata_Linear() = default; + + VkDeviceSize GetSumFreeSize() const override { return m_SumFreeSize; } + bool IsEmpty() const override { return GetAllocationCount() == 0; } + VkDeviceSize GetAllocationOffset(VmaAllocHandle allocHandle) const override { return (VkDeviceSize)allocHandle - 1; } + + void Init(VkDeviceSize size) override; + bool Validate() const override; + size_t GetAllocationCount() const override; + size_t GetFreeRegionsCount() const override; + + void AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const override; + void AddStatistics(VmaStatistics& inoutStats) const override; + +#if VMA_STATS_STRING_ENABLED + void PrintDetailedMap(class VmaJsonWriter& json) const override; +#endif + + bool CreateAllocationRequest( + VkDeviceSize allocSize, + VkDeviceSize allocAlignment, + bool upperAddress, + VmaSuballocationType allocType, + uint32_t strategy, + VmaAllocationRequest* pAllocationRequest) override; + + VkResult CheckCorruption(const void* pBlockData) override; + + void Alloc( + const VmaAllocationRequest& request, + VmaSuballocationType type, + void* userData) override; + + void Free(VmaAllocHandle allocHandle) override; + void GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo) override; + void* GetAllocationUserData(VmaAllocHandle allocHandle) const override; + VmaAllocHandle GetAllocationListBegin() const override; + VmaAllocHandle GetNextAllocation(VmaAllocHandle prevAlloc) const override; + VkDeviceSize GetNextFreeRegionSize(VmaAllocHandle alloc) const override; + void Clear() override; + void SetAllocationUserData(VmaAllocHandle allocHandle, void* userData) override; + void DebugLogAllAllocations() const override; + +private: + /* + There are two suballocation vectors, used in ping-pong way. + The one with index m_1stVectorIndex is called 1st. + The one with index (m_1stVectorIndex ^ 1) is called 2nd. + 2nd can be non-empty only when 1st is not empty. + When 2nd is not empty, m_2ndVectorMode indicates its mode of operation. + */ + typedef VmaVector> SuballocationVectorType; + + enum SECOND_VECTOR_MODE + { + SECOND_VECTOR_EMPTY, + /* + Suballocations in 2nd vector are created later than the ones in 1st, but they + all have smaller offset. + */ + SECOND_VECTOR_RING_BUFFER, + /* + Suballocations in 2nd vector are upper side of double stack. + They all have offsets higher than those in 1st vector. + Top of this stack means smaller offsets, but higher indices in this vector. + */ + SECOND_VECTOR_DOUBLE_STACK, + }; + + VkDeviceSize m_SumFreeSize; + SuballocationVectorType m_Suballocations0, m_Suballocations1; + uint32_t m_1stVectorIndex; + SECOND_VECTOR_MODE m_2ndVectorMode; + // Number of items in 1st vector with hAllocation = null at the beginning. + size_t m_1stNullItemsBeginCount; + // Number of other items in 1st vector with hAllocation = null somewhere in the middle. + size_t m_1stNullItemsMiddleCount; + // Number of items in 2nd vector with hAllocation = null. + size_t m_2ndNullItemsCount; + + SuballocationVectorType& AccessSuballocations1st() { return m_1stVectorIndex ? m_Suballocations1 : m_Suballocations0; } + SuballocationVectorType& AccessSuballocations2nd() { return m_1stVectorIndex ? m_Suballocations0 : m_Suballocations1; } + const SuballocationVectorType& AccessSuballocations1st() const { return m_1stVectorIndex ? m_Suballocations1 : m_Suballocations0; } + const SuballocationVectorType& AccessSuballocations2nd() const { return m_1stVectorIndex ? m_Suballocations0 : m_Suballocations1; } + + VmaSuballocation& FindSuballocation(VkDeviceSize offset) const; + bool ShouldCompact1st() const; + void CleanupAfterFree(); + + bool CreateAllocationRequest_LowerAddress( + VkDeviceSize allocSize, + VkDeviceSize allocAlignment, + VmaSuballocationType allocType, + uint32_t strategy, + VmaAllocationRequest* pAllocationRequest); + bool CreateAllocationRequest_UpperAddress( + VkDeviceSize allocSize, + VkDeviceSize allocAlignment, + VmaSuballocationType allocType, + uint32_t strategy, + VmaAllocationRequest* pAllocationRequest); +}; + +#ifndef _VMA_BLOCK_METADATA_LINEAR_FUNCTIONS +VmaBlockMetadata_Linear::VmaBlockMetadata_Linear(const VkAllocationCallbacks* pAllocationCallbacks, + VkDeviceSize bufferImageGranularity, bool isVirtual) + : VmaBlockMetadata(pAllocationCallbacks, bufferImageGranularity, isVirtual), + m_SumFreeSize(0), + m_Suballocations0(VmaStlAllocator(pAllocationCallbacks)), + m_Suballocations1(VmaStlAllocator(pAllocationCallbacks)), + m_1stVectorIndex(0), + m_2ndVectorMode(SECOND_VECTOR_EMPTY), + m_1stNullItemsBeginCount(0), + m_1stNullItemsMiddleCount(0), + m_2ndNullItemsCount(0) {} + +void VmaBlockMetadata_Linear::Init(VkDeviceSize size) +{ + VmaBlockMetadata::Init(size); + m_SumFreeSize = size; +} + +bool VmaBlockMetadata_Linear::Validate() const +{ + const SuballocationVectorType& suballocations1st = AccessSuballocations1st(); + const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); + + VMA_VALIDATE(suballocations2nd.empty() == (m_2ndVectorMode == SECOND_VECTOR_EMPTY)); + VMA_VALIDATE(!suballocations1st.empty() || + suballocations2nd.empty() || + m_2ndVectorMode != SECOND_VECTOR_RING_BUFFER); + + if (!suballocations1st.empty()) + { + // Null item at the beginning should be accounted into m_1stNullItemsBeginCount. + VMA_VALIDATE(suballocations1st[m_1stNullItemsBeginCount].type != VMA_SUBALLOCATION_TYPE_FREE); + // Null item at the end should be just pop_back(). + VMA_VALIDATE(suballocations1st.back().type != VMA_SUBALLOCATION_TYPE_FREE); + } + if (!suballocations2nd.empty()) + { + // Null item at the end should be just pop_back(). + VMA_VALIDATE(suballocations2nd.back().type != VMA_SUBALLOCATION_TYPE_FREE); + } + + VMA_VALIDATE(m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount <= suballocations1st.size()); + VMA_VALIDATE(m_2ndNullItemsCount <= suballocations2nd.size()); + + VkDeviceSize sumUsedSize = 0; + const size_t suballoc1stCount = suballocations1st.size(); + const VkDeviceSize debugMargin = GetDebugMargin(); + VkDeviceSize offset = 0; + + if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) + { + const size_t suballoc2ndCount = suballocations2nd.size(); + size_t nullItem2ndCount = 0; + for (size_t i = 0; i < suballoc2ndCount; ++i) + { + const VmaSuballocation& suballoc = suballocations2nd[i]; + const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE); + + VmaAllocation const alloc = (VmaAllocation)suballoc.userData; + if (!IsVirtual()) + { + VMA_VALIDATE(currFree == (alloc == VK_NULL_HANDLE)); + } + VMA_VALIDATE(suballoc.offset >= offset); + + if (!currFree) + { + if (!IsVirtual()) + { + VMA_VALIDATE((VkDeviceSize)alloc->GetAllocHandle() == suballoc.offset + 1); + VMA_VALIDATE(alloc->GetSize() == suballoc.size); + } + sumUsedSize += suballoc.size; + } + else + { + ++nullItem2ndCount; + } + + offset = suballoc.offset + suballoc.size + debugMargin; + } + + VMA_VALIDATE(nullItem2ndCount == m_2ndNullItemsCount); + } + + for (size_t i = 0; i < m_1stNullItemsBeginCount; ++i) + { + const VmaSuballocation& suballoc = suballocations1st[i]; + VMA_VALIDATE(suballoc.type == VMA_SUBALLOCATION_TYPE_FREE && + suballoc.userData == VMA_NULL); + } + + size_t nullItem1stCount = m_1stNullItemsBeginCount; + + for (size_t i = m_1stNullItemsBeginCount; i < suballoc1stCount; ++i) + { + const VmaSuballocation& suballoc = suballocations1st[i]; + const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE); + + VmaAllocation const alloc = (VmaAllocation)suballoc.userData; + if (!IsVirtual()) + { + VMA_VALIDATE(currFree == (alloc == VK_NULL_HANDLE)); + } + VMA_VALIDATE(suballoc.offset >= offset); + VMA_VALIDATE(i >= m_1stNullItemsBeginCount || currFree); + + if (!currFree) + { + if (!IsVirtual()) + { + VMA_VALIDATE((VkDeviceSize)alloc->GetAllocHandle() == suballoc.offset + 1); + VMA_VALIDATE(alloc->GetSize() == suballoc.size); + } + sumUsedSize += suballoc.size; + } + else + { + ++nullItem1stCount; + } + + offset = suballoc.offset + suballoc.size + debugMargin; + } + VMA_VALIDATE(nullItem1stCount == m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount); + + if (m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK) + { + const size_t suballoc2ndCount = suballocations2nd.size(); + size_t nullItem2ndCount = 0; + for (size_t i = suballoc2ndCount; i--; ) + { + const VmaSuballocation& suballoc = suballocations2nd[i]; + const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE); + + VmaAllocation const alloc = (VmaAllocation)suballoc.userData; + if (!IsVirtual()) + { + VMA_VALIDATE(currFree == (alloc == VK_NULL_HANDLE)); + } + VMA_VALIDATE(suballoc.offset >= offset); + + if (!currFree) + { + if (!IsVirtual()) + { + VMA_VALIDATE((VkDeviceSize)alloc->GetAllocHandle() == suballoc.offset + 1); + VMA_VALIDATE(alloc->GetSize() == suballoc.size); + } + sumUsedSize += suballoc.size; + } + else + { + ++nullItem2ndCount; + } + + offset = suballoc.offset + suballoc.size + debugMargin; + } + + VMA_VALIDATE(nullItem2ndCount == m_2ndNullItemsCount); + } + + VMA_VALIDATE(offset <= GetSize()); + VMA_VALIDATE(m_SumFreeSize == GetSize() - sumUsedSize); + + return true; +} + +size_t VmaBlockMetadata_Linear::GetAllocationCount() const +{ + return AccessSuballocations1st().size() - m_1stNullItemsBeginCount - m_1stNullItemsMiddleCount + + AccessSuballocations2nd().size() - m_2ndNullItemsCount; +} + +size_t VmaBlockMetadata_Linear::GetFreeRegionsCount() const +{ + // Function only used for defragmentation, which is disabled for this algorithm + VMA_ASSERT(0); + return SIZE_MAX; +} + +void VmaBlockMetadata_Linear::AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const +{ + const VkDeviceSize size = GetSize(); + const SuballocationVectorType& suballocations1st = AccessSuballocations1st(); + const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); + const size_t suballoc1stCount = suballocations1st.size(); + const size_t suballoc2ndCount = suballocations2nd.size(); + + inoutStats.statistics.blockCount++; + inoutStats.statistics.blockBytes += size; + + VkDeviceSize lastOffset = 0; + + if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) + { + const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset; + size_t nextAlloc2ndIndex = 0; + while (lastOffset < freeSpace2ndTo1stEnd) + { + // Find next non-null allocation or move nextAllocIndex to the end. + while (nextAlloc2ndIndex < suballoc2ndCount && + suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL) + { + ++nextAlloc2ndIndex; + } + + // Found non-null allocation. + if (nextAlloc2ndIndex < suballoc2ndCount) + { + const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex]; + + // 1. Process free space before this allocation. + if (lastOffset < suballoc.offset) + { + // There is free space from lastOffset to suballoc.offset. + const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset; + VmaAddDetailedStatisticsUnusedRange(inoutStats, unusedRangeSize); + } + + // 2. Process this allocation. + // There is allocation with suballoc.offset, suballoc.size. + VmaAddDetailedStatisticsAllocation(inoutStats, suballoc.size); + + // 3. Prepare for next iteration. + lastOffset = suballoc.offset + suballoc.size; + ++nextAlloc2ndIndex; + } + // We are at the end. + else + { + // There is free space from lastOffset to freeSpace2ndTo1stEnd. + if (lastOffset < freeSpace2ndTo1stEnd) + { + const VkDeviceSize unusedRangeSize = freeSpace2ndTo1stEnd - lastOffset; + VmaAddDetailedStatisticsUnusedRange(inoutStats, unusedRangeSize); + } + + // End of loop. + lastOffset = freeSpace2ndTo1stEnd; + } + } + } + + size_t nextAlloc1stIndex = m_1stNullItemsBeginCount; + const VkDeviceSize freeSpace1stTo2ndEnd = + m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size; + while (lastOffset < freeSpace1stTo2ndEnd) + { + // Find next non-null allocation or move nextAllocIndex to the end. + while (nextAlloc1stIndex < suballoc1stCount && + suballocations1st[nextAlloc1stIndex].userData == VMA_NULL) + { + ++nextAlloc1stIndex; + } + + // Found non-null allocation. + if (nextAlloc1stIndex < suballoc1stCount) + { + const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex]; + + // 1. Process free space before this allocation. + if (lastOffset < suballoc.offset) + { + // There is free space from lastOffset to suballoc.offset. + const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset; + VmaAddDetailedStatisticsUnusedRange(inoutStats, unusedRangeSize); + } + + // 2. Process this allocation. + // There is allocation with suballoc.offset, suballoc.size. + VmaAddDetailedStatisticsAllocation(inoutStats, suballoc.size); + + // 3. Prepare for next iteration. + lastOffset = suballoc.offset + suballoc.size; + ++nextAlloc1stIndex; + } + // We are at the end. + else + { + // There is free space from lastOffset to freeSpace1stTo2ndEnd. + if (lastOffset < freeSpace1stTo2ndEnd) + { + const VkDeviceSize unusedRangeSize = freeSpace1stTo2ndEnd - lastOffset; + VmaAddDetailedStatisticsUnusedRange(inoutStats, unusedRangeSize); + } + + // End of loop. + lastOffset = freeSpace1stTo2ndEnd; + } + } + + if (m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK) + { + size_t nextAlloc2ndIndex = suballocations2nd.size() - 1; + while (lastOffset < size) + { + // Find next non-null allocation or move nextAllocIndex to the end. + while (nextAlloc2ndIndex != SIZE_MAX && + suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL) + { + --nextAlloc2ndIndex; + } + + // Found non-null allocation. + if (nextAlloc2ndIndex != SIZE_MAX) + { + const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex]; + + // 1. Process free space before this allocation. + if (lastOffset < suballoc.offset) + { + // There is free space from lastOffset to suballoc.offset. + const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset; + VmaAddDetailedStatisticsUnusedRange(inoutStats, unusedRangeSize); + } + + // 2. Process this allocation. + // There is allocation with suballoc.offset, suballoc.size. + VmaAddDetailedStatisticsAllocation(inoutStats, suballoc.size); + + // 3. Prepare for next iteration. + lastOffset = suballoc.offset + suballoc.size; + --nextAlloc2ndIndex; + } + // We are at the end. + else + { + // There is free space from lastOffset to size. + if (lastOffset < size) + { + const VkDeviceSize unusedRangeSize = size - lastOffset; + VmaAddDetailedStatisticsUnusedRange(inoutStats, unusedRangeSize); + } + + // End of loop. + lastOffset = size; + } + } + } +} + +void VmaBlockMetadata_Linear::AddStatistics(VmaStatistics& inoutStats) const +{ + const SuballocationVectorType& suballocations1st = AccessSuballocations1st(); + const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); + const VkDeviceSize size = GetSize(); + const size_t suballoc1stCount = suballocations1st.size(); + const size_t suballoc2ndCount = suballocations2nd.size(); + + inoutStats.blockCount++; + inoutStats.blockBytes += size; + inoutStats.allocationBytes += size - m_SumFreeSize; + + VkDeviceSize lastOffset = 0; + + if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) + { + const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset; + size_t nextAlloc2ndIndex = m_1stNullItemsBeginCount; + while (lastOffset < freeSpace2ndTo1stEnd) + { + // Find next non-null allocation or move nextAlloc2ndIndex to the end. + while (nextAlloc2ndIndex < suballoc2ndCount && + suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL) + { + ++nextAlloc2ndIndex; + } + + // Found non-null allocation. + if (nextAlloc2ndIndex < suballoc2ndCount) + { + const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex]; + + // Process this allocation. + // There is allocation with suballoc.offset, suballoc.size. + ++inoutStats.allocationCount; + + // Prepare for next iteration. + lastOffset = suballoc.offset + suballoc.size; + ++nextAlloc2ndIndex; + } + // We are at the end. + else + { + // End of loop. + lastOffset = freeSpace2ndTo1stEnd; + } + } + } + + size_t nextAlloc1stIndex = m_1stNullItemsBeginCount; + const VkDeviceSize freeSpace1stTo2ndEnd = + m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size; + while (lastOffset < freeSpace1stTo2ndEnd) + { + // Find next non-null allocation or move nextAllocIndex to the end. + while (nextAlloc1stIndex < suballoc1stCount && + suballocations1st[nextAlloc1stIndex].userData == VMA_NULL) + { + ++nextAlloc1stIndex; + } + + // Found non-null allocation. + if (nextAlloc1stIndex < suballoc1stCount) + { + const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex]; + + // Process this allocation. + // There is allocation with suballoc.offset, suballoc.size. + ++inoutStats.allocationCount; + + // Prepare for next iteration. + lastOffset = suballoc.offset + suballoc.size; + ++nextAlloc1stIndex; + } + // We are at the end. + else + { + // End of loop. + lastOffset = freeSpace1stTo2ndEnd; + } + } + + if (m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK) + { + size_t nextAlloc2ndIndex = suballocations2nd.size() - 1; + while (lastOffset < size) + { + // Find next non-null allocation or move nextAlloc2ndIndex to the end. + while (nextAlloc2ndIndex != SIZE_MAX && + suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL) + { + --nextAlloc2ndIndex; + } + + // Found non-null allocation. + if (nextAlloc2ndIndex != SIZE_MAX) + { + const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex]; + + // Process this allocation. + // There is allocation with suballoc.offset, suballoc.size. + ++inoutStats.allocationCount; + + // Prepare for next iteration. + lastOffset = suballoc.offset + suballoc.size; + --nextAlloc2ndIndex; + } + // We are at the end. + else + { + // End of loop. + lastOffset = size; + } + } + } +} + +#if VMA_STATS_STRING_ENABLED +void VmaBlockMetadata_Linear::PrintDetailedMap(class VmaJsonWriter& json) const +{ + const VkDeviceSize size = GetSize(); + const SuballocationVectorType& suballocations1st = AccessSuballocations1st(); + const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); + const size_t suballoc1stCount = suballocations1st.size(); + const size_t suballoc2ndCount = suballocations2nd.size(); + + // FIRST PASS + + size_t unusedRangeCount = 0; + VkDeviceSize usedBytes = 0; + + VkDeviceSize lastOffset = 0; + + size_t alloc2ndCount = 0; + if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) + { + const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset; + size_t nextAlloc2ndIndex = 0; + while (lastOffset < freeSpace2ndTo1stEnd) + { + // Find next non-null allocation or move nextAlloc2ndIndex to the end. + while (nextAlloc2ndIndex < suballoc2ndCount && + suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL) + { + ++nextAlloc2ndIndex; + } + + // Found non-null allocation. + if (nextAlloc2ndIndex < suballoc2ndCount) + { + const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex]; + + // 1. Process free space before this allocation. + if (lastOffset < suballoc.offset) + { + // There is free space from lastOffset to suballoc.offset. + ++unusedRangeCount; + } + + // 2. Process this allocation. + // There is allocation with suballoc.offset, suballoc.size. + ++alloc2ndCount; + usedBytes += suballoc.size; + + // 3. Prepare for next iteration. + lastOffset = suballoc.offset + suballoc.size; + ++nextAlloc2ndIndex; + } + // We are at the end. + else + { + if (lastOffset < freeSpace2ndTo1stEnd) + { + // There is free space from lastOffset to freeSpace2ndTo1stEnd. + ++unusedRangeCount; + } + + // End of loop. + lastOffset = freeSpace2ndTo1stEnd; + } + } + } + + size_t nextAlloc1stIndex = m_1stNullItemsBeginCount; + size_t alloc1stCount = 0; + const VkDeviceSize freeSpace1stTo2ndEnd = + m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size; + while (lastOffset < freeSpace1stTo2ndEnd) + { + // Find next non-null allocation or move nextAllocIndex to the end. + while (nextAlloc1stIndex < suballoc1stCount && + suballocations1st[nextAlloc1stIndex].userData == VMA_NULL) + { + ++nextAlloc1stIndex; + } + + // Found non-null allocation. + if (nextAlloc1stIndex < suballoc1stCount) + { + const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex]; + + // 1. Process free space before this allocation. + if (lastOffset < suballoc.offset) + { + // There is free space from lastOffset to suballoc.offset. + ++unusedRangeCount; + } + + // 2. Process this allocation. + // There is allocation with suballoc.offset, suballoc.size. + ++alloc1stCount; + usedBytes += suballoc.size; + + // 3. Prepare for next iteration. + lastOffset = suballoc.offset + suballoc.size; + ++nextAlloc1stIndex; + } + // We are at the end. + else + { + if (lastOffset < freeSpace1stTo2ndEnd) + { + // There is free space from lastOffset to freeSpace1stTo2ndEnd. + ++unusedRangeCount; + } + + // End of loop. + lastOffset = freeSpace1stTo2ndEnd; + } + } + + if (m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK) + { + size_t nextAlloc2ndIndex = suballocations2nd.size() - 1; + while (lastOffset < size) + { + // Find next non-null allocation or move nextAlloc2ndIndex to the end. + while (nextAlloc2ndIndex != SIZE_MAX && + suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL) + { + --nextAlloc2ndIndex; + } + + // Found non-null allocation. + if (nextAlloc2ndIndex != SIZE_MAX) + { + const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex]; + + // 1. Process free space before this allocation. + if (lastOffset < suballoc.offset) + { + // There is free space from lastOffset to suballoc.offset. + ++unusedRangeCount; + } + + // 2. Process this allocation. + // There is allocation with suballoc.offset, suballoc.size. + ++alloc2ndCount; + usedBytes += suballoc.size; + + // 3. Prepare for next iteration. + lastOffset = suballoc.offset + suballoc.size; + --nextAlloc2ndIndex; + } + // We are at the end. + else + { + if (lastOffset < size) + { + // There is free space from lastOffset to size. + ++unusedRangeCount; + } + + // End of loop. + lastOffset = size; + } + } + } + + const VkDeviceSize unusedBytes = size - usedBytes; + PrintDetailedMap_Begin(json, unusedBytes, alloc1stCount + alloc2ndCount, unusedRangeCount); + + // SECOND PASS + lastOffset = 0; + + if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) + { + const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset; + size_t nextAlloc2ndIndex = 0; + while (lastOffset < freeSpace2ndTo1stEnd) + { + // Find next non-null allocation or move nextAlloc2ndIndex to the end. + while (nextAlloc2ndIndex < suballoc2ndCount && + suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL) + { + ++nextAlloc2ndIndex; + } + + // Found non-null allocation. + if (nextAlloc2ndIndex < suballoc2ndCount) + { + const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex]; + + // 1. Process free space before this allocation. + if (lastOffset < suballoc.offset) + { + // There is free space from lastOffset to suballoc.offset. + const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset; + PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize); + } + + // 2. Process this allocation. + // There is allocation with suballoc.offset, suballoc.size. + PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.size, suballoc.userData); + + // 3. Prepare for next iteration. + lastOffset = suballoc.offset + suballoc.size; + ++nextAlloc2ndIndex; + } + // We are at the end. + else + { + if (lastOffset < freeSpace2ndTo1stEnd) + { + // There is free space from lastOffset to freeSpace2ndTo1stEnd. + const VkDeviceSize unusedRangeSize = freeSpace2ndTo1stEnd - lastOffset; + PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize); + } + + // End of loop. + lastOffset = freeSpace2ndTo1stEnd; + } + } + } + + nextAlloc1stIndex = m_1stNullItemsBeginCount; + while (lastOffset < freeSpace1stTo2ndEnd) + { + // Find next non-null allocation or move nextAllocIndex to the end. + while (nextAlloc1stIndex < suballoc1stCount && + suballocations1st[nextAlloc1stIndex].userData == VMA_NULL) + { + ++nextAlloc1stIndex; + } + + // Found non-null allocation. + if (nextAlloc1stIndex < suballoc1stCount) + { + const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex]; + + // 1. Process free space before this allocation. + if (lastOffset < suballoc.offset) + { + // There is free space from lastOffset to suballoc.offset. + const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset; + PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize); + } + + // 2. Process this allocation. + // There is allocation with suballoc.offset, suballoc.size. + PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.size, suballoc.userData); + + // 3. Prepare for next iteration. + lastOffset = suballoc.offset + suballoc.size; + ++nextAlloc1stIndex; + } + // We are at the end. + else + { + if (lastOffset < freeSpace1stTo2ndEnd) + { + // There is free space from lastOffset to freeSpace1stTo2ndEnd. + const VkDeviceSize unusedRangeSize = freeSpace1stTo2ndEnd - lastOffset; + PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize); + } + + // End of loop. + lastOffset = freeSpace1stTo2ndEnd; + } + } + + if (m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK) + { + size_t nextAlloc2ndIndex = suballocations2nd.size() - 1; + while (lastOffset < size) + { + // Find next non-null allocation or move nextAlloc2ndIndex to the end. + while (nextAlloc2ndIndex != SIZE_MAX && + suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL) + { + --nextAlloc2ndIndex; + } + + // Found non-null allocation. + if (nextAlloc2ndIndex != SIZE_MAX) + { + const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex]; + + // 1. Process free space before this allocation. + if (lastOffset < suballoc.offset) + { + // There is free space from lastOffset to suballoc.offset. + const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset; + PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize); + } + + // 2. Process this allocation. + // There is allocation with suballoc.offset, suballoc.size. + PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.size, suballoc.userData); + + // 3. Prepare for next iteration. + lastOffset = suballoc.offset + suballoc.size; + --nextAlloc2ndIndex; + } + // We are at the end. + else + { + if (lastOffset < size) + { + // There is free space from lastOffset to size. + const VkDeviceSize unusedRangeSize = size - lastOffset; + PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize); + } + + // End of loop. + lastOffset = size; + } + } + } + + PrintDetailedMap_End(json); +} +#endif // VMA_STATS_STRING_ENABLED + +bool VmaBlockMetadata_Linear::CreateAllocationRequest( + VkDeviceSize allocSize, + VkDeviceSize allocAlignment, + bool upperAddress, + VmaSuballocationType allocType, + uint32_t strategy, + VmaAllocationRequest* pAllocationRequest) +{ + VMA_ASSERT(allocSize > 0); + VMA_ASSERT(allocType != VMA_SUBALLOCATION_TYPE_FREE); + VMA_ASSERT(pAllocationRequest != VMA_NULL); + VMA_HEAVY_ASSERT(Validate()); + + if(allocSize > GetSize()) + return false; + + pAllocationRequest->size = allocSize; + return upperAddress ? + CreateAllocationRequest_UpperAddress( + allocSize, allocAlignment, allocType, strategy, pAllocationRequest) : + CreateAllocationRequest_LowerAddress( + allocSize, allocAlignment, allocType, strategy, pAllocationRequest); +} + +VkResult VmaBlockMetadata_Linear::CheckCorruption(const void* pBlockData) +{ + VMA_ASSERT(!IsVirtual()); + SuballocationVectorType& suballocations1st = AccessSuballocations1st(); + for (size_t i = m_1stNullItemsBeginCount, count = suballocations1st.size(); i < count; ++i) + { + const VmaSuballocation& suballoc = suballocations1st[i]; + if (suballoc.type != VMA_SUBALLOCATION_TYPE_FREE) + { + if (!VmaValidateMagicValue(pBlockData, suballoc.offset + suballoc.size)) + { + VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER VALIDATED ALLOCATION!"); + return VK_ERROR_UNKNOWN_COPY; + } + } + } + + SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); + for (size_t i = 0, count = suballocations2nd.size(); i < count; ++i) + { + const VmaSuballocation& suballoc = suballocations2nd[i]; + if (suballoc.type != VMA_SUBALLOCATION_TYPE_FREE) + { + if (!VmaValidateMagicValue(pBlockData, suballoc.offset + suballoc.size)) + { + VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER VALIDATED ALLOCATION!"); + return VK_ERROR_UNKNOWN_COPY; + } + } + } + + return VK_SUCCESS; +} + +void VmaBlockMetadata_Linear::Alloc( + const VmaAllocationRequest& request, + VmaSuballocationType type, + void* userData) +{ + const VkDeviceSize offset = (VkDeviceSize)request.allocHandle - 1; + const VmaSuballocation newSuballoc = { offset, request.size, userData, type }; + + switch (request.type) + { + case VmaAllocationRequestType::UpperAddress: + { + VMA_ASSERT(m_2ndVectorMode != SECOND_VECTOR_RING_BUFFER && + "CRITICAL ERROR: Trying to use linear allocator as double stack while it was already used as ring buffer."); + SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); + suballocations2nd.push_back(newSuballoc); + m_2ndVectorMode = SECOND_VECTOR_DOUBLE_STACK; + } + break; + case VmaAllocationRequestType::EndOf1st: + { + SuballocationVectorType& suballocations1st = AccessSuballocations1st(); + + VMA_ASSERT(suballocations1st.empty() || + offset >= suballocations1st.back().offset + suballocations1st.back().size); + // Check if it fits before the end of the block. + VMA_ASSERT(offset + request.size <= GetSize()); + + suballocations1st.push_back(newSuballoc); + } + break; + case VmaAllocationRequestType::EndOf2nd: + { + SuballocationVectorType& suballocations1st = AccessSuballocations1st(); + // New allocation at the end of 2-part ring buffer, so before first allocation from 1st vector. + VMA_ASSERT(!suballocations1st.empty() && + offset + request.size <= suballocations1st[m_1stNullItemsBeginCount].offset); + SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); + + switch (m_2ndVectorMode) + { + case SECOND_VECTOR_EMPTY: + // First allocation from second part ring buffer. + VMA_ASSERT(suballocations2nd.empty()); + m_2ndVectorMode = SECOND_VECTOR_RING_BUFFER; + break; + case SECOND_VECTOR_RING_BUFFER: + // 2-part ring buffer is already started. + VMA_ASSERT(!suballocations2nd.empty()); + break; + case SECOND_VECTOR_DOUBLE_STACK: + VMA_ASSERT(0 && "CRITICAL ERROR: Trying to use linear allocator as ring buffer while it was already used as double stack."); + break; + default: + VMA_ASSERT(0); + } + + suballocations2nd.push_back(newSuballoc); + } + break; + default: + VMA_ASSERT(0 && "CRITICAL INTERNAL ERROR."); + } + + m_SumFreeSize -= newSuballoc.size; +} + +void VmaBlockMetadata_Linear::Free(VmaAllocHandle allocHandle) +{ + SuballocationVectorType& suballocations1st = AccessSuballocations1st(); + SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); + VkDeviceSize offset = (VkDeviceSize)allocHandle - 1; + + if (!suballocations1st.empty()) + { + // First allocation: Mark it as next empty at the beginning. + VmaSuballocation& firstSuballoc = suballocations1st[m_1stNullItemsBeginCount]; + if (firstSuballoc.offset == offset) + { + firstSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE; + firstSuballoc.userData = VMA_NULL; + m_SumFreeSize += firstSuballoc.size; + ++m_1stNullItemsBeginCount; + CleanupAfterFree(); + return; + } + } + + // Last allocation in 2-part ring buffer or top of upper stack (same logic). + if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER || + m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK) + { + VmaSuballocation& lastSuballoc = suballocations2nd.back(); + if (lastSuballoc.offset == offset) + { + m_SumFreeSize += lastSuballoc.size; + suballocations2nd.pop_back(); + CleanupAfterFree(); + return; + } + } + // Last allocation in 1st vector. + else if (m_2ndVectorMode == SECOND_VECTOR_EMPTY) + { + VmaSuballocation& lastSuballoc = suballocations1st.back(); + if (lastSuballoc.offset == offset) + { + m_SumFreeSize += lastSuballoc.size; + suballocations1st.pop_back(); + CleanupAfterFree(); + return; + } + } + + VmaSuballocation refSuballoc; + refSuballoc.offset = offset; + // Rest of members stays uninitialized intentionally for better performance. + + // Item from the middle of 1st vector. + { + const SuballocationVectorType::iterator it = VmaBinaryFindSorted( + suballocations1st.begin() + m_1stNullItemsBeginCount, + suballocations1st.end(), + refSuballoc, + VmaSuballocationOffsetLess()); + if (it != suballocations1st.end()) + { + it->type = VMA_SUBALLOCATION_TYPE_FREE; + it->userData = VMA_NULL; + ++m_1stNullItemsMiddleCount; + m_SumFreeSize += it->size; + CleanupAfterFree(); + return; + } + } + + if (m_2ndVectorMode != SECOND_VECTOR_EMPTY) + { + // Item from the middle of 2nd vector. + const SuballocationVectorType::iterator it = m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER ? + VmaBinaryFindSorted(suballocations2nd.begin(), suballocations2nd.end(), refSuballoc, VmaSuballocationOffsetLess()) : + VmaBinaryFindSorted(suballocations2nd.begin(), suballocations2nd.end(), refSuballoc, VmaSuballocationOffsetGreater()); + if (it != suballocations2nd.end()) + { + it->type = VMA_SUBALLOCATION_TYPE_FREE; + it->userData = VMA_NULL; + ++m_2ndNullItemsCount; + m_SumFreeSize += it->size; + CleanupAfterFree(); + return; + } + } + + VMA_ASSERT(0 && "Allocation to free not found in linear allocator!"); +} + +void VmaBlockMetadata_Linear::GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo) +{ + outInfo.offset = (VkDeviceSize)allocHandle - 1; + VmaSuballocation& suballoc = FindSuballocation(outInfo.offset); + outInfo.size = suballoc.size; + outInfo.pUserData = suballoc.userData; +} + +void* VmaBlockMetadata_Linear::GetAllocationUserData(VmaAllocHandle allocHandle) const +{ + return FindSuballocation((VkDeviceSize)allocHandle - 1).userData; +} + +VmaAllocHandle VmaBlockMetadata_Linear::GetAllocationListBegin() const +{ + // Function only used for defragmentation, which is disabled for this algorithm + VMA_ASSERT(0); + return VK_NULL_HANDLE; +} + +VmaAllocHandle VmaBlockMetadata_Linear::GetNextAllocation(VmaAllocHandle prevAlloc) const +{ + // Function only used for defragmentation, which is disabled for this algorithm + VMA_ASSERT(0); + return VK_NULL_HANDLE; +} + +VkDeviceSize VmaBlockMetadata_Linear::GetNextFreeRegionSize(VmaAllocHandle alloc) const +{ + // Function only used for defragmentation, which is disabled for this algorithm + VMA_ASSERT(0); + return 0; +} + +void VmaBlockMetadata_Linear::Clear() +{ + m_SumFreeSize = GetSize(); + m_Suballocations0.clear(); + m_Suballocations1.clear(); + // Leaving m_1stVectorIndex unchanged - it doesn't matter. + m_2ndVectorMode = SECOND_VECTOR_EMPTY; + m_1stNullItemsBeginCount = 0; + m_1stNullItemsMiddleCount = 0; + m_2ndNullItemsCount = 0; +} + +void VmaBlockMetadata_Linear::SetAllocationUserData(VmaAllocHandle allocHandle, void* userData) +{ + VmaSuballocation& suballoc = FindSuballocation((VkDeviceSize)allocHandle - 1); + suballoc.userData = userData; +} + +void VmaBlockMetadata_Linear::DebugLogAllAllocations() const +{ + const SuballocationVectorType& suballocations1st = AccessSuballocations1st(); + for (auto it = suballocations1st.begin() + m_1stNullItemsBeginCount; it != suballocations1st.end(); ++it) + if (it->type != VMA_SUBALLOCATION_TYPE_FREE) + DebugLogAllocation(it->offset, it->size, it->userData); + + const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); + for (auto it = suballocations2nd.begin(); it != suballocations2nd.end(); ++it) + if (it->type != VMA_SUBALLOCATION_TYPE_FREE) + DebugLogAllocation(it->offset, it->size, it->userData); +} + +VmaSuballocation& VmaBlockMetadata_Linear::FindSuballocation(VkDeviceSize offset) const +{ + const SuballocationVectorType& suballocations1st = AccessSuballocations1st(); + const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); + + VmaSuballocation refSuballoc; + refSuballoc.offset = offset; + // Rest of members stays uninitialized intentionally for better performance. + + // Item from the 1st vector. + { + SuballocationVectorType::const_iterator it = VmaBinaryFindSorted( + suballocations1st.begin() + m_1stNullItemsBeginCount, + suballocations1st.end(), + refSuballoc, + VmaSuballocationOffsetLess()); + if (it != suballocations1st.end()) + { + return const_cast(*it); + } + } + + if (m_2ndVectorMode != SECOND_VECTOR_EMPTY) + { + // Rest of members stays uninitialized intentionally for better performance. + SuballocationVectorType::const_iterator it = m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER ? + VmaBinaryFindSorted(suballocations2nd.begin(), suballocations2nd.end(), refSuballoc, VmaSuballocationOffsetLess()) : + VmaBinaryFindSorted(suballocations2nd.begin(), suballocations2nd.end(), refSuballoc, VmaSuballocationOffsetGreater()); + if (it != suballocations2nd.end()) + { + return const_cast(*it); + } + } + + VMA_ASSERT(0 && "Allocation not found in linear allocator!"); + return const_cast(suballocations1st.back()); // Should never occur. +} + +bool VmaBlockMetadata_Linear::ShouldCompact1st() const +{ + const size_t nullItemCount = m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount; + const size_t suballocCount = AccessSuballocations1st().size(); + return suballocCount > 32 && nullItemCount * 2 >= (suballocCount - nullItemCount) * 3; +} + +void VmaBlockMetadata_Linear::CleanupAfterFree() +{ + SuballocationVectorType& suballocations1st = AccessSuballocations1st(); + SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); + + if (IsEmpty()) + { + suballocations1st.clear(); + suballocations2nd.clear(); + m_1stNullItemsBeginCount = 0; + m_1stNullItemsMiddleCount = 0; + m_2ndNullItemsCount = 0; + m_2ndVectorMode = SECOND_VECTOR_EMPTY; + } + else + { + const size_t suballoc1stCount = suballocations1st.size(); + const size_t nullItem1stCount = m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount; + VMA_ASSERT(nullItem1stCount <= suballoc1stCount); + + // Find more null items at the beginning of 1st vector. + while (m_1stNullItemsBeginCount < suballoc1stCount && + suballocations1st[m_1stNullItemsBeginCount].type == VMA_SUBALLOCATION_TYPE_FREE) + { + ++m_1stNullItemsBeginCount; + --m_1stNullItemsMiddleCount; + } + + // Find more null items at the end of 1st vector. + while (m_1stNullItemsMiddleCount > 0 && + suballocations1st.back().type == VMA_SUBALLOCATION_TYPE_FREE) + { + --m_1stNullItemsMiddleCount; + suballocations1st.pop_back(); + } + + // Find more null items at the end of 2nd vector. + while (m_2ndNullItemsCount > 0 && + suballocations2nd.back().type == VMA_SUBALLOCATION_TYPE_FREE) + { + --m_2ndNullItemsCount; + suballocations2nd.pop_back(); + } + + // Find more null items at the beginning of 2nd vector. + while (m_2ndNullItemsCount > 0 && + suballocations2nd[0].type == VMA_SUBALLOCATION_TYPE_FREE) + { + --m_2ndNullItemsCount; + VmaVectorRemove(suballocations2nd, 0); + } + + if (ShouldCompact1st()) + { + const size_t nonNullItemCount = suballoc1stCount - nullItem1stCount; + size_t srcIndex = m_1stNullItemsBeginCount; + for (size_t dstIndex = 0; dstIndex < nonNullItemCount; ++dstIndex) + { + while (suballocations1st[srcIndex].type == VMA_SUBALLOCATION_TYPE_FREE) + { + ++srcIndex; + } + if (dstIndex != srcIndex) + { + suballocations1st[dstIndex] = suballocations1st[srcIndex]; + } + ++srcIndex; + } + suballocations1st.resize(nonNullItemCount); + m_1stNullItemsBeginCount = 0; + m_1stNullItemsMiddleCount = 0; + } + + // 2nd vector became empty. + if (suballocations2nd.empty()) + { + m_2ndVectorMode = SECOND_VECTOR_EMPTY; + } + + // 1st vector became empty. + if (suballocations1st.size() - m_1stNullItemsBeginCount == 0) + { + suballocations1st.clear(); + m_1stNullItemsBeginCount = 0; + + if (!suballocations2nd.empty() && m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) + { + // Swap 1st with 2nd. Now 2nd is empty. + m_2ndVectorMode = SECOND_VECTOR_EMPTY; + m_1stNullItemsMiddleCount = m_2ndNullItemsCount; + while (m_1stNullItemsBeginCount < suballocations2nd.size() && + suballocations2nd[m_1stNullItemsBeginCount].type == VMA_SUBALLOCATION_TYPE_FREE) + { + ++m_1stNullItemsBeginCount; + --m_1stNullItemsMiddleCount; + } + m_2ndNullItemsCount = 0; + m_1stVectorIndex ^= 1; + } + } + } + + VMA_HEAVY_ASSERT(Validate()); +} + +bool VmaBlockMetadata_Linear::CreateAllocationRequest_LowerAddress( + VkDeviceSize allocSize, + VkDeviceSize allocAlignment, + VmaSuballocationType allocType, + uint32_t strategy, + VmaAllocationRequest* pAllocationRequest) +{ + const VkDeviceSize blockSize = GetSize(); + const VkDeviceSize debugMargin = GetDebugMargin(); + const VkDeviceSize bufferImageGranularity = GetBufferImageGranularity(); + SuballocationVectorType& suballocations1st = AccessSuballocations1st(); + SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); + + if (m_2ndVectorMode == SECOND_VECTOR_EMPTY || m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK) + { + // Try to allocate at the end of 1st vector. + + VkDeviceSize resultBaseOffset = 0; + if (!suballocations1st.empty()) + { + const VmaSuballocation& lastSuballoc = suballocations1st.back(); + resultBaseOffset = lastSuballoc.offset + lastSuballoc.size + debugMargin; + } + + // Start from offset equal to beginning of free space. + VkDeviceSize resultOffset = resultBaseOffset; + + // Apply alignment. + resultOffset = VmaAlignUp(resultOffset, allocAlignment); + + // Check previous suballocations for BufferImageGranularity conflicts. + // Make bigger alignment if necessary. + if (bufferImageGranularity > 1 && bufferImageGranularity != allocAlignment && !suballocations1st.empty()) + { + bool bufferImageGranularityConflict = false; + for (size_t prevSuballocIndex = suballocations1st.size(); prevSuballocIndex--; ) + { + const VmaSuballocation& prevSuballoc = suballocations1st[prevSuballocIndex]; + if (VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, resultOffset, bufferImageGranularity)) + { + if (VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType)) + { + bufferImageGranularityConflict = true; + break; + } + } + else + // Already on previous page. + break; + } + if (bufferImageGranularityConflict) + { + resultOffset = VmaAlignUp(resultOffset, bufferImageGranularity); + } + } + + const VkDeviceSize freeSpaceEnd = m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? + suballocations2nd.back().offset : blockSize; + + // There is enough free space at the end after alignment. + if (resultOffset + allocSize + debugMargin <= freeSpaceEnd) + { + // Check next suballocations for BufferImageGranularity conflicts. + // If conflict exists, allocation cannot be made here. + if ((allocSize % bufferImageGranularity || resultOffset % bufferImageGranularity) && m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK) + { + for (size_t nextSuballocIndex = suballocations2nd.size(); nextSuballocIndex--; ) + { + const VmaSuballocation& nextSuballoc = suballocations2nd[nextSuballocIndex]; + if (VmaBlocksOnSamePage(resultOffset, allocSize, nextSuballoc.offset, bufferImageGranularity)) + { + if (VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type)) + { + return false; + } + } + else + { + // Already on previous page. + break; + } + } + } + + // All tests passed: Success. + pAllocationRequest->allocHandle = (VmaAllocHandle)(resultOffset + 1); + // pAllocationRequest->item, customData unused. + pAllocationRequest->type = VmaAllocationRequestType::EndOf1st; + return true; + } + } + + // Wrap-around to end of 2nd vector. Try to allocate there, watching for the + // beginning of 1st vector as the end of free space. + if (m_2ndVectorMode == SECOND_VECTOR_EMPTY || m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) + { + VMA_ASSERT(!suballocations1st.empty()); + + VkDeviceSize resultBaseOffset = 0; + if (!suballocations2nd.empty()) + { + const VmaSuballocation& lastSuballoc = suballocations2nd.back(); + resultBaseOffset = lastSuballoc.offset + lastSuballoc.size + debugMargin; + } + + // Start from offset equal to beginning of free space. + VkDeviceSize resultOffset = resultBaseOffset; + + // Apply alignment. + resultOffset = VmaAlignUp(resultOffset, allocAlignment); + + // Check previous suballocations for BufferImageGranularity conflicts. + // Make bigger alignment if necessary. + if (bufferImageGranularity > 1 && bufferImageGranularity != allocAlignment && !suballocations2nd.empty()) + { + bool bufferImageGranularityConflict = false; + for (size_t prevSuballocIndex = suballocations2nd.size(); prevSuballocIndex--; ) + { + const VmaSuballocation& prevSuballoc = suballocations2nd[prevSuballocIndex]; + if (VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, resultOffset, bufferImageGranularity)) + { + if (VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType)) + { + bufferImageGranularityConflict = true; + break; + } + } + else + // Already on previous page. + break; + } + if (bufferImageGranularityConflict) + { + resultOffset = VmaAlignUp(resultOffset, bufferImageGranularity); + } + } + + size_t index1st = m_1stNullItemsBeginCount; + + // There is enough free space at the end after alignment. + if ((index1st == suballocations1st.size() && resultOffset + allocSize + debugMargin <= blockSize) || + (index1st < suballocations1st.size() && resultOffset + allocSize + debugMargin <= suballocations1st[index1st].offset)) + { + // Check next suballocations for BufferImageGranularity conflicts. + // If conflict exists, allocation cannot be made here. + if (allocSize % bufferImageGranularity || resultOffset % bufferImageGranularity) + { + for (size_t nextSuballocIndex = index1st; + nextSuballocIndex < suballocations1st.size(); + nextSuballocIndex++) + { + const VmaSuballocation& nextSuballoc = suballocations1st[nextSuballocIndex]; + if (VmaBlocksOnSamePage(resultOffset, allocSize, nextSuballoc.offset, bufferImageGranularity)) + { + if (VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type)) + { + return false; + } + } + else + { + // Already on next page. + break; + } + } + } + + // All tests passed: Success. + pAllocationRequest->allocHandle = (VmaAllocHandle)(resultOffset + 1); + pAllocationRequest->type = VmaAllocationRequestType::EndOf2nd; + // pAllocationRequest->item, customData unused. + return true; + } + } + + return false; +} + +bool VmaBlockMetadata_Linear::CreateAllocationRequest_UpperAddress( + VkDeviceSize allocSize, + VkDeviceSize allocAlignment, + VmaSuballocationType allocType, + uint32_t strategy, + VmaAllocationRequest* pAllocationRequest) +{ + const VkDeviceSize blockSize = GetSize(); + const VkDeviceSize bufferImageGranularity = GetBufferImageGranularity(); + SuballocationVectorType& suballocations1st = AccessSuballocations1st(); + SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); + + if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) + { + VMA_ASSERT(0 && "Trying to use pool with linear algorithm as double stack, while it is already being used as ring buffer."); + return false; + } + + // Try to allocate before 2nd.back(), or end of block if 2nd.empty(). + if (allocSize > blockSize) + { + return false; + } + VkDeviceSize resultBaseOffset = blockSize - allocSize; + if (!suballocations2nd.empty()) + { + const VmaSuballocation& lastSuballoc = suballocations2nd.back(); + resultBaseOffset = lastSuballoc.offset - allocSize; + if (allocSize > lastSuballoc.offset) + { + return false; + } + } + + // Start from offset equal to end of free space. + VkDeviceSize resultOffset = resultBaseOffset; + + const VkDeviceSize debugMargin = GetDebugMargin(); + + // Apply debugMargin at the end. + if (debugMargin > 0) + { + if (resultOffset < debugMargin) + { + return false; + } + resultOffset -= debugMargin; + } + + // Apply alignment. + resultOffset = VmaAlignDown(resultOffset, allocAlignment); + + // Check next suballocations from 2nd for BufferImageGranularity conflicts. + // Make bigger alignment if necessary. + if (bufferImageGranularity > 1 && bufferImageGranularity != allocAlignment && !suballocations2nd.empty()) + { + bool bufferImageGranularityConflict = false; + for (size_t nextSuballocIndex = suballocations2nd.size(); nextSuballocIndex--; ) + { + const VmaSuballocation& nextSuballoc = suballocations2nd[nextSuballocIndex]; + if (VmaBlocksOnSamePage(resultOffset, allocSize, nextSuballoc.offset, bufferImageGranularity)) + { + if (VmaIsBufferImageGranularityConflict(nextSuballoc.type, allocType)) + { + bufferImageGranularityConflict = true; + break; + } + } + else + // Already on previous page. + break; + } + if (bufferImageGranularityConflict) + { + resultOffset = VmaAlignDown(resultOffset, bufferImageGranularity); + } + } + + // There is enough free space. + const VkDeviceSize endOf1st = !suballocations1st.empty() ? + suballocations1st.back().offset + suballocations1st.back().size : + 0; + if (endOf1st + debugMargin <= resultOffset) + { + // Check previous suballocations for BufferImageGranularity conflicts. + // If conflict exists, allocation cannot be made here. + if (bufferImageGranularity > 1) + { + for (size_t prevSuballocIndex = suballocations1st.size(); prevSuballocIndex--; ) + { + const VmaSuballocation& prevSuballoc = suballocations1st[prevSuballocIndex]; + if (VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, resultOffset, bufferImageGranularity)) + { + if (VmaIsBufferImageGranularityConflict(allocType, prevSuballoc.type)) + { + return false; + } + } + else + { + // Already on next page. + break; + } + } + } + + // All tests passed: Success. + pAllocationRequest->allocHandle = (VmaAllocHandle)(resultOffset + 1); + // pAllocationRequest->item unused. + pAllocationRequest->type = VmaAllocationRequestType::UpperAddress; + return true; + } + + return false; +} +#endif // _VMA_BLOCK_METADATA_LINEAR_FUNCTIONS +#endif // _VMA_BLOCK_METADATA_LINEAR + +#ifndef _VMA_BLOCK_METADATA_TLSF +// To not search current larger region if first allocation won't succeed and skip to smaller range +// use with VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT as strategy in CreateAllocationRequest(). +// When fragmentation and reusal of previous blocks doesn't matter then use with +// VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT for fastest alloc time possible. +class VmaBlockMetadata_TLSF : public VmaBlockMetadata +{ + VMA_CLASS_NO_COPY_NO_MOVE(VmaBlockMetadata_TLSF) +public: + VmaBlockMetadata_TLSF(const VkAllocationCallbacks* pAllocationCallbacks, + VkDeviceSize bufferImageGranularity, bool isVirtual); + virtual ~VmaBlockMetadata_TLSF(); + + size_t GetAllocationCount() const override { return m_AllocCount; } + size_t GetFreeRegionsCount() const override { return m_BlocksFreeCount + 1; } + VkDeviceSize GetSumFreeSize() const override { return m_BlocksFreeSize + m_NullBlock->size; } + bool IsEmpty() const override { return m_NullBlock->offset == 0; } + VkDeviceSize GetAllocationOffset(VmaAllocHandle allocHandle) const override { return ((Block*)allocHandle)->offset; } + + void Init(VkDeviceSize size) override; + bool Validate() const override; + + void AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const override; + void AddStatistics(VmaStatistics& inoutStats) const override; + +#if VMA_STATS_STRING_ENABLED + void PrintDetailedMap(class VmaJsonWriter& json) const override; +#endif + + bool CreateAllocationRequest( + VkDeviceSize allocSize, + VkDeviceSize allocAlignment, + bool upperAddress, + VmaSuballocationType allocType, + uint32_t strategy, + VmaAllocationRequest* pAllocationRequest) override; + + VkResult CheckCorruption(const void* pBlockData) override; + void Alloc( + const VmaAllocationRequest& request, + VmaSuballocationType type, + void* userData) override; + + void Free(VmaAllocHandle allocHandle) override; + void GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo) override; + void* GetAllocationUserData(VmaAllocHandle allocHandle) const override; + VmaAllocHandle GetAllocationListBegin() const override; + VmaAllocHandle GetNextAllocation(VmaAllocHandle prevAlloc) const override; + VkDeviceSize GetNextFreeRegionSize(VmaAllocHandle alloc) const override; + void Clear() override; + void SetAllocationUserData(VmaAllocHandle allocHandle, void* userData) override; + void DebugLogAllAllocations() const override; + +private: + // According to original paper it should be preferable 4 or 5: + // M. Masmano, I. Ripoll, A. Crespo, and J. Real "TLSF: a New Dynamic Memory Allocator for Real-Time Systems" + // http://www.gii.upv.es/tlsf/files/ecrts04_tlsf.pdf + static const uint8_t SECOND_LEVEL_INDEX = 5; + static const uint16_t SMALL_BUFFER_SIZE = 256; + static const uint32_t INITIAL_BLOCK_ALLOC_COUNT = 16; + static const uint8_t MEMORY_CLASS_SHIFT = 7; + static const uint8_t MAX_MEMORY_CLASSES = 65 - MEMORY_CLASS_SHIFT; + + class Block + { + public: + VkDeviceSize offset; + VkDeviceSize size; + Block* prevPhysical; + Block* nextPhysical; + + void MarkFree() { prevFree = VMA_NULL; } + void MarkTaken() { prevFree = this; } + bool IsFree() const { return prevFree != this; } + void*& UserData() { VMA_HEAVY_ASSERT(!IsFree()); return userData; } + Block*& PrevFree() { return prevFree; } + Block*& NextFree() { VMA_HEAVY_ASSERT(IsFree()); return nextFree; } + + private: + Block* prevFree; // Address of the same block here indicates that block is taken + union + { + Block* nextFree; + void* userData; + }; + }; + + size_t m_AllocCount; + // Total number of free blocks besides null block + size_t m_BlocksFreeCount; + // Total size of free blocks excluding null block + VkDeviceSize m_BlocksFreeSize; + uint32_t m_IsFreeBitmap; + uint8_t m_MemoryClasses; + uint32_t m_InnerIsFreeBitmap[MAX_MEMORY_CLASSES]; + uint32_t m_ListsCount; + /* + * 0: 0-3 lists for small buffers + * 1+: 0-(2^SLI-1) lists for normal buffers + */ + Block** m_FreeList; + VmaPoolAllocator m_BlockAllocator; + Block* m_NullBlock; + VmaBlockBufferImageGranularity m_GranularityHandler; + + uint8_t SizeToMemoryClass(VkDeviceSize size) const; + uint16_t SizeToSecondIndex(VkDeviceSize size, uint8_t memoryClass) const; + uint32_t GetListIndex(uint8_t memoryClass, uint16_t secondIndex) const; + uint32_t GetListIndex(VkDeviceSize size) const; + + void RemoveFreeBlock(Block* block); + void InsertFreeBlock(Block* block); + void MergeBlock(Block* block, Block* prev); + + Block* FindFreeBlock(VkDeviceSize size, uint32_t& listIndex) const; + bool CheckBlock( + Block& block, + uint32_t listIndex, + VkDeviceSize allocSize, + VkDeviceSize allocAlignment, + VmaSuballocationType allocType, + VmaAllocationRequest* pAllocationRequest); +}; + +#ifndef _VMA_BLOCK_METADATA_TLSF_FUNCTIONS +VmaBlockMetadata_TLSF::VmaBlockMetadata_TLSF(const VkAllocationCallbacks* pAllocationCallbacks, + VkDeviceSize bufferImageGranularity, bool isVirtual) + : VmaBlockMetadata(pAllocationCallbacks, bufferImageGranularity, isVirtual), + m_AllocCount(0), + m_BlocksFreeCount(0), + m_BlocksFreeSize(0), + m_IsFreeBitmap(0), + m_MemoryClasses(0), + m_ListsCount(0), + m_FreeList(VMA_NULL), + m_BlockAllocator(pAllocationCallbacks, INITIAL_BLOCK_ALLOC_COUNT), + m_NullBlock(VMA_NULL), + m_GranularityHandler(bufferImageGranularity) {} + +VmaBlockMetadata_TLSF::~VmaBlockMetadata_TLSF() +{ + if (m_FreeList) + vma_delete_array(GetAllocationCallbacks(), m_FreeList, m_ListsCount); + m_GranularityHandler.Destroy(GetAllocationCallbacks()); +} + +void VmaBlockMetadata_TLSF::Init(VkDeviceSize size) +{ + VmaBlockMetadata::Init(size); + + if (!IsVirtual()) + m_GranularityHandler.Init(GetAllocationCallbacks(), size); + + m_NullBlock = m_BlockAllocator.Alloc(); + m_NullBlock->size = size; + m_NullBlock->offset = 0; + m_NullBlock->prevPhysical = VMA_NULL; + m_NullBlock->nextPhysical = VMA_NULL; + m_NullBlock->MarkFree(); + m_NullBlock->NextFree() = VMA_NULL; + m_NullBlock->PrevFree() = VMA_NULL; + uint8_t memoryClass = SizeToMemoryClass(size); + uint16_t sli = SizeToSecondIndex(size, memoryClass); + m_ListsCount = (memoryClass == 0 ? 0 : (memoryClass - 1) * (1UL << SECOND_LEVEL_INDEX) + sli) + 1; + if (IsVirtual()) + m_ListsCount += 1UL << SECOND_LEVEL_INDEX; + else + m_ListsCount += 4; + + m_MemoryClasses = memoryClass + uint8_t(2); + memset(m_InnerIsFreeBitmap, 0, MAX_MEMORY_CLASSES * sizeof(uint32_t)); + + m_FreeList = vma_new_array(GetAllocationCallbacks(), Block*, m_ListsCount); + memset(m_FreeList, 0, m_ListsCount * sizeof(Block*)); +} + +bool VmaBlockMetadata_TLSF::Validate() const +{ + VMA_VALIDATE(GetSumFreeSize() <= GetSize()); + + VkDeviceSize calculatedSize = m_NullBlock->size; + VkDeviceSize calculatedFreeSize = m_NullBlock->size; + size_t allocCount = 0; + size_t freeCount = 0; + + // Check integrity of free lists + for (uint32_t list = 0; list < m_ListsCount; ++list) + { + Block* block = m_FreeList[list]; + if (block != VMA_NULL) + { + VMA_VALIDATE(block->IsFree()); + VMA_VALIDATE(block->PrevFree() == VMA_NULL); + while (block->NextFree()) + { + VMA_VALIDATE(block->NextFree()->IsFree()); + VMA_VALIDATE(block->NextFree()->PrevFree() == block); + block = block->NextFree(); + } + } + } + + VkDeviceSize nextOffset = m_NullBlock->offset; + auto validateCtx = m_GranularityHandler.StartValidation(GetAllocationCallbacks(), IsVirtual()); + + VMA_VALIDATE(m_NullBlock->nextPhysical == VMA_NULL); + if (m_NullBlock->prevPhysical) + { + VMA_VALIDATE(m_NullBlock->prevPhysical->nextPhysical == m_NullBlock); + } + // Check all blocks + for (Block* prev = m_NullBlock->prevPhysical; prev != VMA_NULL; prev = prev->prevPhysical) + { + VMA_VALIDATE(prev->offset + prev->size == nextOffset); + nextOffset = prev->offset; + calculatedSize += prev->size; + + uint32_t listIndex = GetListIndex(prev->size); + if (prev->IsFree()) + { + ++freeCount; + // Check if free block belongs to free list + Block* freeBlock = m_FreeList[listIndex]; + VMA_VALIDATE(freeBlock != VMA_NULL); + + bool found = false; + do + { + if (freeBlock == prev) + found = true; + + freeBlock = freeBlock->NextFree(); + } while (!found && freeBlock != VMA_NULL); + + VMA_VALIDATE(found); + calculatedFreeSize += prev->size; + } + else + { + ++allocCount; + // Check if taken block is not on a free list + Block* freeBlock = m_FreeList[listIndex]; + while (freeBlock) + { + VMA_VALIDATE(freeBlock != prev); + freeBlock = freeBlock->NextFree(); + } + + if (!IsVirtual()) + { + VMA_VALIDATE(m_GranularityHandler.Validate(validateCtx, prev->offset, prev->size)); + } + } + + if (prev->prevPhysical) + { + VMA_VALIDATE(prev->prevPhysical->nextPhysical == prev); + } + } + + if (!IsVirtual()) + { + VMA_VALIDATE(m_GranularityHandler.FinishValidation(validateCtx)); + } + + VMA_VALIDATE(nextOffset == 0); + VMA_VALIDATE(calculatedSize == GetSize()); + VMA_VALIDATE(calculatedFreeSize == GetSumFreeSize()); + VMA_VALIDATE(allocCount == m_AllocCount); + VMA_VALIDATE(freeCount == m_BlocksFreeCount); + + return true; +} + +void VmaBlockMetadata_TLSF::AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const +{ + inoutStats.statistics.blockCount++; + inoutStats.statistics.blockBytes += GetSize(); + if (m_NullBlock->size > 0) + VmaAddDetailedStatisticsUnusedRange(inoutStats, m_NullBlock->size); + + for (Block* block = m_NullBlock->prevPhysical; block != VMA_NULL; block = block->prevPhysical) + { + if (block->IsFree()) + VmaAddDetailedStatisticsUnusedRange(inoutStats, block->size); + else + VmaAddDetailedStatisticsAllocation(inoutStats, block->size); + } +} + +void VmaBlockMetadata_TLSF::AddStatistics(VmaStatistics& inoutStats) const +{ + inoutStats.blockCount++; + inoutStats.allocationCount += (uint32_t)m_AllocCount; + inoutStats.blockBytes += GetSize(); + inoutStats.allocationBytes += GetSize() - GetSumFreeSize(); +} + +#if VMA_STATS_STRING_ENABLED +void VmaBlockMetadata_TLSF::PrintDetailedMap(class VmaJsonWriter& json) const +{ + size_t blockCount = m_AllocCount + m_BlocksFreeCount; + VmaStlAllocator allocator(GetAllocationCallbacks()); + VmaVector> blockList(blockCount, allocator); + + size_t i = blockCount; + for (Block* block = m_NullBlock->prevPhysical; block != VMA_NULL; block = block->prevPhysical) + { + blockList[--i] = block; + } + VMA_ASSERT(i == 0); + + VmaDetailedStatistics stats; + VmaClearDetailedStatistics(stats); + AddDetailedStatistics(stats); + + PrintDetailedMap_Begin(json, + stats.statistics.blockBytes - stats.statistics.allocationBytes, + stats.statistics.allocationCount, + stats.unusedRangeCount); + + for (; i < blockCount; ++i) + { + Block* block = blockList[i]; + if (block->IsFree()) + PrintDetailedMap_UnusedRange(json, block->offset, block->size); + else + PrintDetailedMap_Allocation(json, block->offset, block->size, block->UserData()); + } + if (m_NullBlock->size > 0) + PrintDetailedMap_UnusedRange(json, m_NullBlock->offset, m_NullBlock->size); + + PrintDetailedMap_End(json); +} +#endif + +bool VmaBlockMetadata_TLSF::CreateAllocationRequest( + VkDeviceSize allocSize, + VkDeviceSize allocAlignment, + bool upperAddress, + VmaSuballocationType allocType, + uint32_t strategy, + VmaAllocationRequest* pAllocationRequest) +{ + VMA_ASSERT(allocSize > 0 && "Cannot allocate empty block!"); + VMA_ASSERT(!upperAddress && "VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT can be used only with linear algorithm."); + + // For small granularity round up + if (!IsVirtual()) + m_GranularityHandler.RoundupAllocRequest(allocType, allocSize, allocAlignment); + + allocSize += GetDebugMargin(); + // Quick check for too small pool + if (allocSize > GetSumFreeSize()) + return false; + + // If no free blocks in pool then check only null block + if (m_BlocksFreeCount == 0) + return CheckBlock(*m_NullBlock, m_ListsCount, allocSize, allocAlignment, allocType, pAllocationRequest); + + // Round up to the next block + VkDeviceSize sizeForNextList = allocSize; + VkDeviceSize smallSizeStep = VkDeviceSize(SMALL_BUFFER_SIZE / (IsVirtual() ? 1 << SECOND_LEVEL_INDEX : 4)); + if (allocSize > SMALL_BUFFER_SIZE) + { + sizeForNextList += (1ULL << (VMA_BITSCAN_MSB(allocSize) - SECOND_LEVEL_INDEX)); + } + else if (allocSize > SMALL_BUFFER_SIZE - smallSizeStep) + sizeForNextList = SMALL_BUFFER_SIZE + 1; + else + sizeForNextList += smallSizeStep; + + uint32_t nextListIndex = m_ListsCount; + uint32_t prevListIndex = m_ListsCount; + Block* nextListBlock = VMA_NULL; + Block* prevListBlock = VMA_NULL; + + // Check blocks according to strategies + if (strategy & VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT) + { + // Quick check for larger block first + nextListBlock = FindFreeBlock(sizeForNextList, nextListIndex); + if (nextListBlock != VMA_NULL && CheckBlock(*nextListBlock, nextListIndex, allocSize, allocAlignment, allocType, pAllocationRequest)) + return true; + + // If not fitted then null block + if (CheckBlock(*m_NullBlock, m_ListsCount, allocSize, allocAlignment, allocType, pAllocationRequest)) + return true; + + // Null block failed, search larger bucket + while (nextListBlock) + { + if (CheckBlock(*nextListBlock, nextListIndex, allocSize, allocAlignment, allocType, pAllocationRequest)) + return true; + nextListBlock = nextListBlock->NextFree(); + } + + // Failed again, check best fit bucket + prevListBlock = FindFreeBlock(allocSize, prevListIndex); + while (prevListBlock) + { + if (CheckBlock(*prevListBlock, prevListIndex, allocSize, allocAlignment, allocType, pAllocationRequest)) + return true; + prevListBlock = prevListBlock->NextFree(); + } + } + else if (strategy & VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT) + { + // Check best fit bucket + prevListBlock = FindFreeBlock(allocSize, prevListIndex); + while (prevListBlock) + { + if (CheckBlock(*prevListBlock, prevListIndex, allocSize, allocAlignment, allocType, pAllocationRequest)) + return true; + prevListBlock = prevListBlock->NextFree(); + } + + // If failed check null block + if (CheckBlock(*m_NullBlock, m_ListsCount, allocSize, allocAlignment, allocType, pAllocationRequest)) + return true; + + // Check larger bucket + nextListBlock = FindFreeBlock(sizeForNextList, nextListIndex); + while (nextListBlock) + { + if (CheckBlock(*nextListBlock, nextListIndex, allocSize, allocAlignment, allocType, pAllocationRequest)) + return true; + nextListBlock = nextListBlock->NextFree(); + } + } + else if (strategy & VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT ) + { + // Perform search from the start + VmaStlAllocator allocator(GetAllocationCallbacks()); + VmaVector> blockList(m_BlocksFreeCount, allocator); + + size_t i = m_BlocksFreeCount; + for (Block* block = m_NullBlock->prevPhysical; block != VMA_NULL; block = block->prevPhysical) + { + if (block->IsFree() && block->size >= allocSize) + blockList[--i] = block; + } + + for (; i < m_BlocksFreeCount; ++i) + { + Block& block = *blockList[i]; + if (CheckBlock(block, GetListIndex(block.size), allocSize, allocAlignment, allocType, pAllocationRequest)) + return true; + } + + // If failed check null block + if (CheckBlock(*m_NullBlock, m_ListsCount, allocSize, allocAlignment, allocType, pAllocationRequest)) + return true; + + // Whole range searched, no more memory + return false; + } + else + { + // Check larger bucket + nextListBlock = FindFreeBlock(sizeForNextList, nextListIndex); + while (nextListBlock) + { + if (CheckBlock(*nextListBlock, nextListIndex, allocSize, allocAlignment, allocType, pAllocationRequest)) + return true; + nextListBlock = nextListBlock->NextFree(); + } + + // If failed check null block + if (CheckBlock(*m_NullBlock, m_ListsCount, allocSize, allocAlignment, allocType, pAllocationRequest)) + return true; + + // Check best fit bucket + prevListBlock = FindFreeBlock(allocSize, prevListIndex); + while (prevListBlock) + { + if (CheckBlock(*prevListBlock, prevListIndex, allocSize, allocAlignment, allocType, pAllocationRequest)) + return true; + prevListBlock = prevListBlock->NextFree(); + } + } + + // Worst case, full search has to be done + while (++nextListIndex < m_ListsCount) + { + nextListBlock = m_FreeList[nextListIndex]; + while (nextListBlock) + { + if (CheckBlock(*nextListBlock, nextListIndex, allocSize, allocAlignment, allocType, pAllocationRequest)) + return true; + nextListBlock = nextListBlock->NextFree(); + } + } + + // No more memory sadly + return false; +} + +VkResult VmaBlockMetadata_TLSF::CheckCorruption(const void* pBlockData) +{ + for (Block* block = m_NullBlock->prevPhysical; block != VMA_NULL; block = block->prevPhysical) + { + if (!block->IsFree()) + { + if (!VmaValidateMagicValue(pBlockData, block->offset + block->size)) + { + VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER VALIDATED ALLOCATION!"); + return VK_ERROR_UNKNOWN_COPY; + } + } + } + + return VK_SUCCESS; +} + +void VmaBlockMetadata_TLSF::Alloc( + const VmaAllocationRequest& request, + VmaSuballocationType type, + void* userData) +{ + VMA_ASSERT(request.type == VmaAllocationRequestType::TLSF); + + // Get block and pop it from the free list + Block* currentBlock = (Block*)request.allocHandle; + VkDeviceSize offset = request.algorithmData; + VMA_ASSERT(currentBlock != VMA_NULL); + VMA_ASSERT(currentBlock->offset <= offset); + + if (currentBlock != m_NullBlock) + RemoveFreeBlock(currentBlock); + + VkDeviceSize debugMargin = GetDebugMargin(); + VkDeviceSize misssingAlignment = offset - currentBlock->offset; + + // Append missing alignment to prev block or create new one + if (misssingAlignment) + { + Block* prevBlock = currentBlock->prevPhysical; + VMA_ASSERT(prevBlock != VMA_NULL && "There should be no missing alignment at offset 0!"); + + if (prevBlock->IsFree() && prevBlock->size != debugMargin) + { + uint32_t oldList = GetListIndex(prevBlock->size); + prevBlock->size += misssingAlignment; + // Check if new size crosses list bucket + if (oldList != GetListIndex(prevBlock->size)) + { + prevBlock->size -= misssingAlignment; + RemoveFreeBlock(prevBlock); + prevBlock->size += misssingAlignment; + InsertFreeBlock(prevBlock); + } + else + m_BlocksFreeSize += misssingAlignment; + } + else + { + Block* newBlock = m_BlockAllocator.Alloc(); + currentBlock->prevPhysical = newBlock; + prevBlock->nextPhysical = newBlock; + newBlock->prevPhysical = prevBlock; + newBlock->nextPhysical = currentBlock; + newBlock->size = misssingAlignment; + newBlock->offset = currentBlock->offset; + newBlock->MarkTaken(); + + InsertFreeBlock(newBlock); + } + + currentBlock->size -= misssingAlignment; + currentBlock->offset += misssingAlignment; + } + + VkDeviceSize size = request.size + debugMargin; + if (currentBlock->size == size) + { + if (currentBlock == m_NullBlock) + { + // Setup new null block + m_NullBlock = m_BlockAllocator.Alloc(); + m_NullBlock->size = 0; + m_NullBlock->offset = currentBlock->offset + size; + m_NullBlock->prevPhysical = currentBlock; + m_NullBlock->nextPhysical = VMA_NULL; + m_NullBlock->MarkFree(); + m_NullBlock->PrevFree() = VMA_NULL; + m_NullBlock->NextFree() = VMA_NULL; + currentBlock->nextPhysical = m_NullBlock; + currentBlock->MarkTaken(); + } + } + else + { + VMA_ASSERT(currentBlock->size > size && "Proper block already found, shouldn't find smaller one!"); + + // Create new free block + Block* newBlock = m_BlockAllocator.Alloc(); + newBlock->size = currentBlock->size - size; + newBlock->offset = currentBlock->offset + size; + newBlock->prevPhysical = currentBlock; + newBlock->nextPhysical = currentBlock->nextPhysical; + currentBlock->nextPhysical = newBlock; + currentBlock->size = size; + + if (currentBlock == m_NullBlock) + { + m_NullBlock = newBlock; + m_NullBlock->MarkFree(); + m_NullBlock->NextFree() = VMA_NULL; + m_NullBlock->PrevFree() = VMA_NULL; + currentBlock->MarkTaken(); + } + else + { + newBlock->nextPhysical->prevPhysical = newBlock; + newBlock->MarkTaken(); + InsertFreeBlock(newBlock); + } + } + currentBlock->UserData() = userData; + + if (debugMargin > 0) + { + currentBlock->size -= debugMargin; + Block* newBlock = m_BlockAllocator.Alloc(); + newBlock->size = debugMargin; + newBlock->offset = currentBlock->offset + currentBlock->size; + newBlock->prevPhysical = currentBlock; + newBlock->nextPhysical = currentBlock->nextPhysical; + newBlock->MarkTaken(); + currentBlock->nextPhysical->prevPhysical = newBlock; + currentBlock->nextPhysical = newBlock; + InsertFreeBlock(newBlock); + } + + if (!IsVirtual()) + m_GranularityHandler.AllocPages((uint8_t)(uintptr_t)request.customData, + currentBlock->offset, currentBlock->size); + ++m_AllocCount; +} + +void VmaBlockMetadata_TLSF::Free(VmaAllocHandle allocHandle) +{ + Block* block = (Block*)allocHandle; + Block* next = block->nextPhysical; + VMA_ASSERT(!block->IsFree() && "Block is already free!"); + + if (!IsVirtual()) + m_GranularityHandler.FreePages(block->offset, block->size); + --m_AllocCount; + + VkDeviceSize debugMargin = GetDebugMargin(); + if (debugMargin > 0) + { + RemoveFreeBlock(next); + MergeBlock(next, block); + block = next; + next = next->nextPhysical; + } + + // Try merging + Block* prev = block->prevPhysical; + if (prev != VMA_NULL && prev->IsFree() && prev->size != debugMargin) + { + RemoveFreeBlock(prev); + MergeBlock(block, prev); + } + + if (!next->IsFree()) + InsertFreeBlock(block); + else if (next == m_NullBlock) + MergeBlock(m_NullBlock, block); + else + { + RemoveFreeBlock(next); + MergeBlock(next, block); + InsertFreeBlock(next); + } +} + +void VmaBlockMetadata_TLSF::GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo) +{ + Block* block = (Block*)allocHandle; + VMA_ASSERT(!block->IsFree() && "Cannot get allocation info for free block!"); + outInfo.offset = block->offset; + outInfo.size = block->size; + outInfo.pUserData = block->UserData(); +} + +void* VmaBlockMetadata_TLSF::GetAllocationUserData(VmaAllocHandle allocHandle) const +{ + Block* block = (Block*)allocHandle; + VMA_ASSERT(!block->IsFree() && "Cannot get user data for free block!"); + return block->UserData(); +} + +VmaAllocHandle VmaBlockMetadata_TLSF::GetAllocationListBegin() const +{ + if (m_AllocCount == 0) + return VK_NULL_HANDLE; + + for (Block* block = m_NullBlock->prevPhysical; block; block = block->prevPhysical) + { + if (!block->IsFree()) + return (VmaAllocHandle)block; + } + VMA_ASSERT(false && "If m_AllocCount > 0 then should find any allocation!"); + return VK_NULL_HANDLE; +} + +VmaAllocHandle VmaBlockMetadata_TLSF::GetNextAllocation(VmaAllocHandle prevAlloc) const +{ + Block* startBlock = (Block*)prevAlloc; + VMA_ASSERT(!startBlock->IsFree() && "Incorrect block!"); + + for (Block* block = startBlock->prevPhysical; block; block = block->prevPhysical) + { + if (!block->IsFree()) + return (VmaAllocHandle)block; + } + return VK_NULL_HANDLE; +} + +VkDeviceSize VmaBlockMetadata_TLSF::GetNextFreeRegionSize(VmaAllocHandle alloc) const +{ + Block* block = (Block*)alloc; + VMA_ASSERT(!block->IsFree() && "Incorrect block!"); + + if (block->prevPhysical) + return block->prevPhysical->IsFree() ? block->prevPhysical->size : 0; + return 0; +} + +void VmaBlockMetadata_TLSF::Clear() +{ + m_AllocCount = 0; + m_BlocksFreeCount = 0; + m_BlocksFreeSize = 0; + m_IsFreeBitmap = 0; + m_NullBlock->offset = 0; + m_NullBlock->size = GetSize(); + Block* block = m_NullBlock->prevPhysical; + m_NullBlock->prevPhysical = VMA_NULL; + while (block) + { + Block* prev = block->prevPhysical; + m_BlockAllocator.Free(block); + block = prev; + } + memset(m_FreeList, 0, m_ListsCount * sizeof(Block*)); + memset(m_InnerIsFreeBitmap, 0, m_MemoryClasses * sizeof(uint32_t)); + m_GranularityHandler.Clear(); +} + +void VmaBlockMetadata_TLSF::SetAllocationUserData(VmaAllocHandle allocHandle, void* userData) +{ + Block* block = (Block*)allocHandle; + VMA_ASSERT(!block->IsFree() && "Trying to set user data for not allocated block!"); + block->UserData() = userData; +} + +void VmaBlockMetadata_TLSF::DebugLogAllAllocations() const +{ + for (Block* block = m_NullBlock->prevPhysical; block != VMA_NULL; block = block->prevPhysical) + if (!block->IsFree()) + DebugLogAllocation(block->offset, block->size, block->UserData()); +} + +uint8_t VmaBlockMetadata_TLSF::SizeToMemoryClass(VkDeviceSize size) const +{ + if (size > SMALL_BUFFER_SIZE) + return uint8_t(VMA_BITSCAN_MSB(size) - MEMORY_CLASS_SHIFT); + return 0; +} + +uint16_t VmaBlockMetadata_TLSF::SizeToSecondIndex(VkDeviceSize size, uint8_t memoryClass) const +{ + if (memoryClass == 0) + { + if (IsVirtual()) + return static_cast((size - 1) / 8); + else + return static_cast((size - 1) / 64); + } + return static_cast((size >> (memoryClass + MEMORY_CLASS_SHIFT - SECOND_LEVEL_INDEX)) ^ (1U << SECOND_LEVEL_INDEX)); +} + +uint32_t VmaBlockMetadata_TLSF::GetListIndex(uint8_t memoryClass, uint16_t secondIndex) const +{ + if (memoryClass == 0) + return secondIndex; + + const uint32_t index = static_cast(memoryClass - 1) * (1 << SECOND_LEVEL_INDEX) + secondIndex; + if (IsVirtual()) + return index + (1 << SECOND_LEVEL_INDEX); + else + return index + 4; +} + +uint32_t VmaBlockMetadata_TLSF::GetListIndex(VkDeviceSize size) const +{ + uint8_t memoryClass = SizeToMemoryClass(size); + return GetListIndex(memoryClass, SizeToSecondIndex(size, memoryClass)); +} + +void VmaBlockMetadata_TLSF::RemoveFreeBlock(Block* block) +{ + VMA_ASSERT(block != m_NullBlock); + VMA_ASSERT(block->IsFree()); + + if (block->NextFree() != VMA_NULL) + block->NextFree()->PrevFree() = block->PrevFree(); + if (block->PrevFree() != VMA_NULL) + block->PrevFree()->NextFree() = block->NextFree(); + else + { + uint8_t memClass = SizeToMemoryClass(block->size); + uint16_t secondIndex = SizeToSecondIndex(block->size, memClass); + uint32_t index = GetListIndex(memClass, secondIndex); + VMA_ASSERT(m_FreeList[index] == block); + m_FreeList[index] = block->NextFree(); + if (block->NextFree() == VMA_NULL) + { + m_InnerIsFreeBitmap[memClass] &= ~(1U << secondIndex); + if (m_InnerIsFreeBitmap[memClass] == 0) + m_IsFreeBitmap &= ~(1UL << memClass); + } + } + block->MarkTaken(); + block->UserData() = VMA_NULL; + --m_BlocksFreeCount; + m_BlocksFreeSize -= block->size; +} + +void VmaBlockMetadata_TLSF::InsertFreeBlock(Block* block) +{ + VMA_ASSERT(block != m_NullBlock); + VMA_ASSERT(!block->IsFree() && "Cannot insert block twice!"); + + uint8_t memClass = SizeToMemoryClass(block->size); + uint16_t secondIndex = SizeToSecondIndex(block->size, memClass); + uint32_t index = GetListIndex(memClass, secondIndex); + VMA_ASSERT(index < m_ListsCount); + block->PrevFree() = VMA_NULL; + block->NextFree() = m_FreeList[index]; + m_FreeList[index] = block; + if (block->NextFree() != VMA_NULL) + block->NextFree()->PrevFree() = block; + else + { + m_InnerIsFreeBitmap[memClass] |= 1U << secondIndex; + m_IsFreeBitmap |= 1UL << memClass; + } + ++m_BlocksFreeCount; + m_BlocksFreeSize += block->size; +} + +void VmaBlockMetadata_TLSF::MergeBlock(Block* block, Block* prev) +{ + VMA_ASSERT(block->prevPhysical == prev && "Cannot merge separate physical regions!"); + VMA_ASSERT(!prev->IsFree() && "Cannot merge block that belongs to free list!"); + + block->offset = prev->offset; + block->size += prev->size; + block->prevPhysical = prev->prevPhysical; + if (block->prevPhysical) + block->prevPhysical->nextPhysical = block; + m_BlockAllocator.Free(prev); +} + +VmaBlockMetadata_TLSF::Block* VmaBlockMetadata_TLSF::FindFreeBlock(VkDeviceSize size, uint32_t& listIndex) const +{ + uint8_t memoryClass = SizeToMemoryClass(size); + uint32_t innerFreeMap = m_InnerIsFreeBitmap[memoryClass] & (~0U << SizeToSecondIndex(size, memoryClass)); + if (!innerFreeMap) + { + // Check higher levels for available blocks + uint32_t freeMap = m_IsFreeBitmap & (~0UL << (memoryClass + 1)); + if (!freeMap) + return VMA_NULL; // No more memory available + + // Find lowest free region + memoryClass = VMA_BITSCAN_LSB(freeMap); + innerFreeMap = m_InnerIsFreeBitmap[memoryClass]; + VMA_ASSERT(innerFreeMap != 0); + } + // Find lowest free subregion + listIndex = GetListIndex(memoryClass, VMA_BITSCAN_LSB(innerFreeMap)); + VMA_ASSERT(m_FreeList[listIndex]); + return m_FreeList[listIndex]; +} + +bool VmaBlockMetadata_TLSF::CheckBlock( + Block& block, + uint32_t listIndex, + VkDeviceSize allocSize, + VkDeviceSize allocAlignment, + VmaSuballocationType allocType, + VmaAllocationRequest* pAllocationRequest) +{ + VMA_ASSERT(block.IsFree() && "Block is already taken!"); + + VkDeviceSize alignedOffset = VmaAlignUp(block.offset, allocAlignment); + if (block.size < allocSize + alignedOffset - block.offset) + return false; + + // Check for granularity conflicts + if (!IsVirtual() && + m_GranularityHandler.CheckConflictAndAlignUp(alignedOffset, allocSize, block.offset, block.size, allocType)) + return false; + + // Alloc successful + pAllocationRequest->type = VmaAllocationRequestType::TLSF; + pAllocationRequest->allocHandle = (VmaAllocHandle)█ + pAllocationRequest->size = allocSize - GetDebugMargin(); + pAllocationRequest->customData = (void*)allocType; + pAllocationRequest->algorithmData = alignedOffset; + + // Place block at the start of list if it's normal block + if (listIndex != m_ListsCount && block.PrevFree()) + { + block.PrevFree()->NextFree() = block.NextFree(); + if (block.NextFree()) + block.NextFree()->PrevFree() = block.PrevFree(); + block.PrevFree() = VMA_NULL; + block.NextFree() = m_FreeList[listIndex]; + m_FreeList[listIndex] = █ + if (block.NextFree()) + block.NextFree()->PrevFree() = █ + } + + return true; +} +#endif // _VMA_BLOCK_METADATA_TLSF_FUNCTIONS +#endif // _VMA_BLOCK_METADATA_TLSF + +#ifndef _VMA_BLOCK_VECTOR +/* +Sequence of VmaDeviceMemoryBlock. Represents memory blocks allocated for a specific +Vulkan memory type. + +Synchronized internally with a mutex. +*/ +class VmaBlockVector +{ + friend struct VmaDefragmentationContext_T; + VMA_CLASS_NO_COPY_NO_MOVE(VmaBlockVector) +public: + VmaBlockVector( + VmaAllocator hAllocator, + VmaPool hParentPool, + uint32_t memoryTypeIndex, + VkDeviceSize preferredBlockSize, + size_t minBlockCount, + size_t maxBlockCount, + VkDeviceSize bufferImageGranularity, + bool explicitBlockSize, + uint32_t algorithm, + float priority, + VkDeviceSize minAllocationAlignment, + void* pMemoryAllocateNext); + ~VmaBlockVector(); + + VmaAllocator GetAllocator() const { return m_hAllocator; } + VmaPool GetParentPool() const { return m_hParentPool; } + bool IsCustomPool() const { return m_hParentPool != VMA_NULL; } + uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; } + VkDeviceSize GetPreferredBlockSize() const { return m_PreferredBlockSize; } + VkDeviceSize GetBufferImageGranularity() const { return m_BufferImageGranularity; } + uint32_t GetAlgorithm() const { return m_Algorithm; } + bool HasExplicitBlockSize() const { return m_ExplicitBlockSize; } + float GetPriority() const { return m_Priority; } + const void* GetAllocationNextPtr() const { return m_pMemoryAllocateNext; } + // To be used only while the m_Mutex is locked. Used during defragmentation. + size_t GetBlockCount() const { return m_Blocks.size(); } + // To be used only while the m_Mutex is locked. Used during defragmentation. + VmaDeviceMemoryBlock* GetBlock(size_t index) const { return m_Blocks[index]; } + VMA_RW_MUTEX &GetMutex() { return m_Mutex; } + + VkResult CreateMinBlocks(); + void AddStatistics(VmaStatistics& inoutStats); + void AddDetailedStatistics(VmaDetailedStatistics& inoutStats); + bool IsEmpty(); + bool IsCorruptionDetectionEnabled() const; + + VkResult Allocate( + VkDeviceSize size, + VkDeviceSize alignment, + const VmaAllocationCreateInfo& createInfo, + VmaSuballocationType suballocType, + size_t allocationCount, + VmaAllocation* pAllocations); + + void Free(const VmaAllocation hAllocation); + +#if VMA_STATS_STRING_ENABLED + void PrintDetailedMap(class VmaJsonWriter& json); +#endif + + VkResult CheckCorruption(); + +private: + const VmaAllocator m_hAllocator; + const VmaPool m_hParentPool; + const uint32_t m_MemoryTypeIndex; + const VkDeviceSize m_PreferredBlockSize; + const size_t m_MinBlockCount; + const size_t m_MaxBlockCount; + const VkDeviceSize m_BufferImageGranularity; + const bool m_ExplicitBlockSize; + const uint32_t m_Algorithm; + const float m_Priority; + const VkDeviceSize m_MinAllocationAlignment; + + void* const m_pMemoryAllocateNext; + VMA_RW_MUTEX m_Mutex; + // Incrementally sorted by sumFreeSize, ascending. + VmaVector> m_Blocks; + uint32_t m_NextBlockId; + bool m_IncrementalSort = true; + + void SetIncrementalSort(bool val) { m_IncrementalSort = val; } + + VkDeviceSize CalcMaxBlockSize() const; + // Finds and removes given block from vector. + void Remove(VmaDeviceMemoryBlock* pBlock); + // Performs single step in sorting m_Blocks. They may not be fully sorted + // after this call. + void IncrementallySortBlocks(); + void SortByFreeSize(); + + VkResult AllocatePage( + VkDeviceSize size, + VkDeviceSize alignment, + const VmaAllocationCreateInfo& createInfo, + VmaSuballocationType suballocType, + VmaAllocation* pAllocation); + + VkResult AllocateFromBlock( + VmaDeviceMemoryBlock* pBlock, + VkDeviceSize size, + VkDeviceSize alignment, + VmaAllocationCreateFlags allocFlags, + void* pUserData, + VmaSuballocationType suballocType, + uint32_t strategy, + VmaAllocation* pAllocation); + + VkResult CommitAllocationRequest( + VmaAllocationRequest& allocRequest, + VmaDeviceMemoryBlock* pBlock, + VkDeviceSize alignment, + VmaAllocationCreateFlags allocFlags, + void* pUserData, + VmaSuballocationType suballocType, + VmaAllocation* pAllocation); + + VkResult CreateBlock(VkDeviceSize blockSize, size_t* pNewBlockIndex); + bool HasEmptyBlock(); +}; +#endif // _VMA_BLOCK_VECTOR + +#ifndef _VMA_DEFRAGMENTATION_CONTEXT +struct VmaDefragmentationContext_T +{ + VMA_CLASS_NO_COPY_NO_MOVE(VmaDefragmentationContext_T) +public: + VmaDefragmentationContext_T( + VmaAllocator hAllocator, + const VmaDefragmentationInfo& info); + ~VmaDefragmentationContext_T(); + + void GetStats(VmaDefragmentationStats& outStats) { outStats = m_GlobalStats; } + + VkResult DefragmentPassBegin(VmaDefragmentationPassMoveInfo& moveInfo); + VkResult DefragmentPassEnd(VmaDefragmentationPassMoveInfo& moveInfo); + +private: + // Max number of allocations to ignore due to size constraints before ending single pass + static const uint8_t MAX_ALLOCS_TO_IGNORE = 16; + enum class CounterStatus { Pass, Ignore, End }; + + struct FragmentedBlock + { + uint32_t data; + VmaDeviceMemoryBlock* block; + }; + struct StateBalanced + { + VkDeviceSize avgFreeSize = 0; + VkDeviceSize avgAllocSize = UINT64_MAX; + }; + struct StateExtensive + { + enum class Operation : uint8_t + { + FindFreeBlockBuffer, FindFreeBlockTexture, FindFreeBlockAll, + MoveBuffers, MoveTextures, MoveAll, + Cleanup, Done + }; + + Operation operation = Operation::FindFreeBlockTexture; + size_t firstFreeBlock = SIZE_MAX; + }; + struct MoveAllocationData + { + VkDeviceSize size; + VkDeviceSize alignment; + VmaSuballocationType type; + VmaAllocationCreateFlags flags; + VmaDefragmentationMove move = {}; + }; + + const VkDeviceSize m_MaxPassBytes; + const uint32_t m_MaxPassAllocations; + const PFN_vmaCheckDefragmentationBreakFunction m_BreakCallback; + void* m_BreakCallbackUserData; + + VmaStlAllocator m_MoveAllocator; + VmaVector> m_Moves; + + uint8_t m_IgnoredAllocs = 0; + uint32_t m_Algorithm; + uint32_t m_BlockVectorCount; + VmaBlockVector* m_PoolBlockVector; + VmaBlockVector** m_pBlockVectors; + size_t m_ImmovableBlockCount = 0; + VmaDefragmentationStats m_GlobalStats = { 0 }; + VmaDefragmentationStats m_PassStats = { 0 }; + void* m_AlgorithmState = VMA_NULL; + + static MoveAllocationData GetMoveData(VmaAllocHandle handle, VmaBlockMetadata* metadata); + CounterStatus CheckCounters(VkDeviceSize bytes); + bool IncrementCounters(VkDeviceSize bytes); + bool ReallocWithinBlock(VmaBlockVector& vector, VmaDeviceMemoryBlock* block); + bool AllocInOtherBlock(size_t start, size_t end, MoveAllocationData& data, VmaBlockVector& vector); + + bool ComputeDefragmentation(VmaBlockVector& vector, size_t index); + bool ComputeDefragmentation_Fast(VmaBlockVector& vector); + bool ComputeDefragmentation_Balanced(VmaBlockVector& vector, size_t index, bool update); + bool ComputeDefragmentation_Full(VmaBlockVector& vector); + bool ComputeDefragmentation_Extensive(VmaBlockVector& vector, size_t index); + + void UpdateVectorStatistics(VmaBlockVector& vector, StateBalanced& state); + bool MoveDataToFreeBlocks(VmaSuballocationType currentType, + VmaBlockVector& vector, size_t firstFreeBlock, + bool& texturePresent, bool& bufferPresent, bool& otherPresent); +}; +#endif // _VMA_DEFRAGMENTATION_CONTEXT + +#ifndef _VMA_POOL_T +struct VmaPool_T +{ + friend struct VmaPoolListItemTraits; + VMA_CLASS_NO_COPY_NO_MOVE(VmaPool_T) +public: + VmaBlockVector m_BlockVector; + VmaDedicatedAllocationList m_DedicatedAllocations; + + VmaPool_T( + VmaAllocator hAllocator, + const VmaPoolCreateInfo& createInfo, + VkDeviceSize preferredBlockSize); + ~VmaPool_T(); + + uint32_t GetId() const { return m_Id; } + void SetId(uint32_t id) { VMA_ASSERT(m_Id == 0); m_Id = id; } + + const char* GetName() const { return m_Name; } + void SetName(const char* pName); + +#if VMA_STATS_STRING_ENABLED + //void PrintDetailedMap(class VmaStringBuilder& sb); +#endif + +private: + uint32_t m_Id; + char* m_Name; + VmaPool_T* m_PrevPool = VMA_NULL; + VmaPool_T* m_NextPool = VMA_NULL; +}; + +struct VmaPoolListItemTraits +{ + typedef VmaPool_T ItemType; + + static ItemType* GetPrev(const ItemType* item) { return item->m_PrevPool; } + static ItemType* GetNext(const ItemType* item) { return item->m_NextPool; } + static ItemType*& AccessPrev(ItemType* item) { return item->m_PrevPool; } + static ItemType*& AccessNext(ItemType* item) { return item->m_NextPool; } +}; +#endif // _VMA_POOL_T + +#ifndef _VMA_CURRENT_BUDGET_DATA +struct VmaCurrentBudgetData +{ + VMA_CLASS_NO_COPY_NO_MOVE(VmaCurrentBudgetData) +public: + + VMA_ATOMIC_UINT32 m_BlockCount[VK_MAX_MEMORY_HEAPS]; + VMA_ATOMIC_UINT32 m_AllocationCount[VK_MAX_MEMORY_HEAPS]; + VMA_ATOMIC_UINT64 m_BlockBytes[VK_MAX_MEMORY_HEAPS]; + VMA_ATOMIC_UINT64 m_AllocationBytes[VK_MAX_MEMORY_HEAPS]; + +#if VMA_MEMORY_BUDGET + VMA_ATOMIC_UINT32 m_OperationsSinceBudgetFetch; + VMA_RW_MUTEX m_BudgetMutex; + uint64_t m_VulkanUsage[VK_MAX_MEMORY_HEAPS]; + uint64_t m_VulkanBudget[VK_MAX_MEMORY_HEAPS]; + uint64_t m_BlockBytesAtBudgetFetch[VK_MAX_MEMORY_HEAPS]; +#endif // VMA_MEMORY_BUDGET + + VmaCurrentBudgetData(); + + void AddAllocation(uint32_t heapIndex, VkDeviceSize allocationSize); + void RemoveAllocation(uint32_t heapIndex, VkDeviceSize allocationSize); +}; + +#ifndef _VMA_CURRENT_BUDGET_DATA_FUNCTIONS +VmaCurrentBudgetData::VmaCurrentBudgetData() +{ + for (uint32_t heapIndex = 0; heapIndex < VK_MAX_MEMORY_HEAPS; ++heapIndex) + { + m_BlockCount[heapIndex] = 0; + m_AllocationCount[heapIndex] = 0; + m_BlockBytes[heapIndex] = 0; + m_AllocationBytes[heapIndex] = 0; +#if VMA_MEMORY_BUDGET + m_VulkanUsage[heapIndex] = 0; + m_VulkanBudget[heapIndex] = 0; + m_BlockBytesAtBudgetFetch[heapIndex] = 0; +#endif + } + +#if VMA_MEMORY_BUDGET + m_OperationsSinceBudgetFetch = 0; +#endif +} + +void VmaCurrentBudgetData::AddAllocation(uint32_t heapIndex, VkDeviceSize allocationSize) +{ + m_AllocationBytes[heapIndex] += allocationSize; + ++m_AllocationCount[heapIndex]; +#if VMA_MEMORY_BUDGET + ++m_OperationsSinceBudgetFetch; +#endif +} + +void VmaCurrentBudgetData::RemoveAllocation(uint32_t heapIndex, VkDeviceSize allocationSize) +{ + VMA_ASSERT(m_AllocationBytes[heapIndex] >= allocationSize); + m_AllocationBytes[heapIndex] -= allocationSize; + VMA_ASSERT(m_AllocationCount[heapIndex] > 0); + --m_AllocationCount[heapIndex]; +#if VMA_MEMORY_BUDGET + ++m_OperationsSinceBudgetFetch; +#endif +} +#endif // _VMA_CURRENT_BUDGET_DATA_FUNCTIONS +#endif // _VMA_CURRENT_BUDGET_DATA + +#ifndef _VMA_ALLOCATION_OBJECT_ALLOCATOR +/* +Thread-safe wrapper over VmaPoolAllocator free list, for allocation of VmaAllocation_T objects. +*/ +class VmaAllocationObjectAllocator +{ + VMA_CLASS_NO_COPY_NO_MOVE(VmaAllocationObjectAllocator) +public: + VmaAllocationObjectAllocator(const VkAllocationCallbacks* pAllocationCallbacks) + : m_Allocator(pAllocationCallbacks, 1024) {} + + template VmaAllocation Allocate(Types&&... args); + void Free(VmaAllocation hAlloc); + +private: + VMA_MUTEX m_Mutex; + VmaPoolAllocator m_Allocator; +}; + +template +VmaAllocation VmaAllocationObjectAllocator::Allocate(Types&&... args) +{ + VmaMutexLock mutexLock(m_Mutex); + return m_Allocator.Alloc(std::forward(args)...); +} + +void VmaAllocationObjectAllocator::Free(VmaAllocation hAlloc) +{ + VmaMutexLock mutexLock(m_Mutex); + m_Allocator.Free(hAlloc); +} +#endif // _VMA_ALLOCATION_OBJECT_ALLOCATOR + +#ifndef _VMA_VIRTUAL_BLOCK_T +struct VmaVirtualBlock_T +{ + VMA_CLASS_NO_COPY_NO_MOVE(VmaVirtualBlock_T) +public: + const bool m_AllocationCallbacksSpecified; + const VkAllocationCallbacks m_AllocationCallbacks; + + VmaVirtualBlock_T(const VmaVirtualBlockCreateInfo& createInfo); + ~VmaVirtualBlock_T(); + + VkResult Init() { return VK_SUCCESS; } + bool IsEmpty() const { return m_Metadata->IsEmpty(); } + void Free(VmaVirtualAllocation allocation) { m_Metadata->Free((VmaAllocHandle)allocation); } + void SetAllocationUserData(VmaVirtualAllocation allocation, void* userData) { m_Metadata->SetAllocationUserData((VmaAllocHandle)allocation, userData); } + void Clear() { m_Metadata->Clear(); } + + const VkAllocationCallbacks* GetAllocationCallbacks() const; + void GetAllocationInfo(VmaVirtualAllocation allocation, VmaVirtualAllocationInfo& outInfo); + VkResult Allocate(const VmaVirtualAllocationCreateInfo& createInfo, VmaVirtualAllocation& outAllocation, + VkDeviceSize* outOffset); + void GetStatistics(VmaStatistics& outStats) const; + void CalculateDetailedStatistics(VmaDetailedStatistics& outStats) const; +#if VMA_STATS_STRING_ENABLED + void BuildStatsString(bool detailedMap, VmaStringBuilder& sb) const; +#endif + +private: + VmaBlockMetadata* m_Metadata; +}; + +#ifndef _VMA_VIRTUAL_BLOCK_T_FUNCTIONS +VmaVirtualBlock_T::VmaVirtualBlock_T(const VmaVirtualBlockCreateInfo& createInfo) + : m_AllocationCallbacksSpecified(createInfo.pAllocationCallbacks != VMA_NULL), + m_AllocationCallbacks(createInfo.pAllocationCallbacks != VMA_NULL ? *createInfo.pAllocationCallbacks : VmaEmptyAllocationCallbacks) +{ + const uint32_t algorithm = createInfo.flags & VMA_VIRTUAL_BLOCK_CREATE_ALGORITHM_MASK; + switch (algorithm) + { + case 0: + m_Metadata = vma_new(GetAllocationCallbacks(), VmaBlockMetadata_TLSF)(VK_NULL_HANDLE, 1, true); + break; + case VMA_VIRTUAL_BLOCK_CREATE_LINEAR_ALGORITHM_BIT: + m_Metadata = vma_new(GetAllocationCallbacks(), VmaBlockMetadata_Linear)(VK_NULL_HANDLE, 1, true); + break; + default: + VMA_ASSERT(0); + m_Metadata = vma_new(GetAllocationCallbacks(), VmaBlockMetadata_TLSF)(VK_NULL_HANDLE, 1, true); + } + + m_Metadata->Init(createInfo.size); +} + +VmaVirtualBlock_T::~VmaVirtualBlock_T() +{ + // Define macro VMA_DEBUG_LOG_FORMAT or more specialized VMA_LEAK_LOG_FORMAT + // to receive the list of the unfreed allocations. + if (!m_Metadata->IsEmpty()) + m_Metadata->DebugLogAllAllocations(); + // This is the most important assert in the entire library. + // Hitting it means you have some memory leak - unreleased virtual allocations. + VMA_ASSERT_LEAK(m_Metadata->IsEmpty() && "Some virtual allocations were not freed before destruction of this virtual block!"); + + vma_delete(GetAllocationCallbacks(), m_Metadata); +} + +const VkAllocationCallbacks* VmaVirtualBlock_T::GetAllocationCallbacks() const +{ + return m_AllocationCallbacksSpecified ? &m_AllocationCallbacks : VMA_NULL; +} + +void VmaVirtualBlock_T::GetAllocationInfo(VmaVirtualAllocation allocation, VmaVirtualAllocationInfo& outInfo) +{ + m_Metadata->GetAllocationInfo((VmaAllocHandle)allocation, outInfo); +} + +VkResult VmaVirtualBlock_T::Allocate(const VmaVirtualAllocationCreateInfo& createInfo, VmaVirtualAllocation& outAllocation, + VkDeviceSize* outOffset) +{ + VmaAllocationRequest request = {}; + if (m_Metadata->CreateAllocationRequest( + createInfo.size, // allocSize + VMA_MAX(createInfo.alignment, (VkDeviceSize)1), // allocAlignment + (createInfo.flags & VMA_VIRTUAL_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0, // upperAddress + VMA_SUBALLOCATION_TYPE_UNKNOWN, // allocType - unimportant + createInfo.flags & VMA_VIRTUAL_ALLOCATION_CREATE_STRATEGY_MASK, // strategy + &request)) + { + m_Metadata->Alloc(request, + VMA_SUBALLOCATION_TYPE_UNKNOWN, // type - unimportant + createInfo.pUserData); + outAllocation = (VmaVirtualAllocation)request.allocHandle; + if(outOffset) + *outOffset = m_Metadata->GetAllocationOffset(request.allocHandle); + return VK_SUCCESS; + } + outAllocation = (VmaVirtualAllocation)VK_NULL_HANDLE; + if (outOffset) + *outOffset = UINT64_MAX; + return VK_ERROR_OUT_OF_DEVICE_MEMORY; +} + +void VmaVirtualBlock_T::GetStatistics(VmaStatistics& outStats) const +{ + VmaClearStatistics(outStats); + m_Metadata->AddStatistics(outStats); +} + +void VmaVirtualBlock_T::CalculateDetailedStatistics(VmaDetailedStatistics& outStats) const +{ + VmaClearDetailedStatistics(outStats); + m_Metadata->AddDetailedStatistics(outStats); +} + +#if VMA_STATS_STRING_ENABLED +void VmaVirtualBlock_T::BuildStatsString(bool detailedMap, VmaStringBuilder& sb) const +{ + VmaJsonWriter json(GetAllocationCallbacks(), sb); + json.BeginObject(); + + VmaDetailedStatistics stats; + CalculateDetailedStatistics(stats); + + json.WriteString("Stats"); + VmaPrintDetailedStatistics(json, stats); + + if (detailedMap) + { + json.WriteString("Details"); + json.BeginObject(); + m_Metadata->PrintDetailedMap(json); + json.EndObject(); + } + + json.EndObject(); +} +#endif // VMA_STATS_STRING_ENABLED +#endif // _VMA_VIRTUAL_BLOCK_T_FUNCTIONS +#endif // _VMA_VIRTUAL_BLOCK_T + + +// Main allocator object. +struct VmaAllocator_T +{ + VMA_CLASS_NO_COPY_NO_MOVE(VmaAllocator_T) +public: + const bool m_UseMutex; + const uint32_t m_VulkanApiVersion; + bool m_UseKhrDedicatedAllocation; // Can be set only if m_VulkanApiVersion < VK_MAKE_VERSION(1, 1, 0). + bool m_UseKhrBindMemory2; // Can be set only if m_VulkanApiVersion < VK_MAKE_VERSION(1, 1, 0). + bool m_UseExtMemoryBudget; + bool m_UseAmdDeviceCoherentMemory; + bool m_UseKhrBufferDeviceAddress; + bool m_UseExtMemoryPriority; + bool m_UseKhrMaintenance4; + bool m_UseKhrMaintenance5; + bool m_UseKhrExternalMemoryWin32; + const VkDevice m_hDevice; + const VkInstance m_hInstance; + const bool m_AllocationCallbacksSpecified; + const VkAllocationCallbacks m_AllocationCallbacks; + VmaDeviceMemoryCallbacks m_DeviceMemoryCallbacks; + VmaAllocationObjectAllocator m_AllocationObjectAllocator; + + // Each bit (1 << i) is set if HeapSizeLimit is enabled for that heap, so cannot allocate more than the heap size. + uint32_t m_HeapSizeLimitMask; + + VkPhysicalDeviceProperties m_PhysicalDeviceProperties; + VkPhysicalDeviceMemoryProperties m_MemProps; + + // Default pools. + VmaBlockVector* m_pBlockVectors[VK_MAX_MEMORY_TYPES]; + VmaDedicatedAllocationList m_DedicatedAllocations[VK_MAX_MEMORY_TYPES]; + + VmaCurrentBudgetData m_Budget; + VMA_ATOMIC_UINT32 m_DeviceMemoryCount; // Total number of VkDeviceMemory objects. + + VmaAllocator_T(const VmaAllocatorCreateInfo* pCreateInfo); + VkResult Init(const VmaAllocatorCreateInfo* pCreateInfo); + ~VmaAllocator_T(); + + const VkAllocationCallbacks* GetAllocationCallbacks() const + { + return m_AllocationCallbacksSpecified ? &m_AllocationCallbacks : VMA_NULL; + } + const VmaVulkanFunctions& GetVulkanFunctions() const + { + return m_VulkanFunctions; + } + + VkPhysicalDevice GetPhysicalDevice() const { return m_PhysicalDevice; } + + VkDeviceSize GetBufferImageGranularity() const + { + return VMA_MAX( + static_cast(VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY), + m_PhysicalDeviceProperties.limits.bufferImageGranularity); + } + + uint32_t GetMemoryHeapCount() const { return m_MemProps.memoryHeapCount; } + uint32_t GetMemoryTypeCount() const { return m_MemProps.memoryTypeCount; } + + uint32_t MemoryTypeIndexToHeapIndex(uint32_t memTypeIndex) const + { + VMA_ASSERT(memTypeIndex < m_MemProps.memoryTypeCount); + return m_MemProps.memoryTypes[memTypeIndex].heapIndex; + } + // True when specific memory type is HOST_VISIBLE but not HOST_COHERENT. + bool IsMemoryTypeNonCoherent(uint32_t memTypeIndex) const + { + return (m_MemProps.memoryTypes[memTypeIndex].propertyFlags & (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) == + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; + } + // Minimum alignment for all allocations in specific memory type. + VkDeviceSize GetMemoryTypeMinAlignment(uint32_t memTypeIndex) const + { + return IsMemoryTypeNonCoherent(memTypeIndex) ? + VMA_MAX((VkDeviceSize)VMA_MIN_ALIGNMENT, m_PhysicalDeviceProperties.limits.nonCoherentAtomSize) : + (VkDeviceSize)VMA_MIN_ALIGNMENT; + } + + bool IsIntegratedGpu() const + { + return m_PhysicalDeviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU; + } + + uint32_t GetGlobalMemoryTypeBits() const { return m_GlobalMemoryTypeBits; } + + void GetBufferMemoryRequirements( + VkBuffer hBuffer, + VkMemoryRequirements& memReq, + bool& requiresDedicatedAllocation, + bool& prefersDedicatedAllocation) const; + void GetImageMemoryRequirements( + VkImage hImage, + VkMemoryRequirements& memReq, + bool& requiresDedicatedAllocation, + bool& prefersDedicatedAllocation) const; + VkResult FindMemoryTypeIndex( + uint32_t memoryTypeBits, + const VmaAllocationCreateInfo* pAllocationCreateInfo, + VmaBufferImageUsage bufImgUsage, + uint32_t* pMemoryTypeIndex) const; + + // Main allocation function. + VkResult AllocateMemory( + const VkMemoryRequirements& vkMemReq, + bool requiresDedicatedAllocation, + bool prefersDedicatedAllocation, + VkBuffer dedicatedBuffer, + VkImage dedicatedImage, + VmaBufferImageUsage dedicatedBufferImageUsage, + const VmaAllocationCreateInfo& createInfo, + VmaSuballocationType suballocType, + size_t allocationCount, + VmaAllocation* pAllocations); + + // Main deallocation function. + void FreeMemory( + size_t allocationCount, + const VmaAllocation* pAllocations); + + void CalculateStatistics(VmaTotalStatistics* pStats); + + void GetHeapBudgets( + VmaBudget* outBudgets, uint32_t firstHeap, uint32_t heapCount); + +#if VMA_STATS_STRING_ENABLED + void PrintDetailedMap(class VmaJsonWriter& json); +#endif + + void GetAllocationInfo(VmaAllocation hAllocation, VmaAllocationInfo* pAllocationInfo); + void GetAllocationInfo2(VmaAllocation hAllocation, VmaAllocationInfo2* pAllocationInfo); + + VkResult CreatePool(const VmaPoolCreateInfo* pCreateInfo, VmaPool* pPool); + void DestroyPool(VmaPool pool); + void GetPoolStatistics(VmaPool pool, VmaStatistics* pPoolStats); + void CalculatePoolStatistics(VmaPool pool, VmaDetailedStatistics* pPoolStats); + + void SetCurrentFrameIndex(uint32_t frameIndex); + uint32_t GetCurrentFrameIndex() const { return m_CurrentFrameIndex.load(); } + + VkResult CheckPoolCorruption(VmaPool hPool); + VkResult CheckCorruption(uint32_t memoryTypeBits); + + // Call to Vulkan function vkAllocateMemory with accompanying bookkeeping. + VkResult AllocateVulkanMemory(const VkMemoryAllocateInfo* pAllocateInfo, VkDeviceMemory* pMemory); + // Call to Vulkan function vkFreeMemory with accompanying bookkeeping. + void FreeVulkanMemory(uint32_t memoryType, VkDeviceSize size, VkDeviceMemory hMemory); + // Call to Vulkan function vkBindBufferMemory or vkBindBufferMemory2KHR. + VkResult BindVulkanBuffer( + VkDeviceMemory memory, + VkDeviceSize memoryOffset, + VkBuffer buffer, + const void* pNext); + // Call to Vulkan function vkBindImageMemory or vkBindImageMemory2KHR. + VkResult BindVulkanImage( + VkDeviceMemory memory, + VkDeviceSize memoryOffset, + VkImage image, + const void* pNext); + + VkResult Map(VmaAllocation hAllocation, void** ppData); + void Unmap(VmaAllocation hAllocation); + + VkResult BindBufferMemory( + VmaAllocation hAllocation, + VkDeviceSize allocationLocalOffset, + VkBuffer hBuffer, + const void* pNext); + VkResult BindImageMemory( + VmaAllocation hAllocation, + VkDeviceSize allocationLocalOffset, + VkImage hImage, + const void* pNext); + + VkResult FlushOrInvalidateAllocation( + VmaAllocation hAllocation, + VkDeviceSize offset, VkDeviceSize size, + VMA_CACHE_OPERATION op); + VkResult FlushOrInvalidateAllocations( + uint32_t allocationCount, + const VmaAllocation* allocations, + const VkDeviceSize* offsets, const VkDeviceSize* sizes, + VMA_CACHE_OPERATION op); + + VkResult CopyMemoryToAllocation( + const void* pSrcHostPointer, + VmaAllocation dstAllocation, + VkDeviceSize dstAllocationLocalOffset, + VkDeviceSize size); + VkResult CopyAllocationToMemory( + VmaAllocation srcAllocation, + VkDeviceSize srcAllocationLocalOffset, + void* pDstHostPointer, + VkDeviceSize size); + + void FillAllocation(const VmaAllocation hAllocation, uint8_t pattern); + + /* + Returns bit mask of memory types that can support defragmentation on GPU as + they support creation of required buffer for copy operations. + */ + uint32_t GetGpuDefragmentationMemoryTypeBits(); + +#if VMA_EXTERNAL_MEMORY + VkExternalMemoryHandleTypeFlagsKHR GetExternalMemoryHandleTypeFlags(uint32_t memTypeIndex) const + { + return m_TypeExternalMemoryHandleTypes[memTypeIndex]; + } +#endif // #if VMA_EXTERNAL_MEMORY + +private: + VkDeviceSize m_PreferredLargeHeapBlockSize; + + VkPhysicalDevice m_PhysicalDevice; + VMA_ATOMIC_UINT32 m_CurrentFrameIndex; + VMA_ATOMIC_UINT32 m_GpuDefragmentationMemoryTypeBits; // UINT32_MAX means uninitialized. +#if VMA_EXTERNAL_MEMORY + VkExternalMemoryHandleTypeFlagsKHR m_TypeExternalMemoryHandleTypes[VK_MAX_MEMORY_TYPES]; +#endif // #if VMA_EXTERNAL_MEMORY + + VMA_RW_MUTEX m_PoolsMutex; + typedef VmaIntrusiveLinkedList PoolList; + // Protected by m_PoolsMutex. + PoolList m_Pools; + uint32_t m_NextPoolId; + + VmaVulkanFunctions m_VulkanFunctions; + + // Global bit mask AND-ed with any memoryTypeBits to disallow certain memory types. + uint32_t m_GlobalMemoryTypeBits; + + void ImportVulkanFunctions(const VmaVulkanFunctions* pVulkanFunctions); + +#if VMA_STATIC_VULKAN_FUNCTIONS == 1 + void ImportVulkanFunctions_Static(); +#endif + + void ImportVulkanFunctions_Custom(const VmaVulkanFunctions* pVulkanFunctions); + +#if VMA_DYNAMIC_VULKAN_FUNCTIONS == 1 + void ImportVulkanFunctions_Dynamic(); +#endif + + void ValidateVulkanFunctions(); + + VkDeviceSize CalcPreferredBlockSize(uint32_t memTypeIndex); + + VkResult AllocateMemoryOfType( + VmaPool pool, + VkDeviceSize size, + VkDeviceSize alignment, + bool dedicatedPreferred, + VkBuffer dedicatedBuffer, + VkImage dedicatedImage, + VmaBufferImageUsage dedicatedBufferImageUsage, + const VmaAllocationCreateInfo& createInfo, + uint32_t memTypeIndex, + VmaSuballocationType suballocType, + VmaDedicatedAllocationList& dedicatedAllocations, + VmaBlockVector& blockVector, + size_t allocationCount, + VmaAllocation* pAllocations); + + // Helper function only to be used inside AllocateDedicatedMemory. + VkResult AllocateDedicatedMemoryPage( + VmaPool pool, + VkDeviceSize size, + VmaSuballocationType suballocType, + uint32_t memTypeIndex, + const VkMemoryAllocateInfo& allocInfo, + bool map, + bool isUserDataString, + bool isMappingAllowed, + void* pUserData, + VmaAllocation* pAllocation); + + // Allocates and registers new VkDeviceMemory specifically for dedicated allocations. + VkResult AllocateDedicatedMemory( + VmaPool pool, + VkDeviceSize size, + VmaSuballocationType suballocType, + VmaDedicatedAllocationList& dedicatedAllocations, + uint32_t memTypeIndex, + bool map, + bool isUserDataString, + bool isMappingAllowed, + bool canAliasMemory, + void* pUserData, + float priority, + VkBuffer dedicatedBuffer, + VkImage dedicatedImage, + VmaBufferImageUsage dedicatedBufferImageUsage, + size_t allocationCount, + VmaAllocation* pAllocations, + const void* pNextChain = VMA_NULL); + + void FreeDedicatedMemory(const VmaAllocation allocation); + + VkResult CalcMemTypeParams( + VmaAllocationCreateInfo& outCreateInfo, + uint32_t memTypeIndex, + VkDeviceSize size, + size_t allocationCount); + VkResult CalcAllocationParams( + VmaAllocationCreateInfo& outCreateInfo, + bool dedicatedRequired, + bool dedicatedPreferred); + + /* + Calculates and returns bit mask of memory types that can support defragmentation + on GPU as they support creation of required buffer for copy operations. + */ + uint32_t CalculateGpuDefragmentationMemoryTypeBits() const; + uint32_t CalculateGlobalMemoryTypeBits() const; + + bool GetFlushOrInvalidateRange( + VmaAllocation allocation, + VkDeviceSize offset, VkDeviceSize size, + VkMappedMemoryRange& outRange) const; + +#if VMA_MEMORY_BUDGET + void UpdateVulkanBudget(); +#endif // #if VMA_MEMORY_BUDGET +}; + + +#ifndef _VMA_MEMORY_FUNCTIONS +static void* VmaMalloc(VmaAllocator hAllocator, size_t size, size_t alignment) +{ + return VmaMalloc(&hAllocator->m_AllocationCallbacks, size, alignment); +} + +static void VmaFree(VmaAllocator hAllocator, void* ptr) +{ + VmaFree(&hAllocator->m_AllocationCallbacks, ptr); +} + +template +static T* VmaAllocate(VmaAllocator hAllocator) +{ + return (T*)VmaMalloc(hAllocator, sizeof(T), VMA_ALIGN_OF(T)); +} + +template +static T* VmaAllocateArray(VmaAllocator hAllocator, size_t count) +{ + return (T*)VmaMalloc(hAllocator, sizeof(T) * count, VMA_ALIGN_OF(T)); +} + +template +static void vma_delete(VmaAllocator hAllocator, T* ptr) +{ + if(ptr != VMA_NULL) + { + ptr->~T(); + VmaFree(hAllocator, ptr); + } +} + +template +static void vma_delete_array(VmaAllocator hAllocator, T* ptr, size_t count) +{ + if(ptr != VMA_NULL) + { + for(size_t i = count; i--; ) + ptr[i].~T(); + VmaFree(hAllocator, ptr); + } +} +#endif // _VMA_MEMORY_FUNCTIONS + +#ifndef _VMA_DEVICE_MEMORY_BLOCK_FUNCTIONS +VmaDeviceMemoryBlock::VmaDeviceMemoryBlock(VmaAllocator hAllocator) + : m_pMetadata(VMA_NULL), + m_MemoryTypeIndex(UINT32_MAX), + m_Id(0), + m_hMemory(VK_NULL_HANDLE), + m_MapCount(0), + m_pMappedData(VMA_NULL){} + +VmaDeviceMemoryBlock::~VmaDeviceMemoryBlock() +{ + VMA_ASSERT_LEAK(m_MapCount == 0 && "VkDeviceMemory block is being destroyed while it is still mapped."); + VMA_ASSERT_LEAK(m_hMemory == VK_NULL_HANDLE); +} + +void VmaDeviceMemoryBlock::Init( + VmaAllocator hAllocator, + VmaPool hParentPool, + uint32_t newMemoryTypeIndex, + VkDeviceMemory newMemory, + VkDeviceSize newSize, + uint32_t id, + uint32_t algorithm, + VkDeviceSize bufferImageGranularity) +{ + VMA_ASSERT(m_hMemory == VK_NULL_HANDLE); + + m_hParentPool = hParentPool; + m_MemoryTypeIndex = newMemoryTypeIndex; + m_Id = id; + m_hMemory = newMemory; + + switch (algorithm) + { + case 0: + m_pMetadata = vma_new(hAllocator, VmaBlockMetadata_TLSF)(hAllocator->GetAllocationCallbacks(), + bufferImageGranularity, false); // isVirtual + break; + case VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT: + m_pMetadata = vma_new(hAllocator, VmaBlockMetadata_Linear)(hAllocator->GetAllocationCallbacks(), + bufferImageGranularity, false); // isVirtual + break; + default: + VMA_ASSERT(0); + m_pMetadata = vma_new(hAllocator, VmaBlockMetadata_TLSF)(hAllocator->GetAllocationCallbacks(), + bufferImageGranularity, false); // isVirtual + } + m_pMetadata->Init(newSize); +} + +void VmaDeviceMemoryBlock::Destroy(VmaAllocator allocator) +{ + // Define macro VMA_DEBUG_LOG_FORMAT or more specialized VMA_LEAK_LOG_FORMAT + // to receive the list of the unfreed allocations. + if (!m_pMetadata->IsEmpty()) + m_pMetadata->DebugLogAllAllocations(); + // This is the most important assert in the entire library. + // Hitting it means you have some memory leak - unreleased VmaAllocation objects. + VMA_ASSERT_LEAK(m_pMetadata->IsEmpty() && "Some allocations were not freed before destruction of this memory block!"); + + VMA_ASSERT_LEAK(m_hMemory != VK_NULL_HANDLE); + allocator->FreeVulkanMemory(m_MemoryTypeIndex, m_pMetadata->GetSize(), m_hMemory); + m_hMemory = VK_NULL_HANDLE; + + vma_delete(allocator, m_pMetadata); + m_pMetadata = VMA_NULL; +} + +void VmaDeviceMemoryBlock::PostAlloc(VmaAllocator hAllocator) +{ + VmaMutexLock lock(m_MapAndBindMutex, hAllocator->m_UseMutex); + m_MappingHysteresis.PostAlloc(); +} + +void VmaDeviceMemoryBlock::PostFree(VmaAllocator hAllocator) +{ + VmaMutexLock lock(m_MapAndBindMutex, hAllocator->m_UseMutex); + if(m_MappingHysteresis.PostFree()) + { + VMA_ASSERT(m_MappingHysteresis.GetExtraMapping() == 0); + if (m_MapCount == 0) + { + m_pMappedData = VMA_NULL; + (*hAllocator->GetVulkanFunctions().vkUnmapMemory)(hAllocator->m_hDevice, m_hMemory); + } + } +} + +bool VmaDeviceMemoryBlock::Validate() const +{ + VMA_VALIDATE((m_hMemory != VK_NULL_HANDLE) && + (m_pMetadata->GetSize() != 0)); + + return m_pMetadata->Validate(); +} + +VkResult VmaDeviceMemoryBlock::CheckCorruption(VmaAllocator hAllocator) +{ + void* pData = VMA_NULL; + VkResult res = Map(hAllocator, 1, &pData); + if (res != VK_SUCCESS) + { + return res; + } + + res = m_pMetadata->CheckCorruption(pData); + + Unmap(hAllocator, 1); + + return res; +} + +VkResult VmaDeviceMemoryBlock::Map(VmaAllocator hAllocator, uint32_t count, void** ppData) +{ + if (count == 0) + { + return VK_SUCCESS; + } + + VmaMutexLock lock(m_MapAndBindMutex, hAllocator->m_UseMutex); + const uint32_t oldTotalMapCount = m_MapCount + m_MappingHysteresis.GetExtraMapping(); + if (oldTotalMapCount != 0) + { + VMA_ASSERT(m_pMappedData != VMA_NULL); + m_MappingHysteresis.PostMap(); + m_MapCount += count; + if (ppData != VMA_NULL) + { + *ppData = m_pMappedData; + } + return VK_SUCCESS; + } + else + { + VkResult result = (*hAllocator->GetVulkanFunctions().vkMapMemory)( + hAllocator->m_hDevice, + m_hMemory, + 0, // offset + VK_WHOLE_SIZE, + 0, // flags + &m_pMappedData); + if (result == VK_SUCCESS) + { + VMA_ASSERT(m_pMappedData != VMA_NULL); + m_MappingHysteresis.PostMap(); + m_MapCount = count; + if (ppData != VMA_NULL) + { + *ppData = m_pMappedData; + } + } + return result; + } +} + +void VmaDeviceMemoryBlock::Unmap(VmaAllocator hAllocator, uint32_t count) +{ + if (count == 0) + { + return; + } + + VmaMutexLock lock(m_MapAndBindMutex, hAllocator->m_UseMutex); + if (m_MapCount >= count) + { + m_MapCount -= count; + const uint32_t totalMapCount = m_MapCount + m_MappingHysteresis.GetExtraMapping(); + if (totalMapCount == 0) + { + m_pMappedData = VMA_NULL; + (*hAllocator->GetVulkanFunctions().vkUnmapMemory)(hAllocator->m_hDevice, m_hMemory); + } + m_MappingHysteresis.PostUnmap(); + } + else + { + VMA_ASSERT(0 && "VkDeviceMemory block is being unmapped while it was not previously mapped."); + } +} + +VkResult VmaDeviceMemoryBlock::WriteMagicValueAfterAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize) +{ + VMA_ASSERT(VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_MARGIN % 4 == 0 && VMA_DEBUG_DETECT_CORRUPTION); + + void* pData; + VkResult res = Map(hAllocator, 1, &pData); + if (res != VK_SUCCESS) + { + return res; + } + + VmaWriteMagicValue(pData, allocOffset + allocSize); + + Unmap(hAllocator, 1); + return VK_SUCCESS; +} + +VkResult VmaDeviceMemoryBlock::ValidateMagicValueAfterAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize) +{ + VMA_ASSERT(VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_MARGIN % 4 == 0 && VMA_DEBUG_DETECT_CORRUPTION); + + void* pData; + VkResult res = Map(hAllocator, 1, &pData); + if (res != VK_SUCCESS) + { + return res; + } + + if (!VmaValidateMagicValue(pData, allocOffset + allocSize)) + { + VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER FREED ALLOCATION!"); + } + + Unmap(hAllocator, 1); + return VK_SUCCESS; +} + +VkResult VmaDeviceMemoryBlock::BindBufferMemory( + const VmaAllocator hAllocator, + const VmaAllocation hAllocation, + VkDeviceSize allocationLocalOffset, + VkBuffer hBuffer, + const void* pNext) +{ + VMA_ASSERT(hAllocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_BLOCK && + hAllocation->GetBlock() == this); + VMA_ASSERT(allocationLocalOffset < hAllocation->GetSize() && + "Invalid allocationLocalOffset. Did you forget that this offset is relative to the beginning of the allocation, not the whole memory block?"); + const VkDeviceSize memoryOffset = hAllocation->GetOffset() + allocationLocalOffset; + // This lock is important so that we don't call vkBind... and/or vkMap... simultaneously on the same VkDeviceMemory from multiple threads. + VmaMutexLock lock(m_MapAndBindMutex, hAllocator->m_UseMutex); + return hAllocator->BindVulkanBuffer(m_hMemory, memoryOffset, hBuffer, pNext); +} + +VkResult VmaDeviceMemoryBlock::BindImageMemory( + const VmaAllocator hAllocator, + const VmaAllocation hAllocation, + VkDeviceSize allocationLocalOffset, + VkImage hImage, + const void* pNext) +{ + VMA_ASSERT(hAllocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_BLOCK && + hAllocation->GetBlock() == this); + VMA_ASSERT(allocationLocalOffset < hAllocation->GetSize() && + "Invalid allocationLocalOffset. Did you forget that this offset is relative to the beginning of the allocation, not the whole memory block?"); + const VkDeviceSize memoryOffset = hAllocation->GetOffset() + allocationLocalOffset; + // This lock is important so that we don't call vkBind... and/or vkMap... simultaneously on the same VkDeviceMemory from multiple threads. + VmaMutexLock lock(m_MapAndBindMutex, hAllocator->m_UseMutex); + return hAllocator->BindVulkanImage(m_hMemory, memoryOffset, hImage, pNext); +} + +#if VMA_EXTERNAL_MEMORY_WIN32 +VkResult VmaDeviceMemoryBlock::CreateWin32Handle(const VmaAllocator hAllocator, PFN_vkGetMemoryWin32HandleKHR pvkGetMemoryWin32HandleKHR, HANDLE hTargetProcess, HANDLE* pHandle) noexcept +{ + VMA_ASSERT(pHandle); + return m_Handle.GetHandle(hAllocator->m_hDevice, m_hMemory, pvkGetMemoryWin32HandleKHR, hTargetProcess, hAllocator->m_UseMutex, pHandle); +} +#endif // VMA_EXTERNAL_MEMORY_WIN32 +#endif // _VMA_DEVICE_MEMORY_BLOCK_FUNCTIONS + +#ifndef _VMA_ALLOCATION_T_FUNCTIONS +VmaAllocation_T::VmaAllocation_T(bool mappingAllowed) + : m_Alignment{ 1 }, + m_Size{ 0 }, + m_pUserData{ VMA_NULL }, + m_pName{ VMA_NULL }, + m_MemoryTypeIndex{ 0 }, + m_Type{ (uint8_t)ALLOCATION_TYPE_NONE }, + m_SuballocationType{ (uint8_t)VMA_SUBALLOCATION_TYPE_UNKNOWN }, + m_MapCount{ 0 }, + m_Flags{ 0 } +{ + if(mappingAllowed) + m_Flags |= (uint8_t)FLAG_MAPPING_ALLOWED; +} + +VmaAllocation_T::~VmaAllocation_T() +{ + VMA_ASSERT_LEAK(m_MapCount == 0 && "Allocation was not unmapped before destruction."); + + // Check if owned string was freed. + VMA_ASSERT(m_pName == VMA_NULL); +} + +void VmaAllocation_T::InitBlockAllocation( + VmaDeviceMemoryBlock* block, + VmaAllocHandle allocHandle, + VkDeviceSize alignment, + VkDeviceSize size, + uint32_t memoryTypeIndex, + VmaSuballocationType suballocationType, + bool mapped) +{ + VMA_ASSERT(m_Type == ALLOCATION_TYPE_NONE); + VMA_ASSERT(block != VMA_NULL); + m_Type = (uint8_t)ALLOCATION_TYPE_BLOCK; + m_Alignment = alignment; + m_Size = size; + m_MemoryTypeIndex = memoryTypeIndex; + if(mapped) + { + VMA_ASSERT(IsMappingAllowed() && "Mapping is not allowed on this allocation! Please use one of the new VMA_ALLOCATION_CREATE_HOST_ACCESS_* flags when creating it."); + m_Flags |= (uint8_t)FLAG_PERSISTENT_MAP; + } + m_SuballocationType = (uint8_t)suballocationType; + m_BlockAllocation.m_Block = block; + m_BlockAllocation.m_AllocHandle = allocHandle; +} + +void VmaAllocation_T::InitDedicatedAllocation( + VmaAllocator allocator, + VmaPool hParentPool, + uint32_t memoryTypeIndex, + VkDeviceMemory hMemory, + VmaSuballocationType suballocationType, + void* pMappedData, + VkDeviceSize size) +{ + VMA_ASSERT(m_Type == ALLOCATION_TYPE_NONE); + VMA_ASSERT(hMemory != VK_NULL_HANDLE); + m_Type = (uint8_t)ALLOCATION_TYPE_DEDICATED; + m_Alignment = 0; + m_Size = size; + m_MemoryTypeIndex = memoryTypeIndex; + m_SuballocationType = (uint8_t)suballocationType; + m_DedicatedAllocation.m_ExtraData = VMA_NULL; + m_DedicatedAllocation.m_hParentPool = hParentPool; + m_DedicatedAllocation.m_hMemory = hMemory; + m_DedicatedAllocation.m_Prev = VMA_NULL; + m_DedicatedAllocation.m_Next = VMA_NULL; + + if (pMappedData != VMA_NULL) + { + VMA_ASSERT(IsMappingAllowed() && "Mapping is not allowed on this allocation! Please use one of the new VMA_ALLOCATION_CREATE_HOST_ACCESS_* flags when creating it."); + m_Flags |= (uint8_t)FLAG_PERSISTENT_MAP; + EnsureExtraData(allocator); + m_DedicatedAllocation.m_ExtraData->m_pMappedData = pMappedData; + } +} + +void VmaAllocation_T::Destroy(VmaAllocator allocator) +{ + FreeName(allocator); + + if (GetType() == ALLOCATION_TYPE_DEDICATED) + { + vma_delete(allocator, m_DedicatedAllocation.m_ExtraData); + } +} + +void VmaAllocation_T::SetName(VmaAllocator hAllocator, const char* pName) +{ + VMA_ASSERT(pName == VMA_NULL || pName != m_pName); + + FreeName(hAllocator); + + if (pName != VMA_NULL) + m_pName = VmaCreateStringCopy(hAllocator->GetAllocationCallbacks(), pName); +} + +uint8_t VmaAllocation_T::SwapBlockAllocation(VmaAllocator hAllocator, VmaAllocation allocation) +{ + VMA_ASSERT(allocation != VMA_NULL); + VMA_ASSERT(m_Type == ALLOCATION_TYPE_BLOCK); + VMA_ASSERT(allocation->m_Type == ALLOCATION_TYPE_BLOCK); + + if (m_MapCount != 0) + m_BlockAllocation.m_Block->Unmap(hAllocator, m_MapCount); + + m_BlockAllocation.m_Block->m_pMetadata->SetAllocationUserData(m_BlockAllocation.m_AllocHandle, allocation); + std::swap(m_BlockAllocation, allocation->m_BlockAllocation); + m_BlockAllocation.m_Block->m_pMetadata->SetAllocationUserData(m_BlockAllocation.m_AllocHandle, this); + +#if VMA_STATS_STRING_ENABLED + std::swap(m_BufferImageUsage, allocation->m_BufferImageUsage); +#endif + return m_MapCount; +} + +VmaAllocHandle VmaAllocation_T::GetAllocHandle() const +{ + switch (m_Type) + { + case ALLOCATION_TYPE_BLOCK: + return m_BlockAllocation.m_AllocHandle; + case ALLOCATION_TYPE_DEDICATED: + return VK_NULL_HANDLE; + default: + VMA_ASSERT(0); + return VK_NULL_HANDLE; + } +} + +VkDeviceSize VmaAllocation_T::GetOffset() const +{ + switch (m_Type) + { + case ALLOCATION_TYPE_BLOCK: + return m_BlockAllocation.m_Block->m_pMetadata->GetAllocationOffset(m_BlockAllocation.m_AllocHandle); + case ALLOCATION_TYPE_DEDICATED: + return 0; + default: + VMA_ASSERT(0); + return 0; + } +} + +VmaPool VmaAllocation_T::GetParentPool() const +{ + switch (m_Type) + { + case ALLOCATION_TYPE_BLOCK: + return m_BlockAllocation.m_Block->GetParentPool(); + case ALLOCATION_TYPE_DEDICATED: + return m_DedicatedAllocation.m_hParentPool; + default: + VMA_ASSERT(0); + return VK_NULL_HANDLE; + } +} + +VkDeviceMemory VmaAllocation_T::GetMemory() const +{ + switch (m_Type) + { + case ALLOCATION_TYPE_BLOCK: + return m_BlockAllocation.m_Block->GetDeviceMemory(); + case ALLOCATION_TYPE_DEDICATED: + return m_DedicatedAllocation.m_hMemory; + default: + VMA_ASSERT(0); + return VK_NULL_HANDLE; + } +} + +void* VmaAllocation_T::GetMappedData() const +{ + switch (m_Type) + { + case ALLOCATION_TYPE_BLOCK: + if (m_MapCount != 0 || IsPersistentMap()) + { + void* pBlockData = m_BlockAllocation.m_Block->GetMappedData(); + VMA_ASSERT(pBlockData != VMA_NULL); + return (char*)pBlockData + GetOffset(); + } + else + { + return VMA_NULL; + } + break; + case ALLOCATION_TYPE_DEDICATED: + VMA_ASSERT((m_DedicatedAllocation.m_ExtraData != VMA_NULL && m_DedicatedAllocation.m_ExtraData->m_pMappedData != VMA_NULL) == + (m_MapCount != 0 || IsPersistentMap())); + return m_DedicatedAllocation.m_ExtraData != VMA_NULL ? m_DedicatedAllocation.m_ExtraData->m_pMappedData : VMA_NULL; + default: + VMA_ASSERT(0); + return VMA_NULL; + } +} + +void VmaAllocation_T::BlockAllocMap() +{ + VMA_ASSERT(GetType() == ALLOCATION_TYPE_BLOCK); + VMA_ASSERT(IsMappingAllowed() && "Mapping is not allowed on this allocation! Please use one of the new VMA_ALLOCATION_CREATE_HOST_ACCESS_* flags when creating it."); + + if (m_MapCount < 0xFF) + { + ++m_MapCount; + } + else + { + VMA_ASSERT(0 && "Allocation mapped too many times simultaneously."); + } +} + +void VmaAllocation_T::BlockAllocUnmap() +{ + VMA_ASSERT(GetType() == ALLOCATION_TYPE_BLOCK); + + if (m_MapCount > 0) + { + --m_MapCount; + } + else + { + VMA_ASSERT(0 && "Unmapping allocation not previously mapped."); + } +} + +VkResult VmaAllocation_T::DedicatedAllocMap(VmaAllocator hAllocator, void** ppData) +{ + VMA_ASSERT(GetType() == ALLOCATION_TYPE_DEDICATED); + VMA_ASSERT(IsMappingAllowed() && "Mapping is not allowed on this allocation! Please use one of the new VMA_ALLOCATION_CREATE_HOST_ACCESS_* flags when creating it."); + + EnsureExtraData(hAllocator); + + if (m_MapCount != 0 || IsPersistentMap()) + { + if (m_MapCount < 0xFF) + { + VMA_ASSERT(m_DedicatedAllocation.m_ExtraData->m_pMappedData != VMA_NULL); + *ppData = m_DedicatedAllocation.m_ExtraData->m_pMappedData; + ++m_MapCount; + return VK_SUCCESS; + } + else + { + VMA_ASSERT(0 && "Dedicated allocation mapped too many times simultaneously."); + return VK_ERROR_MEMORY_MAP_FAILED; + } + } + else + { + VkResult result = (*hAllocator->GetVulkanFunctions().vkMapMemory)( + hAllocator->m_hDevice, + m_DedicatedAllocation.m_hMemory, + 0, // offset + VK_WHOLE_SIZE, + 0, // flags + ppData); + if (result == VK_SUCCESS) + { + m_DedicatedAllocation.m_ExtraData->m_pMappedData = *ppData; + m_MapCount = 1; + } + return result; + } +} + +void VmaAllocation_T::DedicatedAllocUnmap(VmaAllocator hAllocator) +{ + VMA_ASSERT(GetType() == ALLOCATION_TYPE_DEDICATED); + + if (m_MapCount > 0) + { + --m_MapCount; + if (m_MapCount == 0 && !IsPersistentMap()) + { + VMA_ASSERT(m_DedicatedAllocation.m_ExtraData != VMA_NULL); + m_DedicatedAllocation.m_ExtraData->m_pMappedData = VMA_NULL; + (*hAllocator->GetVulkanFunctions().vkUnmapMemory)( + hAllocator->m_hDevice, + m_DedicatedAllocation.m_hMemory); + } + } + else + { + VMA_ASSERT(0 && "Unmapping dedicated allocation not previously mapped."); + } +} + +#if VMA_STATS_STRING_ENABLED +void VmaAllocation_T::PrintParameters(class VmaJsonWriter& json) const +{ + json.WriteString("Type"); + json.WriteString(VMA_SUBALLOCATION_TYPE_NAMES[m_SuballocationType]); + + json.WriteString("Size"); + json.WriteNumber(m_Size); + json.WriteString("Usage"); + json.WriteNumber(m_BufferImageUsage.Value); // It may be uint32_t or uint64_t. + + if (m_pUserData != VMA_NULL) + { + json.WriteString("CustomData"); + json.BeginString(); + json.ContinueString_Pointer(m_pUserData); + json.EndString(); + } + if (m_pName != VMA_NULL) + { + json.WriteString("Name"); + json.WriteString(m_pName); + } +} +#if VMA_EXTERNAL_MEMORY_WIN32 +VkResult VmaAllocation_T::GetWin32Handle(VmaAllocator hAllocator, HANDLE hTargetProcess, HANDLE* pHandle) noexcept +{ + auto pvkGetMemoryWin32HandleKHR = hAllocator->GetVulkanFunctions().vkGetMemoryWin32HandleKHR; + switch (m_Type) + { + case ALLOCATION_TYPE_BLOCK: + return m_BlockAllocation.m_Block->CreateWin32Handle(hAllocator, pvkGetMemoryWin32HandleKHR, hTargetProcess, pHandle); + case ALLOCATION_TYPE_DEDICATED: + EnsureExtraData(hAllocator); + return m_DedicatedAllocation.m_ExtraData->m_Handle.GetHandle(hAllocator->m_hDevice, m_DedicatedAllocation.m_hMemory, pvkGetMemoryWin32HandleKHR, hTargetProcess, hAllocator->m_UseMutex, pHandle); + default: + VMA_ASSERT(0); + return VK_ERROR_FEATURE_NOT_PRESENT; + } +} +#endif // VMA_EXTERNAL_MEMORY_WIN32 +#endif // VMA_STATS_STRING_ENABLED + +void VmaAllocation_T::EnsureExtraData(VmaAllocator hAllocator) +{ + if (m_DedicatedAllocation.m_ExtraData == VMA_NULL) + { + m_DedicatedAllocation.m_ExtraData = vma_new(hAllocator, VmaAllocationExtraData)(); + } +} + +void VmaAllocation_T::FreeName(VmaAllocator hAllocator) +{ + if(m_pName) + { + VmaFreeString(hAllocator->GetAllocationCallbacks(), m_pName); + m_pName = VMA_NULL; + } +} +#endif // _VMA_ALLOCATION_T_FUNCTIONS + +#ifndef _VMA_BLOCK_VECTOR_FUNCTIONS +VmaBlockVector::VmaBlockVector( + VmaAllocator hAllocator, + VmaPool hParentPool, + uint32_t memoryTypeIndex, + VkDeviceSize preferredBlockSize, + size_t minBlockCount, + size_t maxBlockCount, + VkDeviceSize bufferImageGranularity, + bool explicitBlockSize, + uint32_t algorithm, + float priority, + VkDeviceSize minAllocationAlignment, + void* pMemoryAllocateNext) + : m_hAllocator(hAllocator), + m_hParentPool(hParentPool), + m_MemoryTypeIndex(memoryTypeIndex), + m_PreferredBlockSize(preferredBlockSize), + m_MinBlockCount(minBlockCount), + m_MaxBlockCount(maxBlockCount), + m_BufferImageGranularity(bufferImageGranularity), + m_ExplicitBlockSize(explicitBlockSize), + m_Algorithm(algorithm), + m_Priority(priority), + m_MinAllocationAlignment(minAllocationAlignment), + m_pMemoryAllocateNext(pMemoryAllocateNext), + m_Blocks(VmaStlAllocator(hAllocator->GetAllocationCallbacks())), + m_NextBlockId(0) {} + +VmaBlockVector::~VmaBlockVector() +{ + for (size_t i = m_Blocks.size(); i--; ) + { + m_Blocks[i]->Destroy(m_hAllocator); + vma_delete(m_hAllocator, m_Blocks[i]); + } +} + +VkResult VmaBlockVector::CreateMinBlocks() +{ + for (size_t i = 0; i < m_MinBlockCount; ++i) + { + VkResult res = CreateBlock(m_PreferredBlockSize, VMA_NULL); + if (res != VK_SUCCESS) + { + return res; + } + } + return VK_SUCCESS; +} + +void VmaBlockVector::AddStatistics(VmaStatistics& inoutStats) +{ + VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex); + + const size_t blockCount = m_Blocks.size(); + for (uint32_t blockIndex = 0; blockIndex < blockCount; ++blockIndex) + { + const VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex]; + VMA_ASSERT(pBlock); + VMA_HEAVY_ASSERT(pBlock->Validate()); + pBlock->m_pMetadata->AddStatistics(inoutStats); + } +} + +void VmaBlockVector::AddDetailedStatistics(VmaDetailedStatistics& inoutStats) +{ + VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex); + + const size_t blockCount = m_Blocks.size(); + for (uint32_t blockIndex = 0; blockIndex < blockCount; ++blockIndex) + { + const VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex]; + VMA_ASSERT(pBlock); + VMA_HEAVY_ASSERT(pBlock->Validate()); + pBlock->m_pMetadata->AddDetailedStatistics(inoutStats); + } +} + +bool VmaBlockVector::IsEmpty() +{ + VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex); + return m_Blocks.empty(); +} + +bool VmaBlockVector::IsCorruptionDetectionEnabled() const +{ + const uint32_t requiredMemFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; + return (VMA_DEBUG_DETECT_CORRUPTION != 0) && + (VMA_DEBUG_MARGIN > 0) && + (m_Algorithm == 0 || m_Algorithm == VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT) && + (m_hAllocator->m_MemProps.memoryTypes[m_MemoryTypeIndex].propertyFlags & requiredMemFlags) == requiredMemFlags; +} + +VkResult VmaBlockVector::Allocate( + VkDeviceSize size, + VkDeviceSize alignment, + const VmaAllocationCreateInfo& createInfo, + VmaSuballocationType suballocType, + size_t allocationCount, + VmaAllocation* pAllocations) +{ + size_t allocIndex; + VkResult res = VK_SUCCESS; + + alignment = VMA_MAX(alignment, m_MinAllocationAlignment); + + if (IsCorruptionDetectionEnabled()) + { + size = VmaAlignUp(size, sizeof(VMA_CORRUPTION_DETECTION_MAGIC_VALUE)); + alignment = VmaAlignUp(alignment, sizeof(VMA_CORRUPTION_DETECTION_MAGIC_VALUE)); + } + + { + VmaMutexLockWrite lock(m_Mutex, m_hAllocator->m_UseMutex); + for (allocIndex = 0; allocIndex < allocationCount; ++allocIndex) + { + res = AllocatePage( + size, + alignment, + createInfo, + suballocType, + pAllocations + allocIndex); + if (res != VK_SUCCESS) + { + break; + } + } + } + + if (res != VK_SUCCESS) + { + // Free all already created allocations. + while (allocIndex--) + Free(pAllocations[allocIndex]); + memset(pAllocations, 0, sizeof(VmaAllocation) * allocationCount); + } + + return res; +} + +VkResult VmaBlockVector::AllocatePage( + VkDeviceSize size, + VkDeviceSize alignment, + const VmaAllocationCreateInfo& createInfo, + VmaSuballocationType suballocType, + VmaAllocation* pAllocation) +{ + const bool isUpperAddress = (createInfo.flags & VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0; + + VkDeviceSize freeMemory; + { + const uint32_t heapIndex = m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex); + VmaBudget heapBudget = {}; + m_hAllocator->GetHeapBudgets(&heapBudget, heapIndex, 1); + freeMemory = (heapBudget.usage < heapBudget.budget) ? (heapBudget.budget - heapBudget.usage) : 0; + } + + const bool canFallbackToDedicated = !HasExplicitBlockSize() && + (createInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) == 0; + const bool canCreateNewBlock = + ((createInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) == 0) && + (m_Blocks.size() < m_MaxBlockCount) && + (freeMemory >= size || !canFallbackToDedicated); + uint32_t strategy = createInfo.flags & VMA_ALLOCATION_CREATE_STRATEGY_MASK; + + // Upper address can only be used with linear allocator and within single memory block. + if (isUpperAddress && + (m_Algorithm != VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT || m_MaxBlockCount > 1)) + { + return VK_ERROR_FEATURE_NOT_PRESENT; + } + + // Early reject: requested allocation size is larger that maximum block size for this block vector. + if (size + VMA_DEBUG_MARGIN > m_PreferredBlockSize) + { + return VK_ERROR_OUT_OF_DEVICE_MEMORY; + } + + // 1. Search existing allocations. Try to allocate. + if (m_Algorithm == VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT) + { + // Use only last block. + if (!m_Blocks.empty()) + { + VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks.back(); + VMA_ASSERT(pCurrBlock); + VkResult res = AllocateFromBlock( + pCurrBlock, size, alignment, createInfo.flags, createInfo.pUserData, suballocType, strategy, pAllocation); + if (res == VK_SUCCESS) + { + VMA_DEBUG_LOG_FORMAT(" Returned from last block #%" PRIu32, pCurrBlock->GetId()); + IncrementallySortBlocks(); + return VK_SUCCESS; + } + } + } + else + { + if (strategy != VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT) // MIN_MEMORY or default + { + const bool isHostVisible = + (m_hAllocator->m_MemProps.memoryTypes[m_MemoryTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0; + if(isHostVisible) + { + const bool isMappingAllowed = (createInfo.flags & + (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0; + /* + For non-mappable allocations, check blocks that are not mapped first. + For mappable allocations, check blocks that are already mapped first. + This way, having many blocks, we will separate mappable and non-mappable allocations, + hopefully limiting the number of blocks that are mapped, which will help tools like RenderDoc. + */ + for(size_t mappingI = 0; mappingI < 2; ++mappingI) + { + // Forward order in m_Blocks - prefer blocks with smallest amount of free space. + for (size_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex) + { + VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks[blockIndex]; + VMA_ASSERT(pCurrBlock); + const bool isBlockMapped = pCurrBlock->GetMappedData() != VMA_NULL; + if((mappingI == 0) == (isMappingAllowed == isBlockMapped)) + { + VkResult res = AllocateFromBlock( + pCurrBlock, size, alignment, createInfo.flags, createInfo.pUserData, suballocType, strategy, pAllocation); + if (res == VK_SUCCESS) + { + VMA_DEBUG_LOG_FORMAT(" Returned from existing block #%" PRIu32, pCurrBlock->GetId()); + IncrementallySortBlocks(); + return VK_SUCCESS; + } + } + } + } + } + else + { + // Forward order in m_Blocks - prefer blocks with smallest amount of free space. + for (size_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex) + { + VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks[blockIndex]; + VMA_ASSERT(pCurrBlock); + VkResult res = AllocateFromBlock( + pCurrBlock, size, alignment, createInfo.flags, createInfo.pUserData, suballocType, strategy, pAllocation); + if (res == VK_SUCCESS) + { + VMA_DEBUG_LOG_FORMAT(" Returned from existing block #%" PRIu32, pCurrBlock->GetId()); + IncrementallySortBlocks(); + return VK_SUCCESS; + } + } + } + } + else // VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT + { + // Backward order in m_Blocks - prefer blocks with largest amount of free space. + for (size_t blockIndex = m_Blocks.size(); blockIndex--; ) + { + VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks[blockIndex]; + VMA_ASSERT(pCurrBlock); + VkResult res = AllocateFromBlock(pCurrBlock, size, alignment, createInfo.flags, createInfo.pUserData, suballocType, strategy, pAllocation); + if (res == VK_SUCCESS) + { + VMA_DEBUG_LOG_FORMAT(" Returned from existing block #%" PRIu32, pCurrBlock->GetId()); + IncrementallySortBlocks(); + return VK_SUCCESS; + } + } + } + } + + // 2. Try to create new block. + if (canCreateNewBlock) + { + // Calculate optimal size for new block. + VkDeviceSize newBlockSize = m_PreferredBlockSize; + uint32_t newBlockSizeShift = 0; + const uint32_t NEW_BLOCK_SIZE_SHIFT_MAX = 3; + + if (!m_ExplicitBlockSize) + { + // Allocate 1/8, 1/4, 1/2 as first blocks. + const VkDeviceSize maxExistingBlockSize = CalcMaxBlockSize(); + for (uint32_t i = 0; i < NEW_BLOCK_SIZE_SHIFT_MAX; ++i) + { + const VkDeviceSize smallerNewBlockSize = newBlockSize / 2; + if (smallerNewBlockSize > maxExistingBlockSize && smallerNewBlockSize >= size * 2) + { + newBlockSize = smallerNewBlockSize; + ++newBlockSizeShift; + } + else + { + break; + } + } + } + + size_t newBlockIndex = 0; + VkResult res = (newBlockSize <= freeMemory || !canFallbackToDedicated) ? + CreateBlock(newBlockSize, &newBlockIndex) : VK_ERROR_OUT_OF_DEVICE_MEMORY; + // Allocation of this size failed? Try 1/2, 1/4, 1/8 of m_PreferredBlockSize. + if (!m_ExplicitBlockSize) + { + while (res < 0 && newBlockSizeShift < NEW_BLOCK_SIZE_SHIFT_MAX) + { + const VkDeviceSize smallerNewBlockSize = newBlockSize / 2; + if (smallerNewBlockSize >= size) + { + newBlockSize = smallerNewBlockSize; + ++newBlockSizeShift; + res = (newBlockSize <= freeMemory || !canFallbackToDedicated) ? + CreateBlock(newBlockSize, &newBlockIndex) : VK_ERROR_OUT_OF_DEVICE_MEMORY; + } + else + { + break; + } + } + } + + if (res == VK_SUCCESS) + { + VmaDeviceMemoryBlock* const pBlock = m_Blocks[newBlockIndex]; + VMA_ASSERT(pBlock->m_pMetadata->GetSize() >= size); + + res = AllocateFromBlock( + pBlock, size, alignment, createInfo.flags, createInfo.pUserData, suballocType, strategy, pAllocation); + if (res == VK_SUCCESS) + { + VMA_DEBUG_LOG_FORMAT(" Created new block #%" PRIu32 " Size=%" PRIu64, pBlock->GetId(), newBlockSize); + IncrementallySortBlocks(); + return VK_SUCCESS; + } + else + { + // Allocation from new block failed, possibly due to VMA_DEBUG_MARGIN or alignment. + return VK_ERROR_OUT_OF_DEVICE_MEMORY; + } + } + } + + return VK_ERROR_OUT_OF_DEVICE_MEMORY; +} + +void VmaBlockVector::Free(const VmaAllocation hAllocation) +{ + VmaDeviceMemoryBlock* pBlockToDelete = VMA_NULL; + + bool budgetExceeded = false; + { + const uint32_t heapIndex = m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex); + VmaBudget heapBudget = {}; + m_hAllocator->GetHeapBudgets(&heapBudget, heapIndex, 1); + budgetExceeded = heapBudget.usage >= heapBudget.budget; + } + + // Scope for lock. + { + VmaMutexLockWrite lock(m_Mutex, m_hAllocator->m_UseMutex); + + VmaDeviceMemoryBlock* pBlock = hAllocation->GetBlock(); + + if (IsCorruptionDetectionEnabled()) + { + VkResult res = pBlock->ValidateMagicValueAfterAllocation(m_hAllocator, hAllocation->GetOffset(), hAllocation->GetSize()); + VMA_ASSERT(res == VK_SUCCESS && "Couldn't map block memory to validate magic value."); + } + + if (hAllocation->IsPersistentMap()) + { + pBlock->Unmap(m_hAllocator, 1); + } + + const bool hadEmptyBlockBeforeFree = HasEmptyBlock(); + pBlock->m_pMetadata->Free(hAllocation->GetAllocHandle()); + pBlock->PostFree(m_hAllocator); + VMA_HEAVY_ASSERT(pBlock->Validate()); + + VMA_DEBUG_LOG_FORMAT(" Freed from MemoryTypeIndex=%" PRIu32, m_MemoryTypeIndex); + + const bool canDeleteBlock = m_Blocks.size() > m_MinBlockCount; + // pBlock became empty after this deallocation. + if (pBlock->m_pMetadata->IsEmpty()) + { + // Already had empty block. We don't want to have two, so delete this one. + if ((hadEmptyBlockBeforeFree || budgetExceeded) && canDeleteBlock) + { + pBlockToDelete = pBlock; + Remove(pBlock); + } + // else: We now have one empty block - leave it. A hysteresis to avoid allocating whole block back and forth. + } + // pBlock didn't become empty, but we have another empty block - find and free that one. + // (This is optional, heuristics.) + else if (hadEmptyBlockBeforeFree && canDeleteBlock) + { + VmaDeviceMemoryBlock* pLastBlock = m_Blocks.back(); + if (pLastBlock->m_pMetadata->IsEmpty()) + { + pBlockToDelete = pLastBlock; + m_Blocks.pop_back(); + } + } + + IncrementallySortBlocks(); + } + + // Destruction of a free block. Deferred until this point, outside of mutex + // lock, for performance reason. + if (pBlockToDelete != VMA_NULL) + { + VMA_DEBUG_LOG_FORMAT(" Deleted empty block #%" PRIu32, pBlockToDelete->GetId()); + pBlockToDelete->Destroy(m_hAllocator); + vma_delete(m_hAllocator, pBlockToDelete); + } + + m_hAllocator->m_Budget.RemoveAllocation(m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex), hAllocation->GetSize()); + hAllocation->Destroy(m_hAllocator); + m_hAllocator->m_AllocationObjectAllocator.Free(hAllocation); +} + +VkDeviceSize VmaBlockVector::CalcMaxBlockSize() const +{ + VkDeviceSize result = 0; + for (size_t i = m_Blocks.size(); i--; ) + { + result = VMA_MAX(result, m_Blocks[i]->m_pMetadata->GetSize()); + if (result >= m_PreferredBlockSize) + { + break; + } + } + return result; +} + +void VmaBlockVector::Remove(VmaDeviceMemoryBlock* pBlock) +{ + for (uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex) + { + if (m_Blocks[blockIndex] == pBlock) + { + VmaVectorRemove(m_Blocks, blockIndex); + return; + } + } + VMA_ASSERT(0); +} + +void VmaBlockVector::IncrementallySortBlocks() +{ + if (!m_IncrementalSort) + return; + if (m_Algorithm != VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT) + { + // Bubble sort only until first swap. + for (size_t i = 1; i < m_Blocks.size(); ++i) + { + if (m_Blocks[i - 1]->m_pMetadata->GetSumFreeSize() > m_Blocks[i]->m_pMetadata->GetSumFreeSize()) + { + std::swap(m_Blocks[i - 1], m_Blocks[i]); + return; + } + } + } +} + +void VmaBlockVector::SortByFreeSize() +{ + VMA_SORT(m_Blocks.begin(), m_Blocks.end(), + [](VmaDeviceMemoryBlock* b1, VmaDeviceMemoryBlock* b2) -> bool + { + return b1->m_pMetadata->GetSumFreeSize() < b2->m_pMetadata->GetSumFreeSize(); + }); +} + +VkResult VmaBlockVector::AllocateFromBlock( + VmaDeviceMemoryBlock* pBlock, + VkDeviceSize size, + VkDeviceSize alignment, + VmaAllocationCreateFlags allocFlags, + void* pUserData, + VmaSuballocationType suballocType, + uint32_t strategy, + VmaAllocation* pAllocation) +{ + const bool isUpperAddress = (allocFlags & VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0; + + VmaAllocationRequest currRequest = {}; + if (pBlock->m_pMetadata->CreateAllocationRequest( + size, + alignment, + isUpperAddress, + suballocType, + strategy, + &currRequest)) + { + return CommitAllocationRequest(currRequest, pBlock, alignment, allocFlags, pUserData, suballocType, pAllocation); + } + return VK_ERROR_OUT_OF_DEVICE_MEMORY; +} + +VkResult VmaBlockVector::CommitAllocationRequest( + VmaAllocationRequest& allocRequest, + VmaDeviceMemoryBlock* pBlock, + VkDeviceSize alignment, + VmaAllocationCreateFlags allocFlags, + void* pUserData, + VmaSuballocationType suballocType, + VmaAllocation* pAllocation) +{ + const bool mapped = (allocFlags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0; + const bool isUserDataString = (allocFlags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0; + const bool isMappingAllowed = (allocFlags & + (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0; + + pBlock->PostAlloc(m_hAllocator); + // Allocate from pCurrBlock. + if (mapped) + { + VkResult res = pBlock->Map(m_hAllocator, 1, VMA_NULL); + if (res != VK_SUCCESS) + { + return res; + } + } + + *pAllocation = m_hAllocator->m_AllocationObjectAllocator.Allocate(isMappingAllowed); + pBlock->m_pMetadata->Alloc(allocRequest, suballocType, *pAllocation); + (*pAllocation)->InitBlockAllocation( + pBlock, + allocRequest.allocHandle, + alignment, + allocRequest.size, // Not size, as actual allocation size may be larger than requested! + m_MemoryTypeIndex, + suballocType, + mapped); + VMA_HEAVY_ASSERT(pBlock->Validate()); + if (isUserDataString) + (*pAllocation)->SetName(m_hAllocator, (const char*)pUserData); + else + (*pAllocation)->SetUserData(m_hAllocator, pUserData); + m_hAllocator->m_Budget.AddAllocation(m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex), allocRequest.size); + if (VMA_DEBUG_INITIALIZE_ALLOCATIONS) + { + m_hAllocator->FillAllocation(*pAllocation, VMA_ALLOCATION_FILL_PATTERN_CREATED); + } + if (IsCorruptionDetectionEnabled()) + { + VkResult res = pBlock->WriteMagicValueAfterAllocation(m_hAllocator, (*pAllocation)->GetOffset(), allocRequest.size); + VMA_ASSERT(res == VK_SUCCESS && "Couldn't map block memory to write magic value."); + } + return VK_SUCCESS; +} + +VkResult VmaBlockVector::CreateBlock(VkDeviceSize blockSize, size_t* pNewBlockIndex) +{ + VkMemoryAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO }; + allocInfo.pNext = m_pMemoryAllocateNext; + allocInfo.memoryTypeIndex = m_MemoryTypeIndex; + allocInfo.allocationSize = blockSize; + +#if VMA_BUFFER_DEVICE_ADDRESS + // Every standalone block can potentially contain a buffer with VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT - always enable the feature. + VkMemoryAllocateFlagsInfoKHR allocFlagsInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO_KHR }; + if (m_hAllocator->m_UseKhrBufferDeviceAddress) + { + allocFlagsInfo.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT_KHR; + VmaPnextChainPushFront(&allocInfo, &allocFlagsInfo); + } +#endif // VMA_BUFFER_DEVICE_ADDRESS + +#if VMA_MEMORY_PRIORITY + VkMemoryPriorityAllocateInfoEXT priorityInfo = { VK_STRUCTURE_TYPE_MEMORY_PRIORITY_ALLOCATE_INFO_EXT }; + if (m_hAllocator->m_UseExtMemoryPriority) + { + VMA_ASSERT(m_Priority >= 0.f && m_Priority <= 1.f); + priorityInfo.priority = m_Priority; + VmaPnextChainPushFront(&allocInfo, &priorityInfo); + } +#endif // VMA_MEMORY_PRIORITY + +#if VMA_EXTERNAL_MEMORY + // Attach VkExportMemoryAllocateInfoKHR if necessary. + VkExportMemoryAllocateInfoKHR exportMemoryAllocInfo = { VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR }; + exportMemoryAllocInfo.handleTypes = m_hAllocator->GetExternalMemoryHandleTypeFlags(m_MemoryTypeIndex); + if (exportMemoryAllocInfo.handleTypes != 0) + { + VmaPnextChainPushFront(&allocInfo, &exportMemoryAllocInfo); + } +#endif // VMA_EXTERNAL_MEMORY + + VkDeviceMemory mem = VK_NULL_HANDLE; + VkResult res = m_hAllocator->AllocateVulkanMemory(&allocInfo, &mem); + if (res < 0) + { + return res; + } + + // New VkDeviceMemory successfully created. + + // Create new Allocation for it. + VmaDeviceMemoryBlock* const pBlock = vma_new(m_hAllocator, VmaDeviceMemoryBlock)(m_hAllocator); + pBlock->Init( + m_hAllocator, + m_hParentPool, + m_MemoryTypeIndex, + mem, + allocInfo.allocationSize, + m_NextBlockId++, + m_Algorithm, + m_BufferImageGranularity); + + m_Blocks.push_back(pBlock); + if (pNewBlockIndex != VMA_NULL) + { + *pNewBlockIndex = m_Blocks.size() - 1; + } + + return VK_SUCCESS; +} + +bool VmaBlockVector::HasEmptyBlock() +{ + for (size_t index = 0, count = m_Blocks.size(); index < count; ++index) + { + VmaDeviceMemoryBlock* const pBlock = m_Blocks[index]; + if (pBlock->m_pMetadata->IsEmpty()) + { + return true; + } + } + return false; +} + +#if VMA_STATS_STRING_ENABLED +void VmaBlockVector::PrintDetailedMap(class VmaJsonWriter& json) +{ + VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex); + + + json.BeginObject(); + for (size_t i = 0; i < m_Blocks.size(); ++i) + { + json.BeginString(); + json.ContinueString(m_Blocks[i]->GetId()); + json.EndString(); + + json.BeginObject(); + json.WriteString("MapRefCount"); + json.WriteNumber(m_Blocks[i]->GetMapRefCount()); + + m_Blocks[i]->m_pMetadata->PrintDetailedMap(json); + json.EndObject(); + } + json.EndObject(); +} +#endif // VMA_STATS_STRING_ENABLED + +VkResult VmaBlockVector::CheckCorruption() +{ + if (!IsCorruptionDetectionEnabled()) + { + return VK_ERROR_FEATURE_NOT_PRESENT; + } + + VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex); + for (uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex) + { + VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex]; + VMA_ASSERT(pBlock); + VkResult res = pBlock->CheckCorruption(m_hAllocator); + if (res != VK_SUCCESS) + { + return res; + } + } + return VK_SUCCESS; +} + +#endif // _VMA_BLOCK_VECTOR_FUNCTIONS + +#ifndef _VMA_DEFRAGMENTATION_CONTEXT_FUNCTIONS +VmaDefragmentationContext_T::VmaDefragmentationContext_T( + VmaAllocator hAllocator, + const VmaDefragmentationInfo& info) + : m_MaxPassBytes(info.maxBytesPerPass == 0 ? VK_WHOLE_SIZE : info.maxBytesPerPass), + m_MaxPassAllocations(info.maxAllocationsPerPass == 0 ? UINT32_MAX : info.maxAllocationsPerPass), + m_BreakCallback(info.pfnBreakCallback), + m_BreakCallbackUserData(info.pBreakCallbackUserData), + m_MoveAllocator(hAllocator->GetAllocationCallbacks()), + m_Moves(m_MoveAllocator) +{ + m_Algorithm = info.flags & VMA_DEFRAGMENTATION_FLAG_ALGORITHM_MASK; + + if (info.pool != VMA_NULL) + { + m_BlockVectorCount = 1; + m_PoolBlockVector = &info.pool->m_BlockVector; + m_pBlockVectors = &m_PoolBlockVector; + m_PoolBlockVector->SetIncrementalSort(false); + m_PoolBlockVector->SortByFreeSize(); + } + else + { + m_BlockVectorCount = hAllocator->GetMemoryTypeCount(); + m_PoolBlockVector = VMA_NULL; + m_pBlockVectors = hAllocator->m_pBlockVectors; + for (uint32_t i = 0; i < m_BlockVectorCount; ++i) + { + VmaBlockVector* vector = m_pBlockVectors[i]; + if (vector != VMA_NULL) + { + vector->SetIncrementalSort(false); + vector->SortByFreeSize(); + } + } + } + + switch (m_Algorithm) + { + case 0: // Default algorithm + m_Algorithm = VMA_DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED_BIT; + m_AlgorithmState = vma_new_array(hAllocator, StateBalanced, m_BlockVectorCount); + break; + case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED_BIT: + m_AlgorithmState = vma_new_array(hAllocator, StateBalanced, m_BlockVectorCount); + break; + case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT: + if (hAllocator->GetBufferImageGranularity() > 1) + { + m_AlgorithmState = vma_new_array(hAllocator, StateExtensive, m_BlockVectorCount); + } + break; + } +} + +VmaDefragmentationContext_T::~VmaDefragmentationContext_T() +{ + if (m_PoolBlockVector != VMA_NULL) + { + m_PoolBlockVector->SetIncrementalSort(true); + } + else + { + for (uint32_t i = 0; i < m_BlockVectorCount; ++i) + { + VmaBlockVector* vector = m_pBlockVectors[i]; + if (vector != VMA_NULL) + vector->SetIncrementalSort(true); + } + } + + if (m_AlgorithmState) + { + switch (m_Algorithm) + { + case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED_BIT: + vma_delete_array(m_MoveAllocator.m_pCallbacks, reinterpret_cast(m_AlgorithmState), m_BlockVectorCount); + break; + case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT: + vma_delete_array(m_MoveAllocator.m_pCallbacks, reinterpret_cast(m_AlgorithmState), m_BlockVectorCount); + break; + default: + VMA_ASSERT(0); + } + } +} + +VkResult VmaDefragmentationContext_T::DefragmentPassBegin(VmaDefragmentationPassMoveInfo& moveInfo) +{ + if (m_PoolBlockVector != VMA_NULL) + { + VmaMutexLockWrite lock(m_PoolBlockVector->GetMutex(), m_PoolBlockVector->GetAllocator()->m_UseMutex); + + if (m_PoolBlockVector->GetBlockCount() > 1) + ComputeDefragmentation(*m_PoolBlockVector, 0); + else if (m_PoolBlockVector->GetBlockCount() == 1) + ReallocWithinBlock(*m_PoolBlockVector, m_PoolBlockVector->GetBlock(0)); + } + else + { + for (uint32_t i = 0; i < m_BlockVectorCount; ++i) + { + if (m_pBlockVectors[i] != VMA_NULL) + { + VmaMutexLockWrite lock(m_pBlockVectors[i]->GetMutex(), m_pBlockVectors[i]->GetAllocator()->m_UseMutex); + + if (m_pBlockVectors[i]->GetBlockCount() > 1) + { + if (ComputeDefragmentation(*m_pBlockVectors[i], i)) + break; + } + else if (m_pBlockVectors[i]->GetBlockCount() == 1) + { + if (ReallocWithinBlock(*m_pBlockVectors[i], m_pBlockVectors[i]->GetBlock(0))) + break; + } + } + } + } + + moveInfo.moveCount = static_cast(m_Moves.size()); + if (moveInfo.moveCount > 0) + { + moveInfo.pMoves = m_Moves.data(); + return VK_INCOMPLETE; + } + + moveInfo.pMoves = VMA_NULL; + return VK_SUCCESS; +} + +VkResult VmaDefragmentationContext_T::DefragmentPassEnd(VmaDefragmentationPassMoveInfo& moveInfo) +{ + VMA_ASSERT(moveInfo.moveCount > 0 ? moveInfo.pMoves != VMA_NULL : true); + + VkResult result = VK_SUCCESS; + VmaStlAllocator blockAllocator(m_MoveAllocator.m_pCallbacks); + VmaVector> immovableBlocks(blockAllocator); + VmaVector> mappedBlocks(blockAllocator); + + VmaAllocator allocator = VMA_NULL; + for (uint32_t i = 0; i < moveInfo.moveCount; ++i) + { + VmaDefragmentationMove& move = moveInfo.pMoves[i]; + size_t prevCount = 0, currentCount = 0; + VkDeviceSize freedBlockSize = 0; + + uint32_t vectorIndex; + VmaBlockVector* vector; + if (m_PoolBlockVector != VMA_NULL) + { + vectorIndex = 0; + vector = m_PoolBlockVector; + } + else + { + vectorIndex = move.srcAllocation->GetMemoryTypeIndex(); + vector = m_pBlockVectors[vectorIndex]; + VMA_ASSERT(vector != VMA_NULL); + } + + switch (move.operation) + { + case VMA_DEFRAGMENTATION_MOVE_OPERATION_COPY: + { + uint8_t mapCount = move.srcAllocation->SwapBlockAllocation(vector->m_hAllocator, move.dstTmpAllocation); + if (mapCount > 0) + { + allocator = vector->m_hAllocator; + VmaDeviceMemoryBlock* newMapBlock = move.srcAllocation->GetBlock(); + bool notPresent = true; + for (FragmentedBlock& block : mappedBlocks) + { + if (block.block == newMapBlock) + { + notPresent = false; + block.data += mapCount; + break; + } + } + if (notPresent) + mappedBlocks.push_back({ mapCount, newMapBlock }); + } + + // Scope for locks, Free have it's own lock + { + VmaMutexLockRead lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex); + prevCount = vector->GetBlockCount(); + freedBlockSize = move.dstTmpAllocation->GetBlock()->m_pMetadata->GetSize(); + } + vector->Free(move.dstTmpAllocation); + { + VmaMutexLockRead lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex); + currentCount = vector->GetBlockCount(); + } + + result = VK_INCOMPLETE; + break; + } + case VMA_DEFRAGMENTATION_MOVE_OPERATION_IGNORE: + { + m_PassStats.bytesMoved -= move.srcAllocation->GetSize(); + --m_PassStats.allocationsMoved; + vector->Free(move.dstTmpAllocation); + + VmaDeviceMemoryBlock* newBlock = move.srcAllocation->GetBlock(); + bool notPresent = true; + for (const FragmentedBlock& block : immovableBlocks) + { + if (block.block == newBlock) + { + notPresent = false; + break; + } + } + if (notPresent) + immovableBlocks.push_back({ vectorIndex, newBlock }); + break; + } + case VMA_DEFRAGMENTATION_MOVE_OPERATION_DESTROY: + { + m_PassStats.bytesMoved -= move.srcAllocation->GetSize(); + --m_PassStats.allocationsMoved; + // Scope for locks, Free have it's own lock + { + VmaMutexLockRead lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex); + prevCount = vector->GetBlockCount(); + freedBlockSize = move.srcAllocation->GetBlock()->m_pMetadata->GetSize(); + } + vector->Free(move.srcAllocation); + { + VmaMutexLockRead lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex); + currentCount = vector->GetBlockCount(); + } + freedBlockSize *= prevCount - currentCount; + + VkDeviceSize dstBlockSize; + { + VmaMutexLockRead lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex); + dstBlockSize = move.dstTmpAllocation->GetBlock()->m_pMetadata->GetSize(); + } + vector->Free(move.dstTmpAllocation); + { + VmaMutexLockRead lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex); + freedBlockSize += dstBlockSize * (currentCount - vector->GetBlockCount()); + currentCount = vector->GetBlockCount(); + } + + result = VK_INCOMPLETE; + break; + } + default: + VMA_ASSERT(0); + } + + if (prevCount > currentCount) + { + size_t freedBlocks = prevCount - currentCount; + m_PassStats.deviceMemoryBlocksFreed += static_cast(freedBlocks); + m_PassStats.bytesFreed += freedBlockSize; + } + + if(m_Algorithm == VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT && + m_AlgorithmState != VMA_NULL) + { + // Avoid unnecessary tries to allocate when new free block is available + StateExtensive& state = reinterpret_cast(m_AlgorithmState)[vectorIndex]; + if (state.firstFreeBlock != SIZE_MAX) + { + const size_t diff = prevCount - currentCount; + if (state.firstFreeBlock >= diff) + { + state.firstFreeBlock -= diff; + if (state.firstFreeBlock != 0) + state.firstFreeBlock -= vector->GetBlock(state.firstFreeBlock - 1)->m_pMetadata->IsEmpty(); + } + else + state.firstFreeBlock = 0; + } + } + } + moveInfo.moveCount = 0; + moveInfo.pMoves = VMA_NULL; + m_Moves.clear(); + + // Update stats + m_GlobalStats.allocationsMoved += m_PassStats.allocationsMoved; + m_GlobalStats.bytesFreed += m_PassStats.bytesFreed; + m_GlobalStats.bytesMoved += m_PassStats.bytesMoved; + m_GlobalStats.deviceMemoryBlocksFreed += m_PassStats.deviceMemoryBlocksFreed; + m_PassStats = { 0 }; + + // Move blocks with immovable allocations according to algorithm + if (immovableBlocks.size() > 0) + { + do + { + if(m_Algorithm == VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT) + { + if (m_AlgorithmState != VMA_NULL) + { + bool swapped = false; + // Move to the start of free blocks range + for (const FragmentedBlock& block : immovableBlocks) + { + StateExtensive& state = reinterpret_cast(m_AlgorithmState)[block.data]; + if (state.operation != StateExtensive::Operation::Cleanup) + { + VmaBlockVector* vector = m_pBlockVectors[block.data]; + VmaMutexLockWrite lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex); + + for (size_t i = 0, count = vector->GetBlockCount() - m_ImmovableBlockCount; i < count; ++i) + { + if (vector->GetBlock(i) == block.block) + { + std::swap(vector->m_Blocks[i], vector->m_Blocks[vector->GetBlockCount() - ++m_ImmovableBlockCount]); + if (state.firstFreeBlock != SIZE_MAX) + { + if (i + 1 < state.firstFreeBlock) + { + if (state.firstFreeBlock > 1) + std::swap(vector->m_Blocks[i], vector->m_Blocks[--state.firstFreeBlock]); + else + --state.firstFreeBlock; + } + } + swapped = true; + break; + } + } + } + } + if (swapped) + result = VK_INCOMPLETE; + break; + } + } + + // Move to the beginning + for (const FragmentedBlock& block : immovableBlocks) + { + VmaBlockVector* vector = m_pBlockVectors[block.data]; + VmaMutexLockWrite lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex); + + for (size_t i = m_ImmovableBlockCount; i < vector->GetBlockCount(); ++i) + { + if (vector->GetBlock(i) == block.block) + { + std::swap(vector->m_Blocks[i], vector->m_Blocks[m_ImmovableBlockCount++]); + break; + } + } + } + } while (false); + } + + // Bulk-map destination blocks + for (const FragmentedBlock& block : mappedBlocks) + { + VkResult res = block.block->Map(allocator, block.data, VMA_NULL); + VMA_ASSERT(res == VK_SUCCESS); + } + return result; +} + +bool VmaDefragmentationContext_T::ComputeDefragmentation(VmaBlockVector& vector, size_t index) +{ + switch (m_Algorithm) + { + case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FAST_BIT: + return ComputeDefragmentation_Fast(vector); + case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED_BIT: + return ComputeDefragmentation_Balanced(vector, index, true); + case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FULL_BIT: + return ComputeDefragmentation_Full(vector); + case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT: + return ComputeDefragmentation_Extensive(vector, index); + default: + VMA_ASSERT(0); + return ComputeDefragmentation_Balanced(vector, index, true); + } +} + +VmaDefragmentationContext_T::MoveAllocationData VmaDefragmentationContext_T::GetMoveData( + VmaAllocHandle handle, VmaBlockMetadata* metadata) +{ + MoveAllocationData moveData; + moveData.move.srcAllocation = (VmaAllocation)metadata->GetAllocationUserData(handle); + moveData.size = moveData.move.srcAllocation->GetSize(); + moveData.alignment = moveData.move.srcAllocation->GetAlignment(); + moveData.type = moveData.move.srcAllocation->GetSuballocationType(); + moveData.flags = 0; + + if (moveData.move.srcAllocation->IsPersistentMap()) + moveData.flags |= VMA_ALLOCATION_CREATE_MAPPED_BIT; + if (moveData.move.srcAllocation->IsMappingAllowed()) + moveData.flags |= VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT; + + return moveData; +} + +VmaDefragmentationContext_T::CounterStatus VmaDefragmentationContext_T::CheckCounters(VkDeviceSize bytes) +{ + // Check custom criteria if exists + if (m_BreakCallback && m_BreakCallback(m_BreakCallbackUserData)) + return CounterStatus::End; + + // Ignore allocation if will exceed max size for copy + if (m_PassStats.bytesMoved + bytes > m_MaxPassBytes) + { + if (++m_IgnoredAllocs < MAX_ALLOCS_TO_IGNORE) + return CounterStatus::Ignore; + else + return CounterStatus::End; + } + else + m_IgnoredAllocs = 0; + return CounterStatus::Pass; +} + +bool VmaDefragmentationContext_T::IncrementCounters(VkDeviceSize bytes) +{ + m_PassStats.bytesMoved += bytes; + // Early return when max found + if (++m_PassStats.allocationsMoved >= m_MaxPassAllocations || m_PassStats.bytesMoved >= m_MaxPassBytes) + { + VMA_ASSERT((m_PassStats.allocationsMoved == m_MaxPassAllocations || + m_PassStats.bytesMoved == m_MaxPassBytes) && "Exceeded maximal pass threshold!"); + return true; + } + return false; +} + +bool VmaDefragmentationContext_T::ReallocWithinBlock(VmaBlockVector& vector, VmaDeviceMemoryBlock* block) +{ + VmaBlockMetadata* metadata = block->m_pMetadata; + + for (VmaAllocHandle handle = metadata->GetAllocationListBegin(); + handle != VK_NULL_HANDLE; + handle = metadata->GetNextAllocation(handle)) + { + MoveAllocationData moveData = GetMoveData(handle, metadata); + // Ignore newly created allocations by defragmentation algorithm + if (moveData.move.srcAllocation->GetUserData() == this) + continue; + switch (CheckCounters(moveData.move.srcAllocation->GetSize())) + { + case CounterStatus::Ignore: + continue; + case CounterStatus::End: + return true; + case CounterStatus::Pass: + break; + default: + VMA_ASSERT(0); + } + + VkDeviceSize offset = moveData.move.srcAllocation->GetOffset(); + if (offset != 0 && metadata->GetSumFreeSize() >= moveData.size) + { + VmaAllocationRequest request = {}; + if (metadata->CreateAllocationRequest( + moveData.size, + moveData.alignment, + false, + moveData.type, + VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT, + &request)) + { + if (metadata->GetAllocationOffset(request.allocHandle) < offset) + { + if (vector.CommitAllocationRequest( + request, + block, + moveData.alignment, + moveData.flags, + this, + moveData.type, + &moveData.move.dstTmpAllocation) == VK_SUCCESS) + { + m_Moves.push_back(moveData.move); + if (IncrementCounters(moveData.size)) + return true; + } + } + } + } + } + return false; +} + +bool VmaDefragmentationContext_T::AllocInOtherBlock(size_t start, size_t end, MoveAllocationData& data, VmaBlockVector& vector) +{ + for (; start < end; ++start) + { + VmaDeviceMemoryBlock* dstBlock = vector.GetBlock(start); + if (dstBlock->m_pMetadata->GetSumFreeSize() >= data.size) + { + if (vector.AllocateFromBlock(dstBlock, + data.size, + data.alignment, + data.flags, + this, + data.type, + 0, + &data.move.dstTmpAllocation) == VK_SUCCESS) + { + m_Moves.push_back(data.move); + if (IncrementCounters(data.size)) + return true; + break; + } + } + } + return false; +} + +bool VmaDefragmentationContext_T::ComputeDefragmentation_Fast(VmaBlockVector& vector) +{ + // Move only between blocks + + // Go through allocations in last blocks and try to fit them inside first ones + for (size_t i = vector.GetBlockCount() - 1; i > m_ImmovableBlockCount; --i) + { + VmaBlockMetadata* metadata = vector.GetBlock(i)->m_pMetadata; + + for (VmaAllocHandle handle = metadata->GetAllocationListBegin(); + handle != VK_NULL_HANDLE; + handle = metadata->GetNextAllocation(handle)) + { + MoveAllocationData moveData = GetMoveData(handle, metadata); + // Ignore newly created allocations by defragmentation algorithm + if (moveData.move.srcAllocation->GetUserData() == this) + continue; + switch (CheckCounters(moveData.move.srcAllocation->GetSize())) + { + case CounterStatus::Ignore: + continue; + case CounterStatus::End: + return true; + case CounterStatus::Pass: + break; + default: + VMA_ASSERT(0); + } + + // Check all previous blocks for free space + if (AllocInOtherBlock(0, i, moveData, vector)) + return true; + } + } + return false; +} + +bool VmaDefragmentationContext_T::ComputeDefragmentation_Balanced(VmaBlockVector& vector, size_t index, bool update) +{ + // Go over every allocation and try to fit it in previous blocks at lowest offsets, + // if not possible: realloc within single block to minimize offset (exclude offset == 0), + // but only if there are noticeable gaps between them (some heuristic, ex. average size of allocation in block) + VMA_ASSERT(m_AlgorithmState != VMA_NULL); + + StateBalanced& vectorState = reinterpret_cast(m_AlgorithmState)[index]; + if (update && vectorState.avgAllocSize == UINT64_MAX) + UpdateVectorStatistics(vector, vectorState); + + const size_t startMoveCount = m_Moves.size(); + VkDeviceSize minimalFreeRegion = vectorState.avgFreeSize / 2; + for (size_t i = vector.GetBlockCount() - 1; i > m_ImmovableBlockCount; --i) + { + VmaDeviceMemoryBlock* block = vector.GetBlock(i); + VmaBlockMetadata* metadata = block->m_pMetadata; + VkDeviceSize prevFreeRegionSize = 0; + + for (VmaAllocHandle handle = metadata->GetAllocationListBegin(); + handle != VK_NULL_HANDLE; + handle = metadata->GetNextAllocation(handle)) + { + MoveAllocationData moveData = GetMoveData(handle, metadata); + // Ignore newly created allocations by defragmentation algorithm + if (moveData.move.srcAllocation->GetUserData() == this) + continue; + switch (CheckCounters(moveData.move.srcAllocation->GetSize())) + { + case CounterStatus::Ignore: + continue; + case CounterStatus::End: + return true; + case CounterStatus::Pass: + break; + default: + VMA_ASSERT(0); + } + + // Check all previous blocks for free space + const size_t prevMoveCount = m_Moves.size(); + if (AllocInOtherBlock(0, i, moveData, vector)) + return true; + + VkDeviceSize nextFreeRegionSize = metadata->GetNextFreeRegionSize(handle); + // If no room found then realloc within block for lower offset + VkDeviceSize offset = moveData.move.srcAllocation->GetOffset(); + if (prevMoveCount == m_Moves.size() && offset != 0 && metadata->GetSumFreeSize() >= moveData.size) + { + // Check if realloc will make sense + if (prevFreeRegionSize >= minimalFreeRegion || + nextFreeRegionSize >= minimalFreeRegion || + moveData.size <= vectorState.avgFreeSize || + moveData.size <= vectorState.avgAllocSize) + { + VmaAllocationRequest request = {}; + if (metadata->CreateAllocationRequest( + moveData.size, + moveData.alignment, + false, + moveData.type, + VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT, + &request)) + { + if (metadata->GetAllocationOffset(request.allocHandle) < offset) + { + if (vector.CommitAllocationRequest( + request, + block, + moveData.alignment, + moveData.flags, + this, + moveData.type, + &moveData.move.dstTmpAllocation) == VK_SUCCESS) + { + m_Moves.push_back(moveData.move); + if (IncrementCounters(moveData.size)) + return true; + } + } + } + } + } + prevFreeRegionSize = nextFreeRegionSize; + } + } + + // No moves performed, update statistics to current vector state + if (startMoveCount == m_Moves.size() && !update) + { + vectorState.avgAllocSize = UINT64_MAX; + return ComputeDefragmentation_Balanced(vector, index, false); + } + return false; +} + +bool VmaDefragmentationContext_T::ComputeDefragmentation_Full(VmaBlockVector& vector) +{ + // Go over every allocation and try to fit it in previous blocks at lowest offsets, + // if not possible: realloc within single block to minimize offset (exclude offset == 0) + + for (size_t i = vector.GetBlockCount() - 1; i > m_ImmovableBlockCount; --i) + { + VmaDeviceMemoryBlock* block = vector.GetBlock(i); + VmaBlockMetadata* metadata = block->m_pMetadata; + + for (VmaAllocHandle handle = metadata->GetAllocationListBegin(); + handle != VK_NULL_HANDLE; + handle = metadata->GetNextAllocation(handle)) + { + MoveAllocationData moveData = GetMoveData(handle, metadata); + // Ignore newly created allocations by defragmentation algorithm + if (moveData.move.srcAllocation->GetUserData() == this) + continue; + switch (CheckCounters(moveData.move.srcAllocation->GetSize())) + { + case CounterStatus::Ignore: + continue; + case CounterStatus::End: + return true; + case CounterStatus::Pass: + break; + default: + VMA_ASSERT(0); + } + + // Check all previous blocks for free space + const size_t prevMoveCount = m_Moves.size(); + if (AllocInOtherBlock(0, i, moveData, vector)) + return true; + + // If no room found then realloc within block for lower offset + VkDeviceSize offset = moveData.move.srcAllocation->GetOffset(); + if (prevMoveCount == m_Moves.size() && offset != 0 && metadata->GetSumFreeSize() >= moveData.size) + { + VmaAllocationRequest request = {}; + if (metadata->CreateAllocationRequest( + moveData.size, + moveData.alignment, + false, + moveData.type, + VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT, + &request)) + { + if (metadata->GetAllocationOffset(request.allocHandle) < offset) + { + if (vector.CommitAllocationRequest( + request, + block, + moveData.alignment, + moveData.flags, + this, + moveData.type, + &moveData.move.dstTmpAllocation) == VK_SUCCESS) + { + m_Moves.push_back(moveData.move); + if (IncrementCounters(moveData.size)) + return true; + } + } + } + } + } + } + return false; +} + +bool VmaDefragmentationContext_T::ComputeDefragmentation_Extensive(VmaBlockVector& vector, size_t index) +{ + // First free single block, then populate it to the brim, then free another block, and so on + + // Fallback to previous algorithm since without granularity conflicts it can achieve max packing + if (vector.m_BufferImageGranularity == 1) + return ComputeDefragmentation_Full(vector); + + VMA_ASSERT(m_AlgorithmState != VMA_NULL); + + StateExtensive& vectorState = reinterpret_cast(m_AlgorithmState)[index]; + + bool texturePresent = false, bufferPresent = false, otherPresent = false; + switch (vectorState.operation) + { + case StateExtensive::Operation::Done: // Vector defragmented + return false; + case StateExtensive::Operation::FindFreeBlockBuffer: + case StateExtensive::Operation::FindFreeBlockTexture: + case StateExtensive::Operation::FindFreeBlockAll: + { + // No more blocks to free, just perform fast realloc and move to cleanup + if (vectorState.firstFreeBlock == 0) + { + vectorState.operation = StateExtensive::Operation::Cleanup; + return ComputeDefragmentation_Fast(vector); + } + + // No free blocks, have to clear last one + size_t last = (vectorState.firstFreeBlock == SIZE_MAX ? vector.GetBlockCount() : vectorState.firstFreeBlock) - 1; + VmaBlockMetadata* freeMetadata = vector.GetBlock(last)->m_pMetadata; + + const size_t prevMoveCount = m_Moves.size(); + for (VmaAllocHandle handle = freeMetadata->GetAllocationListBegin(); + handle != VK_NULL_HANDLE; + handle = freeMetadata->GetNextAllocation(handle)) + { + MoveAllocationData moveData = GetMoveData(handle, freeMetadata); + switch (CheckCounters(moveData.move.srcAllocation->GetSize())) + { + case CounterStatus::Ignore: + continue; + case CounterStatus::End: + return true; + case CounterStatus::Pass: + break; + default: + VMA_ASSERT(0); + } + + // Check all previous blocks for free space + if (AllocInOtherBlock(0, last, moveData, vector)) + { + // Full clear performed already + if (prevMoveCount != m_Moves.size() && freeMetadata->GetNextAllocation(handle) == VK_NULL_HANDLE) + vectorState.firstFreeBlock = last; + return true; + } + } + + if (prevMoveCount == m_Moves.size()) + { + // Cannot perform full clear, have to move data in other blocks around + if (last != 0) + { + for (size_t i = last - 1; i; --i) + { + if (ReallocWithinBlock(vector, vector.GetBlock(i))) + return true; + } + } + + if (prevMoveCount == m_Moves.size()) + { + // No possible reallocs within blocks, try to move them around fast + return ComputeDefragmentation_Fast(vector); + } + } + else + { + switch (vectorState.operation) + { + case StateExtensive::Operation::FindFreeBlockBuffer: + vectorState.operation = StateExtensive::Operation::MoveBuffers; + break; + case StateExtensive::Operation::FindFreeBlockTexture: + vectorState.operation = StateExtensive::Operation::MoveTextures; + break; + case StateExtensive::Operation::FindFreeBlockAll: + vectorState.operation = StateExtensive::Operation::MoveAll; + break; + default: + VMA_ASSERT(0); + vectorState.operation = StateExtensive::Operation::MoveTextures; + } + vectorState.firstFreeBlock = last; + // Nothing done, block found without reallocations, can perform another reallocs in same pass + return ComputeDefragmentation_Extensive(vector, index); + } + break; + } + case StateExtensive::Operation::MoveTextures: + { + if (MoveDataToFreeBlocks(VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL, vector, + vectorState.firstFreeBlock, texturePresent, bufferPresent, otherPresent)) + { + if (texturePresent) + { + vectorState.operation = StateExtensive::Operation::FindFreeBlockTexture; + return ComputeDefragmentation_Extensive(vector, index); + } + + if (!bufferPresent && !otherPresent) + { + vectorState.operation = StateExtensive::Operation::Cleanup; + break; + } + + // No more textures to move, check buffers + vectorState.operation = StateExtensive::Operation::MoveBuffers; + bufferPresent = false; + otherPresent = false; + } + else + break; + VMA_FALLTHROUGH; // Fallthrough + } + case StateExtensive::Operation::MoveBuffers: + { + if (MoveDataToFreeBlocks(VMA_SUBALLOCATION_TYPE_BUFFER, vector, + vectorState.firstFreeBlock, texturePresent, bufferPresent, otherPresent)) + { + if (bufferPresent) + { + vectorState.operation = StateExtensive::Operation::FindFreeBlockBuffer; + return ComputeDefragmentation_Extensive(vector, index); + } + + if (!otherPresent) + { + vectorState.operation = StateExtensive::Operation::Cleanup; + break; + } + + // No more buffers to move, check all others + vectorState.operation = StateExtensive::Operation::MoveAll; + otherPresent = false; + } + else + break; + VMA_FALLTHROUGH; // Fallthrough + } + case StateExtensive::Operation::MoveAll: + { + if (MoveDataToFreeBlocks(VMA_SUBALLOCATION_TYPE_FREE, vector, + vectorState.firstFreeBlock, texturePresent, bufferPresent, otherPresent)) + { + if (otherPresent) + { + vectorState.operation = StateExtensive::Operation::FindFreeBlockBuffer; + return ComputeDefragmentation_Extensive(vector, index); + } + // Everything moved + vectorState.operation = StateExtensive::Operation::Cleanup; + } + break; + } + case StateExtensive::Operation::Cleanup: + // Cleanup is handled below so that other operations may reuse the cleanup code. This case is here to prevent the unhandled enum value warning (C4062). + break; + } + + if (vectorState.operation == StateExtensive::Operation::Cleanup) + { + // All other work done, pack data in blocks even tighter if possible + const size_t prevMoveCount = m_Moves.size(); + for (size_t i = 0; i < vector.GetBlockCount(); ++i) + { + if (ReallocWithinBlock(vector, vector.GetBlock(i))) + return true; + } + + if (prevMoveCount == m_Moves.size()) + vectorState.operation = StateExtensive::Operation::Done; + } + return false; +} + +void VmaDefragmentationContext_T::UpdateVectorStatistics(VmaBlockVector& vector, StateBalanced& state) +{ + size_t allocCount = 0; + size_t freeCount = 0; + state.avgFreeSize = 0; + state.avgAllocSize = 0; + + for (size_t i = 0; i < vector.GetBlockCount(); ++i) + { + VmaBlockMetadata* metadata = vector.GetBlock(i)->m_pMetadata; + + allocCount += metadata->GetAllocationCount(); + freeCount += metadata->GetFreeRegionsCount(); + state.avgFreeSize += metadata->GetSumFreeSize(); + state.avgAllocSize += metadata->GetSize(); + } + + state.avgAllocSize = (state.avgAllocSize - state.avgFreeSize) / allocCount; + state.avgFreeSize /= freeCount; +} + +bool VmaDefragmentationContext_T::MoveDataToFreeBlocks(VmaSuballocationType currentType, + VmaBlockVector& vector, size_t firstFreeBlock, + bool& texturePresent, bool& bufferPresent, bool& otherPresent) +{ + const size_t prevMoveCount = m_Moves.size(); + for (size_t i = firstFreeBlock ; i;) + { + VmaDeviceMemoryBlock* block = vector.GetBlock(--i); + VmaBlockMetadata* metadata = block->m_pMetadata; + + for (VmaAllocHandle handle = metadata->GetAllocationListBegin(); + handle != VK_NULL_HANDLE; + handle = metadata->GetNextAllocation(handle)) + { + MoveAllocationData moveData = GetMoveData(handle, metadata); + // Ignore newly created allocations by defragmentation algorithm + if (moveData.move.srcAllocation->GetUserData() == this) + continue; + switch (CheckCounters(moveData.move.srcAllocation->GetSize())) + { + case CounterStatus::Ignore: + continue; + case CounterStatus::End: + return true; + case CounterStatus::Pass: + break; + default: + VMA_ASSERT(0); + } + + // Move only single type of resources at once + if (!VmaIsBufferImageGranularityConflict(moveData.type, currentType)) + { + // Try to fit allocation into free blocks + if (AllocInOtherBlock(firstFreeBlock, vector.GetBlockCount(), moveData, vector)) + return false; + } + + if (!VmaIsBufferImageGranularityConflict(moveData.type, VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL)) + texturePresent = true; + else if (!VmaIsBufferImageGranularityConflict(moveData.type, VMA_SUBALLOCATION_TYPE_BUFFER)) + bufferPresent = true; + else + otherPresent = true; + } + } + return prevMoveCount == m_Moves.size(); +} +#endif // _VMA_DEFRAGMENTATION_CONTEXT_FUNCTIONS + +#ifndef _VMA_POOL_T_FUNCTIONS +VmaPool_T::VmaPool_T( + VmaAllocator hAllocator, + const VmaPoolCreateInfo& createInfo, + VkDeviceSize preferredBlockSize) + : m_BlockVector( + hAllocator, + this, // hParentPool + createInfo.memoryTypeIndex, + createInfo.blockSize != 0 ? createInfo.blockSize : preferredBlockSize, + createInfo.minBlockCount, + createInfo.maxBlockCount, + (createInfo.flags& VMA_POOL_CREATE_IGNORE_BUFFER_IMAGE_GRANULARITY_BIT) != 0 ? 1 : hAllocator->GetBufferImageGranularity(), + createInfo.blockSize != 0, // explicitBlockSize + createInfo.flags & VMA_POOL_CREATE_ALGORITHM_MASK, // algorithm + createInfo.priority, + VMA_MAX(hAllocator->GetMemoryTypeMinAlignment(createInfo.memoryTypeIndex), createInfo.minAllocationAlignment), + createInfo.pMemoryAllocateNext), + m_Id(0), + m_Name(VMA_NULL) {} + +VmaPool_T::~VmaPool_T() +{ + VMA_ASSERT(m_PrevPool == VMA_NULL && m_NextPool == VMA_NULL); + + const VkAllocationCallbacks* allocs = m_BlockVector.GetAllocator()->GetAllocationCallbacks(); + VmaFreeString(allocs, m_Name); +} + +void VmaPool_T::SetName(const char* pName) +{ + const VkAllocationCallbacks* allocs = m_BlockVector.GetAllocator()->GetAllocationCallbacks(); + VmaFreeString(allocs, m_Name); + + if (pName != VMA_NULL) + { + m_Name = VmaCreateStringCopy(allocs, pName); + } + else + { + m_Name = VMA_NULL; + } +} +#endif // _VMA_POOL_T_FUNCTIONS + +#ifndef _VMA_ALLOCATOR_T_FUNCTIONS +VmaAllocator_T::VmaAllocator_T(const VmaAllocatorCreateInfo* pCreateInfo) : + m_UseMutex((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT) == 0), + m_VulkanApiVersion(pCreateInfo->vulkanApiVersion != 0 ? pCreateInfo->vulkanApiVersion : VK_API_VERSION_1_0), + m_UseKhrDedicatedAllocation((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT) != 0), + m_UseKhrBindMemory2((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT) != 0), + m_UseExtMemoryBudget((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT) != 0), + m_UseAmdDeviceCoherentMemory((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_AMD_DEVICE_COHERENT_MEMORY_BIT) != 0), + m_UseKhrBufferDeviceAddress((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT) != 0), + m_UseExtMemoryPriority((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT) != 0), + m_UseKhrMaintenance4((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_MAINTENANCE4_BIT) != 0), + m_UseKhrMaintenance5((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_MAINTENANCE5_BIT) != 0), + m_UseKhrExternalMemoryWin32((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_EXTERNAL_MEMORY_WIN32_BIT) != 0), + m_hDevice(pCreateInfo->device), + m_hInstance(pCreateInfo->instance), + m_AllocationCallbacksSpecified(pCreateInfo->pAllocationCallbacks != VMA_NULL), + m_AllocationCallbacks(pCreateInfo->pAllocationCallbacks ? + *pCreateInfo->pAllocationCallbacks : VmaEmptyAllocationCallbacks), + m_AllocationObjectAllocator(&m_AllocationCallbacks), + m_HeapSizeLimitMask(0), + m_DeviceMemoryCount(0), + m_PreferredLargeHeapBlockSize(0), + m_PhysicalDevice(pCreateInfo->physicalDevice), + m_GpuDefragmentationMemoryTypeBits(UINT32_MAX), + m_NextPoolId(0), + m_GlobalMemoryTypeBits(UINT32_MAX) +{ + if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) + { + m_UseKhrDedicatedAllocation = false; + m_UseKhrBindMemory2 = false; + } + + if(VMA_DEBUG_DETECT_CORRUPTION) + { + // Needs to be multiply of uint32_t size because we are going to write VMA_CORRUPTION_DETECTION_MAGIC_VALUE to it. + VMA_ASSERT(VMA_DEBUG_MARGIN % sizeof(uint32_t) == 0); + } + + VMA_ASSERT(pCreateInfo->physicalDevice && pCreateInfo->device && pCreateInfo->instance); + + if(m_VulkanApiVersion < VK_MAKE_VERSION(1, 1, 0)) + { +#if !(VMA_DEDICATED_ALLOCATION) + if((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT) != 0) + { + VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT set but required extensions are disabled by preprocessor macros."); + } +#endif +#if !(VMA_BIND_MEMORY2) + if((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT) != 0) + { + VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT set but required extension is disabled by preprocessor macros."); + } +#endif + } +#if !(VMA_MEMORY_BUDGET) + if((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT) != 0) + { + VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT set but required extension is disabled by preprocessor macros."); + } +#endif +#if !(VMA_BUFFER_DEVICE_ADDRESS) + if(m_UseKhrBufferDeviceAddress) + { + VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT is set but required extension or Vulkan 1.2 is not available in your Vulkan header or its support in VMA has been disabled by a preprocessor macro."); + } +#endif +#if VMA_VULKAN_VERSION < 1003000 + if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 3, 0)) + { + VMA_ASSERT(0 && "vulkanApiVersion >= VK_API_VERSION_1_3 but required Vulkan version is disabled by preprocessor macros."); + } +#endif +#if VMA_VULKAN_VERSION < 1002000 + if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 2, 0)) + { + VMA_ASSERT(0 && "vulkanApiVersion >= VK_API_VERSION_1_2 but required Vulkan version is disabled by preprocessor macros."); + } +#endif +#if VMA_VULKAN_VERSION < 1001000 + if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) + { + VMA_ASSERT(0 && "vulkanApiVersion >= VK_API_VERSION_1_1 but required Vulkan version is disabled by preprocessor macros."); + } +#endif +#if !(VMA_MEMORY_PRIORITY) + if(m_UseExtMemoryPriority) + { + VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT is set but required extension is not available in your Vulkan header or its support in VMA has been disabled by a preprocessor macro."); + } +#endif +#if !(VMA_KHR_MAINTENANCE4) + if(m_UseKhrMaintenance4) + { + VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_KHR_MAINTENANCE4_BIT is set but required extension is not available in your Vulkan header or its support in VMA has been disabled by a preprocessor macro."); + } +#endif +#if !(VMA_KHR_MAINTENANCE5) + if(m_UseKhrMaintenance5) + { + VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_KHR_MAINTENANCE5_BIT is set but required extension is not available in your Vulkan header or its support in VMA has been disabled by a preprocessor macro."); + } +#endif +#if !(VMA_KHR_MAINTENANCE5) + if(m_UseKhrMaintenance5) + { + VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_KHR_MAINTENANCE5_BIT is set but required extension is not available in your Vulkan header or its support in VMA has been disabled by a preprocessor macro."); + } +#endif + +#if !(VMA_EXTERNAL_MEMORY_WIN32) + if(m_UseKhrExternalMemoryWin32) + { + VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_KHR_EXTERNAL_MEMORY_WIN32_BIT is set but required extension is not available in your Vulkan header or its support in VMA has been disabled by a preprocessor macro."); + } +#endif + + memset(&m_DeviceMemoryCallbacks, 0 ,sizeof(m_DeviceMemoryCallbacks)); + memset(&m_PhysicalDeviceProperties, 0, sizeof(m_PhysicalDeviceProperties)); + memset(&m_MemProps, 0, sizeof(m_MemProps)); + + memset(&m_pBlockVectors, 0, sizeof(m_pBlockVectors)); + memset(&m_VulkanFunctions, 0, sizeof(m_VulkanFunctions)); + +#if VMA_EXTERNAL_MEMORY + memset(&m_TypeExternalMemoryHandleTypes, 0, sizeof(m_TypeExternalMemoryHandleTypes)); +#endif // #if VMA_EXTERNAL_MEMORY + + if(pCreateInfo->pDeviceMemoryCallbacks != VMA_NULL) + { + m_DeviceMemoryCallbacks.pUserData = pCreateInfo->pDeviceMemoryCallbacks->pUserData; + m_DeviceMemoryCallbacks.pfnAllocate = pCreateInfo->pDeviceMemoryCallbacks->pfnAllocate; + m_DeviceMemoryCallbacks.pfnFree = pCreateInfo->pDeviceMemoryCallbacks->pfnFree; + } + + ImportVulkanFunctions(pCreateInfo->pVulkanFunctions); + + (*m_VulkanFunctions.vkGetPhysicalDeviceProperties)(m_PhysicalDevice, &m_PhysicalDeviceProperties); + (*m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties)(m_PhysicalDevice, &m_MemProps); + + VMA_ASSERT(VmaIsPow2(VMA_MIN_ALIGNMENT)); + VMA_ASSERT(VmaIsPow2(VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY)); + VMA_ASSERT(VmaIsPow2(m_PhysicalDeviceProperties.limits.bufferImageGranularity)); + VMA_ASSERT(VmaIsPow2(m_PhysicalDeviceProperties.limits.nonCoherentAtomSize)); + + m_PreferredLargeHeapBlockSize = (pCreateInfo->preferredLargeHeapBlockSize != 0) ? + pCreateInfo->preferredLargeHeapBlockSize : static_cast(VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE); + + m_GlobalMemoryTypeBits = CalculateGlobalMemoryTypeBits(); + +#if VMA_EXTERNAL_MEMORY + if(pCreateInfo->pTypeExternalMemoryHandleTypes != VMA_NULL) + { + memcpy(m_TypeExternalMemoryHandleTypes, pCreateInfo->pTypeExternalMemoryHandleTypes, + sizeof(VkExternalMemoryHandleTypeFlagsKHR) * GetMemoryTypeCount()); + } +#endif // #if VMA_EXTERNAL_MEMORY + + if(pCreateInfo->pHeapSizeLimit != VMA_NULL) + { + for(uint32_t heapIndex = 0; heapIndex < GetMemoryHeapCount(); ++heapIndex) + { + const VkDeviceSize limit = pCreateInfo->pHeapSizeLimit[heapIndex]; + if(limit != VK_WHOLE_SIZE) + { + m_HeapSizeLimitMask |= 1u << heapIndex; + if(limit < m_MemProps.memoryHeaps[heapIndex].size) + { + m_MemProps.memoryHeaps[heapIndex].size = limit; + } + } + } + } + + for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex) + { + // Create only supported types + if((m_GlobalMemoryTypeBits & (1u << memTypeIndex)) != 0) + { + const VkDeviceSize preferredBlockSize = CalcPreferredBlockSize(memTypeIndex); + m_pBlockVectors[memTypeIndex] = vma_new(this, VmaBlockVector)( + this, + VK_NULL_HANDLE, // hParentPool + memTypeIndex, + preferredBlockSize, + 0, + SIZE_MAX, + GetBufferImageGranularity(), + false, // explicitBlockSize + 0, // algorithm + 0.5f, // priority (0.5 is the default per Vulkan spec) + GetMemoryTypeMinAlignment(memTypeIndex), // minAllocationAlignment + VMA_NULL); // // pMemoryAllocateNext + // No need to call m_pBlockVectors[memTypeIndex][blockVectorTypeIndex]->CreateMinBlocks here, + // because minBlockCount is 0. + } + } +} + +VkResult VmaAllocator_T::Init(const VmaAllocatorCreateInfo* pCreateInfo) +{ + VkResult res = VK_SUCCESS; + +#if VMA_MEMORY_BUDGET + if(m_UseExtMemoryBudget) + { + UpdateVulkanBudget(); + } +#endif // #if VMA_MEMORY_BUDGET + + return res; +} + +VmaAllocator_T::~VmaAllocator_T() +{ + VMA_ASSERT(m_Pools.IsEmpty()); + + for(size_t memTypeIndex = GetMemoryTypeCount(); memTypeIndex--; ) + { + vma_delete(this, m_pBlockVectors[memTypeIndex]); + } +} + +void VmaAllocator_T::ImportVulkanFunctions(const VmaVulkanFunctions* pVulkanFunctions) +{ +#if VMA_STATIC_VULKAN_FUNCTIONS == 1 + ImportVulkanFunctions_Static(); +#endif + + if(pVulkanFunctions != VMA_NULL) + { + ImportVulkanFunctions_Custom(pVulkanFunctions); + } + +#if VMA_DYNAMIC_VULKAN_FUNCTIONS == 1 + ImportVulkanFunctions_Dynamic(); +#endif + + ValidateVulkanFunctions(); +} + +#if VMA_STATIC_VULKAN_FUNCTIONS == 1 + +void VmaAllocator_T::ImportVulkanFunctions_Static() +{ + // Vulkan 1.0 + m_VulkanFunctions.vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)vkGetInstanceProcAddr; + m_VulkanFunctions.vkGetDeviceProcAddr = (PFN_vkGetDeviceProcAddr)vkGetDeviceProcAddr; + m_VulkanFunctions.vkGetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties)vkGetPhysicalDeviceProperties; + m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties = (PFN_vkGetPhysicalDeviceMemoryProperties)vkGetPhysicalDeviceMemoryProperties; + m_VulkanFunctions.vkAllocateMemory = (PFN_vkAllocateMemory)vkAllocateMemory; + m_VulkanFunctions.vkFreeMemory = (PFN_vkFreeMemory)vkFreeMemory; + m_VulkanFunctions.vkMapMemory = (PFN_vkMapMemory)vkMapMemory; + m_VulkanFunctions.vkUnmapMemory = (PFN_vkUnmapMemory)vkUnmapMemory; + m_VulkanFunctions.vkFlushMappedMemoryRanges = (PFN_vkFlushMappedMemoryRanges)vkFlushMappedMemoryRanges; + m_VulkanFunctions.vkInvalidateMappedMemoryRanges = (PFN_vkInvalidateMappedMemoryRanges)vkInvalidateMappedMemoryRanges; + m_VulkanFunctions.vkBindBufferMemory = (PFN_vkBindBufferMemory)vkBindBufferMemory; + m_VulkanFunctions.vkBindImageMemory = (PFN_vkBindImageMemory)vkBindImageMemory; + m_VulkanFunctions.vkGetBufferMemoryRequirements = (PFN_vkGetBufferMemoryRequirements)vkGetBufferMemoryRequirements; + m_VulkanFunctions.vkGetImageMemoryRequirements = (PFN_vkGetImageMemoryRequirements)vkGetImageMemoryRequirements; + m_VulkanFunctions.vkCreateBuffer = (PFN_vkCreateBuffer)vkCreateBuffer; + m_VulkanFunctions.vkDestroyBuffer = (PFN_vkDestroyBuffer)vkDestroyBuffer; + m_VulkanFunctions.vkCreateImage = (PFN_vkCreateImage)vkCreateImage; + m_VulkanFunctions.vkDestroyImage = (PFN_vkDestroyImage)vkDestroyImage; + m_VulkanFunctions.vkCmdCopyBuffer = (PFN_vkCmdCopyBuffer)vkCmdCopyBuffer; + + // Vulkan 1.1 +#if VMA_VULKAN_VERSION >= 1001000 + if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) + { + m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR = (PFN_vkGetBufferMemoryRequirements2)vkGetBufferMemoryRequirements2; + m_VulkanFunctions.vkGetImageMemoryRequirements2KHR = (PFN_vkGetImageMemoryRequirements2)vkGetImageMemoryRequirements2; + m_VulkanFunctions.vkBindBufferMemory2KHR = (PFN_vkBindBufferMemory2)vkBindBufferMemory2; + m_VulkanFunctions.vkBindImageMemory2KHR = (PFN_vkBindImageMemory2)vkBindImageMemory2; + } +#endif + +#if VMA_VULKAN_VERSION >= 1001000 + if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) + { + m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties2KHR = (PFN_vkGetPhysicalDeviceMemoryProperties2)vkGetPhysicalDeviceMemoryProperties2; + } +#endif + +#if VMA_VULKAN_VERSION >= 1003000 + if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 3, 0)) + { + m_VulkanFunctions.vkGetDeviceBufferMemoryRequirements = (PFN_vkGetDeviceBufferMemoryRequirements)vkGetDeviceBufferMemoryRequirements; + m_VulkanFunctions.vkGetDeviceImageMemoryRequirements = (PFN_vkGetDeviceImageMemoryRequirements)vkGetDeviceImageMemoryRequirements; + } +#endif +} + +#endif // VMA_STATIC_VULKAN_FUNCTIONS == 1 + +void VmaAllocator_T::ImportVulkanFunctions_Custom(const VmaVulkanFunctions* pVulkanFunctions) +{ + VMA_ASSERT(pVulkanFunctions != VMA_NULL); + +#define VMA_COPY_IF_NOT_NULL(funcName) \ + if(pVulkanFunctions->funcName != VMA_NULL) m_VulkanFunctions.funcName = pVulkanFunctions->funcName; + + VMA_COPY_IF_NOT_NULL(vkGetInstanceProcAddr); + VMA_COPY_IF_NOT_NULL(vkGetDeviceProcAddr); + VMA_COPY_IF_NOT_NULL(vkGetPhysicalDeviceProperties); + VMA_COPY_IF_NOT_NULL(vkGetPhysicalDeviceMemoryProperties); + VMA_COPY_IF_NOT_NULL(vkAllocateMemory); + VMA_COPY_IF_NOT_NULL(vkFreeMemory); + VMA_COPY_IF_NOT_NULL(vkMapMemory); + VMA_COPY_IF_NOT_NULL(vkUnmapMemory); + VMA_COPY_IF_NOT_NULL(vkFlushMappedMemoryRanges); + VMA_COPY_IF_NOT_NULL(vkInvalidateMappedMemoryRanges); + VMA_COPY_IF_NOT_NULL(vkBindBufferMemory); + VMA_COPY_IF_NOT_NULL(vkBindImageMemory); + VMA_COPY_IF_NOT_NULL(vkGetBufferMemoryRequirements); + VMA_COPY_IF_NOT_NULL(vkGetImageMemoryRequirements); + VMA_COPY_IF_NOT_NULL(vkCreateBuffer); + VMA_COPY_IF_NOT_NULL(vkDestroyBuffer); + VMA_COPY_IF_NOT_NULL(vkCreateImage); + VMA_COPY_IF_NOT_NULL(vkDestroyImage); + VMA_COPY_IF_NOT_NULL(vkCmdCopyBuffer); + +#if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000 + VMA_COPY_IF_NOT_NULL(vkGetBufferMemoryRequirements2KHR); + VMA_COPY_IF_NOT_NULL(vkGetImageMemoryRequirements2KHR); +#endif + +#if VMA_BIND_MEMORY2 || VMA_VULKAN_VERSION >= 1001000 + VMA_COPY_IF_NOT_NULL(vkBindBufferMemory2KHR); + VMA_COPY_IF_NOT_NULL(vkBindImageMemory2KHR); +#endif + +#if VMA_MEMORY_BUDGET || VMA_VULKAN_VERSION >= 1001000 + VMA_COPY_IF_NOT_NULL(vkGetPhysicalDeviceMemoryProperties2KHR); +#endif + +#if VMA_KHR_MAINTENANCE4 || VMA_VULKAN_VERSION >= 1003000 + VMA_COPY_IF_NOT_NULL(vkGetDeviceBufferMemoryRequirements); + VMA_COPY_IF_NOT_NULL(vkGetDeviceImageMemoryRequirements); +#endif +#if VMA_EXTERNAL_MEMORY_WIN32 + VMA_COPY_IF_NOT_NULL(vkGetMemoryWin32HandleKHR); +#endif +#undef VMA_COPY_IF_NOT_NULL +} + +#if VMA_DYNAMIC_VULKAN_FUNCTIONS == 1 + +void VmaAllocator_T::ImportVulkanFunctions_Dynamic() +{ + VMA_ASSERT(m_VulkanFunctions.vkGetInstanceProcAddr && m_VulkanFunctions.vkGetDeviceProcAddr && + "To use VMA_DYNAMIC_VULKAN_FUNCTIONS in new versions of VMA you now have to pass " + "VmaVulkanFunctions::vkGetInstanceProcAddr and vkGetDeviceProcAddr as VmaAllocatorCreateInfo::pVulkanFunctions. " + "Other members can be null."); + +#define VMA_FETCH_INSTANCE_FUNC(memberName, functionPointerType, functionNameString) \ + if(m_VulkanFunctions.memberName == VMA_NULL) \ + m_VulkanFunctions.memberName = \ + (functionPointerType)m_VulkanFunctions.vkGetInstanceProcAddr(m_hInstance, functionNameString); +#define VMA_FETCH_DEVICE_FUNC(memberName, functionPointerType, functionNameString) \ + if(m_VulkanFunctions.memberName == VMA_NULL) \ + m_VulkanFunctions.memberName = \ + (functionPointerType)m_VulkanFunctions.vkGetDeviceProcAddr(m_hDevice, functionNameString); + + VMA_FETCH_INSTANCE_FUNC(vkGetPhysicalDeviceProperties, PFN_vkGetPhysicalDeviceProperties, "vkGetPhysicalDeviceProperties"); + VMA_FETCH_INSTANCE_FUNC(vkGetPhysicalDeviceMemoryProperties, PFN_vkGetPhysicalDeviceMemoryProperties, "vkGetPhysicalDeviceMemoryProperties"); + VMA_FETCH_DEVICE_FUNC(vkAllocateMemory, PFN_vkAllocateMemory, "vkAllocateMemory"); + VMA_FETCH_DEVICE_FUNC(vkFreeMemory, PFN_vkFreeMemory, "vkFreeMemory"); + VMA_FETCH_DEVICE_FUNC(vkMapMemory, PFN_vkMapMemory, "vkMapMemory"); + VMA_FETCH_DEVICE_FUNC(vkUnmapMemory, PFN_vkUnmapMemory, "vkUnmapMemory"); + VMA_FETCH_DEVICE_FUNC(vkFlushMappedMemoryRanges, PFN_vkFlushMappedMemoryRanges, "vkFlushMappedMemoryRanges"); + VMA_FETCH_DEVICE_FUNC(vkInvalidateMappedMemoryRanges, PFN_vkInvalidateMappedMemoryRanges, "vkInvalidateMappedMemoryRanges"); + VMA_FETCH_DEVICE_FUNC(vkBindBufferMemory, PFN_vkBindBufferMemory, "vkBindBufferMemory"); + VMA_FETCH_DEVICE_FUNC(vkBindImageMemory, PFN_vkBindImageMemory, "vkBindImageMemory"); + VMA_FETCH_DEVICE_FUNC(vkGetBufferMemoryRequirements, PFN_vkGetBufferMemoryRequirements, "vkGetBufferMemoryRequirements"); + VMA_FETCH_DEVICE_FUNC(vkGetImageMemoryRequirements, PFN_vkGetImageMemoryRequirements, "vkGetImageMemoryRequirements"); + VMA_FETCH_DEVICE_FUNC(vkCreateBuffer, PFN_vkCreateBuffer, "vkCreateBuffer"); + VMA_FETCH_DEVICE_FUNC(vkDestroyBuffer, PFN_vkDestroyBuffer, "vkDestroyBuffer"); + VMA_FETCH_DEVICE_FUNC(vkCreateImage, PFN_vkCreateImage, "vkCreateImage"); + VMA_FETCH_DEVICE_FUNC(vkDestroyImage, PFN_vkDestroyImage, "vkDestroyImage"); + VMA_FETCH_DEVICE_FUNC(vkCmdCopyBuffer, PFN_vkCmdCopyBuffer, "vkCmdCopyBuffer"); + +#if VMA_VULKAN_VERSION >= 1001000 + if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) + { + VMA_FETCH_DEVICE_FUNC(vkGetBufferMemoryRequirements2KHR, PFN_vkGetBufferMemoryRequirements2, "vkGetBufferMemoryRequirements2"); + VMA_FETCH_DEVICE_FUNC(vkGetImageMemoryRequirements2KHR, PFN_vkGetImageMemoryRequirements2, "vkGetImageMemoryRequirements2"); + VMA_FETCH_DEVICE_FUNC(vkBindBufferMemory2KHR, PFN_vkBindBufferMemory2, "vkBindBufferMemory2"); + VMA_FETCH_DEVICE_FUNC(vkBindImageMemory2KHR, PFN_vkBindImageMemory2, "vkBindImageMemory2"); + } +#endif + +#if VMA_MEMORY_BUDGET || VMA_VULKAN_VERSION >= 1001000 + if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) + { + VMA_FETCH_INSTANCE_FUNC(vkGetPhysicalDeviceMemoryProperties2KHR, PFN_vkGetPhysicalDeviceMemoryProperties2KHR, "vkGetPhysicalDeviceMemoryProperties2"); + } + else if(m_UseExtMemoryBudget) + { + VMA_FETCH_INSTANCE_FUNC(vkGetPhysicalDeviceMemoryProperties2KHR, PFN_vkGetPhysicalDeviceMemoryProperties2KHR, "vkGetPhysicalDeviceMemoryProperties2KHR"); + } +#endif + +#if VMA_DEDICATED_ALLOCATION + if(m_UseKhrDedicatedAllocation) + { + VMA_FETCH_DEVICE_FUNC(vkGetBufferMemoryRequirements2KHR, PFN_vkGetBufferMemoryRequirements2KHR, "vkGetBufferMemoryRequirements2KHR"); + VMA_FETCH_DEVICE_FUNC(vkGetImageMemoryRequirements2KHR, PFN_vkGetImageMemoryRequirements2KHR, "vkGetImageMemoryRequirements2KHR"); + } +#endif + +#if VMA_BIND_MEMORY2 + if(m_UseKhrBindMemory2) + { + VMA_FETCH_DEVICE_FUNC(vkBindBufferMemory2KHR, PFN_vkBindBufferMemory2KHR, "vkBindBufferMemory2KHR"); + VMA_FETCH_DEVICE_FUNC(vkBindImageMemory2KHR, PFN_vkBindImageMemory2KHR, "vkBindImageMemory2KHR"); + } +#endif // #if VMA_BIND_MEMORY2 + +#if VMA_MEMORY_BUDGET || VMA_VULKAN_VERSION >= 1001000 + if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) + { + VMA_FETCH_INSTANCE_FUNC(vkGetPhysicalDeviceMemoryProperties2KHR, PFN_vkGetPhysicalDeviceMemoryProperties2KHR, "vkGetPhysicalDeviceMemoryProperties2"); + } + else if(m_UseExtMemoryBudget) + { + VMA_FETCH_INSTANCE_FUNC(vkGetPhysicalDeviceMemoryProperties2KHR, PFN_vkGetPhysicalDeviceMemoryProperties2KHR, "vkGetPhysicalDeviceMemoryProperties2KHR"); + } +#endif // #if VMA_MEMORY_BUDGET + +#if VMA_VULKAN_VERSION >= 1003000 + if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 3, 0)) + { + VMA_FETCH_DEVICE_FUNC(vkGetDeviceBufferMemoryRequirements, PFN_vkGetDeviceBufferMemoryRequirements, "vkGetDeviceBufferMemoryRequirements"); + VMA_FETCH_DEVICE_FUNC(vkGetDeviceImageMemoryRequirements, PFN_vkGetDeviceImageMemoryRequirements, "vkGetDeviceImageMemoryRequirements"); + } +#endif +#if VMA_KHR_MAINTENANCE4 + if(m_UseKhrMaintenance4) + { + VMA_FETCH_DEVICE_FUNC(vkGetDeviceBufferMemoryRequirements, PFN_vkGetDeviceBufferMemoryRequirementsKHR, "vkGetDeviceBufferMemoryRequirementsKHR"); + VMA_FETCH_DEVICE_FUNC(vkGetDeviceImageMemoryRequirements, PFN_vkGetDeviceImageMemoryRequirementsKHR, "vkGetDeviceImageMemoryRequirementsKHR"); + } +#endif +#if VMA_EXTERNAL_MEMORY_WIN32 + if (m_UseKhrExternalMemoryWin32) + { + VMA_FETCH_DEVICE_FUNC(vkGetMemoryWin32HandleKHR, PFN_vkGetMemoryWin32HandleKHR, "vkGetMemoryWin32HandleKHR"); + } +#endif +#undef VMA_FETCH_DEVICE_FUNC +#undef VMA_FETCH_INSTANCE_FUNC +} + +#endif // VMA_DYNAMIC_VULKAN_FUNCTIONS == 1 + +void VmaAllocator_T::ValidateVulkanFunctions() +{ + VMA_ASSERT(m_VulkanFunctions.vkGetPhysicalDeviceProperties != VMA_NULL); + VMA_ASSERT(m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties != VMA_NULL); + VMA_ASSERT(m_VulkanFunctions.vkAllocateMemory != VMA_NULL); + VMA_ASSERT(m_VulkanFunctions.vkFreeMemory != VMA_NULL); + VMA_ASSERT(m_VulkanFunctions.vkMapMemory != VMA_NULL); + VMA_ASSERT(m_VulkanFunctions.vkUnmapMemory != VMA_NULL); + VMA_ASSERT(m_VulkanFunctions.vkFlushMappedMemoryRanges != VMA_NULL); + VMA_ASSERT(m_VulkanFunctions.vkInvalidateMappedMemoryRanges != VMA_NULL); + VMA_ASSERT(m_VulkanFunctions.vkBindBufferMemory != VMA_NULL); + VMA_ASSERT(m_VulkanFunctions.vkBindImageMemory != VMA_NULL); + VMA_ASSERT(m_VulkanFunctions.vkGetBufferMemoryRequirements != VMA_NULL); + VMA_ASSERT(m_VulkanFunctions.vkGetImageMemoryRequirements != VMA_NULL); + VMA_ASSERT(m_VulkanFunctions.vkCreateBuffer != VMA_NULL); + VMA_ASSERT(m_VulkanFunctions.vkDestroyBuffer != VMA_NULL); + VMA_ASSERT(m_VulkanFunctions.vkCreateImage != VMA_NULL); + VMA_ASSERT(m_VulkanFunctions.vkDestroyImage != VMA_NULL); + VMA_ASSERT(m_VulkanFunctions.vkCmdCopyBuffer != VMA_NULL); + +#if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000 + if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0) || m_UseKhrDedicatedAllocation) + { + VMA_ASSERT(m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR != VMA_NULL); + VMA_ASSERT(m_VulkanFunctions.vkGetImageMemoryRequirements2KHR != VMA_NULL); + } +#endif + +#if VMA_BIND_MEMORY2 || VMA_VULKAN_VERSION >= 1001000 + if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0) || m_UseKhrBindMemory2) + { + VMA_ASSERT(m_VulkanFunctions.vkBindBufferMemory2KHR != VMA_NULL); + VMA_ASSERT(m_VulkanFunctions.vkBindImageMemory2KHR != VMA_NULL); + } +#endif + +#if VMA_MEMORY_BUDGET || VMA_VULKAN_VERSION >= 1001000 + if(m_UseExtMemoryBudget || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) + { + VMA_ASSERT(m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties2KHR != VMA_NULL); + } +#endif +#if VMA_EXTERNAL_MEMORY_WIN32 + if (m_UseKhrExternalMemoryWin32) + { + VMA_ASSERT(m_VulkanFunctions.vkGetMemoryWin32HandleKHR != VMA_NULL); + } +#endif + + // Not validating these due to suspected driver bugs with these function + // pointers being null despite correct extension or Vulkan version is enabled. + // See issue #397. Their usage in VMA is optional anyway. + // + // VMA_ASSERT(m_VulkanFunctions.vkGetDeviceBufferMemoryRequirements != VMA_NULL); + // VMA_ASSERT(m_VulkanFunctions.vkGetDeviceImageMemoryRequirements != VMA_NULL); +} + +VkDeviceSize VmaAllocator_T::CalcPreferredBlockSize(uint32_t memTypeIndex) +{ + const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(memTypeIndex); + const VkDeviceSize heapSize = m_MemProps.memoryHeaps[heapIndex].size; + const bool isSmallHeap = heapSize <= VMA_SMALL_HEAP_MAX_SIZE; + return VmaAlignUp(isSmallHeap ? (heapSize / 8) : m_PreferredLargeHeapBlockSize, (VkDeviceSize)32); +} + +VkResult VmaAllocator_T::AllocateMemoryOfType( + VmaPool pool, + VkDeviceSize size, + VkDeviceSize alignment, + bool dedicatedPreferred, + VkBuffer dedicatedBuffer, + VkImage dedicatedImage, + VmaBufferImageUsage dedicatedBufferImageUsage, + const VmaAllocationCreateInfo& createInfo, + uint32_t memTypeIndex, + VmaSuballocationType suballocType, + VmaDedicatedAllocationList& dedicatedAllocations, + VmaBlockVector& blockVector, + size_t allocationCount, + VmaAllocation* pAllocations) +{ + VMA_ASSERT(pAllocations != VMA_NULL); + VMA_DEBUG_LOG_FORMAT(" AllocateMemory: MemoryTypeIndex=%" PRIu32 ", AllocationCount=%zu, Size=%" PRIu64, memTypeIndex, allocationCount, size); + + VmaAllocationCreateInfo finalCreateInfo = createInfo; + VkResult res = CalcMemTypeParams( + finalCreateInfo, + memTypeIndex, + size, + allocationCount); + if(res != VK_SUCCESS) + return res; + + if((finalCreateInfo.flags & VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT) != 0) + { + return AllocateDedicatedMemory( + pool, + size, + suballocType, + dedicatedAllocations, + memTypeIndex, + (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0, + (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0, + (finalCreateInfo.flags & + (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0, + (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_CAN_ALIAS_BIT) != 0, + finalCreateInfo.pUserData, + finalCreateInfo.priority, + dedicatedBuffer, + dedicatedImage, + dedicatedBufferImageUsage, + allocationCount, + pAllocations, + blockVector.GetAllocationNextPtr()); + } + else + { + const bool canAllocateDedicated = + (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) == 0 && + (pool == VK_NULL_HANDLE || !blockVector.HasExplicitBlockSize()); + + if(canAllocateDedicated) + { + // Heuristics: Allocate dedicated memory if requested size if greater than half of preferred block size. + if(size > blockVector.GetPreferredBlockSize() / 2) + { + dedicatedPreferred = true; + } + // Protection against creating each allocation as dedicated when we reach or exceed heap size/budget, + // which can quickly deplete maxMemoryAllocationCount: Don't prefer dedicated allocations when above + // 3/4 of the maximum allocation count. + if(m_PhysicalDeviceProperties.limits.maxMemoryAllocationCount < UINT32_MAX / 4 && + m_DeviceMemoryCount.load() > m_PhysicalDeviceProperties.limits.maxMemoryAllocationCount * 3 / 4) + { + dedicatedPreferred = false; + } + + if(dedicatedPreferred) + { + res = AllocateDedicatedMemory( + pool, + size, + suballocType, + dedicatedAllocations, + memTypeIndex, + (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0, + (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0, + (finalCreateInfo.flags & + (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0, + (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_CAN_ALIAS_BIT) != 0, + finalCreateInfo.pUserData, + finalCreateInfo.priority, + dedicatedBuffer, + dedicatedImage, + dedicatedBufferImageUsage, + allocationCount, + pAllocations, + blockVector.GetAllocationNextPtr()); + if(res == VK_SUCCESS) + { + // Succeeded: AllocateDedicatedMemory function already filled pMemory, nothing more to do here. + VMA_DEBUG_LOG(" Allocated as DedicatedMemory"); + return VK_SUCCESS; + } + } + } + + res = blockVector.Allocate( + size, + alignment, + finalCreateInfo, + suballocType, + allocationCount, + pAllocations); + if(res == VK_SUCCESS) + return VK_SUCCESS; + + // Try dedicated memory. + if(canAllocateDedicated && !dedicatedPreferred) + { + res = AllocateDedicatedMemory( + pool, + size, + suballocType, + dedicatedAllocations, + memTypeIndex, + (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0, + (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0, + (finalCreateInfo.flags & + (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0, + (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_CAN_ALIAS_BIT) != 0, + finalCreateInfo.pUserData, + finalCreateInfo.priority, + dedicatedBuffer, + dedicatedImage, + dedicatedBufferImageUsage, + allocationCount, + pAllocations, + blockVector.GetAllocationNextPtr()); + if(res == VK_SUCCESS) + { + // Succeeded: AllocateDedicatedMemory function already filled pMemory, nothing more to do here. + VMA_DEBUG_LOG(" Allocated as DedicatedMemory"); + return VK_SUCCESS; + } + } + // Everything failed: Return error code. + VMA_DEBUG_LOG(" vkAllocateMemory FAILED"); + return res; + } +} + +VkResult VmaAllocator_T::AllocateDedicatedMemory( + VmaPool pool, + VkDeviceSize size, + VmaSuballocationType suballocType, + VmaDedicatedAllocationList& dedicatedAllocations, + uint32_t memTypeIndex, + bool map, + bool isUserDataString, + bool isMappingAllowed, + bool canAliasMemory, + void* pUserData, + float priority, + VkBuffer dedicatedBuffer, + VkImage dedicatedImage, + VmaBufferImageUsage dedicatedBufferImageUsage, + size_t allocationCount, + VmaAllocation* pAllocations, + const void* pNextChain) +{ + VMA_ASSERT(allocationCount > 0 && pAllocations); + + VkMemoryAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO }; + allocInfo.memoryTypeIndex = memTypeIndex; + allocInfo.allocationSize = size; + allocInfo.pNext = pNextChain; + +#if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000 + VkMemoryDedicatedAllocateInfoKHR dedicatedAllocInfo = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR }; + if(!canAliasMemory) + { + if(m_UseKhrDedicatedAllocation || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) + { + if(dedicatedBuffer != VK_NULL_HANDLE) + { + VMA_ASSERT(dedicatedImage == VK_NULL_HANDLE); + dedicatedAllocInfo.buffer = dedicatedBuffer; + VmaPnextChainPushFront(&allocInfo, &dedicatedAllocInfo); + } + else if(dedicatedImage != VK_NULL_HANDLE) + { + dedicatedAllocInfo.image = dedicatedImage; + VmaPnextChainPushFront(&allocInfo, &dedicatedAllocInfo); + } + } + } +#endif // #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000 + +#if VMA_BUFFER_DEVICE_ADDRESS + VkMemoryAllocateFlagsInfoKHR allocFlagsInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO_KHR }; + if(m_UseKhrBufferDeviceAddress) + { + bool canContainBufferWithDeviceAddress = true; + if(dedicatedBuffer != VK_NULL_HANDLE) + { + canContainBufferWithDeviceAddress = dedicatedBufferImageUsage == VmaBufferImageUsage::UNKNOWN || + dedicatedBufferImageUsage.Contains(VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_EXT); + } + else if(dedicatedImage != VK_NULL_HANDLE) + { + canContainBufferWithDeviceAddress = false; + } + if(canContainBufferWithDeviceAddress) + { + allocFlagsInfo.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT_KHR; + VmaPnextChainPushFront(&allocInfo, &allocFlagsInfo); + } + } +#endif // #if VMA_BUFFER_DEVICE_ADDRESS + +#if VMA_MEMORY_PRIORITY + VkMemoryPriorityAllocateInfoEXT priorityInfo = { VK_STRUCTURE_TYPE_MEMORY_PRIORITY_ALLOCATE_INFO_EXT }; + if(m_UseExtMemoryPriority) + { + VMA_ASSERT(priority >= 0.f && priority <= 1.f); + priorityInfo.priority = priority; + VmaPnextChainPushFront(&allocInfo, &priorityInfo); + } +#endif // #if VMA_MEMORY_PRIORITY + +#if VMA_EXTERNAL_MEMORY + // Attach VkExportMemoryAllocateInfoKHR if necessary. + VkExportMemoryAllocateInfoKHR exportMemoryAllocInfo = { VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR }; + exportMemoryAllocInfo.handleTypes = GetExternalMemoryHandleTypeFlags(memTypeIndex); + if(exportMemoryAllocInfo.handleTypes != 0) + { + VmaPnextChainPushFront(&allocInfo, &exportMemoryAllocInfo); + } +#endif // #if VMA_EXTERNAL_MEMORY + + size_t allocIndex; + VkResult res = VK_SUCCESS; + for(allocIndex = 0; allocIndex < allocationCount; ++allocIndex) + { + res = AllocateDedicatedMemoryPage( + pool, + size, + suballocType, + memTypeIndex, + allocInfo, + map, + isUserDataString, + isMappingAllowed, + pUserData, + pAllocations + allocIndex); + if(res != VK_SUCCESS) + { + break; + } + } + + if(res == VK_SUCCESS) + { + for (allocIndex = 0; allocIndex < allocationCount; ++allocIndex) + { + dedicatedAllocations.Register(pAllocations[allocIndex]); + } + VMA_DEBUG_LOG_FORMAT(" Allocated DedicatedMemory Count=%zu, MemoryTypeIndex=#%" PRIu32, allocationCount, memTypeIndex); + } + else + { + // Free all already created allocations. + while(allocIndex--) + { + VmaAllocation currAlloc = pAllocations[allocIndex]; + VkDeviceMemory hMemory = currAlloc->GetMemory(); + + /* + There is no need to call this, because Vulkan spec allows to skip vkUnmapMemory + before vkFreeMemory. + + if(currAlloc->GetMappedData() != VMA_NULL) + { + (*m_VulkanFunctions.vkUnmapMemory)(m_hDevice, hMemory); + } + */ + + FreeVulkanMemory(memTypeIndex, currAlloc->GetSize(), hMemory); + m_Budget.RemoveAllocation(MemoryTypeIndexToHeapIndex(memTypeIndex), currAlloc->GetSize()); + m_AllocationObjectAllocator.Free(currAlloc); + } + + memset(pAllocations, 0, sizeof(VmaAllocation) * allocationCount); + } + + return res; +} + +VkResult VmaAllocator_T::AllocateDedicatedMemoryPage( + VmaPool pool, + VkDeviceSize size, + VmaSuballocationType suballocType, + uint32_t memTypeIndex, + const VkMemoryAllocateInfo& allocInfo, + bool map, + bool isUserDataString, + bool isMappingAllowed, + void* pUserData, + VmaAllocation* pAllocation) +{ + VkDeviceMemory hMemory = VK_NULL_HANDLE; + VkResult res = AllocateVulkanMemory(&allocInfo, &hMemory); + if(res < 0) + { + VMA_DEBUG_LOG(" vkAllocateMemory FAILED"); + return res; + } + + void* pMappedData = VMA_NULL; + if(map) + { + res = (*m_VulkanFunctions.vkMapMemory)( + m_hDevice, + hMemory, + 0, + VK_WHOLE_SIZE, + 0, + &pMappedData); + if(res < 0) + { + VMA_DEBUG_LOG(" vkMapMemory FAILED"); + FreeVulkanMemory(memTypeIndex, size, hMemory); + return res; + } + } + + *pAllocation = m_AllocationObjectAllocator.Allocate(isMappingAllowed); + (*pAllocation)->InitDedicatedAllocation(this, pool, memTypeIndex, hMemory, suballocType, pMappedData, size); + if (isUserDataString) + (*pAllocation)->SetName(this, (const char*)pUserData); + else + (*pAllocation)->SetUserData(this, pUserData); + m_Budget.AddAllocation(MemoryTypeIndexToHeapIndex(memTypeIndex), size); + if(VMA_DEBUG_INITIALIZE_ALLOCATIONS) + { + FillAllocation(*pAllocation, VMA_ALLOCATION_FILL_PATTERN_CREATED); + } + + return VK_SUCCESS; +} + +void VmaAllocator_T::GetBufferMemoryRequirements( + VkBuffer hBuffer, + VkMemoryRequirements& memReq, + bool& requiresDedicatedAllocation, + bool& prefersDedicatedAllocation) const +{ +#if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000 + if(m_UseKhrDedicatedAllocation || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) + { + VkBufferMemoryRequirementsInfo2KHR memReqInfo = { VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2_KHR }; + memReqInfo.buffer = hBuffer; + + VkMemoryDedicatedRequirementsKHR memDedicatedReq = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR }; + + VkMemoryRequirements2KHR memReq2 = { VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR }; + VmaPnextChainPushFront(&memReq2, &memDedicatedReq); + + (*m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR)(m_hDevice, &memReqInfo, &memReq2); + + memReq = memReq2.memoryRequirements; + requiresDedicatedAllocation = (memDedicatedReq.requiresDedicatedAllocation != VK_FALSE); + prefersDedicatedAllocation = (memDedicatedReq.prefersDedicatedAllocation != VK_FALSE); + } + else +#endif // #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000 + { + (*m_VulkanFunctions.vkGetBufferMemoryRequirements)(m_hDevice, hBuffer, &memReq); + requiresDedicatedAllocation = false; + prefersDedicatedAllocation = false; + } +} + +void VmaAllocator_T::GetImageMemoryRequirements( + VkImage hImage, + VkMemoryRequirements& memReq, + bool& requiresDedicatedAllocation, + bool& prefersDedicatedAllocation) const +{ +#if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000 + if(m_UseKhrDedicatedAllocation || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) + { + VkImageMemoryRequirementsInfo2KHR memReqInfo = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2_KHR }; + memReqInfo.image = hImage; + + VkMemoryDedicatedRequirementsKHR memDedicatedReq = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR }; + + VkMemoryRequirements2KHR memReq2 = { VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR }; + VmaPnextChainPushFront(&memReq2, &memDedicatedReq); + + (*m_VulkanFunctions.vkGetImageMemoryRequirements2KHR)(m_hDevice, &memReqInfo, &memReq2); + + memReq = memReq2.memoryRequirements; + requiresDedicatedAllocation = (memDedicatedReq.requiresDedicatedAllocation != VK_FALSE); + prefersDedicatedAllocation = (memDedicatedReq.prefersDedicatedAllocation != VK_FALSE); + } + else +#endif // #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000 + { + (*m_VulkanFunctions.vkGetImageMemoryRequirements)(m_hDevice, hImage, &memReq); + requiresDedicatedAllocation = false; + prefersDedicatedAllocation = false; + } +} + +VkResult VmaAllocator_T::FindMemoryTypeIndex( + uint32_t memoryTypeBits, + const VmaAllocationCreateInfo* pAllocationCreateInfo, + VmaBufferImageUsage bufImgUsage, + uint32_t* pMemoryTypeIndex) const +{ + memoryTypeBits &= GetGlobalMemoryTypeBits(); + + if(pAllocationCreateInfo->memoryTypeBits != 0) + { + memoryTypeBits &= pAllocationCreateInfo->memoryTypeBits; + } + + VkMemoryPropertyFlags requiredFlags = 0, preferredFlags = 0, notPreferredFlags = 0; + if(!FindMemoryPreferences( + IsIntegratedGpu(), + *pAllocationCreateInfo, + bufImgUsage, + requiredFlags, preferredFlags, notPreferredFlags)) + { + return VK_ERROR_FEATURE_NOT_PRESENT; + } + + *pMemoryTypeIndex = UINT32_MAX; + uint32_t minCost = UINT32_MAX; + for(uint32_t memTypeIndex = 0, memTypeBit = 1; + memTypeIndex < GetMemoryTypeCount(); + ++memTypeIndex, memTypeBit <<= 1) + { + // This memory type is acceptable according to memoryTypeBits bitmask. + if((memTypeBit & memoryTypeBits) != 0) + { + const VkMemoryPropertyFlags currFlags = + m_MemProps.memoryTypes[memTypeIndex].propertyFlags; + // This memory type contains requiredFlags. + if((requiredFlags & ~currFlags) == 0) + { + // Calculate cost as number of bits from preferredFlags not present in this memory type. + uint32_t currCost = VMA_COUNT_BITS_SET(preferredFlags & ~currFlags) + + VMA_COUNT_BITS_SET(currFlags & notPreferredFlags); + // Remember memory type with lowest cost. + if(currCost < minCost) + { + *pMemoryTypeIndex = memTypeIndex; + if(currCost == 0) + { + return VK_SUCCESS; + } + minCost = currCost; + } + } + } + } + return (*pMemoryTypeIndex != UINT32_MAX) ? VK_SUCCESS : VK_ERROR_FEATURE_NOT_PRESENT; +} + +VkResult VmaAllocator_T::CalcMemTypeParams( + VmaAllocationCreateInfo& inoutCreateInfo, + uint32_t memTypeIndex, + VkDeviceSize size, + size_t allocationCount) +{ + // If memory type is not HOST_VISIBLE, disable MAPPED. + if((inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0 && + (m_MemProps.memoryTypes[memTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0) + { + inoutCreateInfo.flags &= ~VMA_ALLOCATION_CREATE_MAPPED_BIT; + } + + if((inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT) != 0 && + (inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT) != 0) + { + const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(memTypeIndex); + VmaBudget heapBudget = {}; + GetHeapBudgets(&heapBudget, heapIndex, 1); + if(heapBudget.usage + size * allocationCount > heapBudget.budget) + { + return VK_ERROR_OUT_OF_DEVICE_MEMORY; + } + } + return VK_SUCCESS; +} + +VkResult VmaAllocator_T::CalcAllocationParams( + VmaAllocationCreateInfo& inoutCreateInfo, + bool dedicatedRequired, + bool dedicatedPreferred) +{ + VMA_ASSERT((inoutCreateInfo.flags & + (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != + (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT) && + "Specifying both flags VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT and VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT is incorrect."); + VMA_ASSERT((((inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT) == 0 || + (inoutCreateInfo.flags & (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0)) && + "Specifying VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT requires also VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT."); + if(inoutCreateInfo.usage == VMA_MEMORY_USAGE_AUTO || inoutCreateInfo.usage == VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE || inoutCreateInfo.usage == VMA_MEMORY_USAGE_AUTO_PREFER_HOST) + { + if((inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0) + { + VMA_ASSERT((inoutCreateInfo.flags & (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0 && + "When using VMA_ALLOCATION_CREATE_MAPPED_BIT and usage = VMA_MEMORY_USAGE_AUTO*, you must also specify VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT."); + } + } + + // If memory is lazily allocated, it should be always dedicated. + if(dedicatedRequired || + inoutCreateInfo.usage == VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED) + { + inoutCreateInfo.flags |= VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT; + } + + if(inoutCreateInfo.pool != VK_NULL_HANDLE) + { + if(inoutCreateInfo.pool->m_BlockVector.HasExplicitBlockSize() && + (inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT) != 0) + { + VMA_ASSERT(0 && "Specifying VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT while current custom pool doesn't support dedicated allocations."); + return VK_ERROR_FEATURE_NOT_PRESENT; + } + inoutCreateInfo.priority = inoutCreateInfo.pool->m_BlockVector.GetPriority(); + } + + if((inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT) != 0 && + (inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0) + { + VMA_ASSERT(0 && "Specifying VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT together with VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT makes no sense."); + return VK_ERROR_FEATURE_NOT_PRESENT; + } + + if(VMA_DEBUG_ALWAYS_DEDICATED_MEMORY && + (inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0) + { + inoutCreateInfo.flags |= VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT; + } + + // Non-auto USAGE values imply HOST_ACCESS flags. + // And so does VMA_MEMORY_USAGE_UNKNOWN because it is used with custom pools. + // Which specific flag is used doesn't matter. They change things only when used with VMA_MEMORY_USAGE_AUTO*. + // Otherwise they just protect from assert on mapping. + if(inoutCreateInfo.usage != VMA_MEMORY_USAGE_AUTO && + inoutCreateInfo.usage != VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE && + inoutCreateInfo.usage != VMA_MEMORY_USAGE_AUTO_PREFER_HOST) + { + if((inoutCreateInfo.flags & (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) == 0) + { + inoutCreateInfo.flags |= VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT; + } + } + + return VK_SUCCESS; +} + +VkResult VmaAllocator_T::AllocateMemory( + const VkMemoryRequirements& vkMemReq, + bool requiresDedicatedAllocation, + bool prefersDedicatedAllocation, + VkBuffer dedicatedBuffer, + VkImage dedicatedImage, + VmaBufferImageUsage dedicatedBufferImageUsage, + const VmaAllocationCreateInfo& createInfo, + VmaSuballocationType suballocType, + size_t allocationCount, + VmaAllocation* pAllocations) +{ + memset(pAllocations, 0, sizeof(VmaAllocation) * allocationCount); + + VMA_ASSERT(VmaIsPow2(vkMemReq.alignment)); + + if(vkMemReq.size == 0) + { + return VK_ERROR_INITIALIZATION_FAILED; + } + + VmaAllocationCreateInfo createInfoFinal = createInfo; + VkResult res = CalcAllocationParams(createInfoFinal, requiresDedicatedAllocation, prefersDedicatedAllocation); + if(res != VK_SUCCESS) + return res; + + if(createInfoFinal.pool != VK_NULL_HANDLE) + { + VmaBlockVector& blockVector = createInfoFinal.pool->m_BlockVector; + return AllocateMemoryOfType( + createInfoFinal.pool, + vkMemReq.size, + vkMemReq.alignment, + prefersDedicatedAllocation, + dedicatedBuffer, + dedicatedImage, + dedicatedBufferImageUsage, + createInfoFinal, + blockVector.GetMemoryTypeIndex(), + suballocType, + createInfoFinal.pool->m_DedicatedAllocations, + blockVector, + allocationCount, + pAllocations); + } + else + { + // Bit mask of memory Vulkan types acceptable for this allocation. + uint32_t memoryTypeBits = vkMemReq.memoryTypeBits; + uint32_t memTypeIndex = UINT32_MAX; + res = FindMemoryTypeIndex(memoryTypeBits, &createInfoFinal, dedicatedBufferImageUsage, &memTypeIndex); + // Can't find any single memory type matching requirements. res is VK_ERROR_FEATURE_NOT_PRESENT. + if(res != VK_SUCCESS) + return res; + do + { + VmaBlockVector* blockVector = m_pBlockVectors[memTypeIndex]; + VMA_ASSERT(blockVector && "Trying to use unsupported memory type!"); + res = AllocateMemoryOfType( + VK_NULL_HANDLE, + vkMemReq.size, + vkMemReq.alignment, + requiresDedicatedAllocation || prefersDedicatedAllocation, + dedicatedBuffer, + dedicatedImage, + dedicatedBufferImageUsage, + createInfoFinal, + memTypeIndex, + suballocType, + m_DedicatedAllocations[memTypeIndex], + *blockVector, + allocationCount, + pAllocations); + // Allocation succeeded + if(res == VK_SUCCESS) + return VK_SUCCESS; + + // Remove old memTypeIndex from list of possibilities. + memoryTypeBits &= ~(1u << memTypeIndex); + // Find alternative memTypeIndex. + res = FindMemoryTypeIndex(memoryTypeBits, &createInfoFinal, dedicatedBufferImageUsage, &memTypeIndex); + } while(res == VK_SUCCESS); + + // No other matching memory type index could be found. + // Not returning res, which is VK_ERROR_FEATURE_NOT_PRESENT, because we already failed to allocate once. + return VK_ERROR_OUT_OF_DEVICE_MEMORY; + } +} + +void VmaAllocator_T::FreeMemory( + size_t allocationCount, + const VmaAllocation* pAllocations) +{ + VMA_ASSERT(pAllocations); + + for(size_t allocIndex = allocationCount; allocIndex--; ) + { + VmaAllocation allocation = pAllocations[allocIndex]; + + if(allocation != VK_NULL_HANDLE) + { + if(VMA_DEBUG_INITIALIZE_ALLOCATIONS) + { + FillAllocation(allocation, VMA_ALLOCATION_FILL_PATTERN_DESTROYED); + } + + switch(allocation->GetType()) + { + case VmaAllocation_T::ALLOCATION_TYPE_BLOCK: + { + VmaBlockVector* pBlockVector = VMA_NULL; + VmaPool hPool = allocation->GetParentPool(); + if(hPool != VK_NULL_HANDLE) + { + pBlockVector = &hPool->m_BlockVector; + } + else + { + const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex(); + pBlockVector = m_pBlockVectors[memTypeIndex]; + VMA_ASSERT(pBlockVector && "Trying to free memory of unsupported type!"); + } + pBlockVector->Free(allocation); + } + break; + case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED: + FreeDedicatedMemory(allocation); + break; + default: + VMA_ASSERT(0); + } + } + } +} + +void VmaAllocator_T::CalculateStatistics(VmaTotalStatistics* pStats) +{ + // Initialize. + VmaClearDetailedStatistics(pStats->total); + for(uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; ++i) + VmaClearDetailedStatistics(pStats->memoryType[i]); + for(uint32_t i = 0; i < VK_MAX_MEMORY_HEAPS; ++i) + VmaClearDetailedStatistics(pStats->memoryHeap[i]); + + // Process default pools. + for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex) + { + VmaBlockVector* const pBlockVector = m_pBlockVectors[memTypeIndex]; + if (pBlockVector != VMA_NULL) + pBlockVector->AddDetailedStatistics(pStats->memoryType[memTypeIndex]); + } + + // Process custom pools. + { + VmaMutexLockRead lock(m_PoolsMutex, m_UseMutex); + for(VmaPool pool = m_Pools.Front(); pool != VMA_NULL; pool = m_Pools.GetNext(pool)) + { + VmaBlockVector& blockVector = pool->m_BlockVector; + const uint32_t memTypeIndex = blockVector.GetMemoryTypeIndex(); + blockVector.AddDetailedStatistics(pStats->memoryType[memTypeIndex]); + pool->m_DedicatedAllocations.AddDetailedStatistics(pStats->memoryType[memTypeIndex]); + } + } + + // Process dedicated allocations. + for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex) + { + m_DedicatedAllocations[memTypeIndex].AddDetailedStatistics(pStats->memoryType[memTypeIndex]); + } + + // Sum from memory types to memory heaps. + for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex) + { + const uint32_t memHeapIndex = m_MemProps.memoryTypes[memTypeIndex].heapIndex; + VmaAddDetailedStatistics(pStats->memoryHeap[memHeapIndex], pStats->memoryType[memTypeIndex]); + } + + // Sum from memory heaps to total. + for(uint32_t memHeapIndex = 0; memHeapIndex < GetMemoryHeapCount(); ++memHeapIndex) + VmaAddDetailedStatistics(pStats->total, pStats->memoryHeap[memHeapIndex]); + + VMA_ASSERT(pStats->total.statistics.allocationCount == 0 || + pStats->total.allocationSizeMax >= pStats->total.allocationSizeMin); + VMA_ASSERT(pStats->total.unusedRangeCount == 0 || + pStats->total.unusedRangeSizeMax >= pStats->total.unusedRangeSizeMin); +} + +void VmaAllocator_T::GetHeapBudgets(VmaBudget* outBudgets, uint32_t firstHeap, uint32_t heapCount) +{ +#if VMA_MEMORY_BUDGET + if(m_UseExtMemoryBudget) + { + if(m_Budget.m_OperationsSinceBudgetFetch < 30) + { + VmaMutexLockRead lockRead(m_Budget.m_BudgetMutex, m_UseMutex); + for(uint32_t i = 0; i < heapCount; ++i, ++outBudgets) + { + const uint32_t heapIndex = firstHeap + i; + + outBudgets->statistics.blockCount = m_Budget.m_BlockCount[heapIndex]; + outBudgets->statistics.allocationCount = m_Budget.m_AllocationCount[heapIndex]; + outBudgets->statistics.blockBytes = m_Budget.m_BlockBytes[heapIndex]; + outBudgets->statistics.allocationBytes = m_Budget.m_AllocationBytes[heapIndex]; + + if(m_Budget.m_VulkanUsage[heapIndex] + outBudgets->statistics.blockBytes > m_Budget.m_BlockBytesAtBudgetFetch[heapIndex]) + { + outBudgets->usage = m_Budget.m_VulkanUsage[heapIndex] + + outBudgets->statistics.blockBytes - m_Budget.m_BlockBytesAtBudgetFetch[heapIndex]; + } + else + { + outBudgets->usage = 0; + } + + // Have to take MIN with heap size because explicit HeapSizeLimit is included in it. + outBudgets->budget = VMA_MIN( + m_Budget.m_VulkanBudget[heapIndex], m_MemProps.memoryHeaps[heapIndex].size); + } + } + else + { + UpdateVulkanBudget(); // Outside of mutex lock + GetHeapBudgets(outBudgets, firstHeap, heapCount); // Recursion + } + } + else +#endif + { + for(uint32_t i = 0; i < heapCount; ++i, ++outBudgets) + { + const uint32_t heapIndex = firstHeap + i; + + outBudgets->statistics.blockCount = m_Budget.m_BlockCount[heapIndex]; + outBudgets->statistics.allocationCount = m_Budget.m_AllocationCount[heapIndex]; + outBudgets->statistics.blockBytes = m_Budget.m_BlockBytes[heapIndex]; + outBudgets->statistics.allocationBytes = m_Budget.m_AllocationBytes[heapIndex]; + + outBudgets->usage = outBudgets->statistics.blockBytes; + outBudgets->budget = m_MemProps.memoryHeaps[heapIndex].size * 8 / 10; // 80% heuristics. + } + } +} + +void VmaAllocator_T::GetAllocationInfo(VmaAllocation hAllocation, VmaAllocationInfo* pAllocationInfo) +{ + pAllocationInfo->memoryType = hAllocation->GetMemoryTypeIndex(); + pAllocationInfo->deviceMemory = hAllocation->GetMemory(); + pAllocationInfo->offset = hAllocation->GetOffset(); + pAllocationInfo->size = hAllocation->GetSize(); + pAllocationInfo->pMappedData = hAllocation->GetMappedData(); + pAllocationInfo->pUserData = hAllocation->GetUserData(); + pAllocationInfo->pName = hAllocation->GetName(); +} + +void VmaAllocator_T::GetAllocationInfo2(VmaAllocation hAllocation, VmaAllocationInfo2* pAllocationInfo) +{ + GetAllocationInfo(hAllocation, &pAllocationInfo->allocationInfo); + + switch (hAllocation->GetType()) + { + case VmaAllocation_T::ALLOCATION_TYPE_BLOCK: + pAllocationInfo->blockSize = hAllocation->GetBlock()->m_pMetadata->GetSize(); + pAllocationInfo->dedicatedMemory = VK_FALSE; + break; + case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED: + pAllocationInfo->blockSize = pAllocationInfo->allocationInfo.size; + pAllocationInfo->dedicatedMemory = VK_TRUE; + break; + default: + VMA_ASSERT(0); + } +} + +VkResult VmaAllocator_T::CreatePool(const VmaPoolCreateInfo* pCreateInfo, VmaPool* pPool) +{ + VMA_DEBUG_LOG_FORMAT(" CreatePool: MemoryTypeIndex=%" PRIu32 ", flags=%" PRIu32, pCreateInfo->memoryTypeIndex, pCreateInfo->flags); + + VmaPoolCreateInfo newCreateInfo = *pCreateInfo; + + // Protection against uninitialized new structure member. If garbage data are left there, this pointer dereference would crash. + if(pCreateInfo->pMemoryAllocateNext) + { + VMA_ASSERT(((const VkBaseInStructure*)pCreateInfo->pMemoryAllocateNext)->sType != 0); + } + + if(newCreateInfo.maxBlockCount == 0) + { + newCreateInfo.maxBlockCount = SIZE_MAX; + } + if(newCreateInfo.minBlockCount > newCreateInfo.maxBlockCount) + { + return VK_ERROR_INITIALIZATION_FAILED; + } + // Memory type index out of range or forbidden. + if(pCreateInfo->memoryTypeIndex >= GetMemoryTypeCount() || + ((1u << pCreateInfo->memoryTypeIndex) & m_GlobalMemoryTypeBits) == 0) + { + return VK_ERROR_FEATURE_NOT_PRESENT; + } + if(newCreateInfo.minAllocationAlignment > 0) + { + VMA_ASSERT(VmaIsPow2(newCreateInfo.minAllocationAlignment)); + } + + const VkDeviceSize preferredBlockSize = CalcPreferredBlockSize(newCreateInfo.memoryTypeIndex); + + *pPool = vma_new(this, VmaPool_T)(this, newCreateInfo, preferredBlockSize); + + VkResult res = (*pPool)->m_BlockVector.CreateMinBlocks(); + if(res != VK_SUCCESS) + { + vma_delete(this, *pPool); + *pPool = VMA_NULL; + return res; + } + + // Add to m_Pools. + { + VmaMutexLockWrite lock(m_PoolsMutex, m_UseMutex); + (*pPool)->SetId(m_NextPoolId++); + m_Pools.PushBack(*pPool); + } + + return VK_SUCCESS; +} + +void VmaAllocator_T::DestroyPool(VmaPool pool) +{ + // Remove from m_Pools. + { + VmaMutexLockWrite lock(m_PoolsMutex, m_UseMutex); + m_Pools.Remove(pool); + } + + vma_delete(this, pool); +} + +void VmaAllocator_T::GetPoolStatistics(VmaPool pool, VmaStatistics* pPoolStats) +{ + VmaClearStatistics(*pPoolStats); + pool->m_BlockVector.AddStatistics(*pPoolStats); + pool->m_DedicatedAllocations.AddStatistics(*pPoolStats); +} + +void VmaAllocator_T::CalculatePoolStatistics(VmaPool pool, VmaDetailedStatistics* pPoolStats) +{ + VmaClearDetailedStatistics(*pPoolStats); + pool->m_BlockVector.AddDetailedStatistics(*pPoolStats); + pool->m_DedicatedAllocations.AddDetailedStatistics(*pPoolStats); +} + +void VmaAllocator_T::SetCurrentFrameIndex(uint32_t frameIndex) +{ + m_CurrentFrameIndex.store(frameIndex); + +#if VMA_MEMORY_BUDGET + if(m_UseExtMemoryBudget) + { + UpdateVulkanBudget(); + } +#endif // #if VMA_MEMORY_BUDGET +} + +VkResult VmaAllocator_T::CheckPoolCorruption(VmaPool hPool) +{ + return hPool->m_BlockVector.CheckCorruption(); +} + +VkResult VmaAllocator_T::CheckCorruption(uint32_t memoryTypeBits) +{ + VkResult finalRes = VK_ERROR_FEATURE_NOT_PRESENT; + + // Process default pools. + for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex) + { + VmaBlockVector* const pBlockVector = m_pBlockVectors[memTypeIndex]; + if(pBlockVector != VMA_NULL) + { + VkResult localRes = pBlockVector->CheckCorruption(); + switch(localRes) + { + case VK_ERROR_FEATURE_NOT_PRESENT: + break; + case VK_SUCCESS: + finalRes = VK_SUCCESS; + break; + default: + return localRes; + } + } + } + + // Process custom pools. + { + VmaMutexLockRead lock(m_PoolsMutex, m_UseMutex); + for(VmaPool pool = m_Pools.Front(); pool != VMA_NULL; pool = m_Pools.GetNext(pool)) + { + if(((1u << pool->m_BlockVector.GetMemoryTypeIndex()) & memoryTypeBits) != 0) + { + VkResult localRes = pool->m_BlockVector.CheckCorruption(); + switch(localRes) + { + case VK_ERROR_FEATURE_NOT_PRESENT: + break; + case VK_SUCCESS: + finalRes = VK_SUCCESS; + break; + default: + return localRes; + } + } + } + } + + return finalRes; +} + +VkResult VmaAllocator_T::AllocateVulkanMemory(const VkMemoryAllocateInfo* pAllocateInfo, VkDeviceMemory* pMemory) +{ + AtomicTransactionalIncrement deviceMemoryCountIncrement; + const uint64_t prevDeviceMemoryCount = deviceMemoryCountIncrement.Increment(&m_DeviceMemoryCount); +#if VMA_DEBUG_DONT_EXCEED_MAX_MEMORY_ALLOCATION_COUNT + if(prevDeviceMemoryCount >= m_PhysicalDeviceProperties.limits.maxMemoryAllocationCount) + { + return VK_ERROR_TOO_MANY_OBJECTS; + } +#endif + + const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(pAllocateInfo->memoryTypeIndex); + + // HeapSizeLimit is in effect for this heap. + if((m_HeapSizeLimitMask & (1u << heapIndex)) != 0) + { + const VkDeviceSize heapSize = m_MemProps.memoryHeaps[heapIndex].size; + VkDeviceSize blockBytes = m_Budget.m_BlockBytes[heapIndex]; + for(;;) + { + const VkDeviceSize blockBytesAfterAllocation = blockBytes + pAllocateInfo->allocationSize; + if(blockBytesAfterAllocation > heapSize) + { + return VK_ERROR_OUT_OF_DEVICE_MEMORY; + } + if(m_Budget.m_BlockBytes[heapIndex].compare_exchange_strong(blockBytes, blockBytesAfterAllocation)) + { + break; + } + } + } + else + { + m_Budget.m_BlockBytes[heapIndex] += pAllocateInfo->allocationSize; + } + ++m_Budget.m_BlockCount[heapIndex]; + + // VULKAN CALL vkAllocateMemory. + VkResult res = (*m_VulkanFunctions.vkAllocateMemory)(m_hDevice, pAllocateInfo, GetAllocationCallbacks(), pMemory); + + if(res == VK_SUCCESS) + { +#if VMA_MEMORY_BUDGET + ++m_Budget.m_OperationsSinceBudgetFetch; +#endif + + // Informative callback. + if(m_DeviceMemoryCallbacks.pfnAllocate != VMA_NULL) + { + (*m_DeviceMemoryCallbacks.pfnAllocate)(this, pAllocateInfo->memoryTypeIndex, *pMemory, pAllocateInfo->allocationSize, m_DeviceMemoryCallbacks.pUserData); + } + + deviceMemoryCountIncrement.Commit(); + } + else + { + --m_Budget.m_BlockCount[heapIndex]; + m_Budget.m_BlockBytes[heapIndex] -= pAllocateInfo->allocationSize; + } + + return res; +} + +void VmaAllocator_T::FreeVulkanMemory(uint32_t memoryType, VkDeviceSize size, VkDeviceMemory hMemory) +{ + // Informative callback. + if(m_DeviceMemoryCallbacks.pfnFree != VMA_NULL) + { + (*m_DeviceMemoryCallbacks.pfnFree)(this, memoryType, hMemory, size, m_DeviceMemoryCallbacks.pUserData); + } + + // VULKAN CALL vkFreeMemory. + (*m_VulkanFunctions.vkFreeMemory)(m_hDevice, hMemory, GetAllocationCallbacks()); + + const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(memoryType); + --m_Budget.m_BlockCount[heapIndex]; + m_Budget.m_BlockBytes[heapIndex] -= size; + + --m_DeviceMemoryCount; +} + +VkResult VmaAllocator_T::BindVulkanBuffer( + VkDeviceMemory memory, + VkDeviceSize memoryOffset, + VkBuffer buffer, + const void* pNext) +{ + if(pNext != VMA_NULL) + { +#if VMA_VULKAN_VERSION >= 1001000 || VMA_BIND_MEMORY2 + if((m_UseKhrBindMemory2 || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) && + m_VulkanFunctions.vkBindBufferMemory2KHR != VMA_NULL) + { + VkBindBufferMemoryInfoKHR bindBufferMemoryInfo = { VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO_KHR }; + bindBufferMemoryInfo.pNext = pNext; + bindBufferMemoryInfo.buffer = buffer; + bindBufferMemoryInfo.memory = memory; + bindBufferMemoryInfo.memoryOffset = memoryOffset; + return (*m_VulkanFunctions.vkBindBufferMemory2KHR)(m_hDevice, 1, &bindBufferMemoryInfo); + } + else +#endif // #if VMA_VULKAN_VERSION >= 1001000 || VMA_BIND_MEMORY2 + { + return VK_ERROR_EXTENSION_NOT_PRESENT; + } + } + else + { + return (*m_VulkanFunctions.vkBindBufferMemory)(m_hDevice, buffer, memory, memoryOffset); + } +} + +VkResult VmaAllocator_T::BindVulkanImage( + VkDeviceMemory memory, + VkDeviceSize memoryOffset, + VkImage image, + const void* pNext) +{ + if(pNext != VMA_NULL) + { +#if VMA_VULKAN_VERSION >= 1001000 || VMA_BIND_MEMORY2 + if((m_UseKhrBindMemory2 || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) && + m_VulkanFunctions.vkBindImageMemory2KHR != VMA_NULL) + { + VkBindImageMemoryInfoKHR bindBufferMemoryInfo = { VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO_KHR }; + bindBufferMemoryInfo.pNext = pNext; + bindBufferMemoryInfo.image = image; + bindBufferMemoryInfo.memory = memory; + bindBufferMemoryInfo.memoryOffset = memoryOffset; + return (*m_VulkanFunctions.vkBindImageMemory2KHR)(m_hDevice, 1, &bindBufferMemoryInfo); + } + else +#endif // #if VMA_BIND_MEMORY2 + { + return VK_ERROR_EXTENSION_NOT_PRESENT; + } + } + else + { + return (*m_VulkanFunctions.vkBindImageMemory)(m_hDevice, image, memory, memoryOffset); + } +} + +VkResult VmaAllocator_T::Map(VmaAllocation hAllocation, void** ppData) +{ + switch(hAllocation->GetType()) + { + case VmaAllocation_T::ALLOCATION_TYPE_BLOCK: + { + VmaDeviceMemoryBlock* const pBlock = hAllocation->GetBlock(); + char *pBytes = VMA_NULL; + VkResult res = pBlock->Map(this, 1, (void**)&pBytes); + if(res == VK_SUCCESS) + { + *ppData = pBytes + (ptrdiff_t)hAllocation->GetOffset(); + hAllocation->BlockAllocMap(); + } + return res; + } + case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED: + return hAllocation->DedicatedAllocMap(this, ppData); + default: + VMA_ASSERT(0); + return VK_ERROR_MEMORY_MAP_FAILED; + } +} + +void VmaAllocator_T::Unmap(VmaAllocation hAllocation) +{ + switch(hAllocation->GetType()) + { + case VmaAllocation_T::ALLOCATION_TYPE_BLOCK: + { + VmaDeviceMemoryBlock* const pBlock = hAllocation->GetBlock(); + hAllocation->BlockAllocUnmap(); + pBlock->Unmap(this, 1); + } + break; + case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED: + hAllocation->DedicatedAllocUnmap(this); + break; + default: + VMA_ASSERT(0); + } +} + +VkResult VmaAllocator_T::BindBufferMemory( + VmaAllocation hAllocation, + VkDeviceSize allocationLocalOffset, + VkBuffer hBuffer, + const void* pNext) +{ + VkResult res = VK_ERROR_UNKNOWN_COPY; + switch(hAllocation->GetType()) + { + case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED: + res = BindVulkanBuffer(hAllocation->GetMemory(), allocationLocalOffset, hBuffer, pNext); + break; + case VmaAllocation_T::ALLOCATION_TYPE_BLOCK: + { + VmaDeviceMemoryBlock* const pBlock = hAllocation->GetBlock(); + VMA_ASSERT(pBlock && "Binding buffer to allocation that doesn't belong to any block."); + res = pBlock->BindBufferMemory(this, hAllocation, allocationLocalOffset, hBuffer, pNext); + break; + } + default: + VMA_ASSERT(0); + } + return res; +} + +VkResult VmaAllocator_T::BindImageMemory( + VmaAllocation hAllocation, + VkDeviceSize allocationLocalOffset, + VkImage hImage, + const void* pNext) +{ + VkResult res = VK_ERROR_UNKNOWN_COPY; + switch(hAllocation->GetType()) + { + case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED: + res = BindVulkanImage(hAllocation->GetMemory(), allocationLocalOffset, hImage, pNext); + break; + case VmaAllocation_T::ALLOCATION_TYPE_BLOCK: + { + VmaDeviceMemoryBlock* pBlock = hAllocation->GetBlock(); + VMA_ASSERT(pBlock && "Binding image to allocation that doesn't belong to any block."); + res = pBlock->BindImageMemory(this, hAllocation, allocationLocalOffset, hImage, pNext); + break; + } + default: + VMA_ASSERT(0); + } + return res; +} + +VkResult VmaAllocator_T::FlushOrInvalidateAllocation( + VmaAllocation hAllocation, + VkDeviceSize offset, VkDeviceSize size, + VMA_CACHE_OPERATION op) +{ + VkResult res = VK_SUCCESS; + + VkMappedMemoryRange memRange = {}; + if(GetFlushOrInvalidateRange(hAllocation, offset, size, memRange)) + { + switch(op) + { + case VMA_CACHE_FLUSH: + res = (*GetVulkanFunctions().vkFlushMappedMemoryRanges)(m_hDevice, 1, &memRange); + break; + case VMA_CACHE_INVALIDATE: + res = (*GetVulkanFunctions().vkInvalidateMappedMemoryRanges)(m_hDevice, 1, &memRange); + break; + default: + VMA_ASSERT(0); + } + } + // else: Just ignore this call. + return res; +} + +VkResult VmaAllocator_T::FlushOrInvalidateAllocations( + uint32_t allocationCount, + const VmaAllocation* allocations, + const VkDeviceSize* offsets, const VkDeviceSize* sizes, + VMA_CACHE_OPERATION op) +{ + typedef VmaStlAllocator RangeAllocator; + typedef VmaSmallVector RangeVector; + RangeVector ranges = RangeVector(RangeAllocator(GetAllocationCallbacks())); + + for(uint32_t allocIndex = 0; allocIndex < allocationCount; ++allocIndex) + { + const VmaAllocation alloc = allocations[allocIndex]; + const VkDeviceSize offset = offsets != VMA_NULL ? offsets[allocIndex] : 0; + const VkDeviceSize size = sizes != VMA_NULL ? sizes[allocIndex] : VK_WHOLE_SIZE; + VkMappedMemoryRange newRange; + if(GetFlushOrInvalidateRange(alloc, offset, size, newRange)) + { + ranges.push_back(newRange); + } + } + + VkResult res = VK_SUCCESS; + if(!ranges.empty()) + { + switch(op) + { + case VMA_CACHE_FLUSH: + res = (*GetVulkanFunctions().vkFlushMappedMemoryRanges)(m_hDevice, (uint32_t)ranges.size(), ranges.data()); + break; + case VMA_CACHE_INVALIDATE: + res = (*GetVulkanFunctions().vkInvalidateMappedMemoryRanges)(m_hDevice, (uint32_t)ranges.size(), ranges.data()); + break; + default: + VMA_ASSERT(0); + } + } + // else: Just ignore this call. + return res; +} + +VkResult VmaAllocator_T::CopyMemoryToAllocation( + const void* pSrcHostPointer, + VmaAllocation dstAllocation, + VkDeviceSize dstAllocationLocalOffset, + VkDeviceSize size) +{ + void* dstMappedData = VMA_NULL; + VkResult res = Map(dstAllocation, &dstMappedData); + if(res == VK_SUCCESS) + { + memcpy((char*)dstMappedData + dstAllocationLocalOffset, pSrcHostPointer, (size_t)size); + Unmap(dstAllocation); + res = FlushOrInvalidateAllocation(dstAllocation, dstAllocationLocalOffset, size, VMA_CACHE_FLUSH); + } + return res; +} + +VkResult VmaAllocator_T::CopyAllocationToMemory( + VmaAllocation srcAllocation, + VkDeviceSize srcAllocationLocalOffset, + void* pDstHostPointer, + VkDeviceSize size) +{ + void* srcMappedData = VMA_NULL; + VkResult res = Map(srcAllocation, &srcMappedData); + if(res == VK_SUCCESS) + { + res = FlushOrInvalidateAllocation(srcAllocation, srcAllocationLocalOffset, size, VMA_CACHE_INVALIDATE); + if(res == VK_SUCCESS) + { + memcpy(pDstHostPointer, (const char*)srcMappedData + srcAllocationLocalOffset, (size_t)size); + Unmap(srcAllocation); + } + } + return res; +} + +void VmaAllocator_T::FreeDedicatedMemory(const VmaAllocation allocation) +{ + VMA_ASSERT(allocation && allocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED); + + const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex(); + VmaPool parentPool = allocation->GetParentPool(); + if(parentPool == VK_NULL_HANDLE) + { + // Default pool + m_DedicatedAllocations[memTypeIndex].Unregister(allocation); + } + else + { + // Custom pool + parentPool->m_DedicatedAllocations.Unregister(allocation); + } + + VkDeviceMemory hMemory = allocation->GetMemory(); + + /* + There is no need to call this, because Vulkan spec allows to skip vkUnmapMemory + before vkFreeMemory. + + if(allocation->GetMappedData() != VMA_NULL) + { + (*m_VulkanFunctions.vkUnmapMemory)(m_hDevice, hMemory); + } + */ + + FreeVulkanMemory(memTypeIndex, allocation->GetSize(), hMemory); + + m_Budget.RemoveAllocation(MemoryTypeIndexToHeapIndex(allocation->GetMemoryTypeIndex()), allocation->GetSize()); + allocation->Destroy(this); + m_AllocationObjectAllocator.Free(allocation); + + VMA_DEBUG_LOG_FORMAT(" Freed DedicatedMemory MemoryTypeIndex=%" PRIu32, memTypeIndex); +} + +uint32_t VmaAllocator_T::CalculateGpuDefragmentationMemoryTypeBits() const +{ + VkBufferCreateInfo dummyBufCreateInfo; + VmaFillGpuDefragmentationBufferCreateInfo(dummyBufCreateInfo); + + uint32_t memoryTypeBits = 0; + + // Create buffer. + VkBuffer buf = VK_NULL_HANDLE; + VkResult res = (*GetVulkanFunctions().vkCreateBuffer)( + m_hDevice, &dummyBufCreateInfo, GetAllocationCallbacks(), &buf); + if(res == VK_SUCCESS) + { + // Query for supported memory types. + VkMemoryRequirements memReq; + (*GetVulkanFunctions().vkGetBufferMemoryRequirements)(m_hDevice, buf, &memReq); + memoryTypeBits = memReq.memoryTypeBits; + + // Destroy buffer. + (*GetVulkanFunctions().vkDestroyBuffer)(m_hDevice, buf, GetAllocationCallbacks()); + } + + return memoryTypeBits; +} + +uint32_t VmaAllocator_T::CalculateGlobalMemoryTypeBits() const +{ + // Make sure memory information is already fetched. + VMA_ASSERT(GetMemoryTypeCount() > 0); + + uint32_t memoryTypeBits = UINT32_MAX; + + if(!m_UseAmdDeviceCoherentMemory) + { + // Exclude memory types that have VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD. + for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex) + { + if((m_MemProps.memoryTypes[memTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD_COPY) != 0) + { + memoryTypeBits &= ~(1u << memTypeIndex); + } + } + } + + return memoryTypeBits; +} + +bool VmaAllocator_T::GetFlushOrInvalidateRange( + VmaAllocation allocation, + VkDeviceSize offset, VkDeviceSize size, + VkMappedMemoryRange& outRange) const +{ + const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex(); + if(size > 0 && IsMemoryTypeNonCoherent(memTypeIndex)) + { + const VkDeviceSize nonCoherentAtomSize = m_PhysicalDeviceProperties.limits.nonCoherentAtomSize; + const VkDeviceSize allocationSize = allocation->GetSize(); + VMA_ASSERT(offset <= allocationSize); + + outRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; + outRange.pNext = VMA_NULL; + outRange.memory = allocation->GetMemory(); + + switch(allocation->GetType()) + { + case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED: + outRange.offset = VmaAlignDown(offset, nonCoherentAtomSize); + if(size == VK_WHOLE_SIZE) + { + outRange.size = allocationSize - outRange.offset; + } + else + { + VMA_ASSERT(offset + size <= allocationSize); + outRange.size = VMA_MIN( + VmaAlignUp(size + (offset - outRange.offset), nonCoherentAtomSize), + allocationSize - outRange.offset); + } + break; + case VmaAllocation_T::ALLOCATION_TYPE_BLOCK: + { + // 1. Still within this allocation. + outRange.offset = VmaAlignDown(offset, nonCoherentAtomSize); + if(size == VK_WHOLE_SIZE) + { + size = allocationSize - offset; + } + else + { + VMA_ASSERT(offset + size <= allocationSize); + } + outRange.size = VmaAlignUp(size + (offset - outRange.offset), nonCoherentAtomSize); + + // 2. Adjust to whole block. + const VkDeviceSize allocationOffset = allocation->GetOffset(); + VMA_ASSERT(allocationOffset % nonCoherentAtomSize == 0); + const VkDeviceSize blockSize = allocation->GetBlock()->m_pMetadata->GetSize(); + outRange.offset += allocationOffset; + outRange.size = VMA_MIN(outRange.size, blockSize - outRange.offset); + + break; + } + default: + VMA_ASSERT(0); + } + return true; + } + return false; +} + +#if VMA_MEMORY_BUDGET +void VmaAllocator_T::UpdateVulkanBudget() +{ + VMA_ASSERT(m_UseExtMemoryBudget); + + VkPhysicalDeviceMemoryProperties2KHR memProps = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2_KHR }; + + VkPhysicalDeviceMemoryBudgetPropertiesEXT budgetProps = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT }; + VmaPnextChainPushFront(&memProps, &budgetProps); + + GetVulkanFunctions().vkGetPhysicalDeviceMemoryProperties2KHR(m_PhysicalDevice, &memProps); + + { + VmaMutexLockWrite lockWrite(m_Budget.m_BudgetMutex, m_UseMutex); + + for(uint32_t heapIndex = 0; heapIndex < GetMemoryHeapCount(); ++heapIndex) + { + m_Budget.m_VulkanUsage[heapIndex] = budgetProps.heapUsage[heapIndex]; + m_Budget.m_VulkanBudget[heapIndex] = budgetProps.heapBudget[heapIndex]; + m_Budget.m_BlockBytesAtBudgetFetch[heapIndex] = m_Budget.m_BlockBytes[heapIndex].load(); + + // Some bugged drivers return the budget incorrectly, e.g. 0 or much bigger than heap size. + if(m_Budget.m_VulkanBudget[heapIndex] == 0) + { + m_Budget.m_VulkanBudget[heapIndex] = m_MemProps.memoryHeaps[heapIndex].size * 8 / 10; // 80% heuristics. + } + else if(m_Budget.m_VulkanBudget[heapIndex] > m_MemProps.memoryHeaps[heapIndex].size) + { + m_Budget.m_VulkanBudget[heapIndex] = m_MemProps.memoryHeaps[heapIndex].size; + } + if(m_Budget.m_VulkanUsage[heapIndex] == 0 && m_Budget.m_BlockBytesAtBudgetFetch[heapIndex] > 0) + { + m_Budget.m_VulkanUsage[heapIndex] = m_Budget.m_BlockBytesAtBudgetFetch[heapIndex]; + } + } + m_Budget.m_OperationsSinceBudgetFetch = 0; + } +} +#endif // VMA_MEMORY_BUDGET + +void VmaAllocator_T::FillAllocation(const VmaAllocation hAllocation, uint8_t pattern) +{ + if(VMA_DEBUG_INITIALIZE_ALLOCATIONS && + hAllocation->IsMappingAllowed() && + (m_MemProps.memoryTypes[hAllocation->GetMemoryTypeIndex()].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0) + { + void* pData = VMA_NULL; + VkResult res = Map(hAllocation, &pData); + if(res == VK_SUCCESS) + { + memset(pData, (int)pattern, (size_t)hAllocation->GetSize()); + FlushOrInvalidateAllocation(hAllocation, 0, VK_WHOLE_SIZE, VMA_CACHE_FLUSH); + Unmap(hAllocation); + } + else + { + VMA_ASSERT(0 && "VMA_DEBUG_INITIALIZE_ALLOCATIONS is enabled, but couldn't map memory to fill allocation."); + } + } +} + +uint32_t VmaAllocator_T::GetGpuDefragmentationMemoryTypeBits() +{ + uint32_t memoryTypeBits = m_GpuDefragmentationMemoryTypeBits.load(); + if(memoryTypeBits == UINT32_MAX) + { + memoryTypeBits = CalculateGpuDefragmentationMemoryTypeBits(); + m_GpuDefragmentationMemoryTypeBits.store(memoryTypeBits); + } + return memoryTypeBits; +} + +#if VMA_STATS_STRING_ENABLED +void VmaAllocator_T::PrintDetailedMap(VmaJsonWriter& json) +{ + json.WriteString("DefaultPools"); + json.BeginObject(); + { + for (uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex) + { + VmaBlockVector* pBlockVector = m_pBlockVectors[memTypeIndex]; + VmaDedicatedAllocationList& dedicatedAllocList = m_DedicatedAllocations[memTypeIndex]; + if (pBlockVector != VMA_NULL) + { + json.BeginString("Type "); + json.ContinueString(memTypeIndex); + json.EndString(); + json.BeginObject(); + { + json.WriteString("PreferredBlockSize"); + json.WriteNumber(pBlockVector->GetPreferredBlockSize()); + + json.WriteString("Blocks"); + pBlockVector->PrintDetailedMap(json); + + json.WriteString("DedicatedAllocations"); + dedicatedAllocList.BuildStatsString(json); + } + json.EndObject(); + } + } + } + json.EndObject(); + + json.WriteString("CustomPools"); + json.BeginObject(); + { + VmaMutexLockRead lock(m_PoolsMutex, m_UseMutex); + if (!m_Pools.IsEmpty()) + { + for (uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex) + { + bool displayType = true; + size_t index = 0; + for (VmaPool pool = m_Pools.Front(); pool != VMA_NULL; pool = m_Pools.GetNext(pool)) + { + VmaBlockVector& blockVector = pool->m_BlockVector; + if (blockVector.GetMemoryTypeIndex() == memTypeIndex) + { + if (displayType) + { + json.BeginString("Type "); + json.ContinueString(memTypeIndex); + json.EndString(); + json.BeginArray(); + displayType = false; + } + + json.BeginObject(); + { + json.WriteString("Name"); + json.BeginString(); + json.ContinueString((uint64_t)index++); + if (pool->GetName()) + { + json.ContinueString(" - "); + json.ContinueString(pool->GetName()); + } + json.EndString(); + + json.WriteString("PreferredBlockSize"); + json.WriteNumber(blockVector.GetPreferredBlockSize()); + + json.WriteString("Blocks"); + blockVector.PrintDetailedMap(json); + + json.WriteString("DedicatedAllocations"); + pool->m_DedicatedAllocations.BuildStatsString(json); + } + json.EndObject(); + } + } + + if (!displayType) + json.EndArray(); + } + } + } + json.EndObject(); +} +#endif // VMA_STATS_STRING_ENABLED +#endif // _VMA_ALLOCATOR_T_FUNCTIONS + + +#ifndef _VMA_PUBLIC_INTERFACE +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAllocator( + const VmaAllocatorCreateInfo* pCreateInfo, + VmaAllocator* pAllocator) +{ + VMA_ASSERT(pCreateInfo && pAllocator); + VMA_ASSERT(pCreateInfo->vulkanApiVersion == 0 || + (VK_VERSION_MAJOR(pCreateInfo->vulkanApiVersion) == 1 && VK_VERSION_MINOR(pCreateInfo->vulkanApiVersion) <= 3)); + VMA_DEBUG_LOG("vmaCreateAllocator"); + *pAllocator = vma_new(pCreateInfo->pAllocationCallbacks, VmaAllocator_T)(pCreateInfo); + VkResult result = (*pAllocator)->Init(pCreateInfo); + if(result < 0) + { + vma_delete(pCreateInfo->pAllocationCallbacks, *pAllocator); + *pAllocator = VK_NULL_HANDLE; + } + return result; +} + +VMA_CALL_PRE void VMA_CALL_POST vmaDestroyAllocator( + VmaAllocator allocator) +{ + if(allocator != VK_NULL_HANDLE) + { + VMA_DEBUG_LOG("vmaDestroyAllocator"); + VkAllocationCallbacks allocationCallbacks = allocator->m_AllocationCallbacks; // Have to copy the callbacks when destroying. + vma_delete(&allocationCallbacks, allocator); + } +} + +VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocatorInfo(VmaAllocator allocator, VmaAllocatorInfo* pAllocatorInfo) +{ + VMA_ASSERT(allocator && pAllocatorInfo); + pAllocatorInfo->instance = allocator->m_hInstance; + pAllocatorInfo->physicalDevice = allocator->GetPhysicalDevice(); + pAllocatorInfo->device = allocator->m_hDevice; +} + +VMA_CALL_PRE void VMA_CALL_POST vmaGetPhysicalDeviceProperties( + VmaAllocator allocator, + const VkPhysicalDeviceProperties **ppPhysicalDeviceProperties) +{ + VMA_ASSERT(allocator && ppPhysicalDeviceProperties); + *ppPhysicalDeviceProperties = &allocator->m_PhysicalDeviceProperties; +} + +VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryProperties( + VmaAllocator allocator, + const VkPhysicalDeviceMemoryProperties** ppPhysicalDeviceMemoryProperties) +{ + VMA_ASSERT(allocator && ppPhysicalDeviceMemoryProperties); + *ppPhysicalDeviceMemoryProperties = &allocator->m_MemProps; +} + +VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryTypeProperties( + VmaAllocator allocator, + uint32_t memoryTypeIndex, + VkMemoryPropertyFlags* pFlags) +{ + VMA_ASSERT(allocator && pFlags); + VMA_ASSERT(memoryTypeIndex < allocator->GetMemoryTypeCount()); + *pFlags = allocator->m_MemProps.memoryTypes[memoryTypeIndex].propertyFlags; +} + +VMA_CALL_PRE void VMA_CALL_POST vmaSetCurrentFrameIndex( + VmaAllocator allocator, + uint32_t frameIndex) +{ + VMA_ASSERT(allocator); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + allocator->SetCurrentFrameIndex(frameIndex); +} + +VMA_CALL_PRE void VMA_CALL_POST vmaCalculateStatistics( + VmaAllocator allocator, + VmaTotalStatistics* pStats) +{ + VMA_ASSERT(allocator && pStats); + VMA_DEBUG_GLOBAL_MUTEX_LOCK + allocator->CalculateStatistics(pStats); +} + +VMA_CALL_PRE void VMA_CALL_POST vmaGetHeapBudgets( + VmaAllocator allocator, + VmaBudget* pBudgets) +{ + VMA_ASSERT(allocator && pBudgets); + VMA_DEBUG_GLOBAL_MUTEX_LOCK + allocator->GetHeapBudgets(pBudgets, 0, allocator->GetMemoryHeapCount()); +} + +#if VMA_STATS_STRING_ENABLED + +VMA_CALL_PRE void VMA_CALL_POST vmaBuildStatsString( + VmaAllocator allocator, + char** ppStatsString, + VkBool32 detailedMap) +{ + VMA_ASSERT(allocator && ppStatsString); + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + VmaStringBuilder sb(allocator->GetAllocationCallbacks()); + { + VmaBudget budgets[VK_MAX_MEMORY_HEAPS]; + allocator->GetHeapBudgets(budgets, 0, allocator->GetMemoryHeapCount()); + + VmaTotalStatistics stats; + allocator->CalculateStatistics(&stats); + + VmaJsonWriter json(allocator->GetAllocationCallbacks(), sb); + json.BeginObject(); + { + json.WriteString("General"); + json.BeginObject(); + { + const VkPhysicalDeviceProperties& deviceProperties = allocator->m_PhysicalDeviceProperties; + const VkPhysicalDeviceMemoryProperties& memoryProperties = allocator->m_MemProps; + + json.WriteString("API"); + json.WriteString("Vulkan"); + + json.WriteString("apiVersion"); + json.BeginString(); + json.ContinueString(VK_VERSION_MAJOR(deviceProperties.apiVersion)); + json.ContinueString("."); + json.ContinueString(VK_VERSION_MINOR(deviceProperties.apiVersion)); + json.ContinueString("."); + json.ContinueString(VK_VERSION_PATCH(deviceProperties.apiVersion)); + json.EndString(); + + json.WriteString("GPU"); + json.WriteString(deviceProperties.deviceName); + json.WriteString("deviceType"); + json.WriteNumber(static_cast(deviceProperties.deviceType)); + + json.WriteString("maxMemoryAllocationCount"); + json.WriteNumber(deviceProperties.limits.maxMemoryAllocationCount); + json.WriteString("bufferImageGranularity"); + json.WriteNumber(deviceProperties.limits.bufferImageGranularity); + json.WriteString("nonCoherentAtomSize"); + json.WriteNumber(deviceProperties.limits.nonCoherentAtomSize); + + json.WriteString("memoryHeapCount"); + json.WriteNumber(memoryProperties.memoryHeapCount); + json.WriteString("memoryTypeCount"); + json.WriteNumber(memoryProperties.memoryTypeCount); + } + json.EndObject(); + } + { + json.WriteString("Total"); + VmaPrintDetailedStatistics(json, stats.total); + } + { + json.WriteString("MemoryInfo"); + json.BeginObject(); + { + for (uint32_t heapIndex = 0; heapIndex < allocator->GetMemoryHeapCount(); ++heapIndex) + { + json.BeginString("Heap "); + json.ContinueString(heapIndex); + json.EndString(); + json.BeginObject(); + { + const VkMemoryHeap& heapInfo = allocator->m_MemProps.memoryHeaps[heapIndex]; + json.WriteString("Flags"); + json.BeginArray(true); + { + if (heapInfo.flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) + json.WriteString("DEVICE_LOCAL"); + #if VMA_VULKAN_VERSION >= 1001000 + if (heapInfo.flags & VK_MEMORY_HEAP_MULTI_INSTANCE_BIT) + json.WriteString("MULTI_INSTANCE"); + #endif + + VkMemoryHeapFlags flags = heapInfo.flags & + ~(VK_MEMORY_HEAP_DEVICE_LOCAL_BIT + #if VMA_VULKAN_VERSION >= 1001000 + | VK_MEMORY_HEAP_MULTI_INSTANCE_BIT + #endif + ); + if (flags != 0) + json.WriteNumber(flags); + } + json.EndArray(); + + json.WriteString("Size"); + json.WriteNumber(heapInfo.size); + + json.WriteString("Budget"); + json.BeginObject(); + { + json.WriteString("BudgetBytes"); + json.WriteNumber(budgets[heapIndex].budget); + json.WriteString("UsageBytes"); + json.WriteNumber(budgets[heapIndex].usage); + } + json.EndObject(); + + json.WriteString("Stats"); + VmaPrintDetailedStatistics(json, stats.memoryHeap[heapIndex]); + + json.WriteString("MemoryPools"); + json.BeginObject(); + { + for (uint32_t typeIndex = 0; typeIndex < allocator->GetMemoryTypeCount(); ++typeIndex) + { + if (allocator->MemoryTypeIndexToHeapIndex(typeIndex) == heapIndex) + { + json.BeginString("Type "); + json.ContinueString(typeIndex); + json.EndString(); + json.BeginObject(); + { + json.WriteString("Flags"); + json.BeginArray(true); + { + VkMemoryPropertyFlags flags = allocator->m_MemProps.memoryTypes[typeIndex].propertyFlags; + if (flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) + json.WriteString("DEVICE_LOCAL"); + if (flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) + json.WriteString("HOST_VISIBLE"); + if (flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) + json.WriteString("HOST_COHERENT"); + if (flags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) + json.WriteString("HOST_CACHED"); + if (flags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) + json.WriteString("LAZILY_ALLOCATED"); + #if VMA_VULKAN_VERSION >= 1001000 + if (flags & VK_MEMORY_PROPERTY_PROTECTED_BIT) + json.WriteString("PROTECTED"); + #endif + #if VK_AMD_device_coherent_memory + if (flags & VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD_COPY) + json.WriteString("DEVICE_COHERENT_AMD"); + if (flags & VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD_COPY) + json.WriteString("DEVICE_UNCACHED_AMD"); + #endif + + flags &= ~(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT + #if VMA_VULKAN_VERSION >= 1001000 + | VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT + #endif + #if VK_AMD_device_coherent_memory + | VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD_COPY + | VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD_COPY + #endif + | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT + | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT + | VK_MEMORY_PROPERTY_HOST_CACHED_BIT); + if (flags != 0) + json.WriteNumber(flags); + } + json.EndArray(); + + json.WriteString("Stats"); + VmaPrintDetailedStatistics(json, stats.memoryType[typeIndex]); + } + json.EndObject(); + } + } + + } + json.EndObject(); + } + json.EndObject(); + } + } + json.EndObject(); + } + + if (detailedMap == VK_TRUE) + allocator->PrintDetailedMap(json); + + json.EndObject(); + } + + *ppStatsString = VmaCreateStringCopy(allocator->GetAllocationCallbacks(), sb.GetData(), sb.GetLength()); +} + +VMA_CALL_PRE void VMA_CALL_POST vmaFreeStatsString( + VmaAllocator allocator, + char* pStatsString) +{ + if(pStatsString != VMA_NULL) + { + VMA_ASSERT(allocator); + VmaFreeString(allocator->GetAllocationCallbacks(), pStatsString); + } +} + +#endif // VMA_STATS_STRING_ENABLED + +/* +This function is not protected by any mutex because it just reads immutable data. +*/ +VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndex( + VmaAllocator allocator, + uint32_t memoryTypeBits, + const VmaAllocationCreateInfo* pAllocationCreateInfo, + uint32_t* pMemoryTypeIndex) +{ + VMA_ASSERT(allocator != VK_NULL_HANDLE); + VMA_ASSERT(pAllocationCreateInfo != VMA_NULL); + VMA_ASSERT(pMemoryTypeIndex != VMA_NULL); + + return allocator->FindMemoryTypeIndex(memoryTypeBits, pAllocationCreateInfo, VmaBufferImageUsage::UNKNOWN, pMemoryTypeIndex); +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForBufferInfo( + VmaAllocator allocator, + const VkBufferCreateInfo* pBufferCreateInfo, + const VmaAllocationCreateInfo* pAllocationCreateInfo, + uint32_t* pMemoryTypeIndex) +{ + VMA_ASSERT(allocator != VK_NULL_HANDLE); + VMA_ASSERT(pBufferCreateInfo != VMA_NULL); + VMA_ASSERT(pAllocationCreateInfo != VMA_NULL); + VMA_ASSERT(pMemoryTypeIndex != VMA_NULL); + + const VkDevice hDev = allocator->m_hDevice; + const VmaVulkanFunctions* funcs = &allocator->GetVulkanFunctions(); + VkResult res; + +#if VMA_KHR_MAINTENANCE4 || VMA_VULKAN_VERSION >= 1003000 + if(funcs->vkGetDeviceBufferMemoryRequirements) + { + // Can query straight from VkBufferCreateInfo :) + VkDeviceBufferMemoryRequirementsKHR devBufMemReq = {VK_STRUCTURE_TYPE_DEVICE_BUFFER_MEMORY_REQUIREMENTS_KHR}; + devBufMemReq.pCreateInfo = pBufferCreateInfo; + + VkMemoryRequirements2 memReq = {VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2}; + (*funcs->vkGetDeviceBufferMemoryRequirements)(hDev, &devBufMemReq, &memReq); + + res = allocator->FindMemoryTypeIndex( + memReq.memoryRequirements.memoryTypeBits, pAllocationCreateInfo, + VmaBufferImageUsage(*pBufferCreateInfo, allocator->m_UseKhrMaintenance5), pMemoryTypeIndex); + } + else +#endif // VMA_KHR_MAINTENANCE4 || VMA_VULKAN_VERSION >= 1003000 + { + // Must create a dummy buffer to query :( + VkBuffer hBuffer = VK_NULL_HANDLE; + res = funcs->vkCreateBuffer( + hDev, pBufferCreateInfo, allocator->GetAllocationCallbacks(), &hBuffer); + if(res == VK_SUCCESS) + { + VkMemoryRequirements memReq = {}; + funcs->vkGetBufferMemoryRequirements(hDev, hBuffer, &memReq); + + res = allocator->FindMemoryTypeIndex( + memReq.memoryTypeBits, pAllocationCreateInfo, + VmaBufferImageUsage(*pBufferCreateInfo, allocator->m_UseKhrMaintenance5), pMemoryTypeIndex); + + funcs->vkDestroyBuffer( + hDev, hBuffer, allocator->GetAllocationCallbacks()); + } + } + return res; +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForImageInfo( + VmaAllocator allocator, + const VkImageCreateInfo* pImageCreateInfo, + const VmaAllocationCreateInfo* pAllocationCreateInfo, + uint32_t* pMemoryTypeIndex) +{ + VMA_ASSERT(allocator != VK_NULL_HANDLE); + VMA_ASSERT(pImageCreateInfo != VMA_NULL); + VMA_ASSERT(pAllocationCreateInfo != VMA_NULL); + VMA_ASSERT(pMemoryTypeIndex != VMA_NULL); + + const VkDevice hDev = allocator->m_hDevice; + const VmaVulkanFunctions* funcs = &allocator->GetVulkanFunctions(); + VkResult res; + +#if VMA_KHR_MAINTENANCE4 || VMA_VULKAN_VERSION >= 1003000 + if(funcs->vkGetDeviceImageMemoryRequirements) + { + // Can query straight from VkImageCreateInfo :) + VkDeviceImageMemoryRequirementsKHR devImgMemReq = {VK_STRUCTURE_TYPE_DEVICE_IMAGE_MEMORY_REQUIREMENTS_KHR}; + devImgMemReq.pCreateInfo = pImageCreateInfo; + VMA_ASSERT(pImageCreateInfo->tiling != VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT_COPY && (pImageCreateInfo->flags & VK_IMAGE_CREATE_DISJOINT_BIT_COPY) == 0 && + "Cannot use this VkImageCreateInfo with vmaFindMemoryTypeIndexForImageInfo as I don't know what to pass as VkDeviceImageMemoryRequirements::planeAspect."); + + VkMemoryRequirements2 memReq = {VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2}; + (*funcs->vkGetDeviceImageMemoryRequirements)(hDev, &devImgMemReq, &memReq); + + res = allocator->FindMemoryTypeIndex( + memReq.memoryRequirements.memoryTypeBits, pAllocationCreateInfo, + VmaBufferImageUsage(*pImageCreateInfo), pMemoryTypeIndex); + } + else +#endif // VMA_KHR_MAINTENANCE4 || VMA_VULKAN_VERSION >= 1003000 + { + // Must create a dummy image to query :( + VkImage hImage = VK_NULL_HANDLE; + res = funcs->vkCreateImage( + hDev, pImageCreateInfo, allocator->GetAllocationCallbacks(), &hImage); + if(res == VK_SUCCESS) + { + VkMemoryRequirements memReq = {}; + funcs->vkGetImageMemoryRequirements(hDev, hImage, &memReq); + + res = allocator->FindMemoryTypeIndex( + memReq.memoryTypeBits, pAllocationCreateInfo, + VmaBufferImageUsage(*pImageCreateInfo), pMemoryTypeIndex); + + funcs->vkDestroyImage( + hDev, hImage, allocator->GetAllocationCallbacks()); + } + } + return res; +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreatePool( + VmaAllocator allocator, + const VmaPoolCreateInfo* pCreateInfo, + VmaPool* pPool) +{ + VMA_ASSERT(allocator && pCreateInfo && pPool); + + VMA_DEBUG_LOG("vmaCreatePool"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + return allocator->CreatePool(pCreateInfo, pPool); +} + +VMA_CALL_PRE void VMA_CALL_POST vmaDestroyPool( + VmaAllocator allocator, + VmaPool pool) +{ + VMA_ASSERT(allocator); + + if(pool == VK_NULL_HANDLE) + { + return; + } + + VMA_DEBUG_LOG("vmaDestroyPool"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + allocator->DestroyPool(pool); +} + +VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolStatistics( + VmaAllocator allocator, + VmaPool pool, + VmaStatistics* pPoolStats) +{ + VMA_ASSERT(allocator && pool && pPoolStats); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + allocator->GetPoolStatistics(pool, pPoolStats); +} + +VMA_CALL_PRE void VMA_CALL_POST vmaCalculatePoolStatistics( + VmaAllocator allocator, + VmaPool pool, + VmaDetailedStatistics* pPoolStats) +{ + VMA_ASSERT(allocator && pool && pPoolStats); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + allocator->CalculatePoolStatistics(pool, pPoolStats); +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCheckPoolCorruption(VmaAllocator allocator, VmaPool pool) +{ + VMA_ASSERT(allocator && pool); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + VMA_DEBUG_LOG("vmaCheckPoolCorruption"); + + return allocator->CheckPoolCorruption(pool); +} + +VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolName( + VmaAllocator allocator, + VmaPool pool, + const char** ppName) +{ + VMA_ASSERT(allocator && pool && ppName); + + VMA_DEBUG_LOG("vmaGetPoolName"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + *ppName = pool->GetName(); +} + +VMA_CALL_PRE void VMA_CALL_POST vmaSetPoolName( + VmaAllocator allocator, + VmaPool pool, + const char* pName) +{ + VMA_ASSERT(allocator && pool); + + VMA_DEBUG_LOG("vmaSetPoolName"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + pool->SetName(pName); +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemory( + VmaAllocator allocator, + const VkMemoryRequirements* pVkMemoryRequirements, + const VmaAllocationCreateInfo* pCreateInfo, + VmaAllocation* pAllocation, + VmaAllocationInfo* pAllocationInfo) +{ + VMA_ASSERT(allocator && pVkMemoryRequirements && pCreateInfo && pAllocation); + + VMA_DEBUG_LOG("vmaAllocateMemory"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + VkResult result = allocator->AllocateMemory( + *pVkMemoryRequirements, + false, // requiresDedicatedAllocation + false, // prefersDedicatedAllocation + VK_NULL_HANDLE, // dedicatedBuffer + VK_NULL_HANDLE, // dedicatedImage + VmaBufferImageUsage::UNKNOWN, // dedicatedBufferImageUsage + *pCreateInfo, + VMA_SUBALLOCATION_TYPE_UNKNOWN, + 1, // allocationCount + pAllocation); + + if(pAllocationInfo != VMA_NULL && result == VK_SUCCESS) + { + allocator->GetAllocationInfo(*pAllocation, pAllocationInfo); + } + + return result; +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryPages( + VmaAllocator allocator, + const VkMemoryRequirements* pVkMemoryRequirements, + const VmaAllocationCreateInfo* pCreateInfo, + size_t allocationCount, + VmaAllocation* pAllocations, + VmaAllocationInfo* pAllocationInfo) +{ + if(allocationCount == 0) + { + return VK_SUCCESS; + } + + VMA_ASSERT(allocator && pVkMemoryRequirements && pCreateInfo && pAllocations); + + VMA_DEBUG_LOG("vmaAllocateMemoryPages"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + VkResult result = allocator->AllocateMemory( + *pVkMemoryRequirements, + false, // requiresDedicatedAllocation + false, // prefersDedicatedAllocation + VK_NULL_HANDLE, // dedicatedBuffer + VK_NULL_HANDLE, // dedicatedImage + VmaBufferImageUsage::UNKNOWN, // dedicatedBufferImageUsage + *pCreateInfo, + VMA_SUBALLOCATION_TYPE_UNKNOWN, + allocationCount, + pAllocations); + + if(pAllocationInfo != VMA_NULL && result == VK_SUCCESS) + { + for(size_t i = 0; i < allocationCount; ++i) + { + allocator->GetAllocationInfo(pAllocations[i], pAllocationInfo + i); + } + } + + return result; +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForBuffer( + VmaAllocator allocator, + VkBuffer buffer, + const VmaAllocationCreateInfo* pCreateInfo, + VmaAllocation* pAllocation, + VmaAllocationInfo* pAllocationInfo) +{ + VMA_ASSERT(allocator && buffer != VK_NULL_HANDLE && pCreateInfo && pAllocation); + + VMA_DEBUG_LOG("vmaAllocateMemoryForBuffer"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + VkMemoryRequirements vkMemReq = {}; + bool requiresDedicatedAllocation = false; + bool prefersDedicatedAllocation = false; + allocator->GetBufferMemoryRequirements(buffer, vkMemReq, + requiresDedicatedAllocation, + prefersDedicatedAllocation); + + VkResult result = allocator->AllocateMemory( + vkMemReq, + requiresDedicatedAllocation, + prefersDedicatedAllocation, + buffer, // dedicatedBuffer + VK_NULL_HANDLE, // dedicatedImage + VmaBufferImageUsage::UNKNOWN, // dedicatedBufferImageUsage + *pCreateInfo, + VMA_SUBALLOCATION_TYPE_BUFFER, + 1, // allocationCount + pAllocation); + + if(pAllocationInfo && result == VK_SUCCESS) + { + allocator->GetAllocationInfo(*pAllocation, pAllocationInfo); + } + + return result; +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForImage( + VmaAllocator allocator, + VkImage image, + const VmaAllocationCreateInfo* pCreateInfo, + VmaAllocation* pAllocation, + VmaAllocationInfo* pAllocationInfo) +{ + VMA_ASSERT(allocator && image != VK_NULL_HANDLE && pCreateInfo && pAllocation); + + VMA_DEBUG_LOG("vmaAllocateMemoryForImage"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + VkMemoryRequirements vkMemReq = {}; + bool requiresDedicatedAllocation = false; + bool prefersDedicatedAllocation = false; + allocator->GetImageMemoryRequirements(image, vkMemReq, + requiresDedicatedAllocation, prefersDedicatedAllocation); + + VkResult result = allocator->AllocateMemory( + vkMemReq, + requiresDedicatedAllocation, + prefersDedicatedAllocation, + VK_NULL_HANDLE, // dedicatedBuffer + image, // dedicatedImage + VmaBufferImageUsage::UNKNOWN, // dedicatedBufferImageUsage + *pCreateInfo, + VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN, + 1, // allocationCount + pAllocation); + + if(pAllocationInfo && result == VK_SUCCESS) + { + allocator->GetAllocationInfo(*pAllocation, pAllocationInfo); + } + + return result; +} + +VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemory( + VmaAllocator allocator, + VmaAllocation allocation) +{ + VMA_ASSERT(allocator); + + if(allocation == VK_NULL_HANDLE) + { + return; + } + + VMA_DEBUG_LOG("vmaFreeMemory"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + allocator->FreeMemory( + 1, // allocationCount + &allocation); +} + +VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemoryPages( + VmaAllocator allocator, + size_t allocationCount, + const VmaAllocation* pAllocations) +{ + if(allocationCount == 0) + { + return; + } + + VMA_ASSERT(allocator); + + VMA_DEBUG_LOG("vmaFreeMemoryPages"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + allocator->FreeMemory(allocationCount, pAllocations); +} + +VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocationInfo( + VmaAllocator allocator, + VmaAllocation allocation, + VmaAllocationInfo* pAllocationInfo) +{ + VMA_ASSERT(allocator && allocation && pAllocationInfo); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + allocator->GetAllocationInfo(allocation, pAllocationInfo); +} + +VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocationInfo2( + VmaAllocator allocator, + VmaAllocation allocation, + VmaAllocationInfo2* pAllocationInfo) +{ + VMA_ASSERT(allocator && allocation && pAllocationInfo); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + allocator->GetAllocationInfo2(allocation, pAllocationInfo); +} + +VMA_CALL_PRE void VMA_CALL_POST vmaSetAllocationUserData( + VmaAllocator allocator, + VmaAllocation allocation, + void* pUserData) +{ + VMA_ASSERT(allocator && allocation); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + allocation->SetUserData(allocator, pUserData); +} + +VMA_CALL_PRE void VMA_CALL_POST vmaSetAllocationName( + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, + const char* VMA_NULLABLE pName) +{ + allocation->SetName(allocator, pName); +} + +VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocationMemoryProperties( + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, + VkMemoryPropertyFlags* VMA_NOT_NULL pFlags) +{ + VMA_ASSERT(allocator && allocation && pFlags); + const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex(); + *pFlags = allocator->m_MemProps.memoryTypes[memTypeIndex].propertyFlags; +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaMapMemory( + VmaAllocator allocator, + VmaAllocation allocation, + void** ppData) +{ + VMA_ASSERT(allocator && allocation && ppData); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + return allocator->Map(allocation, ppData); +} + +VMA_CALL_PRE void VMA_CALL_POST vmaUnmapMemory( + VmaAllocator allocator, + VmaAllocation allocation) +{ + VMA_ASSERT(allocator && allocation); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + allocator->Unmap(allocation); +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaFlushAllocation( + VmaAllocator allocator, + VmaAllocation allocation, + VkDeviceSize offset, + VkDeviceSize size) +{ + VMA_ASSERT(allocator && allocation); + + VMA_DEBUG_LOG("vmaFlushAllocation"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + return allocator->FlushOrInvalidateAllocation(allocation, offset, size, VMA_CACHE_FLUSH); +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaInvalidateAllocation( + VmaAllocator allocator, + VmaAllocation allocation, + VkDeviceSize offset, + VkDeviceSize size) +{ + VMA_ASSERT(allocator && allocation); + + VMA_DEBUG_LOG("vmaInvalidateAllocation"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + return allocator->FlushOrInvalidateAllocation(allocation, offset, size, VMA_CACHE_INVALIDATE); +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaFlushAllocations( + VmaAllocator allocator, + uint32_t allocationCount, + const VmaAllocation* allocations, + const VkDeviceSize* offsets, + const VkDeviceSize* sizes) +{ + VMA_ASSERT(allocator); + + if(allocationCount == 0) + { + return VK_SUCCESS; + } + + VMA_ASSERT(allocations); + + VMA_DEBUG_LOG("vmaFlushAllocations"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + return allocator->FlushOrInvalidateAllocations(allocationCount, allocations, offsets, sizes, VMA_CACHE_FLUSH); +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaInvalidateAllocations( + VmaAllocator allocator, + uint32_t allocationCount, + const VmaAllocation* allocations, + const VkDeviceSize* offsets, + const VkDeviceSize* sizes) +{ + VMA_ASSERT(allocator); + + if(allocationCount == 0) + { + return VK_SUCCESS; + } + + VMA_ASSERT(allocations); + + VMA_DEBUG_LOG("vmaInvalidateAllocations"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + return allocator->FlushOrInvalidateAllocations(allocationCount, allocations, offsets, sizes, VMA_CACHE_INVALIDATE); +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCopyMemoryToAllocation( + VmaAllocator allocator, + const void* pSrcHostPointer, + VmaAllocation dstAllocation, + VkDeviceSize dstAllocationLocalOffset, + VkDeviceSize size) +{ + VMA_ASSERT(allocator && pSrcHostPointer && dstAllocation); + + if(size == 0) + { + return VK_SUCCESS; + } + + VMA_DEBUG_LOG("vmaCopyMemoryToAllocation"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + return allocator->CopyMemoryToAllocation(pSrcHostPointer, dstAllocation, dstAllocationLocalOffset, size); +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCopyAllocationToMemory( + VmaAllocator allocator, + VmaAllocation srcAllocation, + VkDeviceSize srcAllocationLocalOffset, + void* pDstHostPointer, + VkDeviceSize size) +{ + VMA_ASSERT(allocator && srcAllocation && pDstHostPointer); + + if(size == 0) + { + return VK_SUCCESS; + } + + VMA_DEBUG_LOG("vmaCopyAllocationToMemory"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + return allocator->CopyAllocationToMemory(srcAllocation, srcAllocationLocalOffset, pDstHostPointer, size); +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCheckCorruption( + VmaAllocator allocator, + uint32_t memoryTypeBits) +{ + VMA_ASSERT(allocator); + + VMA_DEBUG_LOG("vmaCheckCorruption"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + return allocator->CheckCorruption(memoryTypeBits); +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaBeginDefragmentation( + VmaAllocator allocator, + const VmaDefragmentationInfo* pInfo, + VmaDefragmentationContext* pContext) +{ + VMA_ASSERT(allocator && pInfo && pContext); + + VMA_DEBUG_LOG("vmaBeginDefragmentation"); + + if (pInfo->pool != VMA_NULL) + { + // Check if run on supported algorithms + if (pInfo->pool->m_BlockVector.GetAlgorithm() & VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT) + return VK_ERROR_FEATURE_NOT_PRESENT; + } + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + *pContext = vma_new(allocator, VmaDefragmentationContext_T)(allocator, *pInfo); + return VK_SUCCESS; +} + +VMA_CALL_PRE void VMA_CALL_POST vmaEndDefragmentation( + VmaAllocator allocator, + VmaDefragmentationContext context, + VmaDefragmentationStats* pStats) +{ + VMA_ASSERT(allocator && context); + + VMA_DEBUG_LOG("vmaEndDefragmentation"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + if (pStats) + context->GetStats(*pStats); + vma_delete(allocator, context); +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaBeginDefragmentationPass( + VmaAllocator VMA_NOT_NULL allocator, + VmaDefragmentationContext VMA_NOT_NULL context, + VmaDefragmentationPassMoveInfo* VMA_NOT_NULL pPassInfo) +{ + VMA_ASSERT(context && pPassInfo); + + VMA_DEBUG_LOG("vmaBeginDefragmentationPass"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + return context->DefragmentPassBegin(*pPassInfo); +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaEndDefragmentationPass( + VmaAllocator VMA_NOT_NULL allocator, + VmaDefragmentationContext VMA_NOT_NULL context, + VmaDefragmentationPassMoveInfo* VMA_NOT_NULL pPassInfo) +{ + VMA_ASSERT(context && pPassInfo); + + VMA_DEBUG_LOG("vmaEndDefragmentationPass"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + return context->DefragmentPassEnd(*pPassInfo); +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory( + VmaAllocator allocator, + VmaAllocation allocation, + VkBuffer buffer) +{ + VMA_ASSERT(allocator && allocation && buffer); + + VMA_DEBUG_LOG("vmaBindBufferMemory"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + return allocator->BindBufferMemory(allocation, 0, buffer, VMA_NULL); +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory2( + VmaAllocator allocator, + VmaAllocation allocation, + VkDeviceSize allocationLocalOffset, + VkBuffer buffer, + const void* pNext) +{ + VMA_ASSERT(allocator && allocation && buffer); + + VMA_DEBUG_LOG("vmaBindBufferMemory2"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + return allocator->BindBufferMemory(allocation, allocationLocalOffset, buffer, pNext); +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory( + VmaAllocator allocator, + VmaAllocation allocation, + VkImage image) +{ + VMA_ASSERT(allocator && allocation && image); + + VMA_DEBUG_LOG("vmaBindImageMemory"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + return allocator->BindImageMemory(allocation, 0, image, VMA_NULL); +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory2( + VmaAllocator allocator, + VmaAllocation allocation, + VkDeviceSize allocationLocalOffset, + VkImage image, + const void* pNext) +{ + VMA_ASSERT(allocator && allocation && image); + + VMA_DEBUG_LOG("vmaBindImageMemory2"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + return allocator->BindImageMemory(allocation, allocationLocalOffset, image, pNext); +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateBuffer( + VmaAllocator allocator, + const VkBufferCreateInfo* pBufferCreateInfo, + const VmaAllocationCreateInfo* pAllocationCreateInfo, + VkBuffer* pBuffer, + VmaAllocation* pAllocation, + VmaAllocationInfo* pAllocationInfo) +{ + VMA_ASSERT(allocator && pBufferCreateInfo && pAllocationCreateInfo && pBuffer && pAllocation); + + if(pBufferCreateInfo->size == 0) + { + return VK_ERROR_INITIALIZATION_FAILED; + } + if((pBufferCreateInfo->usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_COPY) != 0 && + !allocator->m_UseKhrBufferDeviceAddress) + { + VMA_ASSERT(0 && "Creating a buffer with VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT is not valid if VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT was not used."); + return VK_ERROR_INITIALIZATION_FAILED; + } + + VMA_DEBUG_LOG("vmaCreateBuffer"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + *pBuffer = VK_NULL_HANDLE; + *pAllocation = VK_NULL_HANDLE; + + // 1. Create VkBuffer. + VkResult res = (*allocator->GetVulkanFunctions().vkCreateBuffer)( + allocator->m_hDevice, + pBufferCreateInfo, + allocator->GetAllocationCallbacks(), + pBuffer); + if(res >= 0) + { + // 2. vkGetBufferMemoryRequirements. + VkMemoryRequirements vkMemReq = {}; + bool requiresDedicatedAllocation = false; + bool prefersDedicatedAllocation = false; + allocator->GetBufferMemoryRequirements(*pBuffer, vkMemReq, + requiresDedicatedAllocation, prefersDedicatedAllocation); + + // 3. Allocate memory using allocator. + res = allocator->AllocateMemory( + vkMemReq, + requiresDedicatedAllocation, + prefersDedicatedAllocation, + *pBuffer, // dedicatedBuffer + VK_NULL_HANDLE, // dedicatedImage + VmaBufferImageUsage(*pBufferCreateInfo, allocator->m_UseKhrMaintenance5), // dedicatedBufferImageUsage + *pAllocationCreateInfo, + VMA_SUBALLOCATION_TYPE_BUFFER, + 1, // allocationCount + pAllocation); + + if(res >= 0) + { + // 3. Bind buffer with memory. + if((pAllocationCreateInfo->flags & VMA_ALLOCATION_CREATE_DONT_BIND_BIT) == 0) + { + res = allocator->BindBufferMemory(*pAllocation, 0, *pBuffer, VMA_NULL); + } + if(res >= 0) + { + // All steps succeeded. + #if VMA_STATS_STRING_ENABLED + (*pAllocation)->InitBufferUsage(*pBufferCreateInfo, allocator->m_UseKhrMaintenance5); + #endif + if(pAllocationInfo != VMA_NULL) + { + allocator->GetAllocationInfo(*pAllocation, pAllocationInfo); + } + + return VK_SUCCESS; + } + allocator->FreeMemory( + 1, // allocationCount + pAllocation); + *pAllocation = VK_NULL_HANDLE; + (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks()); + *pBuffer = VK_NULL_HANDLE; + return res; + } + (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks()); + *pBuffer = VK_NULL_HANDLE; + return res; + } + return res; +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateBufferWithAlignment( + VmaAllocator allocator, + const VkBufferCreateInfo* pBufferCreateInfo, + const VmaAllocationCreateInfo* pAllocationCreateInfo, + VkDeviceSize minAlignment, + VkBuffer* pBuffer, + VmaAllocation* pAllocation, + VmaAllocationInfo* pAllocationInfo) +{ + VMA_ASSERT(allocator && pBufferCreateInfo && pAllocationCreateInfo && VmaIsPow2(minAlignment) && pBuffer && pAllocation); + + if(pBufferCreateInfo->size == 0) + { + return VK_ERROR_INITIALIZATION_FAILED; + } + if((pBufferCreateInfo->usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_COPY) != 0 && + !allocator->m_UseKhrBufferDeviceAddress) + { + VMA_ASSERT(0 && "Creating a buffer with VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT is not valid if VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT was not used."); + return VK_ERROR_INITIALIZATION_FAILED; + } + + VMA_DEBUG_LOG("vmaCreateBufferWithAlignment"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + *pBuffer = VK_NULL_HANDLE; + *pAllocation = VK_NULL_HANDLE; + + // 1. Create VkBuffer. + VkResult res = (*allocator->GetVulkanFunctions().vkCreateBuffer)( + allocator->m_hDevice, + pBufferCreateInfo, + allocator->GetAllocationCallbacks(), + pBuffer); + if(res >= 0) + { + // 2. vkGetBufferMemoryRequirements. + VkMemoryRequirements vkMemReq = {}; + bool requiresDedicatedAllocation = false; + bool prefersDedicatedAllocation = false; + allocator->GetBufferMemoryRequirements(*pBuffer, vkMemReq, + requiresDedicatedAllocation, prefersDedicatedAllocation); + + // 2a. Include minAlignment + vkMemReq.alignment = VMA_MAX(vkMemReq.alignment, minAlignment); + + // 3. Allocate memory using allocator. + res = allocator->AllocateMemory( + vkMemReq, + requiresDedicatedAllocation, + prefersDedicatedAllocation, + *pBuffer, // dedicatedBuffer + VK_NULL_HANDLE, // dedicatedImage + VmaBufferImageUsage(*pBufferCreateInfo, allocator->m_UseKhrMaintenance5), // dedicatedBufferImageUsage + *pAllocationCreateInfo, + VMA_SUBALLOCATION_TYPE_BUFFER, + 1, // allocationCount + pAllocation); + + if(res >= 0) + { + // 3. Bind buffer with memory. + if((pAllocationCreateInfo->flags & VMA_ALLOCATION_CREATE_DONT_BIND_BIT) == 0) + { + res = allocator->BindBufferMemory(*pAllocation, 0, *pBuffer, VMA_NULL); + } + if(res >= 0) + { + // All steps succeeded. + #if VMA_STATS_STRING_ENABLED + (*pAllocation)->InitBufferUsage(*pBufferCreateInfo, allocator->m_UseKhrMaintenance5); + #endif + if(pAllocationInfo != VMA_NULL) + { + allocator->GetAllocationInfo(*pAllocation, pAllocationInfo); + } + + return VK_SUCCESS; + } + allocator->FreeMemory( + 1, // allocationCount + pAllocation); + *pAllocation = VK_NULL_HANDLE; + (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks()); + *pBuffer = VK_NULL_HANDLE; + return res; + } + (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks()); + *pBuffer = VK_NULL_HANDLE; + return res; + } + return res; +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingBuffer( + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, + const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo, + VkBuffer VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pBuffer) +{ + return vmaCreateAliasingBuffer2(allocator, allocation, 0, pBufferCreateInfo, pBuffer); +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingBuffer2( + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, + VkDeviceSize allocationLocalOffset, + const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo, + VkBuffer VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pBuffer) +{ + VMA_ASSERT(allocator && pBufferCreateInfo && pBuffer && allocation); + VMA_ASSERT(allocationLocalOffset + pBufferCreateInfo->size <= allocation->GetSize()); + + VMA_DEBUG_LOG("vmaCreateAliasingBuffer2"); + + *pBuffer = VK_NULL_HANDLE; + + if (pBufferCreateInfo->size == 0) + { + return VK_ERROR_INITIALIZATION_FAILED; + } + if ((pBufferCreateInfo->usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_COPY) != 0 && + !allocator->m_UseKhrBufferDeviceAddress) + { + VMA_ASSERT(0 && "Creating a buffer with VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT is not valid if VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT was not used."); + return VK_ERROR_INITIALIZATION_FAILED; + } + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + // 1. Create VkBuffer. + VkResult res = (*allocator->GetVulkanFunctions().vkCreateBuffer)( + allocator->m_hDevice, + pBufferCreateInfo, + allocator->GetAllocationCallbacks(), + pBuffer); + if (res >= 0) + { + // 2. Bind buffer with memory. + res = allocator->BindBufferMemory(allocation, allocationLocalOffset, *pBuffer, VMA_NULL); + if (res >= 0) + { + return VK_SUCCESS; + } + (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks()); + } + return res; +} + +VMA_CALL_PRE void VMA_CALL_POST vmaDestroyBuffer( + VmaAllocator allocator, + VkBuffer buffer, + VmaAllocation allocation) +{ + VMA_ASSERT(allocator); + + if(buffer == VK_NULL_HANDLE && allocation == VK_NULL_HANDLE) + { + return; + } + + VMA_DEBUG_LOG("vmaDestroyBuffer"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + if(buffer != VK_NULL_HANDLE) + { + (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, buffer, allocator->GetAllocationCallbacks()); + } + + if(allocation != VK_NULL_HANDLE) + { + allocator->FreeMemory( + 1, // allocationCount + &allocation); + } +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateImage( + VmaAllocator allocator, + const VkImageCreateInfo* pImageCreateInfo, + const VmaAllocationCreateInfo* pAllocationCreateInfo, + VkImage* pImage, + VmaAllocation* pAllocation, + VmaAllocationInfo* pAllocationInfo) +{ + VMA_ASSERT(allocator && pImageCreateInfo && pAllocationCreateInfo && pImage && pAllocation); + + if(pImageCreateInfo->extent.width == 0 || + pImageCreateInfo->extent.height == 0 || + pImageCreateInfo->extent.depth == 0 || + pImageCreateInfo->mipLevels == 0 || + pImageCreateInfo->arrayLayers == 0) + { + return VK_ERROR_INITIALIZATION_FAILED; + } + + VMA_DEBUG_LOG("vmaCreateImage"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + *pImage = VK_NULL_HANDLE; + *pAllocation = VK_NULL_HANDLE; + + // 1. Create VkImage. + VkResult res = (*allocator->GetVulkanFunctions().vkCreateImage)( + allocator->m_hDevice, + pImageCreateInfo, + allocator->GetAllocationCallbacks(), + pImage); + if(res >= 0) + { + VmaSuballocationType suballocType = pImageCreateInfo->tiling == VK_IMAGE_TILING_OPTIMAL ? + VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL : + VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR; + + // 2. Allocate memory using allocator. + VkMemoryRequirements vkMemReq = {}; + bool requiresDedicatedAllocation = false; + bool prefersDedicatedAllocation = false; + allocator->GetImageMemoryRequirements(*pImage, vkMemReq, + requiresDedicatedAllocation, prefersDedicatedAllocation); + + res = allocator->AllocateMemory( + vkMemReq, + requiresDedicatedAllocation, + prefersDedicatedAllocation, + VK_NULL_HANDLE, // dedicatedBuffer + *pImage, // dedicatedImage + VmaBufferImageUsage(*pImageCreateInfo), // dedicatedBufferImageUsage + *pAllocationCreateInfo, + suballocType, + 1, // allocationCount + pAllocation); + + if(res >= 0) + { + // 3. Bind image with memory. + if((pAllocationCreateInfo->flags & VMA_ALLOCATION_CREATE_DONT_BIND_BIT) == 0) + { + res = allocator->BindImageMemory(*pAllocation, 0, *pImage, VMA_NULL); + } + if(res >= 0) + { + // All steps succeeded. + #if VMA_STATS_STRING_ENABLED + (*pAllocation)->InitImageUsage(*pImageCreateInfo); + #endif + if(pAllocationInfo != VMA_NULL) + { + allocator->GetAllocationInfo(*pAllocation, pAllocationInfo); + } + + return VK_SUCCESS; + } + allocator->FreeMemory( + 1, // allocationCount + pAllocation); + *pAllocation = VK_NULL_HANDLE; + (*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, *pImage, allocator->GetAllocationCallbacks()); + *pImage = VK_NULL_HANDLE; + return res; + } + (*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, *pImage, allocator->GetAllocationCallbacks()); + *pImage = VK_NULL_HANDLE; + return res; + } + return res; +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingImage( + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, + const VkImageCreateInfo* VMA_NOT_NULL pImageCreateInfo, + VkImage VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pImage) +{ + return vmaCreateAliasingImage2(allocator, allocation, 0, pImageCreateInfo, pImage); +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingImage2( + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, + VkDeviceSize allocationLocalOffset, + const VkImageCreateInfo* VMA_NOT_NULL pImageCreateInfo, + VkImage VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pImage) +{ + VMA_ASSERT(allocator && pImageCreateInfo && pImage && allocation); + + *pImage = VK_NULL_HANDLE; + + VMA_DEBUG_LOG("vmaCreateImage2"); + + if (pImageCreateInfo->extent.width == 0 || + pImageCreateInfo->extent.height == 0 || + pImageCreateInfo->extent.depth == 0 || + pImageCreateInfo->mipLevels == 0 || + pImageCreateInfo->arrayLayers == 0) + { + return VK_ERROR_INITIALIZATION_FAILED; + } + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + // 1. Create VkImage. + VkResult res = (*allocator->GetVulkanFunctions().vkCreateImage)( + allocator->m_hDevice, + pImageCreateInfo, + allocator->GetAllocationCallbacks(), + pImage); + if (res >= 0) + { + // 2. Bind image with memory. + res = allocator->BindImageMemory(allocation, allocationLocalOffset, *pImage, VMA_NULL); + if (res >= 0) + { + return VK_SUCCESS; + } + (*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, *pImage, allocator->GetAllocationCallbacks()); + } + return res; +} + +VMA_CALL_PRE void VMA_CALL_POST vmaDestroyImage( + VmaAllocator VMA_NOT_NULL allocator, + VkImage VMA_NULLABLE_NON_DISPATCHABLE image, + VmaAllocation VMA_NULLABLE allocation) +{ + VMA_ASSERT(allocator); + + if(image == VK_NULL_HANDLE && allocation == VK_NULL_HANDLE) + { + return; + } + + VMA_DEBUG_LOG("vmaDestroyImage"); + + VMA_DEBUG_GLOBAL_MUTEX_LOCK + + if(image != VK_NULL_HANDLE) + { + (*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, image, allocator->GetAllocationCallbacks()); + } + if(allocation != VK_NULL_HANDLE) + { + allocator->FreeMemory( + 1, // allocationCount + &allocation); + } +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateVirtualBlock( + const VmaVirtualBlockCreateInfo* VMA_NOT_NULL pCreateInfo, + VmaVirtualBlock VMA_NULLABLE * VMA_NOT_NULL pVirtualBlock) +{ + VMA_ASSERT(pCreateInfo && pVirtualBlock); + VMA_ASSERT(pCreateInfo->size > 0); + VMA_DEBUG_LOG("vmaCreateVirtualBlock"); + VMA_DEBUG_GLOBAL_MUTEX_LOCK; + *pVirtualBlock = vma_new(pCreateInfo->pAllocationCallbacks, VmaVirtualBlock_T)(*pCreateInfo); + VkResult res = (*pVirtualBlock)->Init(); + if(res < 0) + { + vma_delete(pCreateInfo->pAllocationCallbacks, *pVirtualBlock); + *pVirtualBlock = VK_NULL_HANDLE; + } + return res; +} + +VMA_CALL_PRE void VMA_CALL_POST vmaDestroyVirtualBlock(VmaVirtualBlock VMA_NULLABLE virtualBlock) +{ + if(virtualBlock != VK_NULL_HANDLE) + { + VMA_DEBUG_LOG("vmaDestroyVirtualBlock"); + VMA_DEBUG_GLOBAL_MUTEX_LOCK; + VkAllocationCallbacks allocationCallbacks = virtualBlock->m_AllocationCallbacks; // Have to copy the callbacks when destroying. + vma_delete(&allocationCallbacks, virtualBlock); + } +} + +VMA_CALL_PRE VkBool32 VMA_CALL_POST vmaIsVirtualBlockEmpty(VmaVirtualBlock VMA_NOT_NULL virtualBlock) +{ + VMA_ASSERT(virtualBlock != VK_NULL_HANDLE); + VMA_DEBUG_LOG("vmaIsVirtualBlockEmpty"); + VMA_DEBUG_GLOBAL_MUTEX_LOCK; + return virtualBlock->IsEmpty() ? VK_TRUE : VK_FALSE; +} + +VMA_CALL_PRE void VMA_CALL_POST vmaGetVirtualAllocationInfo(VmaVirtualBlock VMA_NOT_NULL virtualBlock, + VmaVirtualAllocation VMA_NOT_NULL_NON_DISPATCHABLE allocation, VmaVirtualAllocationInfo* VMA_NOT_NULL pVirtualAllocInfo) +{ + VMA_ASSERT(virtualBlock != VK_NULL_HANDLE && pVirtualAllocInfo != VMA_NULL); + VMA_DEBUG_LOG("vmaGetVirtualAllocationInfo"); + VMA_DEBUG_GLOBAL_MUTEX_LOCK; + virtualBlock->GetAllocationInfo(allocation, *pVirtualAllocInfo); +} + +VMA_CALL_PRE VkResult VMA_CALL_POST vmaVirtualAllocate(VmaVirtualBlock VMA_NOT_NULL virtualBlock, + const VmaVirtualAllocationCreateInfo* VMA_NOT_NULL pCreateInfo, VmaVirtualAllocation VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pAllocation, + VkDeviceSize* VMA_NULLABLE pOffset) +{ + VMA_ASSERT(virtualBlock != VK_NULL_HANDLE && pCreateInfo != VMA_NULL && pAllocation != VMA_NULL); + VMA_DEBUG_LOG("vmaVirtualAllocate"); + VMA_DEBUG_GLOBAL_MUTEX_LOCK; + return virtualBlock->Allocate(*pCreateInfo, *pAllocation, pOffset); +} + +VMA_CALL_PRE void VMA_CALL_POST vmaVirtualFree(VmaVirtualBlock VMA_NOT_NULL virtualBlock, VmaVirtualAllocation VMA_NULLABLE_NON_DISPATCHABLE allocation) +{ + if(allocation != VK_NULL_HANDLE) + { + VMA_ASSERT(virtualBlock != VK_NULL_HANDLE); + VMA_DEBUG_LOG("vmaVirtualFree"); + VMA_DEBUG_GLOBAL_MUTEX_LOCK; + virtualBlock->Free(allocation); + } +} + +VMA_CALL_PRE void VMA_CALL_POST vmaClearVirtualBlock(VmaVirtualBlock VMA_NOT_NULL virtualBlock) +{ + VMA_ASSERT(virtualBlock != VK_NULL_HANDLE); + VMA_DEBUG_LOG("vmaClearVirtualBlock"); + VMA_DEBUG_GLOBAL_MUTEX_LOCK; + virtualBlock->Clear(); +} + +VMA_CALL_PRE void VMA_CALL_POST vmaSetVirtualAllocationUserData(VmaVirtualBlock VMA_NOT_NULL virtualBlock, + VmaVirtualAllocation VMA_NOT_NULL_NON_DISPATCHABLE allocation, void* VMA_NULLABLE pUserData) +{ + VMA_ASSERT(virtualBlock != VK_NULL_HANDLE); + VMA_DEBUG_LOG("vmaSetVirtualAllocationUserData"); + VMA_DEBUG_GLOBAL_MUTEX_LOCK; + virtualBlock->SetAllocationUserData(allocation, pUserData); +} + +VMA_CALL_PRE void VMA_CALL_POST vmaGetVirtualBlockStatistics(VmaVirtualBlock VMA_NOT_NULL virtualBlock, + VmaStatistics* VMA_NOT_NULL pStats) +{ + VMA_ASSERT(virtualBlock != VK_NULL_HANDLE && pStats != VMA_NULL); + VMA_DEBUG_LOG("vmaGetVirtualBlockStatistics"); + VMA_DEBUG_GLOBAL_MUTEX_LOCK; + virtualBlock->GetStatistics(*pStats); +} + +VMA_CALL_PRE void VMA_CALL_POST vmaCalculateVirtualBlockStatistics(VmaVirtualBlock VMA_NOT_NULL virtualBlock, + VmaDetailedStatistics* VMA_NOT_NULL pStats) +{ + VMA_ASSERT(virtualBlock != VK_NULL_HANDLE && pStats != VMA_NULL); + VMA_DEBUG_LOG("vmaCalculateVirtualBlockStatistics"); + VMA_DEBUG_GLOBAL_MUTEX_LOCK; + virtualBlock->CalculateDetailedStatistics(*pStats); +} + +#if VMA_STATS_STRING_ENABLED + +VMA_CALL_PRE void VMA_CALL_POST vmaBuildVirtualBlockStatsString(VmaVirtualBlock VMA_NOT_NULL virtualBlock, + char* VMA_NULLABLE * VMA_NOT_NULL ppStatsString, VkBool32 detailedMap) +{ + VMA_ASSERT(virtualBlock != VK_NULL_HANDLE && ppStatsString != VMA_NULL); + VMA_DEBUG_GLOBAL_MUTEX_LOCK; + const VkAllocationCallbacks* allocationCallbacks = virtualBlock->GetAllocationCallbacks(); + VmaStringBuilder sb(allocationCallbacks); + virtualBlock->BuildStatsString(detailedMap != VK_FALSE, sb); + *ppStatsString = VmaCreateStringCopy(allocationCallbacks, sb.GetData(), sb.GetLength()); +} + +VMA_CALL_PRE void VMA_CALL_POST vmaFreeVirtualBlockStatsString(VmaVirtualBlock VMA_NOT_NULL virtualBlock, + char* VMA_NULLABLE pStatsString) +{ + if(pStatsString != VMA_NULL) + { + VMA_ASSERT(virtualBlock != VK_NULL_HANDLE); + VMA_DEBUG_GLOBAL_MUTEX_LOCK; + VmaFreeString(virtualBlock->GetAllocationCallbacks(), pStatsString); + } +} +#if VMA_EXTERNAL_MEMORY_WIN32 +VMA_CALL_PRE VkResult VMA_CALL_POST vmaGetMemoryWin32Handle(VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, HANDLE hTargetProcess, HANDLE* VMA_NOT_NULL pHandle) +{ + VMA_ASSERT(allocator && allocation && pHandle); + VMA_DEBUG_GLOBAL_MUTEX_LOCK; + return allocation->GetWin32Handle(allocator, hTargetProcess, pHandle); +} +#endif // VMA_EXTERNAL_MEMORY_WIN32 +#endif // VMA_STATS_STRING_ENABLED +#endif // _VMA_PUBLIC_INTERFACE +#endif // VMA_IMPLEMENTATION + +/** +\page quick_start Quick start + +\section quick_start_project_setup Project setup + +Vulkan Memory Allocator comes in form of a "stb-style" single header file. +While you can pull the entire repository e.g. as Git module, there is also Cmake script provided, +you don't need to build it as a separate library project. +You can add file "vk_mem_alloc.h" directly to your project and submit it to code repository next to your other source files. + +"Single header" doesn't mean that everything is contained in C/C++ declarations, +like it tends to be in case of inline functions or C++ templates. +It means that implementation is bundled with interface in a single file and needs to be extracted using preprocessor macro. +If you don't do it properly, it will result in linker errors. + +To do it properly: + +-# Include "vk_mem_alloc.h" file in each CPP file where you want to use the library. + This includes declarations of all members of the library. +-# In exactly one CPP file define following macro before this include. + It enables also internal definitions. + +\code +#define VMA_IMPLEMENTATION +#include "vk_mem_alloc.h" +\endcode + +It may be a good idea to create dedicated CPP file just for this purpose, e.g. "VmaUsage.cpp". + +This library includes header ``, which in turn +includes `` on Windows. If you need some specific macros defined +before including these headers (like `WIN32_LEAN_AND_MEAN` or +`WINVER` for Windows, `VK_USE_PLATFORM_WIN32_KHR` for Vulkan), you must define +them before every `#include` of this library. +It may be a good idea to create a dedicate header file for this purpose, e.g. "VmaUsage.h", +that will be included in other source files instead of VMA header directly. + +This library is written in C++, but has C-compatible interface. +Thus, you can include and use "vk_mem_alloc.h" in C or C++ code, but full +implementation with `VMA_IMPLEMENTATION` macro must be compiled as C++, NOT as C. +Some features of C++14 are used and required. Features of C++20 are used optionally when available. +Some headers of standard C and C++ library are used, but STL containers, RTTI, or C++ exceptions are not used. + + +\section quick_start_initialization Initialization + +VMA offers library interface in a style similar to Vulkan, with object handles like #VmaAllocation, +structures describing parameters of objects to be created like #VmaAllocationCreateInfo, +and errors codes returned from functions using `VkResult` type. + +The first and the main object that needs to be created is #VmaAllocator. +It represents the initialization of the entire library. +Only one such object should be created per `VkDevice`. +You should create it at program startup, after `VkDevice` was created, and before any device memory allocator needs to be made. +It must be destroyed before `VkDevice` is destroyed. + +At program startup: + +-# Initialize Vulkan to have `VkInstance`, `VkPhysicalDevice`, `VkDevice` object. +-# Fill VmaAllocatorCreateInfo structure and call vmaCreateAllocator() to create #VmaAllocator object. + +Only members `physicalDevice`, `device`, `instance` are required. +However, you should inform the library which Vulkan version do you use by setting +VmaAllocatorCreateInfo::vulkanApiVersion and which extensions did you enable +by setting VmaAllocatorCreateInfo::flags. +Otherwise, VMA would use only features of Vulkan 1.0 core with no extensions. +See below for details. + +\subsection quick_start_initialization_selecting_vulkan_version Selecting Vulkan version + +VMA supports Vulkan version down to 1.0, for backward compatibility. +If you want to use higher version, you need to inform the library about it. +This is a two-step process. + +Step 1: Compile time. By default, VMA compiles with code supporting the highest +Vulkan version found in the included `` that is also supported by the library. +If this is OK, you don't need to do anything. +However, if you want to compile VMA as if only some lower Vulkan version was available, +define macro `VMA_VULKAN_VERSION` before every `#include "vk_mem_alloc.h"`. +It should have decimal numeric value in form of ABBBCCC, where A = major, BBB = minor, CCC = patch Vulkan version. +For example, to compile against Vulkan 1.2: + +\code +#define VMA_VULKAN_VERSION 1002000 // Vulkan 1.2 +#include "vk_mem_alloc.h" +\endcode + +Step 2: Runtime. Even when compiled with higher Vulkan version available, +VMA can use only features of a lower version, which is configurable during creation of the #VmaAllocator object. +By default, only Vulkan 1.0 is used. +To initialize the allocator with support for higher Vulkan version, you need to set member +VmaAllocatorCreateInfo::vulkanApiVersion to an appropriate value, e.g. using constants like `VK_API_VERSION_1_2`. +See code sample below. + +\subsection quick_start_initialization_importing_vulkan_functions Importing Vulkan functions + +You may need to configure importing Vulkan functions. There are 3 ways to do this: + +-# **If you link with Vulkan static library** (e.g. "vulkan-1.lib" on Windows): + - You don't need to do anything. + - VMA will use these, as macro `VMA_STATIC_VULKAN_FUNCTIONS` is defined to 1 by default. +-# **If you want VMA to fetch pointers to Vulkan functions dynamically** using `vkGetInstanceProcAddr`, + `vkGetDeviceProcAddr` (this is the option presented in the example below): + - Define `VMA_STATIC_VULKAN_FUNCTIONS` to 0, `VMA_DYNAMIC_VULKAN_FUNCTIONS` to 1. + - Provide pointers to these two functions via VmaVulkanFunctions::vkGetInstanceProcAddr, + VmaVulkanFunctions::vkGetDeviceProcAddr. + - The library will fetch pointers to all other functions it needs internally. +-# **If you fetch pointers to all Vulkan functions in a custom way**, e.g. using some loader like + [Volk](https://github.com/zeux/volk): + - Define `VMA_STATIC_VULKAN_FUNCTIONS` and `VMA_DYNAMIC_VULKAN_FUNCTIONS` to 0. + - Pass these pointers via structure #VmaVulkanFunctions. + +\subsection quick_start_initialization_enabling_extensions Enabling extensions + +VMA can automatically use following Vulkan extensions. +If you found them available on the selected physical device and you enabled them +while creating `VkInstance` / `VkDevice` object, inform VMA about their availability +by setting appropriate flags in VmaAllocatorCreateInfo::flags. + +Vulkan extension | VMA flag +------------------------------|----------------------------------------------------- +VK_KHR_dedicated_allocation | #VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT +VK_KHR_bind_memory2 | #VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT +VK_KHR_maintenance4 | #VMA_ALLOCATOR_CREATE_KHR_MAINTENANCE4_BIT +VK_KHR_maintenance5 | #VMA_ALLOCATOR_CREATE_KHR_MAINTENANCE5_BIT +VK_EXT_memory_budget | #VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT +VK_KHR_buffer_device_address | #VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT +VK_EXT_memory_priority | #VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT +VK_AMD_device_coherent_memory | #VMA_ALLOCATOR_CREATE_AMD_DEVICE_COHERENT_MEMORY_BIT +VK_KHR_external_memory_win32 | #VMA_ALLOCATOR_CREATE_KHR_EXTERNAL_MEMORY_WIN32_BIT + +Example with fetching pointers to Vulkan functions dynamically: + +\code +#define VMA_STATIC_VULKAN_FUNCTIONS 0 +#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); + +// Entire program... + +// At the end, don't forget to: +vmaDestroyAllocator(allocator); +\endcode + + +\subsection quick_start_initialization_other_config Other configuration options + +There are additional configuration options available through preprocessor macros that you can define +before including VMA header and through parameters passed in #VmaAllocatorCreateInfo. +They include a possibility to use your own callbacks for host memory allocations (`VkAllocationCallbacks`), +callbacks for device memory allocations (instead of `vkAllocateMemory`, `vkFreeMemory`), +or your custom `VMA_ASSERT` macro, among others. +For more information, see: @ref configuration. + + +\section quick_start_resource_allocation Resource allocation + +When you want to create a buffer or image: + +-# Fill `VkBufferCreateInfo` / `VkImageCreateInfo` structure. +-# Fill VmaAllocationCreateInfo structure. +-# Call vmaCreateBuffer() / vmaCreateImage() to get `VkBuffer`/`VkImage` with memory + already allocated and bound to it, plus #VmaAllocation objects that represents its underlying memory. + +\code +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); +\endcode + +Don't forget to destroy your buffer and allocation objects when no longer needed: + +\code +vmaDestroyBuffer(allocator, buffer, allocation); +\endcode + +If you need to map the buffer, you must set flag +#VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT +in VmaAllocationCreateInfo::flags. +There are many additional parameters that can control the choice of memory type to be used for the allocation +and other features. +For more information, see documentation chapters: @ref choosing_memory_type, @ref memory_mapping. + + +\page choosing_memory_type Choosing memory type + +Physical devices in Vulkan support various combinations of memory heaps and +types. Help with choosing correct and optimal memory type for your specific +resource is one of the key features of this library. You can use it by filling +appropriate members of VmaAllocationCreateInfo structure, as described below. +You can also combine multiple methods. + +-# If you just want to find memory type index that meets your requirements, you + can use function: vmaFindMemoryTypeIndexForBufferInfo(), + vmaFindMemoryTypeIndexForImageInfo(), vmaFindMemoryTypeIndex(). +-# If you want to allocate a region of device memory without association with any + specific image or buffer, you can use function vmaAllocateMemory(). Usage of + this function is not recommended and usually not needed. + vmaAllocateMemoryPages() function is also provided for creating multiple allocations at once, + which may be useful for sparse binding. +-# If you already have a buffer or an image created, you want to allocate memory + for it and then you will bind it yourself, you can use function + vmaAllocateMemoryForBuffer(), vmaAllocateMemoryForImage(). + For binding you should use functions: vmaBindBufferMemory(), vmaBindImageMemory() + or their extended versions: vmaBindBufferMemory2(), vmaBindImageMemory2(). +-# If you want to create a buffer or an image, allocate memory for it, and bind + them together, all in one call, you can use function vmaCreateBuffer(), + vmaCreateImage(). + This is the easiest and recommended way to use this library! + +When using 3. or 4., the library internally queries Vulkan for memory types +supported for that buffer or image (function `vkGetBufferMemoryRequirements()`) +and uses only one of these types. + +If no memory type can be found that meets all the requirements, these functions +return `VK_ERROR_FEATURE_NOT_PRESENT`. + +You can leave VmaAllocationCreateInfo structure completely filled with zeros. +It means no requirements are specified for memory type. +It is valid, although not very useful. + +\section choosing_memory_type_usage Usage + +The easiest way to specify memory requirements is to fill member +VmaAllocationCreateInfo::usage using one of the values of enum #VmaMemoryUsage. +It defines high level, common usage types. +Since version 3 of the library, it is recommended to use #VMA_MEMORY_USAGE_AUTO to let it select best memory type for your resource automatically. + +For example, if you want to create a uniform buffer that will be filled using +transfer only once or infrequently and then used for rendering every frame as a uniform buffer, you can +do it using following code. The buffer will most likely end up in a memory type with +`VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT` to be fast to access by the GPU device. + +\code +VkBufferCreateInfo bufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; +bufferInfo.size = 65536; +bufferInfo.usage = VK_BUFFER_USAGE_UNIFORM_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); +\endcode + +If you have a preference for putting the resource in GPU (device) memory or CPU (host) memory +on systems with discrete graphics card that have the memories separate, you can use +#VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE or #VMA_MEMORY_USAGE_AUTO_PREFER_HOST. + +When using `VMA_MEMORY_USAGE_AUTO*` while you want to map the allocated memory, +you also need to specify one of the host access flags: +#VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT. +This will help the library decide about preferred memory type to ensure it has `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` +so you can map it. + +For example, a staging buffer that will be filled via mapped pointer and then +used as a source of transfer to the buffer described previously can be created like this. +It will likely end up in a memory type that is `HOST_VISIBLE` and `HOST_COHERENT` +but not `HOST_CACHED` (meaning uncached, write-combined) and not `DEVICE_LOCAL` (meaning system RAM). + +\code +VkBufferCreateInfo stagingBufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; +stagingBufferInfo.size = 65536; +stagingBufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; + +VmaAllocationCreateInfo stagingAllocInfo = {}; +stagingAllocInfo.usage = VMA_MEMORY_USAGE_AUTO; +stagingAllocInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT; + +VkBuffer stagingBuffer; +VmaAllocation stagingAllocation; +vmaCreateBuffer(allocator, &stagingBufferInfo, &stagingAllocInfo, &stagingBuffer, &stagingAllocation, nullptr); +\endcode + +For more examples of creating different kinds of resources, see chapter \ref usage_patterns. +See also: @ref memory_mapping. + +Usage values `VMA_MEMORY_USAGE_AUTO*` are legal to use only when the library knows +about the resource being created by having `VkBufferCreateInfo` / `VkImageCreateInfo` passed, +so they work with functions like: vmaCreateBuffer(), vmaCreateImage(), vmaFindMemoryTypeIndexForBufferInfo() etc. +If you allocate raw memory using function vmaAllocateMemory(), you have to use other means of selecting +memory type, as described below. + +\note +Old usage values (`VMA_MEMORY_USAGE_GPU_ONLY`, `VMA_MEMORY_USAGE_CPU_ONLY`, +`VMA_MEMORY_USAGE_CPU_TO_GPU`, `VMA_MEMORY_USAGE_GPU_TO_CPU`, `VMA_MEMORY_USAGE_CPU_COPY`) +are still available and work same way as in previous versions of the library +for backward compatibility, but they are deprecated. + +\section choosing_memory_type_required_preferred_flags Required and preferred flags + +You can specify more detailed requirements by filling members +VmaAllocationCreateInfo::requiredFlags and VmaAllocationCreateInfo::preferredFlags +with a combination of bits from enum `VkMemoryPropertyFlags`. For example, +if you want to create a buffer that will be persistently mapped on host (so it +must be `HOST_VISIBLE`) and preferably will also be `HOST_COHERENT` and `HOST_CACHED`, +use following code: + +\code +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); +\endcode + +A memory type is chosen that has all the required flags and as many preferred +flags set as possible. + +Value passed in VmaAllocationCreateInfo::usage is internally converted to a set of required and preferred flags, +plus some extra "magic" (heuristics). + +\section choosing_memory_type_explicit_memory_types Explicit memory types + +If you inspected memory types available on the physical device and you have +a preference for memory types that you want to use, you can fill member +VmaAllocationCreateInfo::memoryTypeBits. It is a bit mask, where each bit set +means that a memory type with that index is allowed to be used for the +allocation. Special value 0, just like `UINT32_MAX`, means there are no +restrictions to memory type index. + +Please note that this member is NOT just a memory type index. +Still you can use it to choose just one, specific memory type. +For example, if you already determined that your buffer should be created in +memory type 2, use following code: + +\code +uint32_t memoryTypeIndex = 2; + +VmaAllocationCreateInfo allocInfo = {}; +allocInfo.memoryTypeBits = 1u << memoryTypeIndex; + +VkBuffer buffer; +VmaAllocation allocation; +vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr); +\endcode + +You can also use this parameter to exclude some memory types. +If you inspect memory heaps and types available on the current physical device and +you determine that for some reason you don't want to use a specific memory type for the allocation, +you can enable automatic memory type selection but exclude certain memory type or types +by setting all bits of `memoryTypeBits` to 1 except the ones you choose. + +\code +// ... +uint32_t excludedMemoryTypeIndex = 2; +VmaAllocationCreateInfo allocInfo = {}; +allocInfo.usage = VMA_MEMORY_USAGE_AUTO; +allocInfo.memoryTypeBits = ~(1u << excludedMemoryTypeIndex); +// ... +\endcode + + +\section choosing_memory_type_custom_memory_pools Custom memory pools + +If you allocate from custom memory pool, all the ways of specifying memory +requirements described above are not applicable and the aforementioned members +of VmaAllocationCreateInfo structure are ignored. Memory type is selected +explicitly when creating the pool and then used to make all the allocations from +that pool. For further details, see \ref custom_memory_pools. + +\section choosing_memory_type_dedicated_allocations Dedicated allocations + +Memory for allocations is reserved out of larger block of `VkDeviceMemory` +allocated from Vulkan internally. That is the main feature of this whole library. +You can still request a separate memory block to be created for an allocation, +just like you would do in a trivial solution without using any allocator. +In that case, a buffer or image is always bound to that memory at offset 0. +This is called a "dedicated allocation". +You can explicitly request it by using flag #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT. +The library can also internally decide to use dedicated allocation in some cases, e.g.: + +- When the size of the allocation is large. +- When [VK_KHR_dedicated_allocation](@ref vk_khr_dedicated_allocation) extension is enabled + and it reports that dedicated allocation is required or recommended for the resource. +- When allocation of next big memory block fails due to not enough device memory, + but allocation with the exact requested size succeeds. + + +\page memory_mapping Memory mapping + +To "map memory" in Vulkan means to obtain a CPU pointer to `VkDeviceMemory`, +to be able to read from it or write to it in CPU code. +Mapping is possible only of memory allocated from a memory type that has +`VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` flag. +Functions `vkMapMemory()`, `vkUnmapMemory()` are designed for this purpose. +You can use them directly with memory allocated by this library, +but it is not recommended because of following issue: +Mapping the same `VkDeviceMemory` block multiple times is illegal - only one mapping at a time is allowed. +This includes mapping disjoint regions. Mapping is not reference-counted internally by Vulkan. +It is also not thread-safe. +Because of this, Vulkan Memory Allocator provides following facilities: + +\note If you want to be able to map an allocation, you need to specify one of the flags +#VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT +in VmaAllocationCreateInfo::flags. These flags are required for an allocation to be mappable +when using #VMA_MEMORY_USAGE_AUTO or other `VMA_MEMORY_USAGE_AUTO*` enum values. +For other usage values they are ignored and every such allocation made in `HOST_VISIBLE` memory type is mappable, +but these flags can still be used for consistency. + +\section memory_mapping_copy_functions Copy functions + +The easiest way to copy data from a host pointer to an allocation is to use convenience function vmaCopyMemoryToAllocation(). +It automatically maps the Vulkan memory temporarily (if not already mapped), performs `memcpy`, +and calls `vkFlushMappedMemoryRanges` (if required - if memory type is not `HOST_COHERENT`). + +It is also the safest one, because using `memcpy` avoids a risk of accidentally introducing memory reads +(e.g. by doing `pMappedVectors[i] += v`), which may be very slow on memory types that are not `HOST_CACHED`. + +\code +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 allocCreateInfo = {}; +allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO; +allocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT; + +VkBuffer buf; +VmaAllocation alloc; +vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, nullptr); + +vmaCopyMemoryToAllocation(allocator, &constantBufferData, alloc, 0, sizeof(ConstantBuffer)); +\endcode + +Copy in the other direction - from an allocation to a host pointer can be performed the same way using function vmaCopyAllocationToMemory(). + +\section memory_mapping_mapping_functions Mapping functions + +The library provides following functions for mapping of a specific allocation: vmaMapMemory(), vmaUnmapMemory(). +They are safer and more convenient to use than standard Vulkan functions. +You can map an allocation multiple times simultaneously - mapping is reference-counted internally. +You can also map different allocations simultaneously regardless of whether they use the same `VkDeviceMemory` block. +The way it is implemented is that the library always maps entire memory block, not just region of the allocation. +For further details, see description of vmaMapMemory() function. +Example: + +\code +// Having these objects initialized: +struct ConstantBuffer +{ + ... +}; +ConstantBuffer constantBufferData = ... + +VmaAllocator allocator = ... +VkBuffer constantBuffer = ... +VmaAllocation constantBufferAllocation = ... + +// You can map and fill your buffer using following code: + +void* mappedData; +vmaMapMemory(allocator, constantBufferAllocation, &mappedData); +memcpy(mappedData, &constantBufferData, sizeof(constantBufferData)); +vmaUnmapMemory(allocator, constantBufferAllocation); +\endcode + +When mapping, you may see a warning from Vulkan validation layer similar to this one: + +Mapping an image with layout VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL can result in undefined behavior if this memory is used by the device. Only GENERAL or PREINITIALIZED should be used. + +It happens because the library maps entire `VkDeviceMemory` block, where different +types of images and buffers may end up together, especially on GPUs with unified memory like Intel. +You can safely ignore it if you are sure you access only memory of the intended +object that you wanted to map. + + +\section memory_mapping_persistently_mapped_memory Persistently mapped memory + +Keeping your memory persistently mapped is generally OK in Vulkan. +You don't need to unmap it before using its data on the GPU. +The library provides a special feature designed for that: +Allocations made with #VMA_ALLOCATION_CREATE_MAPPED_BIT flag set in +VmaAllocationCreateInfo::flags stay mapped all the time, +so you can just access CPU pointer to it any time +without a need to call any "map" or "unmap" function. +Example: + +\code +VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; +bufCreateInfo.size = sizeof(ConstantBuffer); +bufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; + +VmaAllocationCreateInfo allocCreateInfo = {}; +allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO; +allocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | + VMA_ALLOCATION_CREATE_MAPPED_BIT; + +VkBuffer buf; +VmaAllocation alloc; +VmaAllocationInfo allocInfo; +vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo); + +// Buffer is already mapped. You can access its memory. +memcpy(allocInfo.pMappedData, &constantBufferData, sizeof(constantBufferData)); +\endcode + +\note #VMA_ALLOCATION_CREATE_MAPPED_BIT by itself doesn't guarantee that the allocation will end up +in a mappable memory type. +For this, you need to also specify #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or +#VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT. +#VMA_ALLOCATION_CREATE_MAPPED_BIT only guarantees that if the memory is `HOST_VISIBLE`, the allocation will be mapped on creation. +For an example of how to make use of this fact, see section \ref usage_patterns_advanced_data_uploading. + +\section memory_mapping_cache_control Cache flush and invalidate + +Memory in Vulkan doesn't need to be unmapped before using it on GPU, +but unless a memory types has `VK_MEMORY_PROPERTY_HOST_COHERENT_BIT` flag set, +you need to manually **invalidate** cache before reading of mapped pointer +and **flush** cache after writing to mapped pointer. +Map/unmap operations don't do that automatically. +Vulkan provides following functions for this purpose `vkFlushMappedMemoryRanges()`, +`vkInvalidateMappedMemoryRanges()`, but this library provides more convenient +functions that refer to given allocation object: vmaFlushAllocation(), +vmaInvalidateAllocation(), +or multiple objects at once: vmaFlushAllocations(), vmaInvalidateAllocations(). + +Regions of memory specified for flush/invalidate must be aligned to +`VkPhysicalDeviceLimits::nonCoherentAtomSize`. This is automatically ensured by the library. +In any memory type that is `HOST_VISIBLE` but not `HOST_COHERENT`, all allocations +within blocks are aligned to this value, so their offsets are always multiply of +`nonCoherentAtomSize` and two different allocations never share same "line" of this size. + +Also, Windows drivers from all 3 PC GPU vendors (AMD, Intel, NVIDIA) +currently provide `HOST_COHERENT` flag on all memory types that are +`HOST_VISIBLE`, so on PC you may not need to bother. + + +\page staying_within_budget Staying within budget + +When developing a graphics-intensive game or program, it is important to avoid allocating +more GPU memory than it is physically available. When the memory is over-committed, +various bad things can happen, depending on the specific GPU, graphics driver, and +operating system: + +- It may just work without any problems. +- The application may slow down because some memory blocks are moved to system RAM + and the GPU has to access them through PCI Express bus. +- A new allocation may take very long time to complete, even few seconds, and possibly + freeze entire system. +- The new allocation may fail with `VK_ERROR_OUT_OF_DEVICE_MEMORY`. +- It may even result in GPU crash (TDR), observed as `VK_ERROR_DEVICE_LOST` + returned somewhere later. + +\section staying_within_budget_querying_for_budget Querying for budget + +To query for current memory usage and available budget, use function vmaGetHeapBudgets(). +Returned structure #VmaBudget contains quantities expressed in bytes, per Vulkan memory heap. + +Please note that this function returns different information and works faster than +vmaCalculateStatistics(). vmaGetHeapBudgets() can be called every frame or even before every +allocation, while vmaCalculateStatistics() is intended to be used rarely, +only to obtain statistical information, e.g. for debugging purposes. + +It is recommended to use VK_EXT_memory_budget device extension to obtain information +about the budget from Vulkan device. VMA is able to use this extension automatically. +When not enabled, the allocator behaves same way, but then it estimates current usage +and available budget based on its internal information and Vulkan memory heap sizes, +which may be less precise. In order to use this extension: + +1. Make sure extensions VK_EXT_memory_budget and VK_KHR_get_physical_device_properties2 + required by it are available and enable them. Please note that the first is a device + extension and the second is instance extension! +2. Use flag #VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT when creating #VmaAllocator object. +3. Make sure to call vmaSetCurrentFrameIndex() every frame. Budget is queried from + Vulkan inside of it to avoid overhead of querying it with every allocation. + +\section staying_within_budget_controlling_memory_usage Controlling memory usage + +There are many ways in which you can try to stay within the budget. + +First, when making new allocation requires allocating a new memory block, the library +tries not to exceed the budget automatically. If a block with default recommended size +(e.g. 256 MB) would go over budget, a smaller block is allocated, possibly even +dedicated memory for just this resource. + +If the size of the requested resource plus current memory usage is more than the +budget, by default the library still tries to create it, leaving it to the Vulkan +implementation whether the allocation succeeds or fails. You can change this behavior +by using #VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT flag. With it, the allocation is +not made if it would exceed the budget or if the budget is already exceeded. +VMA then tries to make the allocation from the next eligible Vulkan memory type. +If all of them fail, the call then fails with `VK_ERROR_OUT_OF_DEVICE_MEMORY`. +Example usage pattern may be to pass the #VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT flag +when creating resources that are not essential for the application (e.g. the texture +of a specific object) and not to pass it when creating critically important resources +(e.g. render targets). + +On AMD graphics cards there is a custom vendor extension available: VK_AMD_memory_overallocation_behavior +that allows to control the behavior of the Vulkan implementation in out-of-memory cases - +whether it should fail with an error code or still allow the allocation. +Usage of this extension involves only passing extra structure on Vulkan device creation, +so it is out of scope of this library. + +Finally, you can also use #VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT flag to make sure +a new allocation is created only when it fits inside one of the existing memory blocks. +If it would require to allocate a new block, if fails instead with `VK_ERROR_OUT_OF_DEVICE_MEMORY`. +This also ensures that the function call is very fast because it never goes to Vulkan +to obtain a new block. + +\note Creating \ref custom_memory_pools with VmaPoolCreateInfo::minBlockCount +set to more than 0 will currently try to allocate memory blocks without checking whether they +fit within budget. + + +\page resource_aliasing Resource aliasing (overlap) + +New explicit graphics APIs (Vulkan and Direct3D 12), thanks to manual memory +management, give an opportunity to alias (overlap) multiple resources in the +same region of memory - a feature not available in the old APIs (Direct3D 11, OpenGL). +It can be useful to save video memory, but it must be used with caution. + +For example, if you know the flow of your whole render frame in advance, you +are going to use some intermediate textures or buffers only during a small range of render passes, +and you know these ranges don't overlap in time, you can bind these resources to +the same place in memory, even if they have completely different parameters (width, height, format etc.). + +![Resource aliasing (overlap)](../gfx/Aliasing.png) + +Such scenario is possible using VMA, but you need to create your images manually. +Then you need to calculate parameters of an allocation to be made using formula: + +- allocation size = max(size of each image) +- allocation alignment = max(alignment of each image) +- allocation memoryTypeBits = bitwise AND(memoryTypeBits of each image) + +Following example shows two different images bound to the same place in memory, +allocated to fit largest of them. + +\code +// A 512x512 texture to be sampled. +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 allocCreateInfo = {}; +allocCreateInfo.preferredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + +VmaAllocation alloc; +res = vmaAllocateMemory(allocator, &finalMemReq, &allocCreateInfo, &alloc, nullptr); + +res = vmaBindImageMemory(allocator, alloc, img1); +res = vmaBindImageMemory(allocator, alloc, img2); + +// You can use img1, img2 here, but not at the same time! + +vmaFreeMemory(allocator, alloc); +vkDestroyImage(allocator, img2, nullptr); +vkDestroyImage(allocator, img1, nullptr); +\endcode + +VMA also provides convenience functions that create a buffer or image and bind it to memory +represented by an existing #VmaAllocation: +vmaCreateAliasingBuffer(), vmaCreateAliasingBuffer2(), +vmaCreateAliasingImage(), vmaCreateAliasingImage2(). +Versions with "2" offer additional parameter `allocationLocalOffset`. + +Remember that using resources that alias in memory requires proper synchronization. +You need to issue a memory barrier to make sure commands that use `img1` and `img2` +don't overlap on GPU timeline. +You also need to treat a resource after aliasing as uninitialized - containing garbage data. +For example, if you use `img1` and then want to use `img2`, you need to issue +an image memory barrier for `img2` with `oldLayout` = `VK_IMAGE_LAYOUT_UNDEFINED`. + +Additional considerations: + +- Vulkan also allows to interpret contents of memory between aliasing resources consistently in some cases. +See chapter 11.8. "Memory Aliasing" of Vulkan specification or `VK_IMAGE_CREATE_ALIAS_BIT` flag. +- You can create more complex layout where different images and buffers are bound +at different offsets inside one large allocation. For example, one can imagine +a big texture used in some render passes, aliasing with a set of many small buffers +used between in some further passes. To bind a resource at non-zero offset in an allocation, +use vmaBindBufferMemory2() / vmaBindImageMemory2(). +- Before allocating memory for the resources you want to alias, check `memoryTypeBits` +returned in memory requirements of each resource to make sure the bits overlap. +Some GPUs may expose multiple memory types suitable e.g. only for buffers or +images with `COLOR_ATTACHMENT` usage, so the sets of memory types supported by your +resources may be disjoint. Aliasing them is not possible in that case. + + +\page custom_memory_pools Custom memory pools + +A memory pool contains a number of `VkDeviceMemory` blocks. +The library automatically creates and manages default pool for each memory type available on the device. +Default memory pool automatically grows in size. +Size of allocated blocks is also variable and managed automatically. +You are using default pools whenever you leave VmaAllocationCreateInfo::pool = null. + +You can create custom pool and allocate memory out of it. +It can be useful if you want to: + +- Keep certain kind of allocations separate from others. +- Enforce particular, fixed size of Vulkan memory blocks. +- Limit maximum amount of Vulkan memory allocated for that pool. +- Reserve minimum or fixed amount of Vulkan memory always preallocated for that pool. +- Use extra parameters for a set of your allocations that are available in #VmaPoolCreateInfo but not in + #VmaAllocationCreateInfo - e.g., custom minimum alignment, custom `pNext` chain. +- Perform defragmentation on a specific subset of your allocations. + +To use custom memory pools: + +-# Fill VmaPoolCreateInfo structure. +-# Call vmaCreatePool() to obtain #VmaPool handle. +-# When making an allocation, set VmaAllocationCreateInfo::pool to this handle. + You don't need to specify any other parameters of this structure, like `usage`. + +Example: + +\code +// Find memoryTypeIndex for the pool. +VkBufferCreateInfo sampleBufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; +sampleBufCreateInfo.size = 0x10000; // Doesn't matter. +sampleBufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + +VmaAllocationCreateInfo sampleAllocCreateInfo = {}; +sampleAllocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO; + +uint32_t memTypeIndex; +VkResult res = vmaFindMemoryTypeIndexForBufferInfo(allocator, + &sampleBufCreateInfo, &sampleAllocCreateInfo, &memTypeIndex); +// Check res... + +// Create a pool that can have at most 2 blocks, 128 MiB each. +VmaPoolCreateInfo poolCreateInfo = {}; +poolCreateInfo.memoryTypeIndex = memTypeIndex; +poolCreateInfo.blockSize = 128ull * 1024 * 1024; +poolCreateInfo.maxBlockCount = 2; + +VmaPool pool; +res = vmaCreatePool(allocator, &poolCreateInfo, &pool); +// Check res... + +// Allocate a buffer out of it. +VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; +bufCreateInfo.size = 1024; +bufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + +VmaAllocationCreateInfo allocCreateInfo = {}; +allocCreateInfo.pool = pool; + +VkBuffer buf; +VmaAllocation alloc; +res = vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, nullptr); +// Check res... +\endcode + +You have to free all allocations made from this pool before destroying it. + +\code +vmaDestroyBuffer(allocator, buf, alloc); +vmaDestroyPool(allocator, pool); +\endcode + +New versions of this library support creating dedicated allocations in custom pools. +It is supported only when VmaPoolCreateInfo::blockSize = 0. +To use this feature, set VmaAllocationCreateInfo::pool to the pointer to your custom pool and +VmaAllocationCreateInfo::flags to #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT. + + +\section custom_memory_pools_MemTypeIndex Choosing memory type index + +When creating a pool, you must explicitly specify memory type index. +To find the one suitable for your buffers or images, you can use helper functions +vmaFindMemoryTypeIndexForBufferInfo(), vmaFindMemoryTypeIndexForImageInfo(). +You need to provide structures with example parameters of buffers or images +that you are going to create in that pool. + +\code +VkBufferCreateInfo exampleBufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; +exampleBufCreateInfo.size = 1024; // Doesn't matter +exampleBufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + +VmaAllocationCreateInfo allocCreateInfo = {}; +allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO; + +uint32_t memTypeIndex; +vmaFindMemoryTypeIndexForBufferInfo(allocator, &exampleBufCreateInfo, &allocCreateInfo, &memTypeIndex); + +VmaPoolCreateInfo poolCreateInfo = {}; +poolCreateInfo.memoryTypeIndex = memTypeIndex; +// ... +\endcode + +When creating buffers/images allocated in that pool, provide following parameters: + +- `VkBufferCreateInfo`: Prefer to pass same parameters as above. + Otherwise you risk creating resources in a memory type that is not suitable for them, which may result in undefined behavior. + Using different `VK_BUFFER_USAGE_` flags may work, but you shouldn't create images in a pool intended for buffers + or the other way around. +- VmaAllocationCreateInfo: You don't need to pass same parameters. Fill only `pool` member. + Other members are ignored anyway. + + +\section custom_memory_pools_when_not_use When not to use custom pools + +Custom pools are commonly overused by VMA users. +While it may feel natural to keep some logical groups of resources separate in memory, +in most cases it does more harm than good. +Using custom pool shouldn't be your first choice. +Instead, please make all allocations from default pools first and only use custom pools +if you can prove and measure that it is beneficial in some way, +e.g. it results in lower memory usage, better performance, etc. + +Using custom pools has disadvantages: + +- Each pool has its own collection of `VkDeviceMemory` blocks. + Some of them may be partially or even completely empty. + Spreading allocations across multiple pools increases the amount of wasted (allocated but unbound) memory. +- You must manually choose specific memory type to be used by a custom pool (set as VmaPoolCreateInfo::memoryTypeIndex). + When using default pools, best memory type for each of your allocations can be selected automatically + using a carefully design algorithm that works across all kinds of GPUs. +- If an allocation from a custom pool at specific memory type fails, entire allocation operation returns failure. + When using default pools, VMA tries another compatible memory type. +- If you set VmaPoolCreateInfo::blockSize != 0, each memory block has the same size, + while default pools start from small blocks and only allocate next blocks larger and larger + up to the preferred block size. + +Many of the common concerns can be addressed in a different way than using custom pools: + +- If you want to keep your allocations of certain size (small versus large) or certain lifetime (transient versus long lived) + separate, you likely don't need to. + VMA uses a high quality allocation algorithm that manages memory well in various cases. + Please measure and check if using custom pools provides a benefit. +- If you want to keep your images and buffers separate, you don't need to. + VMA respects `bufferImageGranularity` limit automatically. +- If you want to keep your mapped and not mapped allocations separate, you don't need to. + VMA respects `nonCoherentAtomSize` limit automatically. + It also maps only those `VkDeviceMemory` blocks that need to map any allocation. + It even tries to keep mappable and non-mappable allocations in separate blocks to minimize the amount of mapped memory. +- If you want to choose a custom size for the default memory block, you can set it globally instead + using VmaAllocatorCreateInfo::preferredLargeHeapBlockSize. +- If you want to select specific memory type for your allocation, + you can set VmaAllocationCreateInfo::memoryTypeBits to `(1u << myMemoryTypeIndex)` instead. +- If you need to create a buffer with certain minimum alignment, you can still do it + using default pools with dedicated function vmaCreateBufferWithAlignment(). + + +\section linear_algorithm Linear allocation algorithm + +Each Vulkan memory block managed by this library has accompanying metadata that +keeps track of used and unused regions. By default, the metadata structure and +algorithm tries to find best place for new allocations among free regions to +optimize memory usage. This way you can allocate and free objects in any order. + +![Default allocation algorithm](../gfx/Linear_allocator_1_algo_default.png) + +Sometimes there is a need to use simpler, linear allocation algorithm. You can +create custom pool that uses such algorithm by adding flag +#VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT to VmaPoolCreateInfo::flags while creating +#VmaPool object. Then an alternative metadata management is used. It always +creates new allocations after last one and doesn't reuse free regions after +allocations freed in the middle. It results in better allocation performance and +less memory consumed by metadata. + +![Linear allocation algorithm](../gfx/Linear_allocator_2_algo_linear.png) + +With this one flag, you can create a custom pool that can be used in many ways: +free-at-once, stack, double stack, and ring buffer. See below for details. +You don't need to specify explicitly which of these options you are going to use - it is detected automatically. + +\subsection linear_algorithm_free_at_once Free-at-once + +In a pool that uses linear algorithm, you still need to free all the allocations +individually, e.g. by using vmaFreeMemory() or vmaDestroyBuffer(). You can free +them in any order. New allocations are always made after last one - free space +in the middle is not reused. However, when you release all the allocation and +the pool becomes empty, allocation starts from the beginning again. This way you +can use linear algorithm to speed up creation of allocations that you are going +to release all at once. + +![Free-at-once](../gfx/Linear_allocator_3_free_at_once.png) + +This mode is also available for pools created with VmaPoolCreateInfo::maxBlockCount +value that allows multiple memory blocks. + +\subsection linear_algorithm_stack Stack + +When you free an allocation that was created last, its space can be reused. +Thanks to this, if you always release allocations in the order opposite to their +creation (LIFO - Last In First Out), you can achieve behavior of a stack. + +![Stack](../gfx/Linear_allocator_4_stack.png) + +This mode is also available for pools created with VmaPoolCreateInfo::maxBlockCount +value that allows multiple memory blocks. + +\subsection linear_algorithm_double_stack Double stack + +The space reserved by a custom pool with linear algorithm may be used by two +stacks: + +- First, default one, growing up from offset 0. +- Second, "upper" one, growing down from the end towards lower offsets. + +To make allocation from the upper stack, add flag #VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT +to VmaAllocationCreateInfo::flags. + +![Double stack](../gfx/Linear_allocator_7_double_stack.png) + +Double stack is available only in pools with one memory block - +VmaPoolCreateInfo::maxBlockCount must be 1. Otherwise behavior is undefined. + +When the two stacks' ends meet so there is not enough space between them for a +new allocation, such allocation fails with usual +`VK_ERROR_OUT_OF_DEVICE_MEMORY` error. + +\subsection linear_algorithm_ring_buffer Ring buffer + +When you free some allocations from the beginning and there is not enough free space +for a new one at the end of a pool, allocator's "cursor" wraps around to the +beginning and starts allocation there. Thanks to this, if you always release +allocations in the same order as you created them (FIFO - First In First Out), +you can achieve behavior of a ring buffer / queue. + +![Ring buffer](../gfx/Linear_allocator_5_ring_buffer.png) + +Ring buffer is available only in pools with one memory block - +VmaPoolCreateInfo::maxBlockCount must be 1. Otherwise behavior is undefined. + +\note \ref defragmentation is not supported in custom pools created with #VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT. + + +\page defragmentation Defragmentation + +Interleaved allocations and deallocations of many objects of varying size can +cause fragmentation over time, which can lead to a situation where the library is unable +to find a continuous range of free memory for a new allocation despite there is +enough free space, just scattered across many small free ranges between existing +allocations. + +To mitigate this problem, you can use defragmentation feature. +It doesn't happen automatically though and needs your cooperation, +because VMA is a low level library that only allocates memory. +It cannot recreate buffers and images in a new place as it doesn't remember the contents of `VkBufferCreateInfo` / `VkImageCreateInfo` structures. +It cannot copy their contents as it doesn't record any commands to a command buffer. + +Example: + +\code +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); +\endcode + +Although functions like vmaCreateBuffer(), vmaCreateImage(), vmaDestroyBuffer(), vmaDestroyImage() +create/destroy an allocation and a buffer/image at once, these are just a shortcut for +creating the resource, allocating memory, and binding them together. +Defragmentation works on memory allocations only. You must handle the rest manually. +Defragmentation is an iterative process that should repreat "passes" as long as related functions +return `VK_INCOMPLETE` not `VK_SUCCESS`. +In each pass: + +1. vmaBeginDefragmentationPass() function call: + - Calculates and returns the list of allocations to be moved in this pass. + Note this can be a time-consuming process. + - Reserves destination memory for them by creating temporary destination allocations + that you can query for their `VkDeviceMemory` + offset using vmaGetAllocationInfo(). +2. Inside the pass, **you should**: + - Inspect the returned list of allocations to be moved. + - Create new buffers/images and bind them at the returned destination temporary allocations. + - Copy data from source to destination resources if necessary. + - Destroy the source buffers/images, but NOT their allocations. +3. vmaEndDefragmentationPass() function call: + - Frees the source memory reserved for the allocations that are moved. + - Modifies source #VmaAllocation objects that are moved to point to the destination reserved memory. + - Frees `VkDeviceMemory` blocks that became empty. + +Unlike in previous iterations of the defragmentation API, there is no list of "movable" allocations passed as a parameter. +Defragmentation algorithm tries to move all suitable allocations. +You can, however, refuse to move some of them inside a defragmentation pass, by setting +`pass.pMoves[i].operation` to #VMA_DEFRAGMENTATION_MOVE_OPERATION_IGNORE. +This is not recommended and may result in suboptimal packing of the allocations after defragmentation. +If you cannot ensure any allocation can be moved, it is better to keep movable allocations separate in a custom pool. + +Inside a pass, for each allocation that should be moved: + +- You should copy its data from the source to the destination place by calling e.g. `vkCmdCopyBuffer()`, `vkCmdCopyImage()`. + - You need to make sure these commands finished executing before destroying the source buffers/images and before calling vmaEndDefragmentationPass(). +- If a resource doesn't contain any meaningful data, e.g. it is a transient color attachment image to be cleared, + filled, and used temporarily in each rendering frame, you can just recreate this image + without copying its data. +- If the resource is in `HOST_VISIBLE` and `HOST_CACHED` memory, you can copy its data on the CPU + using `memcpy()`. +- If you cannot move the allocation, you can set `pass.pMoves[i].operation` to #VMA_DEFRAGMENTATION_MOVE_OPERATION_IGNORE. + This will cancel the move. + - vmaEndDefragmentationPass() will then free the destination memory + not the source memory of the allocation, leaving it unchanged. +- If you decide the allocation is unimportant and can be destroyed instead of moved (e.g. it wasn't used for long time), + you can set `pass.pMoves[i].operation` to #VMA_DEFRAGMENTATION_MOVE_OPERATION_DESTROY. + - vmaEndDefragmentationPass() will then free both source and destination memory, and will destroy the source #VmaAllocation object. + +You can defragment a specific custom pool by setting VmaDefragmentationInfo::pool +(like in the example above) or all the default pools by setting this member to null. + +Defragmentation is always performed in each pool separately. +Allocations are never moved between different Vulkan memory types. +The size of the destination memory reserved for a moved allocation is the same as the original one. +Alignment of an allocation as it was determined using `vkGetBufferMemoryRequirements()` etc. is also respected after defragmentation. +Buffers/images should be recreated with the same `VkBufferCreateInfo` / `VkImageCreateInfo` parameters as the original ones. + +You can perform the defragmentation incrementally to limit the number of allocations and bytes to be moved +in each pass, e.g. to call it in sync with render frames and not to experience too big hitches. +See members: VmaDefragmentationInfo::maxBytesPerPass, VmaDefragmentationInfo::maxAllocationsPerPass. + +It is also safe to perform the defragmentation asynchronously to render frames and other Vulkan and VMA +usage, possibly from multiple threads, with the exception that allocations +returned in VmaDefragmentationPassMoveInfo::pMoves shouldn't be destroyed until the defragmentation pass is ended. + +Mapping is preserved on allocations that are moved during defragmentation. +Whether through #VMA_ALLOCATION_CREATE_MAPPED_BIT or vmaMapMemory(), the allocations +are mapped at their new place. Of course, pointer to the mapped data changes, so it needs to be queried +using VmaAllocationInfo::pMappedData. + +\note Defragmentation is not supported in custom pools created with #VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT. + + +\page statistics Statistics + +This library contains several functions that return information about its internal state, +especially the amount of memory allocated from Vulkan. + +\section statistics_numeric_statistics Numeric statistics + +If you need to obtain basic statistics about memory usage per heap, together with current budget, +you can call function vmaGetHeapBudgets() and inspect structure #VmaBudget. +This is useful to keep track of memory usage and stay within budget +(see also \ref staying_within_budget). +Example: + +\code +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); +\endcode + +You can query for more detailed statistics per memory heap, type, and totals, +including minimum and maximum allocation size and unused range size, +by calling function vmaCalculateStatistics() and inspecting structure #VmaTotalStatistics. +This function is slower though, as it has to traverse all the internal data structures, +so it should be used only for debugging purposes. + +You can query for statistics of a custom pool using function vmaGetPoolStatistics() +or vmaCalculatePoolStatistics(). + +You can query for information about a specific allocation using function vmaGetAllocationInfo(). +It fill structure #VmaAllocationInfo. + +\section statistics_json_dump JSON dump + +You can dump internal state of the allocator to a string in JSON format using function vmaBuildStatsString(). +The result is guaranteed to be correct JSON. +It uses ANSI encoding. +Any strings provided by user (see [Allocation names](@ref allocation_names)) +are copied as-is and properly escaped for JSON, so if they use UTF-8, ISO-8859-2 or any other encoding, +this JSON string can be treated as using this encoding. +It must be freed using function vmaFreeStatsString(). + +The format of this JSON string is not part of official documentation of the library, +but it will not change in backward-incompatible way without increasing library major version number +and appropriate mention in changelog. + +The JSON string contains all the data that can be obtained using vmaCalculateStatistics(). +It can also contain detailed map of allocated memory blocks and their regions - +free and occupied by allocations. +This allows e.g. to visualize the memory or assess fragmentation. + + +\page allocation_annotation Allocation names and user data + +\section allocation_user_data Allocation user data + +You can annotate allocations with your own information, e.g. for debugging purposes. +To do that, fill VmaAllocationCreateInfo::pUserData field when creating +an allocation. It is an opaque `void*` pointer. You can use it e.g. as a pointer, +some handle, index, key, ordinal number or any other value that would associate +the allocation with your custom metadata. +It is useful to identify appropriate data structures in your engine given #VmaAllocation, +e.g. when doing \ref defragmentation. + +\code +VkBufferCreateInfo bufCreateInfo = ... + +MyBufferMetadata* pMetadata = CreateBufferMetadata(); + +VmaAllocationCreateInfo allocCreateInfo = {}; +allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO; +allocCreateInfo.pUserData = pMetadata; + +VkBuffer buffer; +VmaAllocation allocation; +vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buffer, &allocation, nullptr); +\endcode + +The pointer may be later retrieved as VmaAllocationInfo::pUserData: + +\code +VmaAllocationInfo allocInfo; +vmaGetAllocationInfo(allocator, allocation, &allocInfo); +MyBufferMetadata* pMetadata = (MyBufferMetadata*)allocInfo.pUserData; +\endcode + +It can also be changed using function vmaSetAllocationUserData(). + +Values of (non-zero) allocations' `pUserData` are printed in JSON report created by +vmaBuildStatsString() in hexadecimal form. + +\section allocation_names Allocation names + +An allocation can also carry a null-terminated string, giving a name to the allocation. +To set it, call vmaSetAllocationName(). +The library creates internal copy of the string, so the pointer you pass doesn't need +to be valid for whole lifetime of the allocation. You can free it after the call. + +\code +std::string imageName = "Texture: "; +imageName += fileName; +vmaSetAllocationName(allocator, allocation, imageName.c_str()); +\endcode + +The string can be later retrieved by inspecting VmaAllocationInfo::pName. +It is also printed in JSON report created by vmaBuildStatsString(). + +\note Setting string name to VMA allocation doesn't automatically set it to the Vulkan buffer or image created with it. +You must do it manually using an extension like VK_EXT_debug_utils, which is independent of this library. + + +\page virtual_allocator Virtual allocator + +As an extra feature, the core allocation algorithm of the library is exposed through a simple and convenient API of "virtual allocator". +It doesn't allocate any real GPU memory. It just keeps track of used and free regions of a "virtual block". +You can use it to allocate your own memory or other objects, even completely unrelated to Vulkan. +A common use case is sub-allocation of pieces of one large GPU buffer. + +\section virtual_allocator_creating_virtual_block Creating virtual block + +To use this functionality, there is no main "allocator" object. +You don't need to have #VmaAllocator object created. +All you need to do is to create a separate #VmaVirtualBlock object for each block of memory you want to be managed by the allocator: + +-# Fill in #VmaVirtualBlockCreateInfo structure. +-# Call vmaCreateVirtualBlock(). Get new #VmaVirtualBlock object. + +Example: + +\code +VmaVirtualBlockCreateInfo blockCreateInfo = {}; +blockCreateInfo.size = 1048576; // 1 MB + +VmaVirtualBlock block; +VkResult res = vmaCreateVirtualBlock(&blockCreateInfo, &block); +\endcode + +\section virtual_allocator_making_virtual_allocations Making virtual allocations + +#VmaVirtualBlock object contains internal data structure that keeps track of free and occupied regions +using the same code as the main Vulkan memory allocator. +Similarly to #VmaAllocation for standard GPU allocations, there is #VmaVirtualAllocation type +that represents an opaque handle to an allocation within the virtual block. + +In order to make such allocation: + +-# Fill in #VmaVirtualAllocationCreateInfo structure. +-# Call vmaVirtualAllocate(). Get new #VmaVirtualAllocation object that represents the allocation. + You can also receive `VkDeviceSize offset` that was assigned to the allocation. + +Example: + +\code +VmaVirtualAllocationCreateInfo allocCreateInfo = {}; +allocCreateInfo.size = 4096; // 4 KB + +VmaVirtualAllocation alloc; +VkDeviceSize offset; +res = vmaVirtualAllocate(block, &allocCreateInfo, &alloc, &offset); +if(res == VK_SUCCESS) +{ + // Use the 4 KB of your memory starting at offset. +} +else +{ + // Allocation failed - no space for it could be found. Handle this error! +} +\endcode + +\section virtual_allocator_deallocation Deallocation + +When no longer needed, an allocation can be freed by calling vmaVirtualFree(). +You can only pass to this function an allocation that was previously returned by vmaVirtualAllocate() +called for the same #VmaVirtualBlock. + +When whole block is no longer needed, the block object can be released by calling vmaDestroyVirtualBlock(). +All allocations must be freed before the block is destroyed, which is checked internally by an assert. +However, if you don't want to call vmaVirtualFree() for each allocation, you can use vmaClearVirtualBlock() to free them all at once - +a feature not available in normal Vulkan memory allocator. Example: + +\code +vmaVirtualFree(block, alloc); +vmaDestroyVirtualBlock(block); +\endcode + +\section virtual_allocator_allocation_parameters Allocation parameters + +You can attach a custom pointer to each allocation by using vmaSetVirtualAllocationUserData(). +Its default value is null. +It can be used to store any data that needs to be associated with that allocation - e.g. an index, a handle, or a pointer to some +larger data structure containing more information. Example: + +\code +struct CustomAllocData +{ + std::string m_AllocName; +}; +CustomAllocData* allocData = new CustomAllocData(); +allocData->m_AllocName = "My allocation 1"; +vmaSetVirtualAllocationUserData(block, alloc, allocData); +\endcode + +The pointer can later be fetched, along with allocation offset and size, by passing the allocation handle to function +vmaGetVirtualAllocationInfo() and inspecting returned structure #VmaVirtualAllocationInfo. +If you allocated a new object to be used as the custom pointer, don't forget to delete that object before freeing the allocation! +Example: + +\code +VmaVirtualAllocationInfo allocInfo; +vmaGetVirtualAllocationInfo(block, alloc, &allocInfo); +delete (CustomAllocData*)allocInfo.pUserData; + +vmaVirtualFree(block, alloc); +\endcode + +\section virtual_allocator_alignment_and_units Alignment and units + +It feels natural to express sizes and offsets in bytes. +If an offset of an allocation needs to be aligned to a multiply of some number (e.g. 4 bytes), you can fill optional member +VmaVirtualAllocationCreateInfo::alignment to request it. Example: + +\code +VmaVirtualAllocationCreateInfo allocCreateInfo = {}; +allocCreateInfo.size = 4096; // 4 KB +allocCreateInfo.alignment = 4; // Returned offset must be a multiply of 4 B + +VmaVirtualAllocation alloc; +res = vmaVirtualAllocate(block, &allocCreateInfo, &alloc, nullptr); +\endcode + +Alignments of different allocations made from one block may vary. +However, if all alignments and sizes are always multiply of some size e.g. 4 B or `sizeof(MyDataStruct)`, +you can express all sizes, alignments, and offsets in multiples of that size instead of individual bytes. +It might be more convenient, but you need to make sure to use this new unit consistently in all the places: + +- VmaVirtualBlockCreateInfo::size +- VmaVirtualAllocationCreateInfo::size and VmaVirtualAllocationCreateInfo::alignment +- Using offset returned by vmaVirtualAllocate() or in VmaVirtualAllocationInfo::offset + +\section virtual_allocator_statistics Statistics + +You can obtain statistics of a virtual block using vmaGetVirtualBlockStatistics() +(to get brief statistics that are fast to calculate) +or vmaCalculateVirtualBlockStatistics() (to get more detailed statistics, slower to calculate). +The functions fill structures #VmaStatistics, #VmaDetailedStatistics respectively - same as used by the normal Vulkan memory allocator. +Example: + +\code +VmaStatistics stats; +vmaGetVirtualBlockStatistics(block, &stats); +printf("My virtual block has %llu bytes used by %u virtual allocations\n", + stats.allocationBytes, stats.allocationCount); +\endcode + +You can also request a full list of allocations and free regions as a string in JSON format by calling +vmaBuildVirtualBlockStatsString(). +Returned string must be later freed using vmaFreeVirtualBlockStatsString(). +The format of this string differs from the one returned by the main Vulkan allocator, but it is similar. + +\section virtual_allocator_additional_considerations Additional considerations + +The "virtual allocator" functionality is implemented on a level of individual memory blocks. +Keeping track of a whole collection of blocks, allocating new ones when out of free space, +deleting empty ones, and deciding which one to try first for a new allocation must be implemented by the user. + +Alternative allocation algorithms are supported, just like in custom pools of the real GPU memory. +See enum #VmaVirtualBlockCreateFlagBits to learn how to specify them (e.g. #VMA_VIRTUAL_BLOCK_CREATE_LINEAR_ALGORITHM_BIT). +You can find their description in chapter \ref custom_memory_pools. +Allocation strategies are also supported. +See enum #VmaVirtualAllocationCreateFlagBits to learn how to specify them (e.g. #VMA_VIRTUAL_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT). + +Following features are supported only by the allocator of the real GPU memory and not by virtual allocations: +buffer-image granularity, `VMA_DEBUG_MARGIN`, `VMA_MIN_ALIGNMENT`. + + +\page debugging_memory_usage Debugging incorrect memory usage + +If you suspect a bug with memory usage, like usage of uninitialized memory or +memory being overwritten out of bounds of an allocation, +you can use debug features of this library to verify this. + +\section debugging_memory_usage_initialization Memory initialization + +If you experience a bug with incorrect and nondeterministic data in your program and you suspect uninitialized memory to be used, +you can enable automatic memory initialization to verify this. +To do it, define macro `VMA_DEBUG_INITIALIZE_ALLOCATIONS` to 1. + +\code +#define VMA_DEBUG_INITIALIZE_ALLOCATIONS 1 +#include "vk_mem_alloc.h" +\endcode + +It makes memory of new allocations initialized to bit pattern `0xDCDCDCDC`. +Before an allocation is destroyed, its memory is filled with bit pattern `0xEFEFEFEF`. +Memory is automatically mapped and unmapped if necessary. + +If you find these values while debugging your program, good chances are that you incorrectly +read Vulkan memory that is allocated but not initialized, or already freed, respectively. + +Memory initialization works only with memory types that are `HOST_VISIBLE` and with allocations that can be mapped. +It works also with dedicated allocations. + +\section debugging_memory_usage_margins Margins + +By default, allocations are laid out in memory blocks next to each other if possible +(considering required alignment, `bufferImageGranularity`, and `nonCoherentAtomSize`). + +![Allocations without margin](../gfx/Margins_1.png) + +Define macro `VMA_DEBUG_MARGIN` to some non-zero value (e.g. 16) to enforce specified +number of bytes as a margin after every allocation. + +\code +#define VMA_DEBUG_MARGIN 16 +#include "vk_mem_alloc.h" +\endcode + +![Allocations with margin](../gfx/Margins_2.png) + +If your bug goes away after enabling margins, it means it may be caused by memory +being overwritten outside of allocation boundaries. It is not 100% certain though. +Change in application behavior may also be caused by different order and distribution +of allocations across memory blocks after margins are applied. + +Margins work with all types of memory. + +Margin is applied only to allocations made out of memory blocks and not to dedicated +allocations, which have their own memory block of specific size. +It is thus not applied to allocations made using #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT flag +or those automatically decided to put into dedicated allocations, e.g. due to its +large size or recommended by VK_KHR_dedicated_allocation extension. + +Margins appear in [JSON dump](@ref statistics_json_dump) as part of free space. + +Note that enabling margins increases memory usage and fragmentation. + +Margins do not apply to \ref virtual_allocator. + +\section debugging_memory_usage_corruption_detection Corruption detection + +You can additionally define macro `VMA_DEBUG_DETECT_CORRUPTION` to 1 to enable validation +of contents of the margins. + +\code +#define VMA_DEBUG_MARGIN 16 +#define VMA_DEBUG_DETECT_CORRUPTION 1 +#include "vk_mem_alloc.h" +\endcode + +When this feature is enabled, number of bytes specified as `VMA_DEBUG_MARGIN` +(it must be multiply of 4) after every allocation is filled with a magic number. +This idea is also know as "canary". +Memory is automatically mapped and unmapped if necessary. + +This number is validated automatically when the allocation is destroyed. +If it is not equal to the expected value, `VMA_ASSERT()` is executed. +It clearly means that either CPU or GPU overwritten the memory outside of boundaries of the allocation, +which indicates a serious bug. + +You can also explicitly request checking margins of all allocations in all memory blocks +that belong to specified memory types by using function vmaCheckCorruption(), +or in memory blocks that belong to specified custom pool, by using function +vmaCheckPoolCorruption(). + +Margin validation (corruption detection) works only for memory types that are +`HOST_VISIBLE` and `HOST_COHERENT`. + + +\section debugging_memory_usage_leak_detection Leak detection features + +At allocation and allocator destruction time VMA checks for unfreed and unmapped blocks using +`VMA_ASSERT_LEAK()`. This macro defaults to an assertion, triggering a typically fatal error in Debug +builds, and doing nothing in Release builds. You can provide your own definition of `VMA_ASSERT_LEAK()` +to change this behavior. + +At memory block destruction time VMA lists out all unfreed allocations using the `VMA_LEAK_LOG_FORMAT()` +macro, which defaults to `VMA_DEBUG_LOG_FORMAT`, which in turn defaults to a no-op. +If you're having trouble with leaks - for example, the aforementioned assertion triggers, but you don't +quite know \em why -, overriding this macro to print out the the leaking blocks, combined with assigning +individual names to allocations using vmaSetAllocationName(), can greatly aid in fixing them. + +\page other_api_interop Interop with other graphics APIs + +VMA provides some features that help with interoperability with other graphics APIs, e.g. OpenGL. + +\section opengl_interop_exporting_memory Exporting memory + +If you want to attach `VkExportMemoryAllocateInfoKHR` or other structure to `pNext` chain of memory allocations made by the library: + +You can create \ref custom_memory_pools for such allocations. +Define and fill in your `VkExportMemoryAllocateInfoKHR` structure and attach it to VmaPoolCreateInfo::pMemoryAllocateNext +while creating the custom pool. +Please note that the structure must remain alive and unchanged for the whole lifetime of the #VmaPool, +not only while creating it, as no copy of the structure is made, +but its original pointer is used for each allocation instead. + +If you want to export all memory allocated by VMA from certain memory types, +also dedicated allocations or other allocations made from default pools, +an alternative solution is to fill in VmaAllocatorCreateInfo::pTypeExternalMemoryHandleTypes. +It should point to an array with `VkExternalMemoryHandleTypeFlagsKHR` to be automatically passed by the library +through `VkExportMemoryAllocateInfoKHR` on each allocation made from a specific memory type. +Please note that new versions of the library also support dedicated allocations created in custom pools. + +You should not mix these two methods in a way that allows to apply both to the same memory type. +Otherwise, `VkExportMemoryAllocateInfoKHR` structure would be attached twice to the `pNext` chain of `VkMemoryAllocateInfo`. + + +\section opengl_interop_custom_alignment Custom alignment + +Buffers or images exported to a different API like OpenGL may require a different alignment, +higher than the one used by the library automatically, queried from functions like `vkGetBufferMemoryRequirements`. +To impose such alignment: + +You can create \ref custom_memory_pools for such allocations. +Set VmaPoolCreateInfo::minAllocationAlignment member to the minimum alignment required for each allocation +to be made out of this pool. +The alignment actually used will be the maximum of this member and the alignment returned for the specific buffer or image +from a function like `vkGetBufferMemoryRequirements`, which is called by VMA automatically. + +If you want to create a buffer with a specific minimum alignment out of default pools, +use special function vmaCreateBufferWithAlignment(), which takes additional parameter `minAlignment`. + +Note the problem of alignment affects only resources placed inside bigger `VkDeviceMemory` blocks and not dedicated +allocations, as these, by definition, always have alignment = 0 because the resource is bound to the beginning of its dedicated block. +You can ensure that an allocation is created as dedicated by using #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT. +Contrary to Direct3D 12, Vulkan doesn't have a concept of alignment of the entire memory block passed on its allocation. + +\section opengl_interop_extended_allocation_information Extended allocation information + +If you want to rely on VMA to allocate your buffers and images inside larger memory blocks, +but you need to know the size of the entire block and whether the allocation was made +with its own dedicated memory, use function vmaGetAllocationInfo2() to retrieve +extended allocation information in structure #VmaAllocationInfo2. + + + +\page usage_patterns Recommended usage patterns + +Vulkan gives great flexibility in memory allocation. +This chapter shows the most common patterns. + +See also slides from talk: +[Sawicki, Adam. Advanced Graphics Techniques Tutorial: Memory management in Vulkan and DX12. Game Developers Conference, 2018](https://www.gdcvault.com/play/1025458/Advanced-Graphics-Techniques-Tutorial-New) + + +\section usage_patterns_gpu_only GPU-only resource + +When: +Any resources that you frequently write and read on GPU, +e.g. images used as color attachments (aka "render targets"), depth-stencil attachments, +images/buffers used as storage image/buffer (aka "Unordered Access View (UAV)"). + +What to do: +Let the library select the optimal memory type, which will likely have `VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT`. + +\code +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; + +VmaAllocationCreateInfo allocCreateInfo = {}; +allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO; +allocCreateInfo.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT; +allocCreateInfo.priority = 1.0f; + +VkImage img; +VmaAllocation alloc; +vmaCreateImage(allocator, &imgCreateInfo, &allocCreateInfo, &img, &alloc, nullptr); +\endcode + +Also consider: +Consider creating them as dedicated allocations using #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT, +especially if they are large or if you plan to destroy and recreate them with different sizes +e.g. when display resolution changes. +Prefer to create such resources first and all other GPU resources (like textures and vertex buffers) later. +When VK_EXT_memory_priority extension is enabled, it is also worth setting high priority to such allocation +to decrease chances to be evicted to system memory by the operating system. + +\section usage_patterns_staging_copy_upload Staging copy for upload + +When: +A "staging" buffer than you want to map and fill from CPU code, then use as a source of transfer +to some GPU resource. + +What to do: +Use flag #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT. +Let the library select the optimal memory type, which will always have `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT`. + +\code +VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; +bufCreateInfo.size = 65536; +bufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; + +VmaAllocationCreateInfo allocCreateInfo = {}; +allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO; +allocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | + VMA_ALLOCATION_CREATE_MAPPED_BIT; + +VkBuffer buf; +VmaAllocation alloc; +VmaAllocationInfo allocInfo; +vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo); + +... + +memcpy(allocInfo.pMappedData, myData, myDataSize); +\endcode + +Also consider: +You can map the allocation using vmaMapMemory() or you can create it as persistenly mapped +using #VMA_ALLOCATION_CREATE_MAPPED_BIT, as in the example above. + + +\section usage_patterns_readback Readback + +When: +Buffers for data written by or transferred from the GPU that you want to read back on the CPU, +e.g. results of some computations. + +What to do: +Use flag #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT. +Let the library select the optimal memory type, which will always have `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` +and `VK_MEMORY_PROPERTY_HOST_CACHED_BIT`. + +\code +VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; +bufCreateInfo.size = 65536; +bufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; + +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); + +... + +const float* downloadedData = (const float*)allocInfo.pMappedData; +\endcode + + +\section usage_patterns_advanced_data_uploading Advanced data uploading + +For resources that you frequently write on CPU via mapped pointer and +frequently read on GPU e.g. as a uniform buffer (also called "dynamic"), multiple options are possible: + +-# Easiest solution is to have one copy of the resource in `HOST_VISIBLE` memory, + even if it means system RAM (not `DEVICE_LOCAL`) on systems with a discrete graphics card, + and make the device reach out to that resource directly. + - Reads performed by the device will then go through PCI Express bus. + The performance of this access may be limited, but it may be fine depending on the size + of this resource (whether it is small enough to quickly end up in GPU cache) and the sparsity + of access. +-# On systems with unified memory (e.g. AMD APU or Intel integrated graphics, mobile chips), + a memory type may be available that is both `HOST_VISIBLE` (available for mapping) and `DEVICE_LOCAL` + (fast to access from the GPU). Then, it is likely the best choice for such type of resource. +-# Systems with a discrete graphics card and separate video memory may or may not expose + a memory type that is both `HOST_VISIBLE` and `DEVICE_LOCAL`, also known as Base Address Register (BAR). + If they do, it represents a piece of VRAM (or entire VRAM, if ReBAR is enabled in the motherboard BIOS) + that is available to CPU for mapping. + - Writes performed by the host to that memory go through PCI Express bus. + The performance of these writes may be limited, but it may be fine, especially on PCIe 4.0, + as long as rules of using uncached and write-combined memory are followed - only sequential writes and no reads. +-# Finally, you may need or prefer to create a separate copy of the resource in `DEVICE_LOCAL` memory, + a separate "staging" copy in `HOST_VISIBLE` memory and perform an explicit transfer command between them. + +Thankfully, VMA offers an aid to create and use such resources in the the way optimal +for the current Vulkan device. To help the library make the best choice, +use flag #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT together with +#VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT. +It will then prefer a memory type that is both `DEVICE_LOCAL` and `HOST_VISIBLE` (integrated memory or BAR), +but if no such memory type is available or allocation from it fails +(PC graphics cards have only 256 MB of BAR by default, unless ReBAR is supported and enabled in BIOS), +it will fall back to `DEVICE_LOCAL` memory for fast GPU access. +It is then up to you to detect that the allocation ended up in a memory type that is not `HOST_VISIBLE`, +so you need to create another "staging" allocation and perform explicit transfers. + +\code +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; +allocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | + VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT | + VMA_ALLOCATION_CREATE_MAPPED_BIT; + +VkBuffer buf; +VmaAllocation alloc; +VmaAllocationInfo allocInfo; +VkResult result = vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo); +// Check result... + +VkMemoryPropertyFlags memPropFlags; +vmaGetAllocationMemoryProperties(allocator, alloc, &memPropFlags); + +if(memPropFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) +{ + // Allocation ended up in a mappable memory and is already mapped - write to it directly. + + // [Executed in runtime]: + memcpy(allocInfo.pMappedData, myData, myDataSize); + result = vmaFlushAllocation(allocator, alloc, 0, VK_WHOLE_SIZE); + // Check result... + + VkBufferMemoryBarrier bufMemBarrier = { VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER }; + bufMemBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; + bufMemBarrier.dstAccessMask = VK_ACCESS_UNIFORM_READ_BIT; + bufMemBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + bufMemBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + bufMemBarrier.buffer = buf; + bufMemBarrier.offset = 0; + bufMemBarrier.size = VK_WHOLE_SIZE; + + vkCmdPipelineBarrier(cmdBuf, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, + 0, 0, nullptr, 1, &bufMemBarrier, 0, nullptr); +} +else +{ + // Allocation ended up in a non-mappable memory - a transfer using a staging buffer is required. + VkBufferCreateInfo stagingBufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; + stagingBufCreateInfo.size = 65536; + stagingBufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; + + VmaAllocationCreateInfo stagingAllocCreateInfo = {}; + stagingAllocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO; + stagingAllocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | + VMA_ALLOCATION_CREATE_MAPPED_BIT; + + VkBuffer stagingBuf; + VmaAllocation stagingAlloc; + VmaAllocationInfo stagingAllocInfo; + result = vmaCreateBuffer(allocator, &stagingBufCreateInfo, &stagingAllocCreateInfo, + &stagingBuf, &stagingAlloc, &stagingAllocInfo); + // Check result... + + // [Executed in runtime]: + memcpy(stagingAllocInfo.pMappedData, myData, myDataSize); + result = vmaFlushAllocation(allocator, stagingAlloc, 0, VK_WHOLE_SIZE); + // Check result... + + VkBufferMemoryBarrier bufMemBarrier = { VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER }; + bufMemBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; + bufMemBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + bufMemBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + bufMemBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + bufMemBarrier.buffer = stagingBuf; + bufMemBarrier.offset = 0; + bufMemBarrier.size = VK_WHOLE_SIZE; + + vkCmdPipelineBarrier(cmdBuf, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, 0, nullptr, 1, &bufMemBarrier, 0, nullptr); + + VkBufferCopy bufCopy = { + 0, // srcOffset + 0, // dstOffset, + myDataSize, // size + }; + + vkCmdCopyBuffer(cmdBuf, stagingBuf, buf, 1, &bufCopy); + + VkBufferMemoryBarrier bufMemBarrier2 = { VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER }; + bufMemBarrier2.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + bufMemBarrier2.dstAccessMask = VK_ACCESS_UNIFORM_READ_BIT; // We created a uniform buffer + bufMemBarrier2.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + bufMemBarrier2.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + bufMemBarrier2.buffer = buf; + bufMemBarrier2.offset = 0; + bufMemBarrier2.size = VK_WHOLE_SIZE; + + vkCmdPipelineBarrier(cmdBuf, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, + 0, 0, nullptr, 1, &bufMemBarrier2, 0, nullptr); +} +\endcode + +\section usage_patterns_other_use_cases Other use cases + +Here are some other, less obvious use cases and their recommended settings: + +- An image that is used only as transfer source and destination, but it should stay on the device, + as it is used to temporarily store a copy of some texture, e.g. from the current to the next frame, + for temporal antialiasing or other temporal effects. + - Use `VkImageCreateInfo::usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT` + - Use VmaAllocationCreateInfo::usage = #VMA_MEMORY_USAGE_AUTO +- An image that is used only as transfer source and destination, but it should be placed + in the system RAM despite it doesn't need to be mapped, because it serves as a "swap" copy to evict + least recently used textures from VRAM. + - Use `VkImageCreateInfo::usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT` + - Use VmaAllocationCreateInfo::usage = #VMA_MEMORY_USAGE_AUTO_PREFER_HOST, + as VMA needs a hint here to differentiate from the previous case. +- A buffer that you want to map and write from the CPU, directly read from the GPU + (e.g. as a uniform or vertex buffer), but you have a clear preference to place it in device or + host memory due to its large size. + - Use `VkBufferCreateInfo::usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT` + - Use VmaAllocationCreateInfo::usage = #VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE or #VMA_MEMORY_USAGE_AUTO_PREFER_HOST + - Use VmaAllocationCreateInfo::flags = #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT + + +\page configuration Configuration + +Please check "CONFIGURATION SECTION" in the code to find macros that you can define +before each include of this file or change directly in this file to provide +your own implementation of basic facilities like assert, `min()` and `max()` functions, +mutex, atomic etc. + +For example, define `VMA_ASSERT(expr)` before including the library to provide +custom implementation of the assertion, compatible with your project. +By default it is defined to standard C `assert(expr)` in `_DEBUG` configuration +and empty otherwise. + +Similarly, you can define `VMA_LEAK_LOG_FORMAT` macro to enable printing of leaked (unfreed) allocations, +including their names and other parameters. Example: + +\code +#define VMA_LEAK_LOG_FORMAT(format, ...) do { \ + printf((format), __VA_ARGS__); \ + printf("\n"); \ + } while(false) +\endcode + +\section config_Vulkan_functions Pointers to Vulkan functions + +There are multiple ways to import pointers to Vulkan functions in the library. +In the simplest case you don't need to do anything. +If the compilation or linking of your program or the initialization of the #VmaAllocator +doesn't work for you, you can try to reconfigure it. + +First, the allocator tries to fetch pointers to Vulkan functions linked statically, +like this: + +\code +m_VulkanFunctions.vkAllocateMemory = (PFN_vkAllocateMemory)vkAllocateMemory; +\endcode + +If you want to disable this feature, set configuration macro: `#define VMA_STATIC_VULKAN_FUNCTIONS 0`. + +Second, you can provide the pointers yourself by setting member VmaAllocatorCreateInfo::pVulkanFunctions. +You can fetch them e.g. using functions `vkGetInstanceProcAddr` and `vkGetDeviceProcAddr` or +by using a helper library like [volk](https://github.com/zeux/volk). + +Third, VMA tries to fetch remaining pointers that are still null by calling +`vkGetInstanceProcAddr` and `vkGetDeviceProcAddr` on its own. +You need to only fill in VmaVulkanFunctions::vkGetInstanceProcAddr and VmaVulkanFunctions::vkGetDeviceProcAddr. +Other pointers will be fetched automatically. +If you want to disable this feature, set configuration macro: `#define VMA_DYNAMIC_VULKAN_FUNCTIONS 0`. + +Finally, all the function pointers required by the library (considering selected +Vulkan version and enabled extensions) are checked with `VMA_ASSERT` if they are not null. + + +\section custom_memory_allocator Custom host memory allocator + +If you use custom allocator for CPU memory rather than default operator `new` +and `delete` from C++, you can make this library using your allocator as well +by filling optional member VmaAllocatorCreateInfo::pAllocationCallbacks. These +functions will be passed to Vulkan, as well as used by the library itself to +make any CPU-side allocations. + +\section allocation_callbacks Device memory allocation callbacks + +The library makes calls to `vkAllocateMemory()` and `vkFreeMemory()` internally. +You can setup callbacks to be informed about these calls, e.g. for the purpose +of gathering some statistics. To do it, fill optional member +VmaAllocatorCreateInfo::pDeviceMemoryCallbacks. + +\section heap_memory_limit Device heap memory limit + +When device memory of certain heap runs out of free space, new allocations may +fail (returning error code) or they may succeed, silently pushing some existing_ +memory blocks from GPU VRAM to system RAM (which degrades performance). This +behavior is implementation-dependent - it depends on GPU vendor and graphics +driver. + +On AMD cards it can be controlled while creating Vulkan device object by using +VK_AMD_memory_overallocation_behavior extension, if available. + +Alternatively, if you want to test how your program behaves with limited amount of Vulkan device +memory available without switching your graphics card to one that really has +smaller VRAM, you can use a feature of this library intended for this purpose. +To do it, fill optional member VmaAllocatorCreateInfo::pHeapSizeLimit. + + + +\page vk_khr_dedicated_allocation VK_KHR_dedicated_allocation + +VK_KHR_dedicated_allocation is a Vulkan extension which can be used to improve +performance on some GPUs. It augments Vulkan API with possibility to query +driver whether it prefers particular buffer or image to have its own, dedicated +allocation (separate `VkDeviceMemory` block) for better efficiency - to be able +to do some internal optimizations. The extension is supported by this library. +It will be used automatically when enabled. + +It has been promoted to core Vulkan 1.1, so if you use eligible Vulkan version +and inform VMA about it by setting VmaAllocatorCreateInfo::vulkanApiVersion, +you are all set. + +Otherwise, if you want to use it as an extension: + +1 . When creating Vulkan device, check if following 2 device extensions are +supported (call `vkEnumerateDeviceExtensionProperties()`). +If yes, enable them (fill `VkDeviceCreateInfo::ppEnabledExtensionNames`). + +- VK_KHR_get_memory_requirements2 +- VK_KHR_dedicated_allocation + +If you enabled these extensions: + +2 . Use #VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT flag when creating +your #VmaAllocator to inform the library that you enabled required extensions +and you want the library to use them. + +\code +allocatorInfo.flags |= VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT; + +vmaCreateAllocator(&allocatorInfo, &allocator); +\endcode + +That is all. The extension will be automatically used whenever you create a +buffer using vmaCreateBuffer() or image using vmaCreateImage(). + +When using the extension together with Vulkan Validation Layer, you will receive +warnings like this: + +_vkBindBufferMemory(): Binding memory to buffer 0x33 but vkGetBufferMemoryRequirements() has not been called on that buffer._ + +It is OK, you should just ignore it. It happens because you use function +`vkGetBufferMemoryRequirements2KHR()` instead of standard +`vkGetBufferMemoryRequirements()`, while the validation layer seems to be +unaware of it. + +To learn more about this extension, see: + +- [VK_KHR_dedicated_allocation in Vulkan specification](https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/chap50.html#VK_KHR_dedicated_allocation) +- [VK_KHR_dedicated_allocation unofficial manual](http://asawicki.info/articles/VK_KHR_dedicated_allocation.php5) + + + +\page vk_ext_memory_priority VK_EXT_memory_priority + +VK_EXT_memory_priority is a device extension that allows to pass additional "priority" +value to Vulkan memory allocations that the implementation may use prefer certain +buffers and images that are critical for performance to stay in device-local memory +in cases when the memory is over-subscribed, while some others may be moved to the system memory. + +VMA offers convenient usage of this extension. +If you enable it, you can pass "priority" parameter when creating allocations or custom pools +and the library automatically passes the value to Vulkan using this extension. + +If you want to use this extension in connection with VMA, follow these steps: + +\section vk_ext_memory_priority_initialization Initialization + +1) Call `vkEnumerateDeviceExtensionProperties` for the physical device. +Check if the extension is supported - if returned array of `VkExtensionProperties` contains "VK_EXT_memory_priority". + +2) Call `vkGetPhysicalDeviceFeatures2` for the physical device instead of old `vkGetPhysicalDeviceFeatures`. +Attach additional structure `VkPhysicalDeviceMemoryPriorityFeaturesEXT` to `VkPhysicalDeviceFeatures2::pNext` to be returned. +Check if the device feature is really supported - check if `VkPhysicalDeviceMemoryPriorityFeaturesEXT::memoryPriority` is true. + +3) While creating device with `vkCreateDevice`, enable this extension - add "VK_EXT_memory_priority" +to the list passed as `VkDeviceCreateInfo::ppEnabledExtensionNames`. + +4) While creating the device, also don't set `VkDeviceCreateInfo::pEnabledFeatures`. +Fill in `VkPhysicalDeviceFeatures2` structure instead and pass it as `VkDeviceCreateInfo::pNext`. +Enable this device feature - attach additional structure `VkPhysicalDeviceMemoryPriorityFeaturesEXT` to +`VkPhysicalDeviceFeatures2::pNext` chain and set its member `memoryPriority` to `VK_TRUE`. + +5) While creating #VmaAllocator with vmaCreateAllocator() inform VMA that you +have enabled this extension and feature - add #VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT +to VmaAllocatorCreateInfo::flags. + +\section vk_ext_memory_priority_usage Usage + +When using this extension, you should initialize following member: + +- VmaAllocationCreateInfo::priority when creating a dedicated allocation with #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT. +- VmaPoolCreateInfo::priority when creating a custom pool. + +It should be a floating-point value between `0.0f` and `1.0f`, where recommended default is `0.5f`. +Memory allocated with higher value can be treated by the Vulkan implementation as higher priority +and so it can have lower chances of being pushed out to system memory, experiencing degraded performance. + +It might be a good idea to create performance-critical resources like color-attachment or depth-stencil images +as dedicated and set high priority to them. For example: + +\code +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; + +VmaAllocationCreateInfo allocCreateInfo = {}; +allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO; +allocCreateInfo.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT; +allocCreateInfo.priority = 1.0f; + +VkImage img; +VmaAllocation alloc; +vmaCreateImage(allocator, &imgCreateInfo, &allocCreateInfo, &img, &alloc, nullptr); +\endcode + +`priority` member is ignored in the following situations: + +- Allocations created in custom pools: They inherit the priority, along with all other allocation parameters + from the parameters passed in #VmaPoolCreateInfo when the pool was created. +- Allocations created in default pools: They inherit the priority from the parameters + VMA used when creating default pools, which means `priority == 0.5f`. + + +\page vk_amd_device_coherent_memory VK_AMD_device_coherent_memory + +VK_AMD_device_coherent_memory is a device extension that enables access to +additional memory types with `VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD` and +`VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD` flag. It is useful mostly for +allocation of buffers intended for writing "breadcrumb markers" in between passes +or draw calls, which in turn are useful for debugging GPU crash/hang/TDR cases. + +When the extension is available but has not been enabled, Vulkan physical device +still exposes those memory types, but their usage is forbidden. VMA automatically +takes care of that - it returns `VK_ERROR_FEATURE_NOT_PRESENT` when an attempt +to allocate memory of such type is made. + +If you want to use this extension in connection with VMA, follow these steps: + +\section vk_amd_device_coherent_memory_initialization Initialization + +1) Call `vkEnumerateDeviceExtensionProperties` for the physical device. +Check if the extension is supported - if returned array of `VkExtensionProperties` contains "VK_AMD_device_coherent_memory". + +2) Call `vkGetPhysicalDeviceFeatures2` for the physical device instead of old `vkGetPhysicalDeviceFeatures`. +Attach additional structure `VkPhysicalDeviceCoherentMemoryFeaturesAMD` to `VkPhysicalDeviceFeatures2::pNext` to be returned. +Check if the device feature is really supported - check if `VkPhysicalDeviceCoherentMemoryFeaturesAMD::deviceCoherentMemory` is true. + +3) While creating device with `vkCreateDevice`, enable this extension - add "VK_AMD_device_coherent_memory" +to the list passed as `VkDeviceCreateInfo::ppEnabledExtensionNames`. + +4) While creating the device, also don't set `VkDeviceCreateInfo::pEnabledFeatures`. +Fill in `VkPhysicalDeviceFeatures2` structure instead and pass it as `VkDeviceCreateInfo::pNext`. +Enable this device feature - attach additional structure `VkPhysicalDeviceCoherentMemoryFeaturesAMD` to +`VkPhysicalDeviceFeatures2::pNext` and set its member `deviceCoherentMemory` to `VK_TRUE`. + +5) While creating #VmaAllocator with vmaCreateAllocator() inform VMA that you +have enabled this extension and feature - add #VMA_ALLOCATOR_CREATE_AMD_DEVICE_COHERENT_MEMORY_BIT +to VmaAllocatorCreateInfo::flags. + +\section vk_amd_device_coherent_memory_usage Usage + +After following steps described above, you can create VMA allocations and custom pools +out of the special `DEVICE_COHERENT` and `DEVICE_UNCACHED` memory types on eligible +devices. There are multiple ways to do it, for example: + +- You can request or prefer to allocate out of such memory types by adding + `VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD` to VmaAllocationCreateInfo::requiredFlags + or VmaAllocationCreateInfo::preferredFlags. Those flags can be freely mixed with + other ways of \ref choosing_memory_type, like setting VmaAllocationCreateInfo::usage. +- If you manually found memory type index to use for this purpose, force allocation + from this specific index by setting VmaAllocationCreateInfo::memoryTypeBits `= 1u << index`. + +\section vk_amd_device_coherent_memory_more_information More information + +To learn more about this extension, see [VK_AMD_device_coherent_memory in Vulkan specification](https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VK_AMD_device_coherent_memory.html) + +Example use of this extension can be found in the code of the sample and test suite +accompanying this library. + + +\page vk_khr_external_memory_win32 VK_KHR_external_memory_win32 + +On Windows, the VK_KHR_external_memory_win32 device extension allows exporting a Win32 `HANDLE` +of a `VkDeviceMemory` block, to be able to reference the memory on other Vulkan logical devices or instances, +in multiple processes, and/or in multiple APIs. +VMA offers support for it. + +\section vk_khr_external_memory_win32_initialization Initialization + +1) Make sure the extension is defined in the code by including following header before including VMA: + +\code +#include +\endcode + +2) Check if "VK_KHR_external_memory_win32" is available among device extensions. +Enable it when creating the `VkDevice` object. + +3) Enable the usage of this extension in VMA by setting flag #VMA_ALLOCATOR_CREATE_KHR_EXTERNAL_MEMORY_WIN32_BIT +when calling vmaCreateAllocator(). + +4) Make sure that VMA has access to the `vkGetMemoryWin32HandleKHR` function by either enabling `VMA_DYNAMIC_VULKAN_FUNCTIONS` macro +or setting VmaVulkanFunctions::vkGetMemoryWin32HandleKHR explicitly. +For more information, see \ref quick_start_initialization_importing_vulkan_functions. + +\section vk_khr_external_memory_win32_preparations Preparations + +You can find example usage among tests, in file "Tests.cpp", function `TestWin32Handles()`. + +To use the extenion, buffers need to be created with `VkExternalMemoryBufferCreateInfoKHR` attached to their `pNext` chain, +and memory allocations need to be made with `VkExportMemoryAllocateInfoKHR` attached to their `pNext` chain. +To make use of them, you need to use \ref custom_memory_pools. Example: + +\code +// Define an example buffer and allocation parameters. +VkExternalMemoryBufferCreateInfoKHR externalMemBufCreateInfo = { + VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO_KHR, + nullptr, + VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT +}; +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; + +VmaAllocationCreateInfo exampleAllocCreateInfo = {}; +exampleAllocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO; + +// Find memory type index to use for the custom pool. +uint32_t memTypeIndex; +VkResult res = vmaFindMemoryTypeIndexForBufferInfo(g_Allocator, + &exampleBufCreateInfo, &exampleAllocCreateInfo, &memTypeIndex); +// Check res... + +// Create a custom pool. +constexpr static VkExportMemoryAllocateInfoKHR exportMemAllocInfo = { + VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR, + nullptr, + VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT +}; +VmaPoolCreateInfo poolCreateInfo = {}; +poolCreateInfo.memoryTypeIndex = memTypeIndex; +poolCreateInfo.pMemoryAllocateNext = (void*)&exportMemAllocInfo; + +VmaPool pool; +res = vmaCreatePool(g_Allocator, &poolCreateInfo, &pool); +// Check res... + +// YOUR OTHER CODE COMES HERE.... + +// At the end, don't forget to destroy it! +vmaDestroyPool(g_Allocator, pool); +\endcode + +Note that the structure passed as VmaPoolCreateInfo::pMemoryAllocateNext must remain alive and unchanged +for the whole lifetime of the custom pool, because it will be used when the pool allocates a new device memory block. +No copy is made internally. This is why variable `exportMemAllocInfo` is defined as `static`. + +\section vk_khr_external_memory_win32_memory_allocation Memory allocation + +Finally, you can create a buffer with an allocation out of the custom pool. +The buffer should use same flags as the sample buffer used to find the memory type. +It should also specify `VkExternalMemoryBufferCreateInfoKHR` in its `pNext` chain. + +\code +VkExternalMemoryBufferCreateInfoKHR externalMemBufCreateInfo = { + VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO_KHR, + nullptr, + VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT +}; +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); +\endcode + +If you need each allocation to have its own device memory block and start at offset 0, you can still do +by using #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT flag. It works also with custom pools. + +\section vk_khr_external_memory_win32_exporting_win32_handle Exporting Win32 handle + +After the allocation is created, you can acquire a Win32 `HANDLE` to the `VkDeviceMemory` block it belongs to. +VMA function vmaGetMemoryWin32Handle() is a replacement of the Vulkan function `vkGetMemoryWin32HandleKHR`. + +\code +HANDLE handle; +res = vmaGetMemoryWin32Handle(g_Allocator, alloc, nullptr, &handle); +// Check res... + +// YOUR OTHER CODE COMES HERE.... + +// At the end, you must close the handle. +CloseHandle(handle); +\endcode + +Documentation of the VK_KHR_external_memory_win32 extension states that: + +> If handleType is defined as an NT handle, vkGetMemoryWin32HandleKHR must be called no more than once for each valid unique combination of memory and handleType. + +This is ensured automatically inside VMA. +The library fetches the handle on first use, remembers it internally, and closes it when the memory block or dedicated allocation is destroyed. +Every time you call vmaGetMemoryWin32Handle(), VMA calls `DuplicateHandle` and returns a new handle that you need to close. + +For further information, please check documentation of the vmaGetMemoryWin32Handle() function. + + +\page enabling_buffer_device_address Enabling buffer device address + +Device extension VK_KHR_buffer_device_address +allow to fetch raw GPU pointer to a buffer and pass it for usage in a shader code. +It has been promoted to core Vulkan 1.2. + +If you want to use this feature in connection with VMA, follow these steps: + +\section enabling_buffer_device_address_initialization Initialization + +1) (For Vulkan version < 1.2) Call `vkEnumerateDeviceExtensionProperties` for the physical device. +Check if the extension is supported - if returned array of `VkExtensionProperties` contains +"VK_KHR_buffer_device_address". + +2) Call `vkGetPhysicalDeviceFeatures2` for the physical device instead of old `vkGetPhysicalDeviceFeatures`. +Attach additional structure `VkPhysicalDeviceBufferDeviceAddressFeatures*` to `VkPhysicalDeviceFeatures2::pNext` to be returned. +Check if the device feature is really supported - check if `VkPhysicalDeviceBufferDeviceAddressFeatures::bufferDeviceAddress` is true. + +3) (For Vulkan version < 1.2) While creating device with `vkCreateDevice`, enable this extension - add +"VK_KHR_buffer_device_address" to the list passed as `VkDeviceCreateInfo::ppEnabledExtensionNames`. + +4) While creating the device, also don't set `VkDeviceCreateInfo::pEnabledFeatures`. +Fill in `VkPhysicalDeviceFeatures2` structure instead and pass it as `VkDeviceCreateInfo::pNext`. +Enable this device feature - attach additional structure `VkPhysicalDeviceBufferDeviceAddressFeatures*` to +`VkPhysicalDeviceFeatures2::pNext` and set its member `bufferDeviceAddress` to `VK_TRUE`. + +5) While creating #VmaAllocator with vmaCreateAllocator() inform VMA that you +have enabled this feature - add #VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT +to VmaAllocatorCreateInfo::flags. + +\section enabling_buffer_device_address_usage Usage + +After following steps described above, you can create buffers with `VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT*` using VMA. +The library automatically adds `VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT*` to +allocated memory blocks wherever it might be needed. + +Please note that the library supports only `VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT*`. +The second part of this functionality related to "capture and replay" is not supported, +as it is intended for usage in debugging tools like RenderDoc, not in everyday Vulkan usage. + +\section enabling_buffer_device_address_more_information More information + +To learn more about this extension, see [VK_KHR_buffer_device_address in Vulkan specification](https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/chap46.html#VK_KHR_buffer_device_address) + +Example use of this extension can be found in the code of the sample and test suite +accompanying this library. + +\page general_considerations General considerations + +\section general_considerations_thread_safety Thread safety + +- The library has no global state, so separate #VmaAllocator objects can be used + independently. + There should be no need to create multiple such objects though - one per `VkDevice` is enough. +- By default, all calls to functions that take #VmaAllocator as first parameter + are safe to call from multiple threads simultaneously because they are + synchronized internally when needed. + This includes allocation and deallocation from default memory pool, as well as custom #VmaPool. +- When the allocator is created with #VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT + flag, calls to functions that take such #VmaAllocator object must be + synchronized externally. +- Access to a #VmaAllocation object must be externally synchronized. For example, + you must not call vmaGetAllocationInfo() and vmaMapMemory() from different + threads at the same time if you pass the same #VmaAllocation object to these + functions. +- #VmaVirtualBlock is not safe to be used from multiple threads simultaneously. + +\section general_considerations_versioning_and_compatibility Versioning and compatibility + +The library uses [**Semantic Versioning**](https://semver.org/), +which means version numbers follow convention: Major.Minor.Patch (e.g. 2.3.0), where: + +- Incremented Patch version means a release is backward- and forward-compatible, + introducing only some internal improvements, bug fixes, optimizations etc. + or changes that are out of scope of the official API described in this documentation. +- Incremented Minor version means a release is backward-compatible, + so existing code that uses the library should continue to work, while some new + symbols could have been added: new structures, functions, new values in existing + enums and bit flags, new structure members, but not new function parameters. +- Incrementing Major version means a release could break some backward compatibility. + +All changes between official releases are documented in file "CHANGELOG.md". + +\warning Backward compatibility is considered on the level of C++ source code, not binary linkage. +Adding new members to existing structures is treated as backward compatible if initializing +the new members to binary zero results in the old behavior. +You should always fully initialize all library structures to zeros and not rely on their +exact binary size. + +\section general_considerations_validation_layer_warnings Validation layer warnings + +When using this library, you can meet following types of warnings issued by +Vulkan validation layer. They don't necessarily indicate a bug, so you may need +to just ignore them. + +- *vkBindBufferMemory(): Binding memory to buffer 0xeb8e4 but vkGetBufferMemoryRequirements() has not been called on that buffer.* + - It happens when VK_KHR_dedicated_allocation extension is enabled. + `vkGetBufferMemoryRequirements2KHR` function is used instead, while validation layer seems to be unaware of it. +- *Mapping an image with layout VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL can result in undefined behavior if this memory is used by the device. Only GENERAL or PREINITIALIZED should be used.* + - It happens when you map a buffer or image, because the library maps entire + `VkDeviceMemory` block, where different types of images and buffers may end + up together, especially on GPUs with unified memory like Intel. +- *Non-linear image 0xebc91 is aliased with linear buffer 0xeb8e4 which may indicate a bug.* + - It may happen when you use [defragmentation](@ref defragmentation). + +\section general_considerations_allocation_algorithm Allocation algorithm + +The library uses following algorithm for allocation, in order: + +-# Try to find free range of memory in existing blocks. +-# If failed, try to create a new block of `VkDeviceMemory`, with preferred block size. +-# If failed, try to create such block with size / 2, size / 4, size / 8. +-# If failed, try to allocate separate `VkDeviceMemory` for this allocation, + just like when you use #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT. +-# If failed, choose other memory type that meets the requirements specified in + VmaAllocationCreateInfo and go to point 1. +-# If failed, return `VK_ERROR_OUT_OF_DEVICE_MEMORY`. + +\section general_considerations_features_not_supported Features not supported + +Features deliberately excluded from the scope of this library: + +-# **Data transfer.** Uploading (streaming) and downloading data of buffers and images + between CPU and GPU memory and related synchronization is responsibility of the user. + Defining some "texture" object that would automatically stream its data from a + staging copy in CPU memory to GPU memory would rather be a feature of another, + higher-level library implemented on top of VMA. + VMA doesn't record any commands to a `VkCommandBuffer`. It just allocates memory. +-# **Recreation of buffers and images.** Although the library has functions for + buffer and image creation: vmaCreateBuffer(), vmaCreateImage(), you need to + recreate these objects yourself after defragmentation. That is because the big + structures `VkBufferCreateInfo`, `VkImageCreateInfo` are not stored in + #VmaAllocation object. +-# **Handling CPU memory allocation failures.** When dynamically creating small C++ + objects in CPU memory (not Vulkan memory), allocation failures are not checked + and handled gracefully, because that would complicate code significantly and + is usually not needed in desktop PC applications anyway. + Success of an allocation is just checked with an assert. +-# **Code free of any compiler warnings.** Maintaining the library to compile and + work correctly on so many different platforms is hard enough. Being free of + any warnings, on any version of any compiler, is simply not feasible. + There are many preprocessor macros that make some variables unused, function parameters unreferenced, + or conditional expressions constant in some configurations. + The code of this library should not be bigger or more complicated just to silence these warnings. + It is recommended to disable such warnings instead. +-# This is a C++ library with C interface. **Bindings or ports to any other programming languages** are welcome as external projects but + are not going to be included into this repository. +*/ diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/.clang-format b/Ifnity/Ifnity/vendor/vk-bootstrap/.clang-format new file mode 100644 index 0000000..d247dee --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/.clang-format @@ -0,0 +1,42 @@ +BasedOnStyle: LLVM + +AccessModifierOffset: 0 +AlignEscapedNewlinesLeft: false +AlignTrailingComments: true +AlignAfterOpenBracket: DontAlign +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortFunctionsOnASingleLine: true +AllowShortIfStatementsOnASingleLine: true +BinPackArguments: false +BinPackParameters: false +BreakBeforeBinaryOperators: false +BreakBeforeTernaryOperators: false +BreakConstructorInitializersBeforeComma: false +ColumnLimit: 120 +ConstructorInitializerAllOnOneLineOrOnePerLine: true +ConstructorInitializerIndentWidth: 0 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: false +DerivePointerBinding: false +IndentCaseLabels: true +IndentFunctionDeclarationAfterType: false +IndentWidth: 4 +Language: Cpp +MaxEmptyLinesToKeep: 4 +PenaltyBreakBeforeFirstCallParameter: 100 +PenaltyBreakComment: 100 +PenaltyBreakFirstLessLess: 0 +PenaltyBreakString: 100 +PenaltyExcessCharacter: 1 +PenaltyReturnTypeOnItsOwnLine: 20 +PointerBindsToType: true +SpaceBeforeAssignmentOperators: true +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: false +SpacesInCStyleCastParentheses: false +SpacesInContainerLiterals: false +SpacesInParentheses: false +Standard: Auto +TabWidth: 4 +SortIncludes: false diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/.github/dependabot.yml b/Ifnity/Ifnity/vendor/vk-bootstrap/.github/dependabot.yml new file mode 100644 index 0000000..0d08e26 --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/.github/dependabot.yml @@ -0,0 +1,11 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file + +version: 2 +updates: + - package-ecosystem: "github-actions" # See documentation for possible values + directory: "/" # Location of package manifests + schedule: + interval: "weekly" diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/.github/workflows/ci_build.yml b/Ifnity/Ifnity/vendor/vk-bootstrap/.github/workflows/ci_build.yml new file mode 100644 index 0000000..b8eea15 --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/.github/workflows/ci_build.yml @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 + +# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated +# documentation files (the “Software”), to deal in the Software without restriction, including without +# limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +# of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +# +# Copyright © 2023 Charles Giessen (charles@lunarg.com) +# + + +name: CI Build + +on: [push, pull_request, workflow_dispatch] + +jobs: + linux: + name: Linux + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + type: ["Debug", "Release"] + cc: ["gcc", "clang"] + cxx: ["g++", "clang++"] + exclude: + - cc: gcc + cxx: clang++ + - cc: clang + cxx: g++ + + + steps: + - uses: actions/checkout@v4 + - uses: lukka/get-cmake@latest + with: + cmakeVersion: 3.15 + + - name: Install build dependencies + run: | + sudo apt-get update + sudo apt-get install -y xorg-dev + + - name: CMake Configure + run: cmake -S. -B build -DCMAKE_BUILD_TYPE=${{matrix.type}} -DVK_BOOTSTRAP_WERROR=ON -DVK_BOOTSTRAP_TEST=ON + + - name: CMake Build + run: cmake --build build + + - name: Install + run: cmake --install build --prefix build/install + + - name: Run tests + working-directory: ./build + run: ctest --output-on-failure -C ${{matrix.type}} + + windows: + name: Windows + runs-on: windows-latest + + strategy: + matrix: + arch: [ Win32, x64 ] + config: [ Debug, Release ] + + steps: + - uses: actions/checkout@v4 + + - name: CMake Configure + run: cmake -S. -B build -D CMAKE_BUILD_TYPE=${{matrix.config}} -D VK_BOOTSTRAP_WERROR=ON -D VK_BOOTSTRAP_TEST=ON -A ${{matrix.arch}} + + - name: CMake Build + run: cmake --build build + + - name: Run tests + working-directory: ./build + run: ctest --output-on-failure -C ${{matrix.config}} diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/.github/workflows/create_tag.yml b/Ifnity/Ifnity/vendor/vk-bootstrap/.github/workflows/create_tag.yml new file mode 100644 index 0000000..b641479 --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/.github/workflows/create_tag.yml @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 + +# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated +# documentation files (the “Software”), to deal in the Software without restriction, including without +# limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +# of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +# +# Copyright © 2023 Charles Giessen (charles@lunarg.com) +# + +name: Tag header update + +on: + workflow_dispatch: + +jobs: + tag_header_update: + name: Tag header update + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Read CurrentBuildVulkanVersion.cmake + id: read-version-file + uses: juliangruber/read-file-action@v1 + with: + path: gen/CurrentBuildVulkanVersion.cmake + + - name: Match regex from version file + uses: actions-ecosystem/action-regex-match@v2 + id: regex-match + with: + text: ${{ steps.read-version-file.outputs.content }} + regex: 'VK_BOOTSTRAP_SOURCE_HEADER_VERSION_GIT_TAG (v[0-9]\.[0-9]\.[0-9]*)' + + - name: Push tag + uses: EndBug/latest-tag@latest + if: ${{ steps.regex-match.outputs.match != '' }} + with: + tag-name: ${{ steps.regex-match.outputs.group1 }} + description: Update to ${{ steps.regex-match.outputs.group1 }} of Vulkan-Headers + diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/.github/workflows/run_autogen.yml b/Ifnity/Ifnity/vendor/vk-bootstrap/.github/workflows/run_autogen.yml new file mode 100644 index 0000000..ce9e60b --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/.github/workflows/run_autogen.yml @@ -0,0 +1,61 @@ +# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated +# documentation files (the “Software”), to deal in the Software without restriction, including without +# limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +# of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +# +# Copyright © 2023 Charles Giessen (charles@lunarg.com) +# + +# The purpose of this script is to automatically run the autogen code every week and submit a PR to include the changes + +name: Run autogen + +on: + schedule: + - cron: '0 0 * * 2' + workflow_dispatch: + +jobs: + run_autogen: + name: Run autogen + runs-on: ubuntu-latest + env: + PR_NUMBER: ${{ github.event.number }} + + steps: + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.9' + + - name: Install python package 'xmltodict' + run: pip install xmltodict + + - name: Check out repository code + uses: actions/checkout@v4 + with: + fetch-depth: 2 + + - name: Run dispatch generator + run: python script/generate_dispatch.py --auto + + - name: Diff source to see if anything changed + id: git-diff + run: echo "::set-output name=git-diff::$(git diff --quiet HEAD~0 || echo true)" + + - name: pull-request + uses: peter-evans/create-pull-request@v7 + if: ${{ steps.git-diff.outputs.git-diff == 'true' }} + with: + commit-message: Update to latest Vulkan-Headers + title: Update to latest Vulkan-Headers + branch: run-autogen + base: main + delete-branch: true diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/.gitignore b/Ifnity/Ifnity/vendor/vk-bootstrap/.gitignore new file mode 100644 index 0000000..579c426 --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/.gitignore @@ -0,0 +1,6 @@ +*.vscode +*.vs +*.idea +cmake-build-* +build +.cache diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/CMakeLists.txt b/Ifnity/Ifnity/vendor/vk-bootstrap/CMakeLists.txt new file mode 100644 index 0000000..4a9bfa5 --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/CMakeLists.txt @@ -0,0 +1,159 @@ +cmake_minimum_required(VERSION 3.15) + +include(gen/CurrentBuildVulkanVersion.cmake) + +project(VulkanBootstrap + LANGUAGES CXX + DESCRIPTION "A Vulkan utility library to ease the initialization steps in Vulkan" + VERSION ${VK_BOOTSTRAP_SOURCE_HEADER_VERSION}) + +option(VK_BOOTSTRAP_DISABLE_WARNINGS "Disable warnings during compilation" OFF) +option(VK_BOOTSTRAP_WERROR "Enable warnings as errors during compilation" OFF) + +if (CMAKE_VERSION VERSION_LESS "3.21") + # By default, only build tests & install if this repo is standalone, but still allow configuration by the user + string(COMPARE EQUAL ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_SOURCE_DIR} PROJECT_IS_TOP_LEVEL) +endif() + +option(VK_BOOTSTRAP_TEST "Test Vk-Bootstrap using Catch2 as well as build examples" ${PROJECT_IS_TOP_LEVEL}) +option(VK_BOOTSTRAP_INSTALL "Enable installing of vk-bootstrap" ${PROJECT_IS_TOP_LEVEL}) + +set(VK_BOOTSTRAP_VULKAN_HEADER_DIR "" CACHE FILEPATH "Specify the location of the Vulkan-Headers include directory.") +mark_as_advanced(VK_BOOTSTRAP_VULKAN_HEADER_DIR) + +# Check if the user has set this variable explicitly +if(IS_DIRECTORY ${VK_BOOTSTRAP_VULKAN_HEADER_DIR}) + add_library(Vulkan-Headers INTERFACE) + add_library(Vulkan::Headers ALIAS Vulkan-Headers) + target_include_directories(Vulkan-Headers INTERFACE $) + # If we had to use a direct path to get the headers, disable installing + set(VK_BOOTSTRAP_INSTALL OFF) +# Check if the target is already defined +elseif(NOT TARGET Vulkan::Headers) + # Try looking for the VulkanHeaders package directly + find_package(VulkanHeaders CONFIG QUIET) + if (NOT VulkanHeaders_FOUND) + # Try looking using the CMake built in Vulkan support + find_package(Vulkan QUIET) + + if(Vulkan_FOUND) + # Older CMake versions don't contain Vulkan::Headers - create it in that case + if (NOT TARGET Vulkan::Headers) + add_library(Vulkan-Headers INTERFACE) + add_library(Vulkan::Headers ALIAS Vulkan-Headers) + target_include_directories(Vulkan-Headers INTERFACE $) + set(VK_BOOTSTRAP_INSTALL OFF) + endif() + else() + # Lastly just grab Vulkan-Headers directly using FetchContent + include(FetchContent) + FetchContent_Declare( + Vulkan-Headers-for-vk-bootstrap + GIT_REPOSITORY https://github.com/KhronosGroup/Vulkan-Headers + GIT_TAG ${VK_BOOTSTRAP_SOURCE_HEADER_VERSION_GIT_TAG} + ) + FetchContent_MakeAvailable(Vulkan-Headers-for-vk-bootstrap) + # If we had to use FetchContent to get the headers, disable installing + set(VK_BOOTSTRAP_INSTALL OFF) + endif() + endif() +endif() + +if(NOT TARGET Vulkan::Headers) + message(FATAL_ERROR "Unable to locate required dependency Vulkan::Headers!") +endif() + +add_library(vk-bootstrap-compiler-warnings INTERFACE) + +set(VK_BOOTSTRAP_COMPILER_FRONTEND ${CMAKE_CXX_COMPILER_FRONTEND_VARIANT}) +if(NOT VK_BOOTSTRAP_COMPILER_FRONTEND) + set(VK_BOOTSTRAP_COMPILER_FRONTEND "None") +endif() + +if(NOT VK_BOOTSTRAP_DISABLE_WARNINGS) + if (CMAKE_CXX_COMPILER_ID MATCHES "GNU|AppleClang" OR (CMAKE_CXX_COMPILER_ID MATCHES "Clang" AND VK_BOOTSTRAP_COMPILER_FRONTEND MATCHES "GNU")) + target_compile_options(vk-bootstrap-compiler-warnings INTERFACE -Wall -Wextra -Wconversion -Wsign-conversion) + if(VK_BOOTSTRAP_WERROR) + target_compile_options(vk-bootstrap-compiler-warnings INTERFACE -pedantic-errors) + endif() + elseif (CMAKE_CXX_COMPILER_ID MATCHES "MSVC" OR (CMAKE_CXX_COMPILER_ID MATCHES "Clang" AND VK_BOOTSTRAP_COMPILER_FRONTEND MATCHES "MSVC")) + target_compile_options(vk-bootstrap-compiler-warnings INTERFACE /W4) + if(VK_BOOTSTRAP_WERROR) + target_compile_options(vk-bootstrap-compiler-warnings INTERFACE /WX) + endif() + endif() +endif() + +add_library(vk-bootstrap STATIC src/VkBootstrap.h src/VkBootstrap.cpp src/VkBootstrapDispatch.h) +add_library(vk-bootstrap::vk-bootstrap ALIAS vk-bootstrap) + +target_include_directories(vk-bootstrap PUBLIC + $ + $) +target_link_libraries(vk-bootstrap + PUBLIC + Vulkan::Headers + PRIVATE + vk-bootstrap-compiler-warnings + ${CMAKE_DL_LIBS}) +target_compile_features(vk-bootstrap PUBLIC cxx_std_17) + +option(VK_BOOTSTRAP_POSITION_INDEPENDENT_CODE "Default value is the value of BUILD_SHARED_LIBS" ${BUILD_SHARED_LIBS}) +set_target_properties(vk-bootstrap PROPERTIES POSITION_INDEPENDENT_CODE ${VK_BOOTSTRAP_POSITION_INDEPENDENT_CODE}) + +if(VK_BOOTSTRAP_TEST) + enable_testing() + add_subdirectory(ext) + add_subdirectory(tests) + add_subdirectory(example) +endif () + +if (VK_BOOTSTRAP_INSTALL) + + include(GNUInstallDirs) + include(CMakePackageConfigHelpers) + + install(FILES src/VkBootstrap.h src/VkBootstrapDispatch.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) + + install( + TARGETS vk-bootstrap vk-bootstrap-compiler-warnings + EXPORT vk-bootstrap-targets + INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} + ) + install( + EXPORT vk-bootstrap-targets + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/vk-bootstrap + NAMESPACE vk-bootstrap:: + ) + + # Create vk-bootstrap-config.cmake + set(VK_BOOTSTRAP_EXPORT_TARGETS ${CMAKE_INSTALL_LIBDIR}/cmake/vk-bootstrap/vk-bootstrap-targets.cmake) + file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/vk-bootstrap-config.cmake.in" [=[ + @PACKAGE_INIT@ + + # Try to find Vulkan-Headers using find_package. Assume the package is available through either Vulkan-Headers or the older Vulkan + # Package managers should have Vulkan-Headers be a dependency of this repo. + find_package(VulkanHeaders CONFIG) + if (NOT VulkanHeaders_FOUND) + find_package(Vulkan) + if (NOT Vulkan_FOUND) + message(FATAL_ERROR "Unable to locate required dependency Vulkan::Headers!") + endif() + endif() + include(@PACKAGE_VK_BOOTSTRAP_EXPORT_TARGETS@) + ]=]) + + configure_package_config_file( + ${CMAKE_CURRENT_BINARY_DIR}/vk-bootstrap-config.cmake.in + ${CMAKE_CURRENT_BINARY_DIR}/vk-bootstrap-config.cmake + INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/vk-bootstrap + PATH_VARS VK_BOOTSTRAP_EXPORT_TARGETS + NO_SET_AND_CHECK_MACRO + NO_CHECK_REQUIRED_COMPONENTS_MACRO + ) + + install(FILES ${CMAKE_CURRENT_BINARY_DIR}/vk-bootstrap-config.cmake + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/vk-bootstrap + ) + +endif() diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/LICENSE.txt b/Ifnity/Ifnity/vendor/vk-bootstrap/LICENSE.txt new file mode 100644 index 0000000..8eececa --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/LICENSE.txt @@ -0,0 +1,7 @@ +Copyright © 2020 Charles Giessen (charles@lunarg.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/README.md b/Ifnity/Ifnity/vendor/vk-bootstrap/README.md new file mode 100644 index 0000000..23b9730 --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/README.md @@ -0,0 +1,157 @@ +# `vk-bootstrap` + +A utility library that jump starts initialization of Vulkan + +This library simplifies the tedious process of: + +* Instance creation +* Physical Device selection +* Device creation +* Getting queues +* Swapchain creation + +It also adds several conveniences for: + +* Enabling validation layers +* Adding a debug callback messenger +* Enabling extensions on a physical device +* Select a gpu based on a set of criteria like features, extensions, memory, etc + +Read the [Getting Started](docs/getting_started.md) guide for a quick start on using `vk-bootstrap` + +## Basic Usage + +```cpp + +#include "VkBootstrap.h" + +bool init_vulkan () { + vkb::InstanceBuilder builder; + auto inst_ret = builder.set_app_name ("Example Vulkan Application") + .request_validation_layers () + .use_default_debug_messenger () + .build (); + if (!inst_ret) { + std::cerr << "Failed to create Vulkan instance. Error: " << inst_ret.error().message() << "\n"; + return false; + } + vkb::Instance vkb_inst = inst_ret.value (); + + vkb::PhysicalDeviceSelector selector{ vkb_inst }; + auto phys_ret = selector.set_surface (/* from user created window*/) + .set_minimum_version (1, 1) // require a vulkan 1.1 capable device + .require_dedicated_transfer_queue () + .select (); + if (!phys_ret) { + std::cerr << "Failed to select Vulkan Physical Device. Error: " << phys_ret.error().message() << "\n"; + return false; + } + + vkb::DeviceBuilder device_builder{ phys_ret.value () }; + // automatically propagate needed data from instance & physical device + auto dev_ret = device_builder.build (); + if (!dev_ret) { + std::cerr << "Failed to create Vulkan device. Error: " << dev_ret.error().message() << "\n"; + return false; + } + vkb::Device vkb_device = dev_ret.value (); + + // Get the VkDevice handle used in the rest of a vulkan application + VkDevice device = vkb_device.device; + + // Get the graphics queue with a helper function + auto graphics_queue_ret = vkb_device.get_queue (vkb::QueueType::graphics); + if (!graphics_queue_ret) { + std::cerr << "Failed to get graphics queue. Error: " << graphics_queue_ret.error().message() << "\n"; + return false; + } + VkQueue graphics_queue = graphics_queue_ret.value (); + + // Turned 400-500 lines of boilerplate into less than fifty. + return true; +} +``` + +See `example/triangle.cpp` for an example that renders a triangle to the screen. + +## Setting up `vk-bootstrap` + +This library has no external dependencies beyond C++17, its standard library, and at least the 1.1 version of the Vulkan Headers. + +Note: on Unix platforms, `vk-bootstrap` will require the dynamic linker in order to compile as the library doesn't link against `vulkan-1.dll`/`libvulkan.so` directly. + +### Copy-Paste + +Copy the `src/VkBootstrap.h`, `src/VkBootstrapDispatch.h`, and `src/VkBootstrap.cpp` files into your project, include them into your build, then compile as you normally would. + +`vk-bootstrap` is *not* a header only library, so no need to worry about macros in the header. + +#### Linux specific + +vk-bootstrap will load the required symbols at runtime, which requires that the application is linked to the system dynamic link. +How the dynamic linker is linked into the project depends on the build system in question. +If CMake is being used, link vk-bootstrap with `${CMAKE_DL_LIBS}`. + +### git-submodule + CMake + +Add this project as a git-submodule into the root directory. Suggested is using a subdirectory to hold all submodules. + +```bash +git submodule add https://github.com/charles-lunarg/vk-bootstrap +``` + +With CMake, add the subdirectory to include the project + +```cmake +add_subdirectory(vk-bootstrap) +``` + +Then use `target_link_libraries` to use the library in whichever target needs it. + +```cmake +target_link_libraries(your_application_name vk-bootstrap::vk-bootstrap) +``` + +### CMake Fetch Content +If cmake 3.12 is available, use the FetchContent capability of cmake to directly download and build the library for you. + +```cmake +include(FetchContent) +FetchContent_Declare( + fetch_vk_bootstrap + GIT_REPOSITORY https://github.com/charles-lunarg/vk-bootstrap + GIT_TAG BRANCH_OR_TAG #suggest using a tag so the library doesn't update whenever new commits are pushed to a branch +) +FetchContent_MakeAvailable(fetch_vk_bootstrap) +target_link_libraries(your_application_name vk-bootstrap::vk-bootstrap) +``` + +### Manually Building + +```bash +git clone https://github.com/charles-lunarg/vk-bootstrap +cd vk-bootstrap +mkdir build +cd build +cmake .. +``` + +### Vulkan-Headers dependency + +By default, when using vk-bootstrap through CMake, it will attempt to locate the Vulkan-Headers on the system and fall back to downloading them directly if they aren't present. If the `VK_BOOTSTRAP_VULKAN_HEADER_DIR` option is specified, it will use that directory instead. + + +### Testing + +Tests will be enabled if you open this project standalone. If you include this project as a subdirectory or sub-project, you can force enable tests by setting the option `VK_BOOTSTRAP_TEST` to `ON`. Testing requires GLFW and Catch2 but are acquired automatically using cmake fetch content. + +```bash +cmake ../path/to/your_project/ -DVK_BOOTSTRAP_TEST=ON +``` + +### Build Options +| Name | Type | Default Value | Description | +| -------------------------------- | ------ | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `VK_BOOTSTRAP_WERROR` | bool | `OFF` | Enable warnings as errors during compilation. | +| `VK_BOOTSTRAP_TEST` | bool | `OFF` | Enable building of the tests in this project. Will download GLFW and Catch2 automatically if enabled. | +| `VK_BOOTSTRAP_VULKAN_HEADER_DIR` | string | `""` | Optional. Specify the directory that contains the Vulkan Headers. Useful if you are downloading the headers manually and don't want vk-bootstrap to download them itself. | diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/docs/getting_started.md b/Ifnity/Ifnity/vendor/vk-bootstrap/docs/getting_started.md new file mode 100644 index 0000000..9ea761d --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/docs/getting_started.md @@ -0,0 +1,295 @@ +# Getting Started + +`vk-bootstrap` reduces the complexity of setting up a vulkan application by simplifying the three initial steps; instance creation, Physical device selection, and device creation. + +## Instance Creation + +Creating an instance with `vk-bootstrap` uses the `vkb::InstanceBuilder` class. + +Simply create a builder variable and call the `build()` member function. +```cpp +vkb::InstanceBuilder instance_builder; +auto instance_builder_return = instance_builder.build(); +``` +Because creating an instance may fail, the builder returns an 'Result' type. This contains either a valid `vkb::Instance` struct, which includes a `VkInstance` handle, or contains an `vkb::InstanceError`. +```cpp +if (!instance_builder_return) { + std::cerr << "Failed to create Vulkan instance. Error: " << instance_builder_return.error().message() << "\n"; + return -1; +} +``` +Once any possible errors have been dealt with, we can pull the `vkb::Instance` struct out of the `Result`. +```cpp +vkb::Instance vkb_instance = instance_builder_return.value(); +``` +This is enough to create a usable `VkInstance` handle but many will want to customize it a bit. To configure instance creation, simply call the member functions on the `vkb::InstanceBuilder` object before `build()` is called. + +The most common customization to instance creation is enabling the "Validation Layers", an invaluable tool for any vulkan application developer. +```cpp +instance_builder.request_validation_layers (); +``` +The other common customization point is setting up the `Debug Messenger Callback`, the mechanism in which an application can control what and where the "Validation Layers" log its output. +```cpp +instance_builder.set_debug_callback ( + [] (VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, + VkDebugUtilsMessageTypeFlagsEXT messageType, + const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, + void *pUserData) + -> VkBool32 { + auto severity = vkb::to_string_message_severity (messageSeverity); + auto type = vkb::to_string_message_type (messageType); + printf ("[%s: %s] %s\n", severity, type, pCallbackData->pMessage); + return VK_FALSE; + } + ); +``` +Alternatively, `vk-bootstrap` provides a 'default debug messenger' that prints to standard output. +```cpp +instance_builder.use_default_debug_messenger(); +``` +Configuration can be chained together and done inline with building, like so. +```cpp +auto inst_builder_ret = instance_builder + .set_app_name ("Awesome Vulkan Application") + .set_engine_name("Excellent Game Engine") + .require_api_version(1,0,0) + .build(); +``` + +To query the available layers and extensions, get a `SystemInfo` struct from `SystemInfo::get_system_info()`. It contains a `is_layer_available()` and `is_extension_available()` function to check for a layer or extensions before enabling it. It also has booleans for if the validation layers are present and if the VK_EXT_debug_utils extension is available. + +```cpp +auto system_info_ret = vkb::SystemInfo::get_system_info(); +if (!system_info_ret) { + printf("%s\n", system_info_ret.error().message()); + return -1; +} +auto system_info = system_info_ret.value(); +if (system_info.is_layer_available("VK_LAYER_LUNARG_api_dump")) { + instance_builder.enable_layer("VK_LAYER_LUNARG_api_dump"); +} +if (system_info.validation_layers_available){ + instance_builder.enable_validation_layers(); +} +``` + +The `vkb::Instance` struct is meant to hold all the necessary instance level data to enable proper Physical Device selection. It also is meant for easy destructuring into custom classes if so desired. +```cpp +struct CustomVulkanWrapper { + VkInstance instance; + //... +}; +CustomVulkanWrapper custom_vk_class; +custom_vk_class.instance = vkb_instance.instance; +``` + +When the application is finished with the vulkan, call `vkb::destroy_instance()` to dispose of the instance and associated data. +```cpp +// cleanup +vkb::destroy_instance(vkb_instance); +``` +### Instance Creation Summary +```cpp +vkb::InstanceBuilder instance_builder; +auto instance_builder_return = instance_builder + // Instance creation configuration + .request_validation_layers() + .use_default_debug_messenger() + .build (); +if (!instance_builder_return) { + // Handle error +} +vkb::Instance vkb_instance = instance_builder_return.value (); + +// at program end +vkb::destroy_instance(vkb_instance); +``` +## Surface Creation + +Presenting images to the screen Vulkan requires creating a surface, encapsulated in a `VkSurfaceKHR` handle. Creating a surface is the responsibility of the windowing system, thus is out of scope for `vk-bootstrap`. However, `vk-bootstrap` does try to make the process as painless as possible by automatically enabling the correct windowing extensions in `VkInstance` creation. + +Windowing libraries which support Vulkan usually provide a way of getting the `VkSurfaceKHR` handle for the window. These methods require a valid Vulkan instance, thus must be done after instance creation. + +Examples for GLFW and SDL2 are listed below. +```cpp +vkb::Instance vkb_instance; //valid vkb::Instance +VkSurfaceKHR surface = nullptr; +// window is a valid library specific Window handle + +// GLFW +VkResult err = glfwCreateWindowSurface (vkb_instance.instance, window, NULL, &surface); +if (err != VK_SUCCESS) { /* handle error */ } + +// SDL2 +SDL_bool err = SDL_Vulkan_CreateSurface(window, vkb_instance.instance, &surface); +if (!err){ /* handle error */ } + +``` + +## Physical Device Selection + +Once a Vulkan instance has been created, the next step is to find a suitable GPU for the application to use. `vk-bootstrap` provide the `vkb::PhysicalDeviceSelector` class to streamline this process. + +Creating a `vkb::PhysicalDeviceSelector` requires a valid `vkb::Instance` to construct. + +It follows the same pattern laid out by `vkb::InstanceBuilder`. +```cpp +vkb::PhysicalDeviceSelector phys_device_selector (vkb_instance); +auto physical_device_selector_return = phys_device_selector + .set_surface(surface_handle) + .select (); +if (!physical_device_selector_return) { + // Handle error +} +auto phys_device = physical_device_selector_return.value (); +``` + +To select a physical device, call `select()` on the `vkb::PhysicalDeviceSelector` object. +By default, this will prefer a discrete GPU. + +No cleanup is required for `vkb::PhysicalDevice`. + +The `vkb::PhysicalDeviceSelector` will look for the first device in the list that satisfied all the specified criteria, and if none is found, will return the first device that partially satisfies the criteria. + +The various "require" functions indicate to `vk-bootstrap` what features and capabilities are necessary for an application. A "require" function will fail any `VkPhysicalDevice` that doesn't satisfy the constraint. + +For example, "requiring" certain device extensions to be supported is done as follows: + +```cpp +// Application cannot function without this extension +phys_device_selector.add_required_extension("VK_KHR_timeline_semaphore"); + +// Application can deal with the lack of this extension +phys_device_selector.add_desired_extension("VK_KHR_imageless_framebuffer"); +``` + +While requiring that certain features are available is as follows: + +```cpp +VkPhysicalDeviceFeatures required_features{}; +required_features.multiViewport = true; + +phys_device_selector.set_required_features(required_features); +``` + +To enable features for newer versions of Vulkan, use `set_required_features_11()`, `set_required_features_12()`, and `set_required_features_13()` and follow the same pattern as `set_required_features()` of passing in the features struct, corresponding to the version. + +Note that `set_required_features_11()` was released with 1.2, so it cannot be used for 1.1 only capable Vulkan devices. + +Features only available through extensions need to use `add_required_extension_features()`. For example: + +```cpp +VkPhysicalDeviceDescriptorIndexingFeatures descriptor_indexing_features{}; +descriptor_indexing_features. = true; + +phys_device_selector.add_required_extension_features(descriptor_indexing_features); +``` + +The features and extensions used as selection criteria in `vkb::PhysicalDeviceSelector` automatically propagate into `vkb::DeviceBuilder`. That means the application only needs to state the feature requirement once, and `vk-bootstrap` will handle enabling it on the resulting device. + +Note: + +Because `vk-bootstrap` does not manage creating a `VkSurfaceKHR` handle, it is explicitly passed into the `vkb::PhysicalDeviceSelector` for proper querying of surface support details. Unless the `vkb::InstanceBuilder::set_headless()` function was called, the physical device selector will emit `no_surface_provided` error. If an application does intend to present but cannot create a `VkSurfaceKHR` handle before physical device selection, use `defer_surface_initialization()` to disable the `no_surface_provided` error. + +## Physical Device + +The `vkb::PhysicalDevice` represents a chosen physical device, along with all the necessary details about how to create a `VkDevice` from it with the requested features and extensions. While most use cases will simply give the `vkb::PhysicalDevice` to `vkb::DeviceBuilder`, there are a handful of useful things that can be done with it. + +Adding optional extensions. It is occasionally useful to enable features if they are present but not require that they be available on the physical device. + +This is done using `enable_extension_if_present()` as follows. + +```cpp +bool supported = phys_device.enable_extension_if_present("VK_KHR_timeline_semaphore"); +if (supported){ + // allows easy feedback whether an extension is supported or not. +} +``` + +Use `enable_extensions_if_present()` to check if a group of extensions are available, and enable all of them if they are all present. This will *not* enable any extension unless they are all present, useful for handling dependencies between extensions, where one extension requires another one to be enabled. + +## Device Creation + +Once a `VkPhysicalDevice` has been selected, a `VkDevice` can be created. Facilitating that is the `vkb::DeviceBuilder`. Creation and usage follows the forms laid out by `vkb::InstanceBuilder`. + +```cpp +vkb::DeviceBuilder device_builder{ phys_device}; +auto dev_ret = device_builder.build (); +if (!dev_ret) { + // error +} +vkb::Device vkb_device = dev_ret.value(); + ``` + +To destroy a `vkb::Device`, call `vkb::destroy_device()`. +```cpp +vkb::destroy_device(vkb_device); +``` + +### Queues + +By default, `vkb::DeviceBuilder` will enable one queue from each queue family available on the `VkPhysicalDevice`. This is done because in practice, most use cases only need a single queue from each family. + +To get a `VkQueue` or the index of a `VkQueue`, use the `get_queue(QueueType type)` and `get_queue_index(QueueType type)` functions of `vkb::Device`. These will return the appropriate `VkQueue` or `uint32_t` if they exist and were enabled, else they will return an error. + +```cpp +auto queue_ret = vkb_device.get_queue (vkb::QueueType::graphics); +if (!queue_ret) { + // handle error +} +graphics_queue = queue_ret.value (); +``` + +Queue families represent a set of queues with similar operations, such as graphics, transfer, and compute. Because not all Vulkan hardware has queue families for each operation category, an application should be able to handle the presence or lack of certain queue families. For this reason the `get_dedicated_queue` and `get_dedicated_queue_index` functions of `vkb::Device` exist to allow applications to easily know if there is a queue dedicated to a particular operation, such as compute or transfer operations. + +#### Custom queue setup + +If an application wishes to have more fine grained control over their queue setup, they should create a `std::vector` of `vkb::CustomQueueDescription` which describe the index, count and a `std::vector` of priorities. To build up such a vector, use the `get_queue_families` function in `vkb::PhysicalDevice` to get a `std::vector` + +For example +```cpp +std::vector queue_descriptions; +auto queue_families = phys_device.get_queue_families (); +for (uint32_t i = 0; i < static_cast(queue_families.size ()); i++) { + if (queue_families[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) { + // Find the first queue family with graphics operations supported + queue_descriptions.push_back (vkb::CustomQueueDescription ( + i, std::vector (queue_families[i].queueCount, 1.0f))); + } +} +``` +## Swapchain + +Creating a swapchain follows the same form outlined by `vkb::InstanceBuilder` and `vkb::DeviceBuilder`. Create the `vkb::SwapchainBuilder`, provide `vkb::Device`, call the appropriate builder functions, and call `build()`. + +```cpp +vkb::SwapchainBuilder swapchain_builder{ device }; +auto swap_ret = swapchain_builder.build (); +if (!swap_ret){ + +} +vkb::Swapchain swapchain = swap_ret.value(); +``` + +By default, the swapchain will use the VK_FORMAT_B8G8R8A8_SRGB or VK_FORMAT_R8G8B8A8_SRGB image format with the color space VK_COLOR_SPACE_SRGB_NONLINEAR_KHR. The present mode will default to VK_PRESENT_MODE_MAILBOX_KHR if available and fallback to VK_PRESENT_MODE_FIFO_KHR. The image usage default flag is VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT. + +Recreating the swapchain is equivalent to creating a new swapchain but providing the old swapchain as a source. Be sure to not use the same `VkSwapchainKHR` again as it expires when it is recycled after trying to create a new swapchain. +```cpp +vkb::SwapchainBuilder swapchain_builder{ device }; +auto swap_ret = swapchain_builder.set_old_swapchain (vkb_swapchain) + .build (); +if !(swap_ret){ + // If it failed to create a swapchain, the old swapchain handle is invalid. + vkb_swapchain.swapchain = VK_NULL_HANDLE; +} +// Even though we recycled the previous swapchain, we need to free its resources. +vkb::destroy_swapchain(vkb_swapchain); +// Get the new swapchain and place it in our variable +vkb_swapchain = swap_ret.value(); +``` + +To destroy the swapchain, call `vkb::destroy_swapchain()`. This is null out the VkSwapchainHandle inside of it. + +```cpp +vkb::destroy_swapchain(vkb_swapchain); +``` diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/example/CMakeLists.txt b/Ifnity/Ifnity/vendor/vk-bootstrap/example/CMakeLists.txt new file mode 100644 index 0000000..89d45cc --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/example/CMakeLists.txt @@ -0,0 +1,21 @@ +add_executable(vk-bootstrap-triangle triangle.cpp) +target_link_libraries(vk-bootstrap-triangle + PRIVATE + glfw + vk-bootstrap + vk-bootstrap-compiler-warnings + Vulkan::Headers) +target_include_directories(vk-bootstrap-triangle PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) # path to build directory for shaders + +add_custom_command( + TARGET vk-bootstrap-triangle + POST_BUILD + COMMAND + ${CMAKE_COMMAND} -E copy_directory + ${CMAKE_SOURCE_DIR}/example/shaders ${CMAKE_CURRENT_BINARY_DIR} + DEPENDS ${CMAKE_CURRENT_BINARY_DIR}) + +configure_file ( + "${PROJECT_SOURCE_DIR}/example/example_config.h.in" + "${CMAKE_CURRENT_BINARY_DIR}/example_config.h" +) diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/example/example_config.h.in b/Ifnity/Ifnity/vendor/vk-bootstrap/example/example_config.h.in new file mode 100644 index 0000000..a29bed4 --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/example/example_config.h.in @@ -0,0 +1,4 @@ +#pragma once + +#define EXAMPLE_SOURCE_DIRECTORY "${CMAKE_SOURCE_DIR}" +#define EXAMPLE_BUILD_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}" \ No newline at end of file diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/example/shaders/frag.glsl b/Ifnity/Ifnity/vendor/vk-bootstrap/example/shaders/frag.glsl new file mode 100644 index 0000000..e939750 --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/example/shaders/frag.glsl @@ -0,0 +1,8 @@ +#version 450 +#extension GL_ARB_separate_shader_objects : enable + +layout (location = 0) in vec3 fragColor; + +layout (location = 0) out vec4 outColor; + +void main () { outColor = vec4 (fragColor, 1.0); } diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/example/shaders/frag.spv b/Ifnity/Ifnity/vendor/vk-bootstrap/example/shaders/frag.spv new file mode 100644 index 0000000..1331eb4 Binary files /dev/null and b/Ifnity/Ifnity/vendor/vk-bootstrap/example/shaders/frag.spv differ diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/example/shaders/vert.glsl b/Ifnity/Ifnity/vendor/vk-bootstrap/example/shaders/vert.glsl new file mode 100644 index 0000000..8b5aee3 --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/example/shaders/vert.glsl @@ -0,0 +1,14 @@ +#version 450 +#extension GL_ARB_separate_shader_objects : enable + +layout (location = 0) out vec3 fragColor; + +vec2 positions[3] = vec2[](vec2 (0.0, -0.5), vec2 (0.5, 0.5), vec2 (-0.5, 0.5)); + +vec3 colors[3] = vec3[](vec3 (1.0, 0.0, 0.0), vec3 (0.0, 1.0, 0.0), vec3 (0.0, 0.0, 1.0)); + +void main () +{ + gl_Position = vec4 (positions[gl_VertexIndex], 0.0, 1.0); + fragColor = colors[gl_VertexIndex]; +} \ No newline at end of file diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/example/shaders/vert.spv b/Ifnity/Ifnity/vendor/vk-bootstrap/example/shaders/vert.spv new file mode 100644 index 0000000..c4d9925 Binary files /dev/null and b/Ifnity/Ifnity/vendor/vk-bootstrap/example/shaders/vert.spv differ diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/example/triangle.cpp b/Ifnity/Ifnity/vendor/vk-bootstrap/example/triangle.cpp new file mode 100644 index 0000000..593628d --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/example/triangle.cpp @@ -0,0 +1,607 @@ +#include + +#include +#include +#include +#include + +#include +#include + +#include + +#include "example_config.h" + +const int MAX_FRAMES_IN_FLIGHT = 2; + +struct Init { + GLFWwindow* window; + vkb::Instance instance; + vkb::InstanceDispatchTable inst_disp; + VkSurfaceKHR surface; + vkb::Device device; + vkb::DispatchTable disp; + vkb::Swapchain swapchain; +}; + +struct RenderData { + VkQueue graphics_queue; + VkQueue present_queue; + + std::vector swapchain_images; + std::vector swapchain_image_views; + std::vector framebuffers; + + VkRenderPass render_pass; + VkPipelineLayout pipeline_layout; + VkPipeline graphics_pipeline; + + VkCommandPool command_pool; + std::vector command_buffers; + + std::vector available_semaphores; + std::vector finished_semaphore; + std::vector in_flight_fences; + std::vector image_in_flight; + size_t current_frame = 0; +}; + +GLFWwindow* create_window_glfw(const char* window_name = "", bool resize = true) { + glfwInit(); + glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); + if (!resize) glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); + + return glfwCreateWindow(1024, 1024, window_name, NULL, NULL); +} + +void destroy_window_glfw(GLFWwindow* window) { + glfwDestroyWindow(window); + glfwTerminate(); +} + +VkSurfaceKHR create_surface_glfw(VkInstance instance, GLFWwindow* window, VkAllocationCallbacks* allocator = nullptr) { + VkSurfaceKHR surface = VK_NULL_HANDLE; + VkResult err = glfwCreateWindowSurface(instance, window, allocator, &surface); + if (err) { + const char* error_msg; + int ret = glfwGetError(&error_msg); + if (ret != 0) { + std::cout << ret << " "; + if (error_msg != nullptr) std::cout << error_msg; + std::cout << "\n"; + } + surface = VK_NULL_HANDLE; + } + return surface; +} + +int device_initialization(Init& init) { + init.window = create_window_glfw("Vulkan Triangle", true); + + vkb::InstanceBuilder instance_builder; + auto instance_ret = instance_builder.use_default_debug_messenger().request_validation_layers().build(); + if (!instance_ret) { + std::cout << instance_ret.error().message() << "\n"; + return -1; + } + init.instance = instance_ret.value(); + + init.inst_disp = init.instance.make_table(); + + init.surface = create_surface_glfw(init.instance, init.window); + + vkb::PhysicalDeviceSelector phys_device_selector(init.instance); + auto phys_device_ret = phys_device_selector.set_surface(init.surface).select(); + if (!phys_device_ret) { + std::cout << phys_device_ret.error().message() << "\n"; + return -1; + } + vkb::PhysicalDevice physical_device = phys_device_ret.value(); + + vkb::DeviceBuilder device_builder{ physical_device }; + auto device_ret = device_builder.build(); + if (!device_ret) { + std::cout << device_ret.error().message() << "\n"; + return -1; + } + init.device = device_ret.value(); + + init.disp = init.device.make_table(); + + return 0; +} + +int create_swapchain(Init& init) { + + vkb::SwapchainBuilder swapchain_builder{ init.device }; + auto swap_ret = swapchain_builder.set_old_swapchain(init.swapchain).build(); + if (!swap_ret) { + std::cout << swap_ret.error().message() << " " << swap_ret.vk_result() << "\n"; + return -1; + } + vkb::destroy_swapchain(init.swapchain); + init.swapchain = swap_ret.value(); + return 0; +} + +int get_queues(Init& init, RenderData& data) { + auto gq = init.device.get_queue(vkb::QueueType::graphics); + if (!gq.has_value()) { + std::cout << "failed to get graphics queue: " << gq.error().message() << "\n"; + return -1; + } + data.graphics_queue = gq.value(); + + auto pq = init.device.get_queue(vkb::QueueType::present); + if (!pq.has_value()) { + std::cout << "failed to get present queue: " << pq.error().message() << "\n"; + return -1; + } + data.present_queue = pq.value(); + return 0; +} + +int create_render_pass(Init& init, RenderData& data) { + VkAttachmentDescription color_attachment = {}; + color_attachment.format = init.swapchain.image_format; + color_attachment.samples = VK_SAMPLE_COUNT_1_BIT; + color_attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; + color_attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; + color_attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + color_attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + color_attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + color_attachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + + VkAttachmentReference color_attachment_ref = {}; + color_attachment_ref.attachment = 0; + color_attachment_ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + + VkSubpassDescription subpass = {}; + subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; + subpass.colorAttachmentCount = 1; + subpass.pColorAttachments = &color_attachment_ref; + + VkSubpassDependency dependency = {}; + dependency.srcSubpass = VK_SUBPASS_EXTERNAL; + dependency.dstSubpass = 0; + dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + dependency.srcAccessMask = 0; + dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + + VkRenderPassCreateInfo render_pass_info = {}; + render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; + render_pass_info.attachmentCount = 1; + render_pass_info.pAttachments = &color_attachment; + render_pass_info.subpassCount = 1; + render_pass_info.pSubpasses = &subpass; + render_pass_info.dependencyCount = 1; + render_pass_info.pDependencies = &dependency; + + if (init.disp.createRenderPass(&render_pass_info, nullptr, &data.render_pass) != VK_SUCCESS) { + std::cout << "failed to create render pass\n"; + return -1; // failed to create render pass! + } + return 0; +} + +std::vector readFile(const std::string& filename) { + std::ifstream file(filename, std::ios::ate | std::ios::binary); + + if (!file.is_open()) { + throw std::runtime_error("failed to open file!"); + } + + size_t file_size = (size_t)file.tellg(); + std::vector buffer(file_size); + + file.seekg(0); + file.read(buffer.data(), static_cast(file_size)); + + file.close(); + + return buffer; +} + +VkShaderModule createShaderModule(Init& init, const std::vector& code) { + VkShaderModuleCreateInfo create_info = {}; + create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + create_info.codeSize = code.size(); + create_info.pCode = reinterpret_cast(code.data()); + + VkShaderModule shaderModule; + if (init.disp.createShaderModule(&create_info, nullptr, &shaderModule) != VK_SUCCESS) { + return VK_NULL_HANDLE; // failed to create shader module + } + + return shaderModule; +} + +int create_graphics_pipeline(Init& init, RenderData& data) { + auto vert_code = readFile(std::string(EXAMPLE_BUILD_DIRECTORY) + "/vert.spv"); + auto frag_code = readFile(std::string(EXAMPLE_BUILD_DIRECTORY) + "/frag.spv"); + + VkShaderModule vert_module = createShaderModule(init, vert_code); + VkShaderModule frag_module = createShaderModule(init, frag_code); + if (vert_module == VK_NULL_HANDLE || frag_module == VK_NULL_HANDLE) { + std::cout << "failed to create shader module\n"; + return -1; // failed to create shader modules + } + + VkPipelineShaderStageCreateInfo vert_stage_info = {}; + vert_stage_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + vert_stage_info.stage = VK_SHADER_STAGE_VERTEX_BIT; + vert_stage_info.module = vert_module; + vert_stage_info.pName = "main"; + + VkPipelineShaderStageCreateInfo frag_stage_info = {}; + frag_stage_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + frag_stage_info.stage = VK_SHADER_STAGE_FRAGMENT_BIT; + frag_stage_info.module = frag_module; + frag_stage_info.pName = "main"; + + VkPipelineShaderStageCreateInfo shader_stages[] = { vert_stage_info, frag_stage_info }; + + VkPipelineVertexInputStateCreateInfo vertex_input_info = {}; + vertex_input_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; + vertex_input_info.vertexBindingDescriptionCount = 0; + vertex_input_info.vertexAttributeDescriptionCount = 0; + + VkPipelineInputAssemblyStateCreateInfo input_assembly = {}; + input_assembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; + input_assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + input_assembly.primitiveRestartEnable = VK_FALSE; + + VkViewport viewport = {}; + viewport.x = 0.0f; + viewport.y = 0.0f; + viewport.width = (float)init.swapchain.extent.width; + viewport.height = (float)init.swapchain.extent.height; + viewport.minDepth = 0.0f; + viewport.maxDepth = 1.0f; + + VkRect2D scissor = {}; + scissor.offset = { 0, 0 }; + scissor.extent = init.swapchain.extent; + + VkPipelineViewportStateCreateInfo viewport_state = {}; + viewport_state.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; + viewport_state.viewportCount = 1; + viewport_state.pViewports = &viewport; + viewport_state.scissorCount = 1; + viewport_state.pScissors = &scissor; + + VkPipelineRasterizationStateCreateInfo rasterizer = {}; + rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; + rasterizer.depthClampEnable = VK_FALSE; + rasterizer.rasterizerDiscardEnable = VK_FALSE; + rasterizer.polygonMode = VK_POLYGON_MODE_FILL; + rasterizer.lineWidth = 1.0f; + rasterizer.cullMode = VK_CULL_MODE_BACK_BIT; + rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE; + rasterizer.depthBiasEnable = VK_FALSE; + + VkPipelineMultisampleStateCreateInfo multisampling = {}; + multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; + multisampling.sampleShadingEnable = VK_FALSE; + multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + + VkPipelineColorBlendAttachmentState colorBlendAttachment = {}; + colorBlendAttachment.colorWriteMask = + VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; + colorBlendAttachment.blendEnable = VK_FALSE; + + VkPipelineColorBlendStateCreateInfo color_blending = {}; + color_blending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; + color_blending.logicOpEnable = VK_FALSE; + color_blending.logicOp = VK_LOGIC_OP_COPY; + color_blending.attachmentCount = 1; + color_blending.pAttachments = &colorBlendAttachment; + color_blending.blendConstants[0] = 0.0f; + color_blending.blendConstants[1] = 0.0f; + color_blending.blendConstants[2] = 0.0f; + color_blending.blendConstants[3] = 0.0f; + + VkPipelineLayoutCreateInfo pipeline_layout_info = {}; + pipeline_layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + pipeline_layout_info.setLayoutCount = 0; + pipeline_layout_info.pushConstantRangeCount = 0; + + if (init.disp.createPipelineLayout(&pipeline_layout_info, nullptr, &data.pipeline_layout) != VK_SUCCESS) { + std::cout << "failed to create pipeline layout\n"; + return -1; // failed to create pipeline layout + } + + std::vector dynamic_states = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; + + VkPipelineDynamicStateCreateInfo dynamic_info = {}; + dynamic_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; + dynamic_info.dynamicStateCount = static_cast(dynamic_states.size()); + dynamic_info.pDynamicStates = dynamic_states.data(); + + VkGraphicsPipelineCreateInfo pipeline_info = {}; + pipeline_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; + pipeline_info.stageCount = 2; + pipeline_info.pStages = shader_stages; + pipeline_info.pVertexInputState = &vertex_input_info; + pipeline_info.pInputAssemblyState = &input_assembly; + pipeline_info.pViewportState = &viewport_state; + pipeline_info.pRasterizationState = &rasterizer; + pipeline_info.pMultisampleState = &multisampling; + pipeline_info.pColorBlendState = &color_blending; + pipeline_info.pDynamicState = &dynamic_info; + pipeline_info.layout = data.pipeline_layout; + pipeline_info.renderPass = data.render_pass; + pipeline_info.subpass = 0; + pipeline_info.basePipelineHandle = VK_NULL_HANDLE; + + if (init.disp.createGraphicsPipelines(VK_NULL_HANDLE, 1, &pipeline_info, nullptr, &data.graphics_pipeline) != VK_SUCCESS) { + std::cout << "failed to create pipline\n"; + return -1; // failed to create graphics pipeline + } + + init.disp.destroyShaderModule(frag_module, nullptr); + init.disp.destroyShaderModule(vert_module, nullptr); + return 0; +} + +int create_framebuffers(Init& init, RenderData& data) { + data.swapchain_images = init.swapchain.get_images().value(); + data.swapchain_image_views = init.swapchain.get_image_views().value(); + + data.framebuffers.resize(data.swapchain_image_views.size()); + + for (size_t i = 0; i < data.swapchain_image_views.size(); i++) { + VkImageView attachments[] = { data.swapchain_image_views[i] }; + + VkFramebufferCreateInfo framebuffer_info = {}; + framebuffer_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; + framebuffer_info.renderPass = data.render_pass; + framebuffer_info.attachmentCount = 1; + framebuffer_info.pAttachments = attachments; + framebuffer_info.width = init.swapchain.extent.width; + framebuffer_info.height = init.swapchain.extent.height; + framebuffer_info.layers = 1; + + if (init.disp.createFramebuffer(&framebuffer_info, nullptr, &data.framebuffers[i]) != VK_SUCCESS) { + return -1; // failed to create framebuffer + } + } + return 0; +} + +int create_command_pool(Init& init, RenderData& data) { + VkCommandPoolCreateInfo pool_info = {}; + pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; + pool_info.queueFamilyIndex = init.device.get_queue_index(vkb::QueueType::graphics).value(); + + if (init.disp.createCommandPool(&pool_info, nullptr, &data.command_pool) != VK_SUCCESS) { + std::cout << "failed to create command pool\n"; + return -1; // failed to create command pool + } + return 0; +} + +int create_command_buffers(Init& init, RenderData& data) { + data.command_buffers.resize(data.framebuffers.size()); + + VkCommandBufferAllocateInfo allocInfo = {}; + allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + allocInfo.commandPool = data.command_pool; + allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + allocInfo.commandBufferCount = (uint32_t)data.command_buffers.size(); + + if (init.disp.allocateCommandBuffers(&allocInfo, data.command_buffers.data()) != VK_SUCCESS) { + return -1; // failed to allocate command buffers; + } + + for (size_t i = 0; i < data.command_buffers.size(); i++) { + VkCommandBufferBeginInfo begin_info = {}; + begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + + if (init.disp.beginCommandBuffer(data.command_buffers[i], &begin_info) != VK_SUCCESS) { + return -1; // failed to begin recording command buffer + } + + VkRenderPassBeginInfo render_pass_info = {}; + render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; + render_pass_info.renderPass = data.render_pass; + render_pass_info.framebuffer = data.framebuffers[i]; + render_pass_info.renderArea.offset = { 0, 0 }; + render_pass_info.renderArea.extent = init.swapchain.extent; + VkClearValue clearColor{ { { 0.0f, 0.0f, 0.0f, 1.0f } } }; + render_pass_info.clearValueCount = 1; + render_pass_info.pClearValues = &clearColor; + + VkViewport viewport = {}; + viewport.x = 0.0f; + viewport.y = 0.0f; + viewport.width = (float)init.swapchain.extent.width; + viewport.height = (float)init.swapchain.extent.height; + viewport.minDepth = 0.0f; + viewport.maxDepth = 1.0f; + + VkRect2D scissor = {}; + scissor.offset = { 0, 0 }; + scissor.extent = init.swapchain.extent; + + init.disp.cmdSetViewport(data.command_buffers[i], 0, 1, &viewport); + init.disp.cmdSetScissor(data.command_buffers[i], 0, 1, &scissor); + + init.disp.cmdBeginRenderPass(data.command_buffers[i], &render_pass_info, VK_SUBPASS_CONTENTS_INLINE); + + init.disp.cmdBindPipeline(data.command_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, data.graphics_pipeline); + + init.disp.cmdDraw(data.command_buffers[i], 3, 1, 0, 0); + + init.disp.cmdEndRenderPass(data.command_buffers[i]); + + if (init.disp.endCommandBuffer(data.command_buffers[i]) != VK_SUCCESS) { + std::cout << "failed to record command buffer\n"; + return -1; // failed to record command buffer! + } + } + return 0; +} + +int create_sync_objects(Init& init, RenderData& data) { + data.available_semaphores.resize(MAX_FRAMES_IN_FLIGHT); + data.finished_semaphore.resize(MAX_FRAMES_IN_FLIGHT); + data.in_flight_fences.resize(MAX_FRAMES_IN_FLIGHT); + data.image_in_flight.resize(init.swapchain.image_count, VK_NULL_HANDLE); + + VkSemaphoreCreateInfo semaphore_info = {}; + semaphore_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; + + VkFenceCreateInfo fence_info = {}; + fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; + fence_info.flags = VK_FENCE_CREATE_SIGNALED_BIT; + + for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { + if (init.disp.createSemaphore(&semaphore_info, nullptr, &data.available_semaphores[i]) != VK_SUCCESS || + init.disp.createSemaphore(&semaphore_info, nullptr, &data.finished_semaphore[i]) != VK_SUCCESS || + init.disp.createFence(&fence_info, nullptr, &data.in_flight_fences[i]) != VK_SUCCESS) { + std::cout << "failed to create sync objects\n"; + return -1; // failed to create synchronization objects for a frame + } + } + return 0; +} + +int recreate_swapchain(Init& init, RenderData& data) { + init.disp.deviceWaitIdle(); + + init.disp.destroyCommandPool(data.command_pool, nullptr); + + for (auto framebuffer : data.framebuffers) { + init.disp.destroyFramebuffer(framebuffer, nullptr); + } + + init.swapchain.destroy_image_views(data.swapchain_image_views); + + if (0 != create_swapchain(init)) return -1; + if (0 != create_framebuffers(init, data)) return -1; + if (0 != create_command_pool(init, data)) return -1; + if (0 != create_command_buffers(init, data)) return -1; + return 0; +} + +int draw_frame(Init& init, RenderData& data) { + init.disp.waitForFences(1, &data.in_flight_fences[data.current_frame], VK_TRUE, UINT64_MAX); + + uint32_t image_index = 0; + VkResult result = init.disp.acquireNextImageKHR( + init.swapchain, UINT64_MAX, data.available_semaphores[data.current_frame], VK_NULL_HANDLE, &image_index); + + if (result == VK_ERROR_OUT_OF_DATE_KHR) { + return recreate_swapchain(init, data); + } else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) { + std::cout << "failed to acquire swapchain image. Error " << result << "\n"; + return -1; + } + + if (data.image_in_flight[image_index] != VK_NULL_HANDLE) { + init.disp.waitForFences(1, &data.image_in_flight[image_index], VK_TRUE, UINT64_MAX); + } + data.image_in_flight[image_index] = data.in_flight_fences[data.current_frame]; + + VkSubmitInfo submitInfo = {}; + submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + + VkSemaphore wait_semaphores[] = { data.available_semaphores[data.current_frame] }; + VkPipelineStageFlags wait_stages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT }; + submitInfo.waitSemaphoreCount = 1; + submitInfo.pWaitSemaphores = wait_semaphores; + submitInfo.pWaitDstStageMask = wait_stages; + + submitInfo.commandBufferCount = 1; + submitInfo.pCommandBuffers = &data.command_buffers[image_index]; + + VkSemaphore signal_semaphores[] = { data.finished_semaphore[data.current_frame] }; + submitInfo.signalSemaphoreCount = 1; + submitInfo.pSignalSemaphores = signal_semaphores; + + init.disp.resetFences(1, &data.in_flight_fences[data.current_frame]); + + if (init.disp.queueSubmit(data.graphics_queue, 1, &submitInfo, data.in_flight_fences[data.current_frame]) != VK_SUCCESS) { + std::cout << "failed to submit draw command buffer\n"; + return -1; //"failed to submit draw command buffer + } + + VkPresentInfoKHR present_info = {}; + present_info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; + + present_info.waitSemaphoreCount = 1; + present_info.pWaitSemaphores = signal_semaphores; + + VkSwapchainKHR swapChains[] = { init.swapchain }; + present_info.swapchainCount = 1; + present_info.pSwapchains = swapChains; + + present_info.pImageIndices = &image_index; + + result = init.disp.queuePresentKHR(data.present_queue, &present_info); + if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR) { + return recreate_swapchain(init, data); + } else if (result != VK_SUCCESS) { + std::cout << "failed to present swapchain image\n"; + return -1; + } + + data.current_frame = (data.current_frame + 1) % MAX_FRAMES_IN_FLIGHT; + return 0; +} + +void cleanup(Init& init, RenderData& data) { + for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { + init.disp.destroySemaphore(data.finished_semaphore[i], nullptr); + init.disp.destroySemaphore(data.available_semaphores[i], nullptr); + init.disp.destroyFence(data.in_flight_fences[i], nullptr); + } + + init.disp.destroyCommandPool(data.command_pool, nullptr); + + for (auto framebuffer : data.framebuffers) { + init.disp.destroyFramebuffer(framebuffer, nullptr); + } + + init.disp.destroyPipeline(data.graphics_pipeline, nullptr); + init.disp.destroyPipelineLayout(data.pipeline_layout, nullptr); + init.disp.destroyRenderPass(data.render_pass, nullptr); + + init.swapchain.destroy_image_views(data.swapchain_image_views); + + vkb::destroy_swapchain(init.swapchain); + vkb::destroy_device(init.device); + vkb::destroy_surface(init.instance, init.surface); + vkb::destroy_instance(init.instance); + destroy_window_glfw(init.window); +} + +int main() { + Init init; + RenderData render_data; + + if (0 != device_initialization(init)) return -1; + if (0 != create_swapchain(init)) return -1; + if (0 != get_queues(init, render_data)) return -1; + if (0 != create_render_pass(init, render_data)) return -1; + if (0 != create_graphics_pipeline(init, render_data)) return -1; + if (0 != create_framebuffers(init, render_data)) return -1; + if (0 != create_command_pool(init, render_data)) return -1; + if (0 != create_command_buffers(init, render_data)) return -1; + if (0 != create_sync_objects(init, render_data)) return -1; + + while (!glfwWindowShouldClose(init.window)) { + glfwPollEvents(); + int res = draw_frame(init, render_data); + if (res != 0) { + std::cout << "failed to draw frame \n"; + return -1; + } + } + init.disp.deviceWaitIdle(); + + cleanup(init, render_data); + return 0; +} diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/ext/CMakeLists.txt b/Ifnity/Ifnity/vendor/vk-bootstrap/ext/CMakeLists.txt new file mode 100644 index 0000000..4dc1655 --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/ext/CMakeLists.txt @@ -0,0 +1,25 @@ +option(GLFW_BUILD_TESTS "" OFF) +option(GLFW_BUILD_DOCS "" OFF) +option(GLFW_INSTALL "" OFF) +option(GLFW_BUILD_EXAMPLES "" OFF) + +option(CATCH_BUILD_TESTING "" OFF) +option(CATCH_ENABLE_WERROR "" OFF) +option(CATCH_INSTALL_DOCS "" OFF) +option(CATCH_INSTALL_HELPERS "" OFF) +option(CATCH_INSTALL_EXTRAS "" OFF) + +include(FetchContent) +FetchContent_Declare( + glfw + GIT_REPOSITORY https://github.com/glfw/glfw + GIT_TAG 3.3.8 +) +FetchContent_MakeAvailable(glfw) +FetchContent_Declare( + Catch2 + GIT_REPOSITORY https://github.com/catchorg/Catch2 + GIT_TAG v3.4.0 +) +FetchContent_MakeAvailable(Catch2) + diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/gen/CurrentBuildVulkanVersion.cmake b/Ifnity/Ifnity/vendor/vk-bootstrap/gen/CurrentBuildVulkanVersion.cmake new file mode 100644 index 0000000..403f254 --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/gen/CurrentBuildVulkanVersion.cmake @@ -0,0 +1,2 @@ +set(VK_BOOTSTRAP_SOURCE_HEADER_VERSION 1.3.295) +set(VK_BOOTSTRAP_SOURCE_HEADER_VERSION_GIT_TAG v1.3.295) diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/script/generate_dispatch.py b/Ifnity/Ifnity/vendor/vk-bootstrap/script/generate_dispatch.py new file mode 100644 index 0000000..beccde6 --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/script/generate_dispatch.py @@ -0,0 +1,431 @@ + +# +# generate_dispatch.py +# +# Copyright © 2021 Cody Goodson (contact@vibimanx.com) +# Copyright © 2022 Charles Giessen (charles@lunarg.com) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated +# documentation files (the “Software”), to deal in the Software without restriction, including without +# limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +# of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +# This file is a part of VkBootstrap +# https://github.com/charles-lunarg/vk-bootstrap + +# On run, vk.xml is pulled from the master of Khronos's Vulkan-Headers repo and a VkBoostrapDispatch header +# is generated and placed in VkBoostrap's source directory +# https://raw.githubusercontent.com/KhronosGroup/Vulkan-Headers/master/registry/vk.xml + +# This script makes use of xmltodict +# https://github.com/martinblech/xmltodict +# User will be prompted to install if not detected + +# Command Line Arguments +# [--auto] Don't ask for input from the command line + + +import sys +import os +import subprocess +import copy +import codecs +import re +from string import Template +import urllib.request +import pkg_resources + +# Exclusions +exclusions = [ + 'vkGetDeviceProcAddr', + 'vkCreateDevice', + 'vkDestroyDevice' +] + +# Excluded extension authors - don't generate anything for these types of extensions +excluded_extension_authors = [ + 'NVX' +] + +excluded_alias_types = [ + 'VkPipelineInfoKHR' +] + +# Check for/install xmltodict +installed = {pkg.key for pkg in pkg_resources.working_set} +xmltodict_missing = {'xmltodict'} - installed + +# Install xmltodict +if xmltodict_missing: + if '--auto' not in sys.argv: + val = input('xmltodict is required to run this script. Would you like to install? (y/n): ') + else: + val = 'y' + if val.lower() == 'y': + try: + subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'xmltodict']) + except subprocess.CalledProcessError as error: + print('Failed to install xmltodict due to error:') + print(error) + if '--auto' not in sys.argv: + input('Press Enter to continue...') + sys.exit() + else: + sys.exit() + +# Fetch fresh vk.xml from Khronos repo +import xmltodict + +try: + response = urllib.request.urlopen('https://raw.githubusercontent.com/KhronosGroup/Vulkan-Headers/main/registry/vk.xml') +except urllib.error.URLError as error: + print('Failed to download vk.xml due to error:') + print(error.reason) + if '-q' not in sys.argv: + input('Press Enter to continue...') + sys.exit() +vk_xml_raw = response.read() + +vk_xml = xmltodict.parse(vk_xml_raw,process_namespaces=True) + +command_params = {'return_type': '', 'args': [], 'dispatch_type': '', 'requirements': [], 'macro_template': Template('')} + +commands = {} + +INSTANCE = 'instance' +DEVICE = 'device' + +# No good way to detect incompatibilities with the macro defines and the actual functions. Just keep a list here +HEADER_VERSION_WORKAROUNDS = { + 'vkGetLatencyTimingsNV': '271', # Changed API parameters + 'vkCmdSetDiscardRectangleEnableEXT': '241', # new function in older extension + 'vkCmdSetDiscardRectangleModeEXT': '241', # new function in older extension + 'vkCmdSetExclusiveScissorEnableNV': '241', # new function in older extension +} + +def get_macro_guard(reqs_collection, command_name): + guard = '' + count = len(reqs_collection) + if count > 0: + while count > 0: + for reqs in reqs_collection: + reqs_count = len(reqs) + guard += '(' + for req in reqs: + guard += f'defined({req})' + reqs_count -= 1 + if reqs_count > 0: + guard += ' && ' + guard += ')' + if count > 0: + count -= 1 + if count > 0: + guard += ' || ' + # API breaking change causes this function to fail compilation + for function, version in HEADER_VERSION_WORKAROUNDS.items(): + if command_name == function: + guard = f'({guard}) && VK_HEADER_VERSION >= {version}' + return guard + + +aliased_types = {} +types_node = vk_xml['registry']['types']['type'] +for type_node in types_node: + if '@alias' in type_node: + aliased_types[type_node['@alias']] = type_node['@name'] + +# Gather all device functions/aliases for filtering core/extension function fetching +commands_node = vk_xml['registry']['commands']['command'] +aliases = {} +for command_node in commands_node: + if 'proto' in command_node: + command_name = command_node['proto']['name'] + new_command_params = copy.deepcopy(command_params) + new_command_params['return_type'] = command_node['proto']['type'] + if isinstance(command_node['param'], list): + params = command_node['param'] + else: + params = [command_node['param']] + new_command_params['args'] = [] + for param in params: + # if the api attribute does exist, make sure it is for vulkan + if not '@api' in param or param['@api'] == 'vulkan': + new_command_params['args'].append(param) + if not command_name in exclusions: + commands[command_name] = new_command_params + commands[command_name]['is_alias'] = False + if new_command_params['args'][0]['type'] in ['VkDevice', 'VkCommandBuffer', 'VkQueue']: + commands[command_name]['dispatch_type'] = DEVICE + elif new_command_params['args'][0]['type'] in ['VkInstance', 'VkPhysicalDevice']: + commands[command_name]['dispatch_type'] = INSTANCE + elif '@alias' in command_node: + aliases[command_node['@alias']] = command_node['@name'] + +# Push the alias name as a device function if the alias exists in device commands +for aliased_type, alias in aliases.items(): + if aliased_type in commands: + commands[alias] = copy.deepcopy(commands[aliased_type]) + commands[alias]['is_alias'] = True + +# Add requirements for core PFN's +features_node = vk_xml['registry']['feature'] +for feature_node in features_node: + if feature_node['@name'] != 'VK_VERSION_1_0': + for require_node in feature_node['require']: + for param_node in require_node: + if param_node == 'command': + if not isinstance(require_node[param_node], list): + require_node[param_node] = [require_node[param_node]] + for param in require_node[param_node]: + if param['@name'] in commands: + commands[param['@name']]['requirements'] += [[feature_node['@name']]] + + +# Add requirements for extension PFN's +extensions_node = vk_xml['registry']['extensions']['extension'] +for extension_node in extensions_node: + extension_name = extension_node['@name'] + if 'require' in extension_node.keys(): + require_nodes = extension_node['require'] + for require_node in require_nodes: + requirements = [extension_name] + if not isinstance(require_node, str): + if 'command' in require_node.keys(): + if '@feature' in require_node.keys(): + requirements.append(require_node['@feature']) + if '@extension' in require_node.keys(): + requirements.extend(require_node['@extension'].split(',')) + if not isinstance(require_node['command'], list): + require_node['command'] = [require_node['command']] + for command_node in require_node['command']: + if command_node['@name'] in commands: + if '@author' in extension_node and extension_node['@author'] in excluded_extension_authors: + commands.pop(command_node['@name']) + else: + commands[command_node['@name']]['requirements'] += [requirements] + elif require_node == 'command': + if not isinstance(require_nodes['command'], list): + require_nodes['command'] = [require_nodes['command']] + for command_node in require_nodes['command']: + if command_node['@name'] in commands: + if '@author' in extension_node and extension_node['@author'] in excluded_extension_authors: + commands.pop(command_node['@name']) + else: + commands[command_node['@name']]['requirements'] += [requirements] + +# Generate macro templates +for command_name, command in commands.items(): + if len(commands[command_name]['requirements']) > 0: + macro_guard = get_macro_guard(commands[command_name]['requirements'], command_name) + macro = f'#if {macro_guard}\n$body#endif\n' + else: + macro = '$body' + commands[command_name]['macro_template'] = Template(macro) + +for command_name, command in commands.items(): + if len(commands[command_name]['requirements']) > 0: + macro_guard = get_macro_guard(commands[command_name]['requirements'], command_name) + pfn_decl_macro = f'#if {macro_guard}\n$body#else\n void * fp_{command_name}{{}};\n#endif\n' + else: + pfn_decl_macro = '$body' + commands[command_name]['pfn_decl_macro_template'] = Template(pfn_decl_macro) + +# License +dispatch_license = '''/* + * Copyright © 2021 Cody Goodson (contact@vibimanx.com) + * Copyright © 2022 Charles Giessen (charles@lunarg.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the “Software”), to deal in the Software without restriction, including without + * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + * of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT + * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +''' + +# Info +info = '// This file is a part of VkBootstrap\n' +info += '// https://github.com/charles-lunarg/vk-bootstrap\n\n' + +# # Content +head = '\n#pragma once\n\n#include \n\n' +head += 'namespace vkb {\n\n' + +def create_dispatch_table(dispatch_type): + out = '' + if dispatch_type == INSTANCE: + out += 'struct InstanceDispatchTable {\n' + out += ' InstanceDispatchTable() = default;\n' + out += ' InstanceDispatchTable(VkInstance instance, PFN_vkGetInstanceProcAddr procAddr) : instance(instance), populated(true) {\n' + else: + out += 'struct DispatchTable {\n' + out += ' DispatchTable() = default;\n' + out += ' DispatchTable(VkDevice device, PFN_vkGetDeviceProcAddr procAddr) : device(device), populated(true) {\n' + + proxy_section = '' + fp_decl_section = '' + pfn_load_section = '' + + proxy_template = Template(' $return_type $proxy_name($args_full) const noexcept {\n $opt_return$fp_name($args_names);\n }\n') + fp_decl_template = Template(' $pfn_name $fp_name = nullptr;\n') + if dispatch_type == INSTANCE: + pfn_load_template = Template(' $fp_name = reinterpret_cast<$pfn_name>(procAddr(instance, "$command_name"));\n') + else: + pfn_load_template = Template(' $fp_name = reinterpret_cast<$pfn_name>(procAddr(device, "$command_name"));\n') + + for command_name, command in commands.items(): + if command['dispatch_type'] != dispatch_type: + continue + params = commands[command_name] + # easy stuff out of the way + return_type = params['return_type'] + if return_type != 'void': + opt_return = 'return ' + else: + opt_return = '' + proxy_name = command_name[2].lower() + command_name[3:] + fp_name = 'fp_' + command_name + pfn_name = 'PFN_' + command_name + + # Now for args + arg_template = Template('$front_mods$arg_type$back_mods$arg_name$array') + args_full = '' + args_names = '' + args_count = len(params['args']) + i = args_count + for arg in params['args']: + front_mods = '' + back_mods = ' ' + array = '' + arg_type = arg['type'] + arg_name = arg['name'] + if '#text' in arg: + text = arg['#text'] + text = text.replace(' ', '') + array_index = text.find('[') + if array_index != -1: + array = text[array_index:] + text = text[0:array_index] + if text == '*': + front_mods = '' + back_mods = '* ' + elif text == '**': + front_mods = '' + back_mods = '** ' + elif text == 'struct*': + front_mods = 'struct ' + back_mods = '* ' + elif text == 'struct**': + front_mods = 'struct ' + back_mods = '** ' + elif text == 'const': + front_mods = 'const ' + back_mods = ' ' + elif text == 'const*': + front_mods = 'const ' + back_mods = '* ' + elif text == 'const**': + front_mods = 'const ' + back_mods = '** ' + elif text == 'const*const*': + front_mods = 'const ' + back_mods = '* const* ' + elif text == 'conststruct*': + front_mods = 'const struct ' + back_mods = '* ' + else: + print("Unhandled Text Case!") + assert(False) + if i == args_count and (dispatch_type == INSTANCE and arg_type == 'VkInstance') or (dispatch_type == DEVICE and arg_type == 'VkDevice'): + args_names += arg_name + if i > 0: + i -= 1 + if i > 0: + args_names += ', ' + else: + if arg_type in aliased_types and arg_type not in excluded_alias_types: + arg_type = aliased_types[arg_type] + args_full += arg_template.substitute(front_mods = front_mods, arg_type = arg_type, back_mods = back_mods, arg_name = arg_name, array = array) + args_names += arg_name + if i > 0: + i -= 1 + if i > 0: + args_full += ', ' + args_names += ', ' + + proxy_body = proxy_template.substitute(return_type = return_type, proxy_name = proxy_name, args_full = args_full, opt_return = opt_return, fp_name = fp_name, args_names = args_names) + fp_decl_body = fp_decl_template.substitute(pfn_name = pfn_name, fp_name = fp_name) + pfn_load_body = pfn_load_template.substitute(fp_name = fp_name, pfn_name = pfn_name, command_name = command_name) + + macro_template = params['macro_template'] + pfn_decl_macro_template = params['pfn_decl_macro_template'] + proxy_section += macro_template.substitute(body=proxy_body) + fp_decl_section += pfn_decl_macro_template.substitute(body=fp_decl_body) + pfn_load_section += macro_template.substitute(body=pfn_load_body) + + out += pfn_load_section + out += ' }\n' + out += proxy_section + out += fp_decl_section + out += ' bool is_populated() const { return populated; }\n' + if dispatch_type == INSTANCE: + out += ' VkInstance instance = VK_NULL_HANDLE;\n' + else: + out += ' VkDevice device = VK_NULL_HANDLE;\n' + out += 'private:\n' + out += ' bool populated = false;\n' + out += '};\n\n' + return out + +tail = '} // namespace vkb' + +# find the version used to generate the code +for type_node in types_node: + if '@api' in type_node and type_node['@api'] == 'vulkan' and 'name' in type_node and type_node['name'] == 'VK_HEADER_VERSION_COMPLETE': + complete_header_version = type_node['#text'] + if '@api' in type_node and type_node['@api'] == 'vulkan' and 'name' in type_node and type_node['name'] == 'VK_HEADER_VERSION': + vk_header_version = type_node['#text'] +find_number_fields = re.compile('[0-9]+') +version_fields = find_number_fields.findall(complete_header_version) +header_version_field = find_number_fields.findall(vk_header_version)[0] +version_tag = f'{version_fields[1]}.{version_fields[2]}.{header_version_field}' + +path_to_src = os.path.join('src') +if not os.path.exists(path_to_src): + path_to_src = os.path.join('..', 'src') +if not os.path.exists(path_to_src): + print('Could not find source folder. Is the current directory wrong?') + sys.exit() + +header_file = codecs.open(os.path.join(path_to_src,'VkBootstrapDispatch.h'), 'w', 'utf-8') +header_file.write(dispatch_license + info + head + create_dispatch_table('instance') + create_dispatch_table('device') + tail) +header_file.close() + +path_to_gen = os.path.join('gen') +if not os.path.exists(path_to_gen): + path_to_gen = os.path.join('..', 'gen') +if not os.path.exists(path_to_gen): + print('Could not find gen folder. Is the current directory wrong?') + sys.exit() + +# Generate a CMake file that contains the header version used. +cmake_version_file = codecs.open(os.path.join(path_to_gen,'CurrentBuildVulkanVersion.cmake'), 'w', 'utf-8') +cmake_version_file.write(f'set(VK_BOOTSTRAP_SOURCE_HEADER_VERSION {version_tag})\n') +cmake_version_file.write(f'set(VK_BOOTSTRAP_SOURCE_HEADER_VERSION_GIT_TAG v{version_tag})\n') +cmake_version_file.close() + +print('Generation finished.') diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/src/VkBootstrap.cpp b/Ifnity/Ifnity/vendor/vk-bootstrap/src/VkBootstrap.cpp new file mode 100644 index 0000000..9bb886d --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/src/VkBootstrap.cpp @@ -0,0 +1,2556 @@ +/* + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the “Software”), to deal in the Software without restriction, including without + * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + * of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT + * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * Copyright © 2020 Charles Giessen (charles@lunarg.com) + */ + +#include "VkBootstrap.h" + +#include + +#if defined(_WIN32) +#include +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#endif // _WIN32 + +#if defined(__linux__) || defined(__APPLE__) +#include +#endif + +#include +#include + +namespace vkb { + + namespace detail { + + GenericFeaturesPNextNode::GenericFeaturesPNextNode() { memset(fields, UINT8_MAX, sizeof(VkBool32) * field_capacity); } + + bool GenericFeaturesPNextNode::match(GenericFeaturesPNextNode const& requested, GenericFeaturesPNextNode const& supported) noexcept + { + assert(requested.sType == supported.sType && "Non-matching sTypes in features nodes!"); + for (uint32_t i = 0; i < field_capacity; i++) + { + if (requested.fields[i] && !supported.fields[i]) return false; + } + return true; + } + + void GenericFeaturesPNextNode::combine(GenericFeaturesPNextNode const& right) noexcept + { + assert(sType == right.sType && "Non-matching sTypes in features nodes!"); + for (uint32_t i = 0; i < GenericFeaturesPNextNode::field_capacity; i++) + { + fields[i] = fields[i] || right.fields[i]; + } + } + + bool GenericFeatureChain::match_all(GenericFeatureChain const& extension_requested) const noexcept + { + // Should only be false if extension_supported was unable to be filled out, due to the + // physical device not supporting vkGetPhysicalDeviceFeatures2 in any capacity. + if (extension_requested.nodes.size() != nodes.size()) + { + return false; + } + + for (size_t i = 0; i < nodes.size() && i < nodes.size(); ++i) + { + if (!GenericFeaturesPNextNode::match(extension_requested.nodes[i], nodes[i])) return false; + } + return true; + } + + bool GenericFeatureChain::find_and_match(GenericFeatureChain const& extensions_requested) const noexcept + { + for (const auto& requested_extension_node : extensions_requested.nodes) + { + bool found = false; + for (const auto& supported_node : nodes) + { + if (supported_node.sType == requested_extension_node.sType) + { + found = true; + if (!GenericFeaturesPNextNode::match(requested_extension_node, supported_node)) return false; + break; + } + } + if (!found) return false; + } + return true; + } + + void GenericFeatureChain::chain_up(VkPhysicalDeviceFeatures2& feats2) noexcept + { + detail::GenericFeaturesPNextNode* prev = nullptr; + for (auto& extension : nodes) + { + if (prev != nullptr) + { + prev->pNext = &extension; + } + prev = &extension; + } + feats2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2; + feats2.pNext = !nodes.empty() ? &nodes.at(0) : nullptr; + } + + void GenericFeatureChain::combine(GenericFeatureChain const& right) noexcept + { + for (const auto& right_node : right.nodes) + { + bool already_contained = false; + for (auto& left_node : nodes) + { + if (left_node.sType == right_node.sType) + { + left_node.combine(right_node); + already_contained = true; + } + } + if (!already_contained) + { + nodes.push_back(right_node); + } + } + } + + + class VulkanFunctions { + private: + std::mutex init_mutex; + +#if defined(__linux__) || defined(__APPLE__) + void* library = nullptr; +#elif defined(_WIN32) + HMODULE library = nullptr; +#endif + + bool load_vulkan_library() + { + // Can immediately return if it has already been loaded + if (library) + { + return true; + } +#if defined(__linux__) + library = dlopen("libvulkan.so.1", RTLD_NOW | RTLD_LOCAL); + if (!library) library = dlopen("libvulkan.so", RTLD_NOW | RTLD_LOCAL); +#elif defined(__APPLE__) + library = dlopen("libvulkan.dylib", RTLD_NOW | RTLD_LOCAL); + if (!library) library = dlopen("libvulkan.1.dylib", RTLD_NOW | RTLD_LOCAL); + if (!library) library = dlopen("libMoltenVK.dylib", RTLD_NOW | RTLD_LOCAL); +#elif defined(_WIN32) + library = LoadLibrary(TEXT("vulkan-1.dll")); +#else + assert(false && "Unsupported platform"); +#endif + if (!library) return false; + load_func(ptr_vkGetInstanceProcAddr, "vkGetInstanceProcAddr"); + return ptr_vkGetInstanceProcAddr != nullptr; + } + + template void load_func(T& func_dest, const char* func_name) + { +#if defined(__linux__) || defined(__APPLE__) + func_dest = reinterpret_cast(dlsym(library, func_name)); +#elif defined(_WIN32) + func_dest = reinterpret_cast(GetProcAddress(library, func_name)); +#endif + } + void close() + { +#if defined(__linux__) || defined(__APPLE__) + dlclose(library); +#elif defined(_WIN32) + FreeLibrary(library); +#endif + library = 0; + } + + public: + bool init_vulkan_funcs(PFN_vkGetInstanceProcAddr fp_vkGetInstanceProcAddr = nullptr) + { + std::lock_guard lg(init_mutex); + if (fp_vkGetInstanceProcAddr != nullptr) + { + ptr_vkGetInstanceProcAddr = fp_vkGetInstanceProcAddr; + } + else + { + bool ret = load_vulkan_library(); + if (!ret) return false; + } + + fp_vkEnumerateInstanceExtensionProperties = reinterpret_cast( + ptr_vkGetInstanceProcAddr(VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties")); + fp_vkEnumerateInstanceLayerProperties = reinterpret_cast( + ptr_vkGetInstanceProcAddr(VK_NULL_HANDLE, "vkEnumerateInstanceLayerProperties")); + fp_vkEnumerateInstanceVersion = reinterpret_cast( + ptr_vkGetInstanceProcAddr(VK_NULL_HANDLE, "vkEnumerateInstanceVersion")); + fp_vkCreateInstance = + reinterpret_cast(ptr_vkGetInstanceProcAddr(VK_NULL_HANDLE, "vkCreateInstance")); + return true; + } + + public: + template void get_inst_proc_addr(T& out_ptr, const char* func_name) + { + out_ptr = reinterpret_cast(ptr_vkGetInstanceProcAddr(instance, func_name)); + } + + template void get_device_proc_addr(VkDevice device, T& out_ptr, const char* func_name) + { + out_ptr = reinterpret_cast(fp_vkGetDeviceProcAddr(device, func_name)); + } + + PFN_vkGetInstanceProcAddr ptr_vkGetInstanceProcAddr = nullptr; + VkInstance instance = nullptr; + + PFN_vkEnumerateInstanceExtensionProperties fp_vkEnumerateInstanceExtensionProperties = nullptr; + PFN_vkEnumerateInstanceLayerProperties fp_vkEnumerateInstanceLayerProperties = nullptr; + PFN_vkEnumerateInstanceVersion fp_vkEnumerateInstanceVersion = nullptr; + PFN_vkCreateInstance fp_vkCreateInstance = nullptr; + + PFN_vkDestroyInstance fp_vkDestroyInstance = nullptr; + PFN_vkCreateDebugUtilsMessengerEXT fp_vkCreateDebugUtilsMessengerEXT = nullptr; + PFN_vkDestroyDebugUtilsMessengerEXT fp_vkDestroyDebugUtilsMessengerEXT = nullptr; + PFN_vkEnumeratePhysicalDevices fp_vkEnumeratePhysicalDevices = nullptr; + PFN_vkGetPhysicalDeviceFeatures fp_vkGetPhysicalDeviceFeatures = nullptr; + PFN_vkGetPhysicalDeviceFeatures2 fp_vkGetPhysicalDeviceFeatures2 = nullptr; + PFN_vkGetPhysicalDeviceFeatures2KHR fp_vkGetPhysicalDeviceFeatures2KHR = nullptr; + PFN_vkGetPhysicalDeviceProperties fp_vkGetPhysicalDeviceProperties = nullptr; + PFN_vkGetPhysicalDeviceQueueFamilyProperties fp_vkGetPhysicalDeviceQueueFamilyProperties = nullptr; + PFN_vkGetPhysicalDeviceMemoryProperties fp_vkGetPhysicalDeviceMemoryProperties = nullptr; + PFN_vkEnumerateDeviceExtensionProperties fp_vkEnumerateDeviceExtensionProperties = nullptr; + + PFN_vkCreateDevice fp_vkCreateDevice = nullptr; + PFN_vkGetDeviceProcAddr fp_vkGetDeviceProcAddr = nullptr; + + PFN_vkDestroySurfaceKHR fp_vkDestroySurfaceKHR = nullptr; + PFN_vkGetPhysicalDeviceSurfaceSupportKHR fp_vkGetPhysicalDeviceSurfaceSupportKHR = nullptr; + PFN_vkGetPhysicalDeviceSurfaceFormatsKHR fp_vkGetPhysicalDeviceSurfaceFormatsKHR = nullptr; + PFN_vkGetPhysicalDeviceSurfacePresentModesKHR fp_vkGetPhysicalDeviceSurfacePresentModesKHR = nullptr; + PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR fp_vkGetPhysicalDeviceSurfaceCapabilitiesKHR = nullptr; + + void init_instance_funcs(VkInstance inst) + { + instance = inst; + get_inst_proc_addr(fp_vkDestroyInstance, "vkDestroyInstance"); + get_inst_proc_addr(fp_vkCreateDebugUtilsMessengerEXT, "vkCreateDebugUtilsMessengerEXT"); + get_inst_proc_addr(fp_vkDestroyDebugUtilsMessengerEXT, "vkDestroyDebugUtilsMessengerEXT"); + get_inst_proc_addr(fp_vkEnumeratePhysicalDevices, "vkEnumeratePhysicalDevices"); + + get_inst_proc_addr(fp_vkGetPhysicalDeviceFeatures, "vkGetPhysicalDeviceFeatures"); + get_inst_proc_addr(fp_vkGetPhysicalDeviceFeatures2, "vkGetPhysicalDeviceFeatures2"); + get_inst_proc_addr(fp_vkGetPhysicalDeviceFeatures2KHR, "vkGetPhysicalDeviceFeatures2KHR"); + get_inst_proc_addr(fp_vkGetPhysicalDeviceProperties, "vkGetPhysicalDeviceProperties"); + get_inst_proc_addr(fp_vkGetPhysicalDeviceQueueFamilyProperties, "vkGetPhysicalDeviceQueueFamilyProperties"); + get_inst_proc_addr(fp_vkGetPhysicalDeviceMemoryProperties, "vkGetPhysicalDeviceMemoryProperties"); + get_inst_proc_addr(fp_vkEnumerateDeviceExtensionProperties, "vkEnumerateDeviceExtensionProperties"); + + get_inst_proc_addr(fp_vkCreateDevice, "vkCreateDevice"); + get_inst_proc_addr(fp_vkGetDeviceProcAddr, "vkGetDeviceProcAddr"); + + get_inst_proc_addr(fp_vkDestroySurfaceKHR, "vkDestroySurfaceKHR"); + get_inst_proc_addr(fp_vkGetPhysicalDeviceSurfaceSupportKHR, "vkGetPhysicalDeviceSurfaceSupportKHR"); + get_inst_proc_addr(fp_vkGetPhysicalDeviceSurfaceFormatsKHR, "vkGetPhysicalDeviceSurfaceFormatsKHR"); + get_inst_proc_addr(fp_vkGetPhysicalDeviceSurfacePresentModesKHR, "vkGetPhysicalDeviceSurfacePresentModesKHR"); + get_inst_proc_addr(fp_vkGetPhysicalDeviceSurfaceCapabilitiesKHR, "vkGetPhysicalDeviceSurfaceCapabilitiesKHR"); + } + }; + + static VulkanFunctions& vulkan_functions() + { + static VulkanFunctions v; + return v; + } + + // Helper for robustly executing the two-call pattern + template auto get_vector(std::vector& out, F&& f, Ts&&... ts) -> VkResult + { + uint32_t count = 0; + VkResult err; + do + { + err = f(ts..., &count, nullptr); + if (err != VK_SUCCESS) + { + return err; + }; + out.resize(count); + err = f(ts..., &count, out.data()); + out.resize(count); + } while (err == VK_INCOMPLETE); + return err; + } + + template auto get_vector_noerror(F&& f, Ts&&... ts) -> std::vector + { + uint32_t count = 0; + std::vector results; + f(ts..., &count, nullptr); + results.resize(count); + f(ts..., &count, results.data()); + results.resize(count); + return results; + } + } // namespace detail + + const char* to_string_message_severity(VkDebugUtilsMessageSeverityFlagBitsEXT s) + { + switch (s) + { + case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT: + return "VERBOSE"; + case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT: + return "ERROR"; + case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT: + return "WARNING"; + case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT: + return "INFO"; + default: + return "UNKNOWN"; + } + } + const char* to_string_message_type(VkDebugUtilsMessageTypeFlagsEXT s) + { + if (s == 7) return "General | Validation | Performance"; + if (s == 6) return "Validation | Performance"; + if (s == 5) return "General | Performance"; + if (s == 4 /*VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT*/) return "Performance"; + if (s == 3) return "General | Validation"; + if (s == 2 /*VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT*/) return "Validation"; + if (s == 1 /*VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT*/) return "General"; + return "Unknown"; + } + + VkResult create_debug_utils_messenger(VkInstance instance, + PFN_vkDebugUtilsMessengerCallbackEXT debug_callback, + VkDebugUtilsMessageSeverityFlagsEXT severity, + VkDebugUtilsMessageTypeFlagsEXT type, + void* user_data_pointer, + VkDebugUtilsMessengerEXT* pDebugMessenger, + VkAllocationCallbacks* allocation_callbacks) + { + + if (debug_callback == nullptr) debug_callback = default_debug_callback; + VkDebugUtilsMessengerCreateInfoEXT messengerCreateInfo = {}; + messengerCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT; + messengerCreateInfo.pNext = nullptr; + messengerCreateInfo.messageSeverity = severity; + messengerCreateInfo.messageType = type; + messengerCreateInfo.pfnUserCallback = debug_callback; + messengerCreateInfo.pUserData = user_data_pointer; + + if (detail::vulkan_functions().fp_vkCreateDebugUtilsMessengerEXT != nullptr) + { + return detail::vulkan_functions().fp_vkCreateDebugUtilsMessengerEXT( + instance, &messengerCreateInfo, allocation_callbacks, pDebugMessenger); + } + else + { + return VK_ERROR_EXTENSION_NOT_PRESENT; + } + } + + void destroy_debug_utils_messenger( + VkInstance instance, VkDebugUtilsMessengerEXT debugMessenger, VkAllocationCallbacks* allocation_callbacks) + { + + if (detail::vulkan_functions().fp_vkDestroyDebugUtilsMessengerEXT != nullptr) + { + detail::vulkan_functions().fp_vkDestroyDebugUtilsMessengerEXT(instance, debugMessenger, allocation_callbacks); + } + } + + namespace detail { + bool check_layer_supported(std::vector const& available_layers, const char* layer_name) + { + if (!layer_name) return false; + for (const auto& layer_properties : available_layers) + { + if (strcmp(layer_name, layer_properties.layerName) == 0) + { + return true; + } + } + return false; + } + + bool check_layers_supported(std::vector const& available_layers, std::vector const& layer_names) + { + bool all_found = true; + for (const auto& layer_name : layer_names) + { + bool found = check_layer_supported(available_layers, layer_name); + if (!found) all_found = false; + } + return all_found; + } + + bool check_extension_supported(std::vector const& available_extensions, const char* extension_name) + { + if (!extension_name) return false; + for (const auto& extension_properties : available_extensions) + { + if (strcmp(extension_name, extension_properties.extensionName) == 0) + { + return true; + } + } + return false; + } + + bool check_extensions_supported( + std::vector const& available_extensions, std::vector const& extension_names) + { + bool all_found = true; + for (const auto& extension_name : extension_names) + { + bool found = check_extension_supported(available_extensions, extension_name); + if (!found) all_found = false; + } + return all_found; + } + + template void setup_pNext_chain(T& structure, std::vector const& structs) + { + structure.pNext = nullptr; + if (structs.size() <= 0) return; + for (size_t i = 0; i < structs.size() - 1; i++) + { + structs.at(i)->pNext = structs.at(i + 1); + } + structure.pNext = structs.at(0); + } + const char* validation_layer_name = "VK_LAYER_KHRONOS_validation"; + + struct InstanceErrorCategory : std::error_category { + const char* name() const noexcept override { return "vkb_instance"; } + std::string message(int err) const override { return to_string(static_cast(err)); } + }; + const InstanceErrorCategory instance_error_category; + + struct PhysicalDeviceErrorCategory : std::error_category { + const char* name() const noexcept override { return "vkb_physical_device"; } + std::string message(int err) const override { return to_string(static_cast(err)); } + }; + const PhysicalDeviceErrorCategory physical_device_error_category; + + struct QueueErrorCategory : std::error_category { + const char* name() const noexcept override { return "vkb_queue"; } + std::string message(int err) const override { return to_string(static_cast(err)); } + }; + const QueueErrorCategory queue_error_category; + + struct DeviceErrorCategory : std::error_category { + const char* name() const noexcept override { return "vkb_device"; } + std::string message(int err) const override { return to_string(static_cast(err)); } + }; + const DeviceErrorCategory device_error_category; + + struct SwapchainErrorCategory : std::error_category { + const char* name() const noexcept override { return "vbk_swapchain"; } + std::string message(int err) const override { return to_string(static_cast(err)); } + }; + const SwapchainErrorCategory swapchain_error_category; + + } // namespace detail + + std::error_code make_error_code(InstanceError instance_error) + { + return { static_cast(instance_error), detail::instance_error_category }; + } + std::error_code make_error_code(PhysicalDeviceError physical_device_error) + { + return { static_cast(physical_device_error), detail::physical_device_error_category }; + } + std::error_code make_error_code(QueueError queue_error) + { + return { static_cast(queue_error), detail::queue_error_category }; + } + std::error_code make_error_code(DeviceError device_error) + { + return { static_cast(device_error), detail::device_error_category }; + } + std::error_code make_error_code(SwapchainError swapchain_error) + { + return { static_cast(swapchain_error), detail::swapchain_error_category }; + } +#define CASE_TO_STRING(CATEGORY, TYPE) \ + case CATEGORY::TYPE: \ + return #TYPE; + + const char* to_string(InstanceError err) + { + switch (err) + { + CASE_TO_STRING(InstanceError, vulkan_unavailable) + CASE_TO_STRING(InstanceError, vulkan_version_unavailable) + CASE_TO_STRING(InstanceError, vulkan_version_1_1_unavailable) + CASE_TO_STRING(InstanceError, vulkan_version_1_2_unavailable) + CASE_TO_STRING(InstanceError, failed_create_debug_messenger) + CASE_TO_STRING(InstanceError, failed_create_instance) + CASE_TO_STRING(InstanceError, requested_layers_not_present) + CASE_TO_STRING(InstanceError, requested_extensions_not_present) + CASE_TO_STRING(InstanceError, windowing_extensions_not_present) + default: + return ""; + } + } + const char* to_string(PhysicalDeviceError err) + { + switch (err) + { + CASE_TO_STRING(PhysicalDeviceError, no_surface_provided) + CASE_TO_STRING(PhysicalDeviceError, failed_enumerate_physical_devices) + CASE_TO_STRING(PhysicalDeviceError, no_physical_devices_found) + CASE_TO_STRING(PhysicalDeviceError, no_suitable_device) + default: + return ""; + } + } + const char* to_string(QueueError err) + { + switch (err) + { + CASE_TO_STRING(QueueError, present_unavailable) + CASE_TO_STRING(QueueError, graphics_unavailable) + CASE_TO_STRING(QueueError, compute_unavailable) + CASE_TO_STRING(QueueError, transfer_unavailable) + CASE_TO_STRING(QueueError, queue_index_out_of_range) + CASE_TO_STRING(QueueError, invalid_queue_family_index) + default: + return ""; + } + } + const char* to_string(DeviceError err) + { + switch (err) + { + CASE_TO_STRING(DeviceError, failed_create_device) + default: + return ""; + } + } + const char* to_string(SwapchainError err) + { + switch (err) + { + CASE_TO_STRING(SwapchainError, surface_handle_not_provided) + CASE_TO_STRING(SwapchainError, failed_query_surface_support_details) + CASE_TO_STRING(SwapchainError, failed_create_swapchain) + CASE_TO_STRING(SwapchainError, failed_get_swapchain_images) + CASE_TO_STRING(SwapchainError, failed_create_swapchain_image_views) + CASE_TO_STRING(SwapchainError, required_min_image_count_too_low) + CASE_TO_STRING(SwapchainError, required_usage_not_supported) + default: + return ""; + } + } + + Result SystemInfo::get_system_info() + { + if (!detail::vulkan_functions().init_vulkan_funcs(nullptr)) + { + return make_error_code(InstanceError::vulkan_unavailable); + } + return SystemInfo(); + } + + Result SystemInfo::get_system_info(PFN_vkGetInstanceProcAddr fp_vkGetInstanceProcAddr) + { + // Using externally provided function pointers, assume the loader is available + if (!detail::vulkan_functions().init_vulkan_funcs(fp_vkGetInstanceProcAddr)) + { + return make_error_code(InstanceError::vulkan_unavailable); + } + return SystemInfo(); + } + + SystemInfo::SystemInfo() + { + auto available_layers_ret = detail::get_vector( + this->available_layers, detail::vulkan_functions().fp_vkEnumerateInstanceLayerProperties); + if (available_layers_ret != VK_SUCCESS) + { + this->available_layers.clear(); + } + + for (auto& layer : this->available_layers) + if (strcmp(layer.layerName, detail::validation_layer_name) == 0) validation_layers_available = true; + + auto available_extensions_ret = detail::get_vector( + this->available_extensions, detail::vulkan_functions().fp_vkEnumerateInstanceExtensionProperties, nullptr); + if (available_extensions_ret != VK_SUCCESS) + { + this->available_extensions.clear(); + } + + for (auto& ext : this->available_extensions) + { + if (strcmp(ext.extensionName, VK_EXT_DEBUG_UTILS_EXTENSION_NAME) == 0) + { + debug_utils_available = true; + } + } + + for (auto& layer : this->available_layers) + { + std::vector layer_extensions; + auto layer_extensions_ret = detail::get_vector( + layer_extensions, detail::vulkan_functions().fp_vkEnumerateInstanceExtensionProperties, layer.layerName); + if (layer_extensions_ret == VK_SUCCESS) + { + this->available_extensions.insert( + this->available_extensions.end(), layer_extensions.begin(), layer_extensions.end()); + for (auto& ext : layer_extensions) + { + if (strcmp(ext.extensionName, VK_EXT_DEBUG_UTILS_EXTENSION_NAME) == 0) + { + debug_utils_available = true; + } + } + } + } + } + bool SystemInfo::is_extension_available(const char* extension_name) const + { + if (!extension_name) return false; + return detail::check_extension_supported(available_extensions, extension_name); + } + bool SystemInfo::is_layer_available(const char* layer_name) const + { + if (!layer_name) return false; + return detail::check_layer_supported(available_layers, layer_name); + } + void destroy_surface(Instance const& instance, VkSurfaceKHR surface) + { + if (instance.instance != VK_NULL_HANDLE && surface != VK_NULL_HANDLE) + { + detail::vulkan_functions().fp_vkDestroySurfaceKHR(instance.instance, surface, instance.allocation_callbacks); + } + } + void destroy_surface(VkInstance instance, VkSurfaceKHR surface, VkAllocationCallbacks* callbacks) + { + if (instance != VK_NULL_HANDLE && surface != VK_NULL_HANDLE) + { + detail::vulkan_functions().fp_vkDestroySurfaceKHR(instance, surface, callbacks); + } + } + void destroy_instance(Instance const& instance) + { + if (instance.instance != VK_NULL_HANDLE) + { + if (instance.debug_messenger != VK_NULL_HANDLE) + destroy_debug_utils_messenger(instance.instance, instance.debug_messenger, instance.allocation_callbacks); + detail::vulkan_functions().fp_vkDestroyInstance(instance.instance, instance.allocation_callbacks); + } + } + + Instance::operator VkInstance() const { return this->instance; } + + InstanceDispatchTable Instance::make_table() const { return { instance, fp_vkGetInstanceProcAddr }; } + + InstanceBuilder::InstanceBuilder(PFN_vkGetInstanceProcAddr fp_vkGetInstanceProcAddr) + { + info.fp_vkGetInstanceProcAddr = fp_vkGetInstanceProcAddr; + } + InstanceBuilder::InstanceBuilder() {} + + Result InstanceBuilder::build() const + { + + auto sys_info_ret = SystemInfo::get_system_info(info.fp_vkGetInstanceProcAddr); + if (!sys_info_ret) return sys_info_ret.error(); + auto system = sys_info_ret.value(); + + uint32_t instance_version = VKB_VK_API_VERSION_1_0; + + if (info.minimum_instance_version > VKB_VK_API_VERSION_1_0 || info.required_api_version > VKB_VK_API_VERSION_1_0 || + info.desired_api_version > VKB_VK_API_VERSION_1_0) + { + PFN_vkEnumerateInstanceVersion pfn_vkEnumerateInstanceVersion = detail::vulkan_functions().fp_vkEnumerateInstanceVersion; + + if (pfn_vkEnumerateInstanceVersion != nullptr) + { + VkResult res = pfn_vkEnumerateInstanceVersion(&instance_version); + // Should always return VK_SUCCESS + if (res != VK_SUCCESS && info.required_api_version > 0) + return make_error_code(InstanceError::vulkan_version_unavailable); + } + if (pfn_vkEnumerateInstanceVersion == nullptr || instance_version < info.minimum_instance_version || + (info.minimum_instance_version == 0 && instance_version < info.required_api_version)) + { + if (VK_VERSION_MINOR(info.required_api_version) == 2) + return make_error_code(InstanceError::vulkan_version_1_2_unavailable); + else if (VK_VERSION_MINOR(info.required_api_version)) + return make_error_code(InstanceError::vulkan_version_1_1_unavailable); + else + return make_error_code(InstanceError::vulkan_version_unavailable); + } + } + + uint32_t api_version = instance_version < VKB_VK_API_VERSION_1_1 ? instance_version : info.required_api_version; + + if (info.desired_api_version > VKB_VK_API_VERSION_1_0 && instance_version >= info.desired_api_version) + { + instance_version = info.desired_api_version; + api_version = info.desired_api_version; + } + + VkApplicationInfo app_info = {}; + app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; + app_info.pNext = nullptr; + app_info.pApplicationName = info.app_name != nullptr ? info.app_name : ""; + app_info.applicationVersion = info.application_version; + app_info.pEngineName = info.engine_name != nullptr ? info.engine_name : ""; + app_info.engineVersion = info.engine_version; + app_info.apiVersion = api_version; + + std::vector extensions; + std::vector layers; + + for (auto& ext : info.extensions) + extensions.push_back(ext); + if (info.debug_callback != nullptr && info.use_debug_messenger && system.debug_utils_available) + { + extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); + } + bool properties2_ext_enabled = + api_version < VKB_VK_API_VERSION_1_1 && detail::check_extension_supported(system.available_extensions, + VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME); + if (properties2_ext_enabled) + { + extensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME); + } + +#if defined(VK_KHR_portability_enumeration) + bool portability_enumeration_support = + detail::check_extension_supported(system.available_extensions, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME); + if (portability_enumeration_support) + { + extensions.push_back(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME); + } +#else + bool portability_enumeration_support = false; +#endif + if (!info.headless_context) + { + auto check_add_window_ext = [&](const char* name) -> bool + { + if (!detail::check_extension_supported(system.available_extensions, name)) return false; + extensions.push_back(name); + return true; + }; + bool khr_surface_added = check_add_window_ext("VK_KHR_surface"); +#if defined(_WIN32) + bool added_window_exts = check_add_window_ext("VK_KHR_win32_surface"); +#elif defined(__ANDROID__) + bool added_window_exts = check_add_window_ext("VK_KHR_android_surface"); +#elif defined(_DIRECT2DISPLAY) + bool added_window_exts = check_add_window_ext("VK_KHR_display"); +#elif defined(__linux__) + // make sure all three calls to check_add_window_ext, don't allow short circuiting + bool added_window_exts = check_add_window_ext("VK_KHR_xcb_surface"); + added_window_exts = check_add_window_ext("VK_KHR_xlib_surface") || added_window_exts; + added_window_exts = check_add_window_ext("VK_KHR_wayland_surface") || added_window_exts; +#elif defined(__APPLE__) + bool added_window_exts = check_add_window_ext("VK_EXT_metal_surface"); +#endif + if (!khr_surface_added || !added_window_exts) + return make_error_code(InstanceError::windowing_extensions_not_present); + } + bool all_extensions_supported = detail::check_extensions_supported(system.available_extensions, extensions); + if (!all_extensions_supported) + { + return make_error_code(InstanceError::requested_extensions_not_present); + } + + for (auto& layer : info.layers) + layers.push_back(layer); + + if (info.enable_validation_layers || (info.request_validation_layers && system.validation_layers_available)) + { + layers.push_back(detail::validation_layer_name); + } + bool all_layers_supported = detail::check_layers_supported(system.available_layers, layers); + if (!all_layers_supported) + { + return make_error_code(InstanceError::requested_layers_not_present); + } + + std::vector pNext_chain; + + VkDebugUtilsMessengerCreateInfoEXT messengerCreateInfo = {}; + if (info.use_debug_messenger) + { + messengerCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT; + messengerCreateInfo.pNext = nullptr; + messengerCreateInfo.messageSeverity = info.debug_message_severity; + messengerCreateInfo.messageType = info.debug_message_type; + messengerCreateInfo.pfnUserCallback = info.debug_callback; + messengerCreateInfo.pUserData = info.debug_user_data_pointer; + pNext_chain.push_back(reinterpret_cast(&messengerCreateInfo)); + } + + VkValidationFeaturesEXT features{}; + if (info.enabled_validation_features.size() != 0 || info.disabled_validation_features.size()) + { + features.sType = VK_STRUCTURE_TYPE_VALIDATION_FEATURES_EXT; + features.pNext = nullptr; + features.enabledValidationFeatureCount = static_cast(info.enabled_validation_features.size()); + features.pEnabledValidationFeatures = info.enabled_validation_features.data(); + features.disabledValidationFeatureCount = static_cast(info.disabled_validation_features.size()); + features.pDisabledValidationFeatures = info.disabled_validation_features.data(); + pNext_chain.push_back(reinterpret_cast(&features)); + } + + VkValidationFlagsEXT checks{}; + if (info.disabled_validation_checks.size() != 0) + { + checks.sType = VK_STRUCTURE_TYPE_VALIDATION_FLAGS_EXT; + checks.pNext = nullptr; + checks.disabledValidationCheckCount = static_cast(info.disabled_validation_checks.size()); + checks.pDisabledValidationChecks = info.disabled_validation_checks.data(); + pNext_chain.push_back(reinterpret_cast(&checks)); + } + + VkInstanceCreateInfo instance_create_info = {}; + instance_create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; + detail::setup_pNext_chain(instance_create_info, pNext_chain); +#if !defined(NDEBUG) + for (auto& node : pNext_chain) + { + assert(node->sType != VK_STRUCTURE_TYPE_APPLICATION_INFO); + } +#endif + instance_create_info.flags = info.flags; + instance_create_info.pApplicationInfo = &app_info; + instance_create_info.enabledExtensionCount = static_cast(extensions.size()); + instance_create_info.ppEnabledExtensionNames = extensions.data(); + instance_create_info.enabledLayerCount = static_cast(layers.size()); + instance_create_info.ppEnabledLayerNames = layers.data(); +#if defined(VK_KHR_portability_enumeration) + if (portability_enumeration_support) + { + instance_create_info.flags |= VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR; + } +#endif + + Instance instance; + VkResult res = + detail::vulkan_functions().fp_vkCreateInstance(&instance_create_info, info.allocation_callbacks, &instance.instance); + if (res != VK_SUCCESS) return Result(InstanceError::failed_create_instance, res); + + detail::vulkan_functions().init_instance_funcs(instance.instance); + + if (info.use_debug_messenger) + { + res = create_debug_utils_messenger(instance.instance, + info.debug_callback, + info.debug_message_severity, + info.debug_message_type, + info.debug_user_data_pointer, + &instance.debug_messenger, + info.allocation_callbacks); + if (res != VK_SUCCESS) + { + return Result(InstanceError::failed_create_debug_messenger, res); + } + } + + instance.headless = info.headless_context; + instance.properties2_ext_enabled = properties2_ext_enabled; + instance.allocation_callbacks = info.allocation_callbacks; + instance.instance_version = instance_version; + instance.api_version = api_version; + instance.fp_vkGetInstanceProcAddr = detail::vulkan_functions().ptr_vkGetInstanceProcAddr; + instance.fp_vkGetDeviceProcAddr = detail::vulkan_functions().fp_vkGetDeviceProcAddr; + return instance; + } + + InstanceBuilder& InstanceBuilder::set_app_name(const char* app_name) + { + if (!app_name) return *this; + info.app_name = app_name; + return *this; + } + InstanceBuilder& InstanceBuilder::set_engine_name(const char* engine_name) + { + if (!engine_name) return *this; + info.engine_name = engine_name; + return *this; + } + InstanceBuilder& InstanceBuilder::set_app_version(uint32_t app_version) + { + info.application_version = app_version; + return *this; + } + InstanceBuilder& InstanceBuilder::set_app_version(uint32_t major, uint32_t minor, uint32_t patch) + { + info.application_version = VKB_MAKE_VK_VERSION(0, major, minor, patch); + return *this; + } + InstanceBuilder& InstanceBuilder::set_engine_version(uint32_t engine_version) + { + info.engine_version = engine_version; + return *this; + } + InstanceBuilder& InstanceBuilder::set_engine_version(uint32_t major, uint32_t minor, uint32_t patch) + { + info.engine_version = VKB_MAKE_VK_VERSION(0, major, minor, patch); + return *this; + } + InstanceBuilder& InstanceBuilder::require_api_version(uint32_t required_api_version) + { + info.required_api_version = required_api_version; + return *this; + } + InstanceBuilder& InstanceBuilder::require_api_version(uint32_t major, uint32_t minor, uint32_t patch) + { + info.required_api_version = VKB_MAKE_VK_VERSION(0, major, minor, patch); + return *this; + } + InstanceBuilder& InstanceBuilder::set_minimum_instance_version(uint32_t minimum_instance_version) + { + info.minimum_instance_version = minimum_instance_version; + return *this; + } + InstanceBuilder& InstanceBuilder::set_minimum_instance_version(uint32_t major, uint32_t minor, uint32_t patch) + { + info.minimum_instance_version = VKB_MAKE_VK_VERSION(0, major, minor, patch); + return *this; + } + InstanceBuilder& InstanceBuilder::desire_api_version(uint32_t preferred_vulkan_version) + { + info.desired_api_version = preferred_vulkan_version; + return *this; + } + InstanceBuilder& InstanceBuilder::desire_api_version(uint32_t major, uint32_t minor, uint32_t patch) + { + info.desired_api_version = VKB_MAKE_VK_VERSION(0, major, minor, patch); + return *this; + } + InstanceBuilder& InstanceBuilder::enable_layer(const char* layer_name) + { + if (!layer_name) return *this; + info.layers.push_back(layer_name); + return *this; + } + InstanceBuilder& InstanceBuilder::enable_extension(const char* extension_name) + { + if (!extension_name) return *this; + info.extensions.push_back(extension_name); + return *this; + } + InstanceBuilder& InstanceBuilder::enable_extensions(std::vector const& extensions) + { + for (const auto extension : extensions) + { + info.extensions.push_back(extension); + } + return *this; + } + InstanceBuilder& InstanceBuilder::enable_extensions(size_t count, const char* const* extensions) + { + if (!extensions || count == 0) return *this; + for (size_t i = 0; i < count; i++) + { + info.extensions.push_back(extensions[i]); + } + return *this; + } + InstanceBuilder& InstanceBuilder::enable_validation_layers(bool enable_validation) + { + info.enable_validation_layers = enable_validation; + return *this; + } + InstanceBuilder& InstanceBuilder::request_validation_layers(bool enable_validation) + { + info.request_validation_layers = enable_validation; + return *this; + } + + InstanceBuilder& InstanceBuilder::use_default_debug_messenger() + { + info.use_debug_messenger = true; + info.debug_callback = default_debug_callback; + return *this; + } + InstanceBuilder& InstanceBuilder::set_debug_callback(PFN_vkDebugUtilsMessengerCallbackEXT callback) + { + info.use_debug_messenger = true; + info.debug_callback = callback; + return *this; + } + InstanceBuilder& InstanceBuilder::set_debug_callback_user_data_pointer(void* user_data_pointer) + { + info.debug_user_data_pointer = user_data_pointer; + return *this; + } + InstanceBuilder& InstanceBuilder::set_headless(bool headless) + { + info.headless_context = headless; + return *this; + } + InstanceBuilder& InstanceBuilder::set_debug_messenger_severity(VkDebugUtilsMessageSeverityFlagsEXT severity) + { + info.debug_message_severity = severity; + return *this; + } + InstanceBuilder& InstanceBuilder::add_debug_messenger_severity(VkDebugUtilsMessageSeverityFlagsEXT severity) + { + info.debug_message_severity = info.debug_message_severity | severity; + return *this; + } + InstanceBuilder& InstanceBuilder::set_debug_messenger_type(VkDebugUtilsMessageTypeFlagsEXT type) + { + info.debug_message_type = type; + return *this; + } + InstanceBuilder& InstanceBuilder::add_debug_messenger_type(VkDebugUtilsMessageTypeFlagsEXT type) + { + info.debug_message_type = info.debug_message_type | type; + return *this; + } + InstanceBuilder& InstanceBuilder::add_validation_disable(VkValidationCheckEXT check) + { + info.disabled_validation_checks.push_back(check); + return *this; + } + InstanceBuilder& InstanceBuilder::add_validation_feature_enable(VkValidationFeatureEnableEXT enable) + { + info.enabled_validation_features.push_back(enable); + return *this; + } + InstanceBuilder& InstanceBuilder::add_validation_feature_disable(VkValidationFeatureDisableEXT disable) + { + info.disabled_validation_features.push_back(disable); + return *this; + } + InstanceBuilder& InstanceBuilder::set_allocation_callbacks(VkAllocationCallbacks* callbacks) + { + info.allocation_callbacks = callbacks; + return *this; + } + + void destroy_debug_messenger(VkInstance const instance, VkDebugUtilsMessengerEXT const messenger); + + + // ---- Physical Device ---- // + + namespace detail { + + std::vector check_device_extension_support( + std::vector const& available_extensions, std::vector const& desired_extensions) + { + std::vector extensions_to_enable; + for (const auto& avail_ext : available_extensions) + { + for (auto& req_ext : desired_extensions) + { + if (avail_ext == req_ext) + { + extensions_to_enable.push_back(req_ext); + break; + } + } + } + return extensions_to_enable; + } + + // clang-format off + void combine_features(VkPhysicalDeviceFeatures& dest, VkPhysicalDeviceFeatures src) + { + dest.robustBufferAccess = dest.robustBufferAccess || src.robustBufferAccess; + dest.fullDrawIndexUint32 = dest.fullDrawIndexUint32 || src.fullDrawIndexUint32; + dest.imageCubeArray = dest.imageCubeArray || src.imageCubeArray; + dest.independentBlend = dest.independentBlend || src.independentBlend; + dest.geometryShader = dest.geometryShader || src.geometryShader; + dest.tessellationShader = dest.tessellationShader || src.tessellationShader; + dest.sampleRateShading = dest.sampleRateShading || src.sampleRateShading; + dest.dualSrcBlend = dest.dualSrcBlend || src.dualSrcBlend; + dest.logicOp = dest.logicOp || src.logicOp; + dest.multiDrawIndirect = dest.multiDrawIndirect || src.multiDrawIndirect; + dest.drawIndirectFirstInstance = dest.drawIndirectFirstInstance || src.drawIndirectFirstInstance; + dest.depthClamp = dest.depthClamp || src.depthClamp; + dest.depthBiasClamp = dest.depthBiasClamp || src.depthBiasClamp; + dest.fillModeNonSolid = dest.fillModeNonSolid || src.fillModeNonSolid; + dest.depthBounds = dest.depthBounds || src.depthBounds; + dest.wideLines = dest.wideLines || src.wideLines; + dest.largePoints = dest.largePoints || src.largePoints; + dest.alphaToOne = dest.alphaToOne || src.alphaToOne; + dest.multiViewport = dest.multiViewport || src.multiViewport; + dest.samplerAnisotropy = dest.samplerAnisotropy || src.samplerAnisotropy; + dest.textureCompressionETC2 = dest.textureCompressionETC2 || src.textureCompressionETC2; + dest.textureCompressionASTC_LDR = dest.textureCompressionASTC_LDR || src.textureCompressionASTC_LDR; + dest.textureCompressionBC = dest.textureCompressionBC || src.textureCompressionBC; + dest.occlusionQueryPrecise = dest.occlusionQueryPrecise || src.occlusionQueryPrecise; + dest.pipelineStatisticsQuery = dest.pipelineStatisticsQuery || src.pipelineStatisticsQuery; + dest.vertexPipelineStoresAndAtomics = dest.vertexPipelineStoresAndAtomics || src.vertexPipelineStoresAndAtomics; + dest.fragmentStoresAndAtomics = dest.fragmentStoresAndAtomics || src.fragmentStoresAndAtomics; + dest.shaderTessellationAndGeometryPointSize = dest.shaderTessellationAndGeometryPointSize || src.shaderTessellationAndGeometryPointSize; + dest.shaderImageGatherExtended = dest.shaderImageGatherExtended || src.shaderImageGatherExtended; + dest.shaderStorageImageExtendedFormats = dest.shaderStorageImageExtendedFormats || src.shaderStorageImageExtendedFormats; + dest.shaderStorageImageMultisample = dest.shaderStorageImageMultisample || src.shaderStorageImageMultisample; + dest.shaderStorageImageReadWithoutFormat = dest.shaderStorageImageReadWithoutFormat || src.shaderStorageImageReadWithoutFormat; + dest.shaderStorageImageWriteWithoutFormat = dest.shaderStorageImageWriteWithoutFormat || src.shaderStorageImageWriteWithoutFormat; + dest.shaderUniformBufferArrayDynamicIndexing = dest.shaderUniformBufferArrayDynamicIndexing || src.shaderUniformBufferArrayDynamicIndexing; + dest.shaderSampledImageArrayDynamicIndexing = dest.shaderSampledImageArrayDynamicIndexing || src.shaderSampledImageArrayDynamicIndexing; + dest.shaderStorageBufferArrayDynamicIndexing = dest.shaderStorageBufferArrayDynamicIndexing || src.shaderStorageBufferArrayDynamicIndexing; + dest.shaderStorageImageArrayDynamicIndexing = dest.shaderStorageImageArrayDynamicIndexing || src.shaderStorageImageArrayDynamicIndexing; + dest.shaderClipDistance = dest.shaderClipDistance || src.shaderClipDistance; + dest.shaderCullDistance = dest.shaderCullDistance || src.shaderCullDistance; + dest.shaderFloat64 = dest.shaderFloat64 || src.shaderFloat64; + dest.shaderInt64 = dest.shaderInt64 || src.shaderInt64; + dest.shaderInt16 = dest.shaderInt16 || src.shaderInt16; + dest.shaderResourceResidency = dest.shaderResourceResidency || src.shaderResourceResidency; + dest.shaderResourceMinLod = dest.shaderResourceMinLod || src.shaderResourceMinLod; + dest.sparseBinding = dest.sparseBinding || src.sparseBinding; + dest.sparseResidencyBuffer = dest.sparseResidencyBuffer || src.sparseResidencyBuffer; + dest.sparseResidencyImage2D = dest.sparseResidencyImage2D || src.sparseResidencyImage2D; + dest.sparseResidencyImage3D = dest.sparseResidencyImage3D || src.sparseResidencyImage3D; + dest.sparseResidency2Samples = dest.sparseResidency2Samples || src.sparseResidency2Samples; + dest.sparseResidency4Samples = dest.sparseResidency4Samples || src.sparseResidency4Samples; + dest.sparseResidency8Samples = dest.sparseResidency8Samples || src.sparseResidency8Samples; + dest.sparseResidency16Samples = dest.sparseResidency16Samples || src.sparseResidency16Samples; + dest.sparseResidencyAliased = dest.sparseResidencyAliased || src.sparseResidencyAliased; + dest.variableMultisampleRate = dest.variableMultisampleRate || src.variableMultisampleRate; + dest.inheritedQueries = dest.inheritedQueries || src.inheritedQueries; + } + + bool supports_features(const VkPhysicalDeviceFeatures& supported, + const VkPhysicalDeviceFeatures& requested, + const GenericFeatureChain& extension_supported, + const GenericFeatureChain& extension_requested) + { + + if (requested.robustBufferAccess && !supported.robustBufferAccess) return false; + if (requested.fullDrawIndexUint32 && !supported.fullDrawIndexUint32) return false; + if (requested.imageCubeArray && !supported.imageCubeArray) return false; + if (requested.independentBlend && !supported.independentBlend) return false; + if (requested.geometryShader && !supported.geometryShader) return false; + if (requested.tessellationShader && !supported.tessellationShader) return false; + if (requested.sampleRateShading && !supported.sampleRateShading) return false; + if (requested.dualSrcBlend && !supported.dualSrcBlend) return false; + if (requested.logicOp && !supported.logicOp) return false; + if (requested.multiDrawIndirect && !supported.multiDrawIndirect) return false; + if (requested.drawIndirectFirstInstance && !supported.drawIndirectFirstInstance) return false; + if (requested.depthClamp && !supported.depthClamp) return false; + if (requested.depthBiasClamp && !supported.depthBiasClamp) return false; + if (requested.fillModeNonSolid && !supported.fillModeNonSolid) return false; + if (requested.depthBounds && !supported.depthBounds) return false; + if (requested.wideLines && !supported.wideLines) return false; + if (requested.largePoints && !supported.largePoints) return false; + if (requested.alphaToOne && !supported.alphaToOne) return false; + if (requested.multiViewport && !supported.multiViewport) return false; + if (requested.samplerAnisotropy && !supported.samplerAnisotropy) return false; + if (requested.textureCompressionETC2 && !supported.textureCompressionETC2) return false; + if (requested.textureCompressionASTC_LDR && !supported.textureCompressionASTC_LDR) return false; + if (requested.textureCompressionBC && !supported.textureCompressionBC) return false; + if (requested.occlusionQueryPrecise && !supported.occlusionQueryPrecise) return false; + if (requested.pipelineStatisticsQuery && !supported.pipelineStatisticsQuery) return false; + if (requested.vertexPipelineStoresAndAtomics && !supported.vertexPipelineStoresAndAtomics) return false; + if (requested.fragmentStoresAndAtomics && !supported.fragmentStoresAndAtomics) return false; + if (requested.shaderTessellationAndGeometryPointSize && !supported.shaderTessellationAndGeometryPointSize) return false; + if (requested.shaderImageGatherExtended && !supported.shaderImageGatherExtended) return false; + if (requested.shaderStorageImageExtendedFormats && !supported.shaderStorageImageExtendedFormats) return false; + if (requested.shaderStorageImageMultisample && !supported.shaderStorageImageMultisample) return false; + if (requested.shaderStorageImageReadWithoutFormat && !supported.shaderStorageImageReadWithoutFormat) return false; + if (requested.shaderStorageImageWriteWithoutFormat && !supported.shaderStorageImageWriteWithoutFormat) return false; + if (requested.shaderUniformBufferArrayDynamicIndexing && !supported.shaderUniformBufferArrayDynamicIndexing) return false; + if (requested.shaderSampledImageArrayDynamicIndexing && !supported.shaderSampledImageArrayDynamicIndexing) return false; + if (requested.shaderStorageBufferArrayDynamicIndexing && !supported.shaderStorageBufferArrayDynamicIndexing) return false; + if (requested.shaderStorageImageArrayDynamicIndexing && !supported.shaderStorageImageArrayDynamicIndexing) return false; + if (requested.shaderClipDistance && !supported.shaderClipDistance) return false; + if (requested.shaderCullDistance && !supported.shaderCullDistance) return false; + if (requested.shaderFloat64 && !supported.shaderFloat64) return false; + if (requested.shaderInt64 && !supported.shaderInt64) return false; + if (requested.shaderInt16 && !supported.shaderInt16) return false; + if (requested.shaderResourceResidency && !supported.shaderResourceResidency) return false; + if (requested.shaderResourceMinLod && !supported.shaderResourceMinLod) return false; + if (requested.sparseBinding && !supported.sparseBinding) return false; + if (requested.sparseResidencyBuffer && !supported.sparseResidencyBuffer) return false; + if (requested.sparseResidencyImage2D && !supported.sparseResidencyImage2D) return false; + if (requested.sparseResidencyImage3D && !supported.sparseResidencyImage3D) return false; + if (requested.sparseResidency2Samples && !supported.sparseResidency2Samples) return false; + if (requested.sparseResidency4Samples && !supported.sparseResidency4Samples) return false; + if (requested.sparseResidency8Samples && !supported.sparseResidency8Samples) return false; + if (requested.sparseResidency16Samples && !supported.sparseResidency16Samples) return false; + if (requested.sparseResidencyAliased && !supported.sparseResidencyAliased) return false; + if (requested.variableMultisampleRate && !supported.variableMultisampleRate) return false; + if (requested.inheritedQueries && !supported.inheritedQueries) return false; + + return extension_supported.match_all(extension_requested); + } + // clang-format on + // Finds the first queue which supports the desired operations. Returns QUEUE_INDEX_MAX_VALUE if none is found + uint32_t get_first_queue_index(std::vector const& families, VkQueueFlags desired_flags) + { + for (uint32_t i = 0; i < static_cast(families.size()); i++) + { + if ((families[i].queueFlags & desired_flags) == desired_flags) return i; + } + return QUEUE_INDEX_MAX_VALUE; + } + // Finds the queue which is separate from the graphics queue and has the desired flag and not the + // undesired flag, but will select it if no better options are available compute support. Returns + // QUEUE_INDEX_MAX_VALUE if none is found. + uint32_t get_separate_queue_index( + std::vector const& families, VkQueueFlags desired_flags, VkQueueFlags undesired_flags) + { + uint32_t index = QUEUE_INDEX_MAX_VALUE; + for (uint32_t i = 0; i < static_cast(families.size()); i++) + { + if ((families[i].queueFlags & desired_flags) == desired_flags && ((families[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) == 0)) + { + if ((families[i].queueFlags & undesired_flags) == 0) + { + return i; + } + else + { + index = i; + } + } + } + return index; + } + + // finds the first queue which supports only the desired flag (not graphics or transfer). Returns QUEUE_INDEX_MAX_VALUE if none is found. + uint32_t get_dedicated_queue_index( + std::vector const& families, VkQueueFlags desired_flags, VkQueueFlags undesired_flags) + { + for (uint32_t i = 0; i < static_cast(families.size()); i++) + { + if ((families[i].queueFlags & desired_flags) == desired_flags && + (families[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) == 0 && (families[i].queueFlags & undesired_flags) == 0) + return i; + } + return QUEUE_INDEX_MAX_VALUE; + } + + // finds the first queue which supports presenting. returns QUEUE_INDEX_MAX_VALUE if none is found + uint32_t get_present_queue_index( + VkPhysicalDevice const phys_device, VkSurfaceKHR const surface, std::vector const& families) + { + for (uint32_t i = 0; i < static_cast(families.size()); i++) + { + VkBool32 presentSupport = false; + if (surface != VK_NULL_HANDLE) + { + VkResult res = detail::vulkan_functions().fp_vkGetPhysicalDeviceSurfaceSupportKHR(phys_device, i, surface, &presentSupport); + if (res != VK_SUCCESS) return QUEUE_INDEX_MAX_VALUE; // TODO: determine if this should fail another way + } + if (presentSupport == VK_TRUE) return i; + } + return QUEUE_INDEX_MAX_VALUE; + } + } // namespace detail + + PhysicalDevice PhysicalDeviceSelector::populate_device_details( + VkPhysicalDevice vk_phys_device, detail::GenericFeatureChain const& src_extended_features_chain) const + { + PhysicalDevice physical_device{}; + physical_device.physical_device = vk_phys_device; + physical_device.surface = instance_info.surface; + physical_device.defer_surface_initialization = criteria.defer_surface_initialization; + physical_device.instance_version = instance_info.version; + auto queue_families = detail::get_vector_noerror( + detail::vulkan_functions().fp_vkGetPhysicalDeviceQueueFamilyProperties, vk_phys_device); + physical_device.queue_families = queue_families; + + detail::vulkan_functions().fp_vkGetPhysicalDeviceProperties(vk_phys_device, &physical_device.properties); + detail::vulkan_functions().fp_vkGetPhysicalDeviceFeatures(vk_phys_device, &physical_device.features); + detail::vulkan_functions().fp_vkGetPhysicalDeviceMemoryProperties(vk_phys_device, &physical_device.memory_properties); + + physical_device.name = physical_device.properties.deviceName; + + std::vector available_extensions; + auto available_extensions_ret = detail::get_vector( + available_extensions, detail::vulkan_functions().fp_vkEnumerateDeviceExtensionProperties, vk_phys_device, nullptr); + if (available_extensions_ret != VK_SUCCESS) return physical_device; + for (const auto& ext : available_extensions) + { + physical_device.available_extensions.push_back(&ext.extensionName[0]); + } + + physical_device.properties2_ext_enabled = instance_info.properties2_ext_enabled; + + auto fill_chain = src_extended_features_chain; + + bool instance_is_1_1 = instance_info.version >= VKB_VK_API_VERSION_1_1; + if (!fill_chain.nodes.empty() && (instance_is_1_1 || instance_info.properties2_ext_enabled)) + { + VkPhysicalDeviceFeatures2 local_features{}; + fill_chain.chain_up(local_features); + // Use KHR function if not able to use the core function + if (instance_is_1_1) + { + detail::vulkan_functions().fp_vkGetPhysicalDeviceFeatures2(vk_phys_device, &local_features); + } + else + { + detail::vulkan_functions().fp_vkGetPhysicalDeviceFeatures2KHR(vk_phys_device, &local_features); + } + physical_device.extended_features_chain = fill_chain; + } + + return physical_device; + } + + PhysicalDevice::Suitable PhysicalDeviceSelector::is_device_suitable(PhysicalDevice const& pd) const + { + PhysicalDevice::Suitable suitable = PhysicalDevice::Suitable::yes; + + if (criteria.name.size() > 0 && criteria.name != pd.properties.deviceName) return PhysicalDevice::Suitable::no; + + if (criteria.required_version > pd.properties.apiVersion) return PhysicalDevice::Suitable::no; + if (criteria.desired_version > pd.properties.apiVersion) suitable = PhysicalDevice::Suitable::partial; + + bool dedicated_compute = detail::get_dedicated_queue_index(pd.queue_families, VK_QUEUE_COMPUTE_BIT, VK_QUEUE_TRANSFER_BIT) != + detail::QUEUE_INDEX_MAX_VALUE; + bool dedicated_transfer = detail::get_dedicated_queue_index(pd.queue_families, VK_QUEUE_TRANSFER_BIT, VK_QUEUE_COMPUTE_BIT) != + detail::QUEUE_INDEX_MAX_VALUE; + bool separate_compute = detail::get_separate_queue_index(pd.queue_families, VK_QUEUE_COMPUTE_BIT, VK_QUEUE_TRANSFER_BIT) != + detail::QUEUE_INDEX_MAX_VALUE; + bool separate_transfer = detail::get_separate_queue_index(pd.queue_families, VK_QUEUE_TRANSFER_BIT, VK_QUEUE_COMPUTE_BIT) != + detail::QUEUE_INDEX_MAX_VALUE; + + bool present_queue = detail::get_present_queue_index(pd.physical_device, instance_info.surface, pd.queue_families) != + detail::QUEUE_INDEX_MAX_VALUE; + + if (criteria.require_dedicated_compute_queue && !dedicated_compute) return PhysicalDevice::Suitable::no; + if (criteria.require_dedicated_transfer_queue && !dedicated_transfer) return PhysicalDevice::Suitable::no; + if (criteria.require_separate_compute_queue && !separate_compute) return PhysicalDevice::Suitable::no; + if (criteria.require_separate_transfer_queue && !separate_transfer) return PhysicalDevice::Suitable::no; + if (criteria.require_present && !present_queue && !criteria.defer_surface_initialization) + return PhysicalDevice::Suitable::no; + + auto required_extensions_supported = + detail::check_device_extension_support(pd.available_extensions, criteria.required_extensions); + if (required_extensions_supported.size() != criteria.required_extensions.size()) + return PhysicalDevice::Suitable::no; + + auto desired_extensions_supported = detail::check_device_extension_support(pd.available_extensions, criteria.desired_extensions); + if (desired_extensions_supported.size() != criteria.desired_extensions.size()) + suitable = PhysicalDevice::Suitable::partial; + + if (!criteria.defer_surface_initialization && criteria.require_present) + { + std::vector formats; + std::vector present_modes; + + auto formats_ret = detail::get_vector(formats, + detail::vulkan_functions().fp_vkGetPhysicalDeviceSurfaceFormatsKHR, + pd.physical_device, + instance_info.surface); + auto present_modes_ret = detail::get_vector(present_modes, + detail::vulkan_functions().fp_vkGetPhysicalDeviceSurfacePresentModesKHR, + pd.physical_device, + instance_info.surface); + + if (formats_ret != VK_SUCCESS || present_modes_ret != VK_SUCCESS || formats.empty() || present_modes.empty()) + { + return PhysicalDevice::Suitable::no; + } + } + + if (!criteria.allow_any_type && pd.properties.deviceType != static_cast(criteria.preferred_type)) + { + suitable = PhysicalDevice::Suitable::partial; + } + + bool required_features_supported = detail::supports_features( + pd.features, criteria.required_features, pd.extended_features_chain, criteria.extended_features_chain); + if (!required_features_supported) return PhysicalDevice::Suitable::no; + + for (uint32_t i = 0; i < pd.memory_properties.memoryHeapCount; i++) + { + if (pd.memory_properties.memoryHeaps[i].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) + { + if (pd.memory_properties.memoryHeaps[i].size < criteria.required_mem_size) + { + return PhysicalDevice::Suitable::no; + } + else if (pd.memory_properties.memoryHeaps[i].size < criteria.desired_mem_size) + { + suitable = PhysicalDevice::Suitable::partial; + } + } + } + + return suitable; + } + // delegate construction to the one with an explicit surface parameter + PhysicalDeviceSelector::PhysicalDeviceSelector(Instance const& instance) + : PhysicalDeviceSelector(instance, VK_NULL_HANDLE) + { + } + + PhysicalDeviceSelector::PhysicalDeviceSelector(Instance const& instance, VkSurfaceKHR surface) + { + instance_info.instance = instance.instance; + instance_info.version = instance.instance_version; + instance_info.properties2_ext_enabled = instance.properties2_ext_enabled; + instance_info.surface = surface; + criteria.require_present = !instance.headless; + criteria.required_version = instance.api_version; + criteria.desired_version = instance.api_version; + } + + Result> PhysicalDeviceSelector::select_impl(DeviceSelectionMode selection) const + { +#if !defined(NDEBUG) + // Validation + for (const auto& node : criteria.extended_features_chain.nodes) + { + assert(node.sType != static_cast(0) && + "Features struct sType must be filled with the struct's " + "corresponding VkStructureType enum"); + assert(node.sType != VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2 && + "Do not pass VkPhysicalDeviceFeatures2 as a required extension feature structure. An " + "instance of this is managed internally for selection criteria and device creation."); + } +#endif + + if (criteria.require_present && !criteria.defer_surface_initialization) + { + if (instance_info.surface == VK_NULL_HANDLE) + return Result>{ PhysicalDeviceError::no_surface_provided }; + } + + // Get the VkPhysicalDevice handles on the system + std::vector vk_physical_devices; + + auto vk_physical_devices_ret = detail::get_vector( + vk_physical_devices, detail::vulkan_functions().fp_vkEnumeratePhysicalDevices, instance_info.instance); + if (vk_physical_devices_ret != VK_SUCCESS) + { + return Result>{ PhysicalDeviceError::failed_enumerate_physical_devices, vk_physical_devices_ret }; + } + if (vk_physical_devices.size() == 0) + { + return Result>{ PhysicalDeviceError::no_physical_devices_found }; + } + + auto fill_out_phys_dev_with_criteria = [&](PhysicalDevice& phys_dev) + { + phys_dev.features = criteria.required_features; + phys_dev.extended_features_chain = criteria.extended_features_chain; + bool portability_ext_available = false; + for (const auto& ext : phys_dev.available_extensions) + if (criteria.enable_portability_subset && ext == "VK_KHR_portability_subset") + portability_ext_available = true; + + auto desired_extensions_supported = + detail::check_device_extension_support(phys_dev.available_extensions, criteria.desired_extensions); + + phys_dev.extensions_to_enable.clear(); + phys_dev.extensions_to_enable.insert( + phys_dev.extensions_to_enable.end(), criteria.required_extensions.begin(), criteria.required_extensions.end()); + phys_dev.extensions_to_enable.insert( + phys_dev.extensions_to_enable.end(), desired_extensions_supported.begin(), desired_extensions_supported.end()); + if (portability_ext_available) + { + phys_dev.extensions_to_enable.push_back("VK_KHR_portability_subset"); + } + }; + + // if this option is set, always return only the first physical device found + if (criteria.use_first_gpu_unconditionally && vk_physical_devices.size() > 0) + { + PhysicalDevice physical_device = populate_device_details(vk_physical_devices[0], criteria.extended_features_chain); + fill_out_phys_dev_with_criteria(physical_device); + return std::vector{ physical_device }; + } + + // Populate their details and check their suitability + std::vector physical_devices; + for (auto& vk_physical_device : vk_physical_devices) + { + PhysicalDevice phys_dev = populate_device_details(vk_physical_device, criteria.extended_features_chain); + phys_dev.suitable = is_device_suitable(phys_dev); + if (phys_dev.suitable != PhysicalDevice::Suitable::no) + { + physical_devices.push_back(phys_dev); + } + } + + // sort the list into fully and partially suitable devices. use stable_partition to maintain relative order + const auto partition_index = std::stable_partition(physical_devices.begin(), physical_devices.end(), [](auto const& pd) + { + return pd.suitable == PhysicalDevice::Suitable::yes; + }); + + // Remove the partially suitable elements if they aren't desired + if (selection == DeviceSelectionMode::only_fully_suitable) + { + physical_devices.erase(partition_index, physical_devices.end()); + } + + // Make the physical device ready to be used to create a Device from it + for (auto& physical_device : physical_devices) + { + fill_out_phys_dev_with_criteria(physical_device); + } + + return physical_devices; + } + + Result PhysicalDeviceSelector::select(DeviceSelectionMode selection) const + { + auto const selected_devices = select_impl(selection); + + if (!selected_devices) return Result{ selected_devices.error() }; + if (selected_devices.value().size() == 0) + { + return Result{ PhysicalDeviceError::no_suitable_device }; + } + + return selected_devices.value().at(0); + } + + // Return all devices which are considered suitable - intended for applications which want to let the user pick the physical device + Result> PhysicalDeviceSelector::select_devices(DeviceSelectionMode selection) const + { + auto const selected_devices = select_impl(selection); + if (!selected_devices) return Result>{ selected_devices.error() }; + if (selected_devices.value().size() == 0) + { + return Result>{ PhysicalDeviceError::no_suitable_device }; + } + return selected_devices.value(); + } + + Result> PhysicalDeviceSelector::select_device_names(DeviceSelectionMode selection) const + { + auto const selected_devices = select_impl(selection); + if (!selected_devices) return Result>{ selected_devices.error() }; + if (selected_devices.value().size() == 0) + { + return Result>{ PhysicalDeviceError::no_suitable_device }; + } + std::vector names; + for (const auto& pd : selected_devices.value()) + { + names.push_back(pd.name); + } + return names; + } + PhysicalDeviceSelector& PhysicalDeviceSelector::set_surface(VkSurfaceKHR surface) + { + instance_info.surface = surface; + return *this; + } + PhysicalDeviceSelector& PhysicalDeviceSelector::set_name(std::string const& name) + { + criteria.name = name; + return *this; + } + PhysicalDeviceSelector& PhysicalDeviceSelector::prefer_gpu_device_type(PreferredDeviceType type) + { + criteria.preferred_type = type; + return *this; + } + PhysicalDeviceSelector& PhysicalDeviceSelector::allow_any_gpu_device_type(bool allow_any_type) + { + criteria.allow_any_type = allow_any_type; + return *this; + } + PhysicalDeviceSelector& PhysicalDeviceSelector::require_present(bool require) + { + criteria.require_present = require; + return *this; + } + PhysicalDeviceSelector& PhysicalDeviceSelector::require_dedicated_transfer_queue() + { + criteria.require_dedicated_transfer_queue = true; + return *this; + } + PhysicalDeviceSelector& PhysicalDeviceSelector::require_dedicated_compute_queue() + { + criteria.require_dedicated_compute_queue = true; + return *this; + } + PhysicalDeviceSelector& PhysicalDeviceSelector::require_separate_transfer_queue() + { + criteria.require_separate_transfer_queue = true; + return *this; + } + PhysicalDeviceSelector& PhysicalDeviceSelector::require_separate_compute_queue() + { + criteria.require_separate_compute_queue = true; + return *this; + } + PhysicalDeviceSelector& PhysicalDeviceSelector::required_device_memory_size(VkDeviceSize size) + { + criteria.required_mem_size = size; + return *this; + } + PhysicalDeviceSelector& PhysicalDeviceSelector::desired_device_memory_size(VkDeviceSize size) + { + criteria.desired_mem_size = size; + return *this; + } + PhysicalDeviceSelector& PhysicalDeviceSelector::add_required_extension(const char* extension) + { + criteria.required_extensions.push_back(extension); + return *this; + } + PhysicalDeviceSelector& PhysicalDeviceSelector::add_required_extensions(std::vector const& extensions) + { + for (const auto& ext : extensions) + { + criteria.required_extensions.push_back(ext); + } + return *this; + } + PhysicalDeviceSelector& PhysicalDeviceSelector::add_required_extensions(size_t count, const char* const* extensions) + { + if (!extensions || count == 0) return *this; + for (size_t i = 0; i < count; i++) + { + criteria.required_extensions.push_back(extensions[i]); + } + return *this; + } + PhysicalDeviceSelector& PhysicalDeviceSelector::add_desired_extension(const char* extension) + { + criteria.desired_extensions.push_back(extension); + return *this; + } + PhysicalDeviceSelector& PhysicalDeviceSelector::add_desired_extensions(const std::vector& extensions) + { + for (const auto& ext : extensions) + { + criteria.desired_extensions.push_back(ext); + } + return *this; + } + PhysicalDeviceSelector& PhysicalDeviceSelector::set_minimum_version(uint32_t major, uint32_t minor) + { + criteria.required_version = VKB_MAKE_VK_VERSION(0, major, minor, 0); + return *this; + } + PhysicalDeviceSelector& PhysicalDeviceSelector::set_desired_version(uint32_t major, uint32_t minor) + { + criteria.desired_version = VKB_MAKE_VK_VERSION(0, major, minor, 0); + return *this; + } + PhysicalDeviceSelector& PhysicalDeviceSelector::disable_portability_subset() + { + criteria.enable_portability_subset = false; + return *this; + } + + PhysicalDeviceSelector& PhysicalDeviceSelector::set_required_features(VkPhysicalDeviceFeatures const& features) + { + detail::combine_features(criteria.required_features, features); + return *this; + } +#if defined(VKB_VK_API_VERSION_1_2) + // The implementation of the set_required_features_1X functions sets the sType manually. This was a poor choice since + // users of Vulkan should expect to fill out their structs properly. To make the functions take the struct parameter by + // const reference, a local copy must be made in order to set the sType. + PhysicalDeviceSelector& PhysicalDeviceSelector::set_required_features_11(VkPhysicalDeviceVulkan11Features const& features_11) + { + VkPhysicalDeviceVulkan11Features features_11_copy = features_11; + features_11_copy.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES; + add_required_extension_features(features_11_copy); + return *this; + } + PhysicalDeviceSelector& PhysicalDeviceSelector::set_required_features_12(VkPhysicalDeviceVulkan12Features const& features_12) + { + VkPhysicalDeviceVulkan12Features features_12_copy = features_12; + features_12_copy.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES; + add_required_extension_features(features_12_copy); + return *this; + } +#endif +#if defined(VKB_VK_API_VERSION_1_3) + PhysicalDeviceSelector& PhysicalDeviceSelector::set_required_features_13(VkPhysicalDeviceVulkan13Features const& features_13) + { + VkPhysicalDeviceVulkan13Features features_13_copy = features_13; + features_13_copy.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES; + add_required_extension_features(features_13_copy); + return *this; + } +#endif + PhysicalDeviceSelector& PhysicalDeviceSelector::defer_surface_initialization() + { + criteria.defer_surface_initialization = true; + return *this; + } + PhysicalDeviceSelector& PhysicalDeviceSelector::select_first_device_unconditionally(bool unconditionally) + { + criteria.use_first_gpu_unconditionally = unconditionally; + return *this; + } + + // PhysicalDevice + bool PhysicalDevice::has_dedicated_compute_queue() const + { + return detail::get_dedicated_queue_index(queue_families, VK_QUEUE_COMPUTE_BIT, VK_QUEUE_TRANSFER_BIT) != detail::QUEUE_INDEX_MAX_VALUE; + } + bool PhysicalDevice::has_separate_compute_queue() const + { + return detail::get_separate_queue_index(queue_families, VK_QUEUE_COMPUTE_BIT, VK_QUEUE_TRANSFER_BIT) != detail::QUEUE_INDEX_MAX_VALUE; + } + bool PhysicalDevice::has_dedicated_transfer_queue() const + { + return detail::get_dedicated_queue_index(queue_families, VK_QUEUE_TRANSFER_BIT, VK_QUEUE_COMPUTE_BIT) != detail::QUEUE_INDEX_MAX_VALUE; + } + bool PhysicalDevice::has_separate_transfer_queue() const + { + return detail::get_separate_queue_index(queue_families, VK_QUEUE_TRANSFER_BIT, VK_QUEUE_COMPUTE_BIT) != detail::QUEUE_INDEX_MAX_VALUE; + } + std::vector PhysicalDevice::get_queue_families() const { return queue_families; } + std::vector PhysicalDevice::get_extensions() const { return extensions_to_enable; } + std::vector PhysicalDevice::get_available_extensions() const { return available_extensions; } + bool PhysicalDevice::is_extension_present(const char* ext) const + { + return std::find_if(std::begin(available_extensions), std::end(available_extensions), [ext](std::string const& ext_name) + { + return ext_name == ext; + }) != std::end(available_extensions); + } + bool PhysicalDevice::enable_extension_if_present(const char* extension) + { + auto it = std::find_if(std::begin(available_extensions), + std::end(available_extensions), + [extension](std::string const& ext_name) { return ext_name == extension; }); + if (it != std::end(available_extensions)) + { + extensions_to_enable.push_back(extension); + return true; + } + return false; + } + bool PhysicalDevice::enable_extensions_if_present(const std::vector& extensions) + { + for (const auto extension : extensions) + { + auto it = std::find_if(std::begin(available_extensions), + std::end(available_extensions), + [extension](std::string const& ext_name) { return ext_name == extension; }); + if (it == std::end(available_extensions)) return false; + } + for (const auto extension : extensions) + extensions_to_enable.push_back(extension); + return true; + } + + bool PhysicalDevice::enable_features_if_present(const VkPhysicalDeviceFeatures& features_to_enable) + { + VkPhysicalDeviceFeatures actual_pdf{}; + detail::vulkan_functions().fp_vkGetPhysicalDeviceFeatures(physical_device, &actual_pdf); + + bool required_features_supported = detail::supports_features(actual_pdf, features_to_enable, {}, {}); + if (required_features_supported) + { + detail::combine_features(features, features_to_enable); + } + return required_features_supported; + } + + bool PhysicalDevice::is_features_node_present(detail::GenericFeaturesPNextNode const& node) const + { + detail::GenericFeatureChain requested_features; + requested_features.nodes.push_back(node); + + return extended_features_chain.find_and_match(requested_features); + } + + bool PhysicalDevice::enable_features_node_if_present(detail::GenericFeaturesPNextNode const& node) + { + VkPhysicalDeviceFeatures2 actual_pdf2{}; + + detail::GenericFeatureChain requested_features; + requested_features.nodes.push_back(node); + + detail::GenericFeatureChain fill_chain = requested_features; + // Zero out supported features + memset(fill_chain.nodes.front().fields, UINT8_MAX, sizeof(VkBool32) * detail::GenericFeaturesPNextNode::field_capacity); + + actual_pdf2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2; + fill_chain.chain_up(actual_pdf2); + + bool required_features_supported = false; + bool instance_is_1_1 = instance_version >= VKB_VK_API_VERSION_1_1; + if (instance_is_1_1 || properties2_ext_enabled) + { + if (instance_is_1_1) + { + detail::vulkan_functions().fp_vkGetPhysicalDeviceFeatures2(physical_device, &actual_pdf2); + } + else + { + detail::vulkan_functions().fp_vkGetPhysicalDeviceFeatures2KHR(physical_device, &actual_pdf2); + } + required_features_supported = fill_chain.match_all(requested_features); + if (required_features_supported) + { + extended_features_chain.combine(requested_features); + } + } + return required_features_supported; + } + + + PhysicalDevice::operator VkPhysicalDevice() const { return this->physical_device; } + + // ---- Queues ---- // + + Result Device::get_queue_index(QueueType type) const + { + uint32_t index = detail::QUEUE_INDEX_MAX_VALUE; + switch (type) + { + case QueueType::present: + index = detail::get_present_queue_index(physical_device.physical_device, surface, queue_families); + if (index == detail::QUEUE_INDEX_MAX_VALUE) return Result{ QueueError::present_unavailable }; + break; + case QueueType::graphics: + index = detail::get_first_queue_index(queue_families, VK_QUEUE_GRAPHICS_BIT); + if (index == detail::QUEUE_INDEX_MAX_VALUE) return Result{ QueueError::graphics_unavailable }; + break; + case QueueType::compute: + index = detail::get_separate_queue_index(queue_families, VK_QUEUE_COMPUTE_BIT, VK_QUEUE_TRANSFER_BIT); + if (index == detail::QUEUE_INDEX_MAX_VALUE) return Result{ QueueError::compute_unavailable }; + break; + case QueueType::transfer: + index = detail::get_separate_queue_index(queue_families, VK_QUEUE_TRANSFER_BIT, VK_QUEUE_COMPUTE_BIT); + if (index == detail::QUEUE_INDEX_MAX_VALUE) return Result{ QueueError::transfer_unavailable }; + break; + default: + return Result{ QueueError::invalid_queue_family_index }; + } + return index; + } + Result Device::get_dedicated_queue_index(QueueType type) const + { + uint32_t index = detail::QUEUE_INDEX_MAX_VALUE; + switch (type) + { + case QueueType::compute: + index = detail::get_dedicated_queue_index(queue_families, VK_QUEUE_COMPUTE_BIT, VK_QUEUE_TRANSFER_BIT); + if (index == detail::QUEUE_INDEX_MAX_VALUE) return Result{ QueueError::compute_unavailable }; + break; + case QueueType::transfer: + index = detail::get_dedicated_queue_index(queue_families, VK_QUEUE_TRANSFER_BIT, VK_QUEUE_COMPUTE_BIT); + if (index == detail::QUEUE_INDEX_MAX_VALUE) return Result{ QueueError::transfer_unavailable }; + break; + default: + return Result{ QueueError::invalid_queue_family_index }; + } + return index; + } + + Result Device::get_queue(QueueType type) const + { + auto index = get_queue_index(type); + if (!index.has_value()) return { index.error() }; + VkQueue out_queue; + internal_table.fp_vkGetDeviceQueue(device, index.value(), 0, &out_queue); + return out_queue; + } + Result Device::get_dedicated_queue(QueueType type) const + { + auto index = get_dedicated_queue_index(type); + if (!index.has_value()) return { index.error() }; + VkQueue out_queue; + internal_table.fp_vkGetDeviceQueue(device, index.value(), 0, &out_queue); + return out_queue; + } + + // ---- Dispatch ---- // + + DispatchTable Device::make_table() const { return { device, fp_vkGetDeviceProcAddr }; } + + // ---- Device ---- // + + Device::operator VkDevice() const { return this->device; } + + CustomQueueDescription::CustomQueueDescription(uint32_t index, std::vector priorities) + : index(index), priorities(std::move(priorities)) + { + } + + void destroy_device(Device const& device) + { + device.internal_table.fp_vkDestroyDevice(device.device, device.allocation_callbacks); + } + + DeviceBuilder::DeviceBuilder(PhysicalDevice phys_device) { physical_device = std::move(phys_device); } + + Result DeviceBuilder::build() const + { + + std::vector queue_descriptions; + queue_descriptions.insert(queue_descriptions.end(), info.queue_descriptions.begin(), info.queue_descriptions.end()); + + if (queue_descriptions.empty()) + { + for (uint32_t i = 0; i < physical_device.queue_families.size(); i++) + { + queue_descriptions.emplace_back(i, std::vector{ 1.0f }); + } + } + + std::vector queueCreateInfos; + for (auto& desc : queue_descriptions) + { + VkDeviceQueueCreateInfo queue_create_info = {}; + queue_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; + queue_create_info.queueFamilyIndex = desc.index; + queue_create_info.queueCount = static_cast(desc.priorities.size()); + queue_create_info.pQueuePriorities = desc.priorities.data(); + queueCreateInfos.push_back(queue_create_info); + } + + std::vector extensions_to_enable; + for (const auto& ext : physical_device.extensions_to_enable) + { + extensions_to_enable.push_back(ext.c_str()); + } + +#ifdef _DEBUG + if (std::find(physical_device.extensions_to_enable.begin(), physical_device.extensions_to_enable.end(), VK_EXT_DEBUG_UTILS_EXTENSION_NAME) != physical_device.extensions_to_enable.end()) + { + extensions_to_enable.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); + } + + bool is_markers_enabled = false; + if (std::find(physical_device.extensions_to_enable.begin(), physical_device.extensions_to_enable.end(), VK_EXT_DEBUG_MARKER_EXTENSION_NAME) != physical_device.extensions_to_enable.end()) + { + is_markers_enabled = true; + extensions_to_enable.push_back(VK_EXT_DEBUG_MARKER_EXTENSION_NAME); + } +#endif + + if (physical_device.surface != VK_NULL_HANDLE || physical_device.defer_surface_initialization) + extensions_to_enable.push_back({ VK_KHR_SWAPCHAIN_EXTENSION_NAME }); + + std::vector final_pnext_chain; + VkDeviceCreateInfo device_create_info = {}; + + bool user_defined_phys_dev_features_2 = false; + for (auto& pnext : info.pNext_chain) + { + if (pnext->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2) + { + user_defined_phys_dev_features_2 = true; + break; + } + } + + if (user_defined_phys_dev_features_2 && !physical_device.extended_features_chain.nodes.empty()) + { + return { DeviceError::VkPhysicalDeviceFeatures2_in_pNext_chain_while_using_add_required_extension_features }; + } + + // These objects must be alive during the call to vkCreateDevice + auto physical_device_extension_features_copy = physical_device.extended_features_chain; + VkPhysicalDeviceFeatures2 local_features2{}; + local_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2; + local_features2.features = physical_device.features; + + if (!user_defined_phys_dev_features_2) + { + if (physical_device.instance_version >= VKB_VK_API_VERSION_1_1 || physical_device.properties2_ext_enabled) + { + final_pnext_chain.push_back(reinterpret_cast(&local_features2)); + for (auto& features_node : physical_device_extension_features_copy.nodes) + { + final_pnext_chain.push_back(reinterpret_cast(&features_node)); + } + } + else + { + // Only set device_create_info.pEnabledFeatures when the pNext chain does not contain a VkPhysicalDeviceFeatures2 structure + device_create_info.pEnabledFeatures = &physical_device.features; + } + } + + for (auto& pnext : info.pNext_chain) + { + final_pnext_chain.push_back(pnext); + } + + detail::setup_pNext_chain(device_create_info, final_pnext_chain); +#if !defined(NDEBUG) + for (auto& node : final_pnext_chain) + { + assert(node->sType != VK_STRUCTURE_TYPE_APPLICATION_INFO); + } +#endif + device_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; + device_create_info.flags = info.flags; + device_create_info.queueCreateInfoCount = static_cast(queueCreateInfos.size()); + device_create_info.pQueueCreateInfos = queueCreateInfos.data(); + device_create_info.enabledExtensionCount = static_cast(extensions_to_enable.size()); + device_create_info.ppEnabledExtensionNames = extensions_to_enable.data(); + + Device device; + + VkResult res = detail::vulkan_functions().fp_vkCreateDevice( + physical_device.physical_device, &device_create_info, info.allocation_callbacks, &device.device); + if (res != VK_SUCCESS) + { + return { DeviceError::failed_create_device, res }; + } + + device.physical_device = physical_device; + device.surface = physical_device.surface; + device.queue_families = physical_device.queue_families; + device.allocation_callbacks = info.allocation_callbacks; + device.fp_vkGetDeviceProcAddr = detail::vulkan_functions().fp_vkGetDeviceProcAddr; + detail::vulkan_functions().get_device_proc_addr(device.device, device.internal_table.fp_vkGetDeviceQueue, "vkGetDeviceQueue"); + detail::vulkan_functions().get_device_proc_addr(device.device, device.internal_table.fp_vkDestroyDevice, "vkDestroyDevice"); + device.instance_version = physical_device.instance_version; + return device; + } + DeviceBuilder& DeviceBuilder::custom_queue_setup(std::vector queue_descriptions) + { + info.queue_descriptions = std::move(queue_descriptions); + return *this; + } + DeviceBuilder& DeviceBuilder::set_allocation_callbacks(VkAllocationCallbacks* callbacks) + { + info.allocation_callbacks = callbacks; + return *this; + } + + // ---- Swapchain ---- // + + namespace detail { + struct SurfaceSupportDetails { + VkSurfaceCapabilitiesKHR capabilities; + std::vector formats; + std::vector present_modes; + }; + + enum class SurfaceSupportError { + surface_handle_null, + failed_get_surface_capabilities, + failed_enumerate_surface_formats, + failed_enumerate_present_modes, + no_suitable_desired_format + }; + + struct SurfaceSupportErrorCategory : std::error_category { + const char* name() const noexcept override { return "vbk_surface_support"; } + std::string message(int err) const override + { + switch (static_cast(err)) + { + CASE_TO_STRING(SurfaceSupportError, surface_handle_null) + CASE_TO_STRING(SurfaceSupportError, failed_get_surface_capabilities) + CASE_TO_STRING(SurfaceSupportError, failed_enumerate_surface_formats) + CASE_TO_STRING(SurfaceSupportError, failed_enumerate_present_modes) + CASE_TO_STRING(SurfaceSupportError, no_suitable_desired_format) + default: + return ""; + } + } + }; + const SurfaceSupportErrorCategory surface_support_error_category; + + std::error_code make_error_code(SurfaceSupportError surface_support_error) + { + return { static_cast(surface_support_error), detail::surface_support_error_category }; + } + + Result query_surface_support_details(VkPhysicalDevice phys_device, VkSurfaceKHR surface) + { + if (surface == VK_NULL_HANDLE) return make_error_code(SurfaceSupportError::surface_handle_null); + + VkSurfaceCapabilitiesKHR capabilities; + VkResult res = detail::vulkan_functions().fp_vkGetPhysicalDeviceSurfaceCapabilitiesKHR(phys_device, surface, &capabilities); + if (res != VK_SUCCESS) + { + return { make_error_code(SurfaceSupportError::failed_get_surface_capabilities), res }; + } + + std::vector formats; + std::vector present_modes; + + auto formats_ret = detail::get_vector( + formats, detail::vulkan_functions().fp_vkGetPhysicalDeviceSurfaceFormatsKHR, phys_device, surface); + if (formats_ret != VK_SUCCESS) + return { make_error_code(SurfaceSupportError::failed_enumerate_surface_formats), formats_ret }; + auto present_modes_ret = detail::get_vector( + present_modes, detail::vulkan_functions().fp_vkGetPhysicalDeviceSurfacePresentModesKHR, phys_device, surface); + if (present_modes_ret != VK_SUCCESS) + return { make_error_code(SurfaceSupportError::failed_enumerate_present_modes), present_modes_ret }; + + return SurfaceSupportDetails{ capabilities, formats, present_modes }; + } + + Result find_desired_surface_format( + std::vector const& available_formats, std::vector const& desired_formats) + { + for (auto const& desired_format : desired_formats) + { + for (auto const& available_format : available_formats) + { + // finds the first format that is desired and available + if (desired_format.format == available_format.format && desired_format.colorSpace == available_format.colorSpace) + { + return desired_format; + } + } + } + + // if no desired format is available, we report that no format is suitable to the user request + return { make_error_code(SurfaceSupportError::no_suitable_desired_format) }; + } + + VkSurfaceFormatKHR find_best_surface_format( + std::vector const& available_formats, std::vector const& desired_formats) + { + auto surface_format_ret = detail::find_desired_surface_format(available_formats, desired_formats); + if (surface_format_ret.has_value()) return surface_format_ret.value(); + + // use the first available format as a fallback if any desired formats aren't found + return available_formats[0]; + } + + VkPresentModeKHR find_present_mode(std::vector const& available_resent_modes, + std::vector const& desired_present_modes) + { + for (auto const& desired_pm : desired_present_modes) + { + for (auto const& available_pm : available_resent_modes) + { + // finds the first present mode that is desired and available + if (desired_pm == available_pm) return desired_pm; + } + } + // only present mode required, use as a fallback + return VK_PRESENT_MODE_FIFO_KHR; + } + + template T minimum(T a, T b) { return a < b ? a : b; } + template T maximum(T a, T b) { return a > b ? a : b; } + + VkExtent2D find_extent(VkSurfaceCapabilitiesKHR const& capabilities, uint32_t desired_width, uint32_t desired_height) + { + if (capabilities.currentExtent.width != UINT32_MAX) + { + return capabilities.currentExtent; + } + else + { + VkExtent2D actualExtent = { desired_width, desired_height }; + + actualExtent.width = + maximum(capabilities.minImageExtent.width, minimum(capabilities.maxImageExtent.width, actualExtent.width)); + actualExtent.height = + maximum(capabilities.minImageExtent.height, minimum(capabilities.maxImageExtent.height, actualExtent.height)); + + return actualExtent; + } + } + } // namespace detail + + void destroy_swapchain(Swapchain const& swapchain) + { + if (swapchain.device != VK_NULL_HANDLE && swapchain.swapchain != VK_NULL_HANDLE) + { + swapchain.internal_table.fp_vkDestroySwapchainKHR(swapchain.device, swapchain.swapchain, swapchain.allocation_callbacks); + } + } + + SwapchainBuilder::SwapchainBuilder(Device const& device) + { + info.physical_device = device.physical_device.physical_device; + info.device = device.device; + info.surface = device.surface; + info.instance_version = device.instance_version; + auto present = device.get_queue_index(QueueType::present); + auto graphics = device.get_queue_index(QueueType::graphics); + assert(graphics.has_value() && present.has_value() && "Graphics and Present queue indexes must be valid"); + info.graphics_queue_index = present.value(); + info.present_queue_index = graphics.value(); + info.allocation_callbacks = device.allocation_callbacks; + } + SwapchainBuilder::SwapchainBuilder(Device const& device, VkSurfaceKHR const surface) + { + info.physical_device = device.physical_device.physical_device; + info.device = device.device; + info.surface = surface; + info.instance_version = device.instance_version; + Device temp_device = device; + temp_device.surface = surface; + auto present = temp_device.get_queue_index(QueueType::present); + auto graphics = temp_device.get_queue_index(QueueType::graphics); + assert(graphics.has_value() && present.has_value() && "Graphics and Present queue indexes must be valid"); + info.graphics_queue_index = graphics.value(); + info.present_queue_index = present.value(); + info.allocation_callbacks = device.allocation_callbacks; + } + SwapchainBuilder::SwapchainBuilder(VkPhysicalDevice const physical_device, + VkDevice const device, + VkSurfaceKHR const surface, + uint32_t graphics_queue_index, + uint32_t present_queue_index) + { + info.physical_device = physical_device; + info.device = device; + info.surface = surface; + info.graphics_queue_index = graphics_queue_index; + info.present_queue_index = present_queue_index; + if (graphics_queue_index == detail::QUEUE_INDEX_MAX_VALUE || present_queue_index == detail::QUEUE_INDEX_MAX_VALUE) + { + auto queue_families = detail::get_vector_noerror( + detail::vulkan_functions().fp_vkGetPhysicalDeviceQueueFamilyProperties, physical_device); + if (graphics_queue_index == detail::QUEUE_INDEX_MAX_VALUE) + info.graphics_queue_index = detail::get_first_queue_index(queue_families, VK_QUEUE_GRAPHICS_BIT); + if (present_queue_index == detail::QUEUE_INDEX_MAX_VALUE) + info.present_queue_index = detail::get_present_queue_index(physical_device, surface, queue_families); + } + } + Result SwapchainBuilder::build() const + { + if (info.surface == VK_NULL_HANDLE) + { + return Error{ SwapchainError::surface_handle_not_provided }; + } + + auto desired_formats = info.desired_formats; + if (desired_formats.size() == 0) add_desired_formats(desired_formats); + auto desired_present_modes = info.desired_present_modes; + if (desired_present_modes.size() == 0) add_desired_present_modes(desired_present_modes); + + auto surface_support_ret = detail::query_surface_support_details(info.physical_device, info.surface); + if (!surface_support_ret.has_value()) + return Error{ SwapchainError::failed_query_surface_support_details, surface_support_ret.vk_result() }; + auto surface_support = surface_support_ret.value(); + + uint32_t image_count = info.min_image_count; + if (info.required_min_image_count >= 1) + { + if (info.required_min_image_count < surface_support.capabilities.minImageCount) + return make_error_code(SwapchainError::required_min_image_count_too_low); + + image_count = info.required_min_image_count; + } + else if (info.min_image_count == 0) + { + // We intentionally use minImageCount + 1 to maintain existing behavior, even if it typically results in triple buffering on most systems. + image_count = surface_support.capabilities.minImageCount + 1; + } + else + { + image_count = info.min_image_count; + if (image_count < surface_support.capabilities.minImageCount) + image_count = surface_support.capabilities.minImageCount; + } + if (surface_support.capabilities.maxImageCount > 0 && image_count > surface_support.capabilities.maxImageCount) + { + image_count = surface_support.capabilities.maxImageCount; + } + + VkSurfaceFormatKHR surface_format = detail::find_best_surface_format(surface_support.formats, desired_formats); + + VkExtent2D extent = detail::find_extent(surface_support.capabilities, info.desired_width, info.desired_height); + + uint32_t image_array_layers = info.array_layer_count; + if (surface_support.capabilities.maxImageArrayLayers < info.array_layer_count) + image_array_layers = surface_support.capabilities.maxImageArrayLayers; + if (info.array_layer_count == 0) image_array_layers = 1; + + uint32_t queue_family_indices[] = { info.graphics_queue_index, info.present_queue_index }; + + + VkPresentModeKHR present_mode = detail::find_present_mode(surface_support.present_modes, desired_present_modes); + + // VkSurfaceCapabilitiesKHR::supportedUsageFlags is only only valid for some present modes. For shared present modes, we should also check VkSharedPresentSurfaceCapabilitiesKHR::sharedPresentSupportedUsageFlags. + auto is_unextended_present_mode = [](VkPresentModeKHR present_mode) + { + return (present_mode == VK_PRESENT_MODE_IMMEDIATE_KHR) || (present_mode == VK_PRESENT_MODE_MAILBOX_KHR) || + (present_mode == VK_PRESENT_MODE_FIFO_KHR) || (present_mode == VK_PRESENT_MODE_FIFO_RELAXED_KHR); + }; + + if (is_unextended_present_mode(present_mode) && + (info.image_usage_flags & surface_support.capabilities.supportedUsageFlags) != info.image_usage_flags) + { + return Error{ SwapchainError::required_usage_not_supported }; + } + + VkSurfaceTransformFlagBitsKHR pre_transform = info.pre_transform; + if (info.pre_transform == static_cast(0)) + pre_transform = surface_support.capabilities.currentTransform; + + VkSwapchainCreateInfoKHR swapchain_create_info = {}; + swapchain_create_info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; + detail::setup_pNext_chain(swapchain_create_info, info.pNext_chain); +#if !defined(NDEBUG) + for (auto& node : info.pNext_chain) + { + assert(node->sType != VK_STRUCTURE_TYPE_APPLICATION_INFO); + } +#endif + swapchain_create_info.flags = info.create_flags; + swapchain_create_info.surface = info.surface; + swapchain_create_info.minImageCount = image_count; + swapchain_create_info.imageFormat = surface_format.format; + swapchain_create_info.imageColorSpace = surface_format.colorSpace; + swapchain_create_info.imageExtent = extent; + swapchain_create_info.imageArrayLayers = image_array_layers; + swapchain_create_info.imageUsage = info.image_usage_flags; + + if (info.graphics_queue_index != info.present_queue_index) + { + swapchain_create_info.imageSharingMode = VK_SHARING_MODE_CONCURRENT; + swapchain_create_info.queueFamilyIndexCount = 2; + swapchain_create_info.pQueueFamilyIndices = queue_family_indices; + } + else + { + swapchain_create_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; + } + + swapchain_create_info.preTransform = pre_transform; + swapchain_create_info.compositeAlpha = info.composite_alpha; + swapchain_create_info.presentMode = present_mode; + swapchain_create_info.clipped = info.clipped; + swapchain_create_info.oldSwapchain = info.old_swapchain; + Swapchain swapchain{}; + PFN_vkCreateSwapchainKHR swapchain_create_proc; + detail::vulkan_functions().get_device_proc_addr(info.device, swapchain_create_proc, "vkCreateSwapchainKHR"); + auto res = swapchain_create_proc(info.device, &swapchain_create_info, info.allocation_callbacks, &swapchain.swapchain); + + if (res != VK_SUCCESS) + { + return Error{ SwapchainError::failed_create_swapchain, res }; + } + swapchain.device = info.device; + swapchain.image_format = surface_format.format; + swapchain.color_space = surface_format.colorSpace; + swapchain.image_usage_flags = info.image_usage_flags; + swapchain.extent = extent; + detail::vulkan_functions().get_device_proc_addr( + info.device, swapchain.internal_table.fp_vkGetSwapchainImagesKHR, "vkGetSwapchainImagesKHR"); + detail::vulkan_functions().get_device_proc_addr(info.device, swapchain.internal_table.fp_vkCreateImageView, "vkCreateImageView"); + detail::vulkan_functions().get_device_proc_addr(info.device, swapchain.internal_table.fp_vkDestroyImageView, "vkDestroyImageView"); + detail::vulkan_functions().get_device_proc_addr( + info.device, swapchain.internal_table.fp_vkDestroySwapchainKHR, "vkDestroySwapchainKHR"); + auto images = swapchain.get_images(); + if (!images) + { + return Error{ SwapchainError::failed_get_swapchain_images }; + } + swapchain.requested_min_image_count = image_count; + swapchain.present_mode = present_mode; + swapchain.image_count = static_cast(images.value().size()); + swapchain.instance_version = info.instance_version; + swapchain.allocation_callbacks = info.allocation_callbacks; + return swapchain; + } + Result> Swapchain::get_images() + { + std::vector swapchain_images; + + auto swapchain_images_ret = + detail::get_vector(swapchain_images, internal_table.fp_vkGetSwapchainImagesKHR, device, swapchain); + if (swapchain_images_ret != VK_SUCCESS) + { + return Error{ SwapchainError::failed_get_swapchain_images, swapchain_images_ret }; + } + return swapchain_images; + } + Result> Swapchain::get_image_views() { return get_image_views(nullptr); } + Result> Swapchain::get_image_views(const void* pNext) + { + const auto swapchain_images_ret = get_images(); + if (!swapchain_images_ret) return swapchain_images_ret.error(); + const auto& swapchain_images = swapchain_images_ret.value(); + + bool already_contains_image_view_usage = false; + while (pNext) + { + if (reinterpret_cast(pNext)->sType == VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO) + { + already_contains_image_view_usage = true; + break; + } + pNext = reinterpret_cast(pNext)->pNext; + } + VkImageViewUsageCreateInfo desired_flags{}; + desired_flags.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO; + desired_flags.pNext = pNext; + desired_flags.usage = image_usage_flags; + + std::vector views(swapchain_images.size()); + for (size_t i = 0; i < swapchain_images.size(); i++) + { + VkImageViewCreateInfo createInfo = {}; + createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + if (instance_version >= VKB_VK_API_VERSION_1_1 && !already_contains_image_view_usage) + { + createInfo.pNext = &desired_flags; + } + else + { + createInfo.pNext = pNext; + } + + createInfo.image = swapchain_images[i]; + createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; + createInfo.format = image_format; + createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; + createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; + createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; + createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; + createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + createInfo.subresourceRange.baseMipLevel = 0; + createInfo.subresourceRange.levelCount = 1; + createInfo.subresourceRange.baseArrayLayer = 0; + createInfo.subresourceRange.layerCount = 1; + VkResult res = internal_table.fp_vkCreateImageView(device, &createInfo, allocation_callbacks, &views[i]); + if (res != VK_SUCCESS) return Error{ SwapchainError::failed_create_swapchain_image_views, res }; + } + return views; + } + void Swapchain::destroy_image_views(std::vector const& image_views) + { + for (auto& image_view : image_views) + { + internal_table.fp_vkDestroyImageView(device, image_view, allocation_callbacks); + } + } + Swapchain::operator VkSwapchainKHR() const { return this->swapchain; } + SwapchainBuilder& SwapchainBuilder::set_old_swapchain(VkSwapchainKHR old_swapchain) + { + info.old_swapchain = old_swapchain; + return *this; + } + SwapchainBuilder& SwapchainBuilder::set_old_swapchain(Swapchain const& swapchain) + { + info.old_swapchain = swapchain.swapchain; + return *this; + } + SwapchainBuilder& SwapchainBuilder::set_desired_extent(uint32_t width, uint32_t height) + { + info.desired_width = width; + info.desired_height = height; + return *this; + } + SwapchainBuilder& SwapchainBuilder::set_desired_format(VkSurfaceFormatKHR format) + { + info.desired_formats.insert(info.desired_formats.begin(), format); + return *this; + } + SwapchainBuilder& SwapchainBuilder::add_fallback_format(VkSurfaceFormatKHR format) + { + info.desired_formats.push_back(format); + return *this; + } + SwapchainBuilder& SwapchainBuilder::use_default_format_selection() + { + info.desired_formats.clear(); + add_desired_formats(info.desired_formats); + return *this; + } + + SwapchainBuilder& SwapchainBuilder::set_desired_present_mode(VkPresentModeKHR present_mode) + { + info.desired_present_modes.insert(info.desired_present_modes.begin(), present_mode); + return *this; + } + SwapchainBuilder& SwapchainBuilder::add_fallback_present_mode(VkPresentModeKHR present_mode) + { + info.desired_present_modes.push_back(present_mode); + return *this; + } + SwapchainBuilder& SwapchainBuilder::use_default_present_mode_selection() + { + info.desired_present_modes.clear(); + add_desired_present_modes(info.desired_present_modes); + return *this; + } + SwapchainBuilder& SwapchainBuilder::set_allocation_callbacks(VkAllocationCallbacks* callbacks) + { + info.allocation_callbacks = callbacks; + return *this; + } + SwapchainBuilder& SwapchainBuilder::set_image_usage_flags(VkImageUsageFlags usage_flags) + { + info.image_usage_flags = usage_flags; + return *this; + } + SwapchainBuilder& SwapchainBuilder::add_image_usage_flags(VkImageUsageFlags usage_flags) + { + info.image_usage_flags = info.image_usage_flags | usage_flags; + return *this; + } + SwapchainBuilder& SwapchainBuilder::use_default_image_usage_flags() + { + info.image_usage_flags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + return *this; + } + SwapchainBuilder& SwapchainBuilder::set_image_array_layer_count(uint32_t array_layer_count) + { + info.array_layer_count = array_layer_count; + return *this; + } + SwapchainBuilder& SwapchainBuilder::set_desired_min_image_count(uint32_t min_image_count) + { + info.min_image_count = min_image_count; + return *this; + } + SwapchainBuilder& SwapchainBuilder::set_required_min_image_count(uint32_t required_min_image_count) + { + info.required_min_image_count = required_min_image_count; + return *this; + } + SwapchainBuilder& SwapchainBuilder::set_clipped(bool clipped) + { + info.clipped = clipped; + return *this; + } + SwapchainBuilder& SwapchainBuilder::set_create_flags(VkSwapchainCreateFlagBitsKHR create_flags) + { + info.create_flags = create_flags; + return *this; + } + SwapchainBuilder& SwapchainBuilder::set_pre_transform_flags(VkSurfaceTransformFlagBitsKHR pre_transform_flags) + { + info.pre_transform = pre_transform_flags; + return *this; + } + SwapchainBuilder& SwapchainBuilder::set_composite_alpha_flags(VkCompositeAlphaFlagBitsKHR composite_alpha_flags) + { + info.composite_alpha = composite_alpha_flags; + return *this; + } + + void SwapchainBuilder::add_desired_formats(std::vector& formats) const + { + formats.push_back({ VK_FORMAT_B8G8R8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR }); + formats.push_back({ VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR }); + } + void SwapchainBuilder::add_desired_present_modes(std::vector& modes) const + { + modes.push_back(VK_PRESENT_MODE_MAILBOX_KHR); + modes.push_back(VK_PRESENT_MODE_FIFO_KHR); + } +} // namespace vkb diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/src/VkBootstrap.h b/Ifnity/Ifnity/vendor/vk-bootstrap/src/VkBootstrap.h new file mode 100644 index 0000000..ca51b82 --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/src/VkBootstrap.h @@ -0,0 +1,1008 @@ +/* + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the “Software”), to deal in the Software without restriction, including without + * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + * of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT + * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * Copyright © 2020 Charles Giessen (charles@lunarg.com) + */ + +#pragma once + +#include +#include +#include + +#include +#include +#include + +#include + +#include "VkBootstrapDispatch.h" + +#ifdef VK_MAKE_API_VERSION +#define VKB_MAKE_VK_VERSION(variant, major, minor, patch) VK_MAKE_API_VERSION(variant, major, minor, patch) +#elif defined(VK_MAKE_VERSION) +#define VKB_MAKE_VK_VERSION(variant, major, minor, patch) VK_MAKE_VERSION(major, minor, patch) +#endif + +#if defined(VK_API_VERSION_1_3) || defined(VK_VERSION_1_3) +#define VKB_VK_API_VERSION_1_3 VKB_MAKE_VK_VERSION(0, 1, 3, 0) +#endif + +#if defined(VK_API_VERSION_1_2) || defined(VK_VERSION_1_2) +#define VKB_VK_API_VERSION_1_2 VKB_MAKE_VK_VERSION(0, 1, 2, 0) +#endif + +#if defined(VK_API_VERSION_1_1) || defined(VK_VERSION_1_1) +#define VKB_VK_API_VERSION_1_1 VKB_MAKE_VK_VERSION(0, 1, 1, 0) +#endif + +#if defined(VK_API_VERSION_1_0) || defined(VK_VERSION_1_0) +#define VKB_VK_API_VERSION_1_0 VKB_MAKE_VK_VERSION(0, 1, 0, 0) +#endif + +namespace vkb { + +struct Error { + std::error_code type; + VkResult vk_result = VK_SUCCESS; // optional error value if a vulkan call failed +}; + +template class Result { + public: + Result(const T& value) noexcept : m_value{ value }, m_init{ true } {} + Result(T&& value) noexcept : m_value{ std::move(value) }, m_init{ true } {} + + Result(Error error) noexcept : m_error{ error }, m_init{ false } {} + + Result(std::error_code error_code, VkResult result = VK_SUCCESS) noexcept + : m_error{ error_code, result }, m_init{ false } {} + + ~Result() noexcept { destroy(); } + Result(Result const& expected) noexcept : m_init(expected.m_init) { + if (m_init) + new (&m_value) T{ expected.m_value }; + else + m_error = expected.m_error; + } + Result& operator=(Result const& result) noexcept { + m_init = result.m_init; + if (m_init) + new (&m_value) T{ result.m_value }; + else + m_error = result.m_error; + return *this; + } + Result(Result&& expected) noexcept : m_init(expected.m_init) { + if (m_init) + new (&m_value) T{ std::move(expected.m_value) }; + else + m_error = std::move(expected.m_error); + expected.destroy(); + } + Result& operator=(Result&& result) noexcept { + m_init = result.m_init; + if (m_init) + new (&m_value) T{ std::move(result.m_value) }; + else + m_error = std::move(result.m_error); + return *this; + } + Result& operator=(const T& expect) noexcept { + destroy(); + m_init = true; + new (&m_value) T{ expect }; + return *this; + } + Result& operator=(T&& expect) noexcept { + destroy(); + m_init = true; + new (&m_value) T{ std::move(expect) }; + return *this; + } + Result& operator=(const Error& error) noexcept { + destroy(); + m_init = false; + m_error = error; + return *this; + } + Result& operator=(Error&& error) noexcept { + destroy(); + m_init = false; + m_error = error; + return *this; + } + // clang-format off + const T* operator-> () const noexcept { assert (m_init); return &m_value; } + T* operator-> () noexcept { assert (m_init); return &m_value; } + const T& operator* () const& noexcept { assert (m_init); return m_value; } + T& operator* () & noexcept { assert (m_init); return m_value; } + T operator* () && noexcept { assert (m_init); return std::move (m_value); } + const T& value () const& noexcept { assert (m_init); return m_value; } + T& value () & noexcept { assert (m_init); return m_value; } + T value () && noexcept { assert (m_init); return std::move (m_value); } + + // std::error_code associated with the error + std::error_code error() const { assert (!m_init); return m_error.type; } + // optional VkResult that could of been produced due to the error + VkResult vk_result() const { assert (!m_init); return m_error.vk_result; } + // Returns the struct that holds the std::error_code and VkResult + Error full_error() const { assert (!m_init); return m_error; } + // clang-format on + + // check if the result has an error that matches a specific error case + template bool matches_error(E error_enum_value) const { + return !m_init && static_cast(m_error.type.value()) == error_enum_value; + } + + bool has_value() const { return m_init; } + explicit operator bool() const { return m_init; } + + private: + void destroy() { + if (m_init) m_value.~T(); + } + union { + T m_value; + Error m_error; + }; + bool m_init; +}; + +namespace detail { +struct GenericFeaturesPNextNode { + + static const uint32_t field_capacity = 256; + + GenericFeaturesPNextNode(); + + template GenericFeaturesPNextNode(T const& features) noexcept { + memset(fields, UINT8_MAX, sizeof(VkBool32) * field_capacity); + memcpy(this, &features, sizeof(T)); + } + + static bool match(GenericFeaturesPNextNode const& requested, GenericFeaturesPNextNode const& supported) noexcept; + + void combine(GenericFeaturesPNextNode const& right) noexcept; + + VkStructureType sType = static_cast(0); + void* pNext = nullptr; + VkBool32 fields[field_capacity]; +}; + +struct GenericFeatureChain { + std::vector nodes; + + template void add(T const& features) noexcept { + // If this struct is already in the list, combine it + for (auto& node : nodes) { + if (static_cast(features.sType) == node.sType) { + node.combine(features); + return; + } + } + // Otherwise append to the end + nodes.push_back(features); + } + + bool match_all(GenericFeatureChain const& extension_requested) const noexcept; + bool find_and_match(GenericFeatureChain const& extension_requested) const noexcept; + + void chain_up(VkPhysicalDeviceFeatures2& feats2) noexcept; + + void combine(GenericFeatureChain const& right) noexcept; +}; + +} // namespace detail + +enum class InstanceError { + vulkan_unavailable, + vulkan_version_unavailable, + vulkan_version_1_1_unavailable, + vulkan_version_1_2_unavailable, + failed_create_instance, + failed_create_debug_messenger, + requested_layers_not_present, + requested_extensions_not_present, + windowing_extensions_not_present, +}; +enum class PhysicalDeviceError { + no_surface_provided, + failed_enumerate_physical_devices, + no_physical_devices_found, + no_suitable_device, +}; +enum class QueueError { + present_unavailable, + graphics_unavailable, + compute_unavailable, + transfer_unavailable, + queue_index_out_of_range, + invalid_queue_family_index +}; +enum class DeviceError { + failed_create_device, + VkPhysicalDeviceFeatures2_in_pNext_chain_while_using_add_required_extension_features, +}; +enum class SwapchainError { + surface_handle_not_provided, + failed_query_surface_support_details, + failed_create_swapchain, + failed_get_swapchain_images, + failed_create_swapchain_image_views, + required_min_image_count_too_low, + required_usage_not_supported +}; + +std::error_code make_error_code(InstanceError instance_error); +std::error_code make_error_code(PhysicalDeviceError physical_device_error); +std::error_code make_error_code(QueueError queue_error); +std::error_code make_error_code(DeviceError device_error); +std::error_code make_error_code(SwapchainError swapchain_error); + +const char* to_string_message_severity(VkDebugUtilsMessageSeverityFlagBitsEXT s); +const char* to_string_message_type(VkDebugUtilsMessageTypeFlagsEXT s); + +const char* to_string(InstanceError err); +const char* to_string(PhysicalDeviceError err); +const char* to_string(QueueError err); +const char* to_string(DeviceError err); +const char* to_string(SwapchainError err); + +// Gathers useful information about the available vulkan capabilities, like layers and instance +// extensions. Use this for enabling features conditionally, ie if you would like an extension but +// can use a fallback if it isn't supported but need to know if support is available first. +struct SystemInfo { + private: + SystemInfo(); + + public: + // Use get_system_info to create a SystemInfo struct. This is because loading vulkan could fail. + static Result get_system_info(); + static Result get_system_info(PFN_vkGetInstanceProcAddr fp_vkGetInstanceProcAddr); + + // Returns true if a layer is available + bool is_layer_available(const char* layer_name) const; + // Returns true if an extension is available + bool is_extension_available(const char* extension_name) const; + + std::vector available_layers; + std::vector available_extensions; + bool validation_layers_available = false; + bool debug_utils_available = false; +}; + +// Forward declared - check VkBoostrap.cpp for implementations +const char* to_string_message_severity(VkDebugUtilsMessageSeverityFlagBitsEXT s); +const char* to_string_message_type(VkDebugUtilsMessageTypeFlagsEXT s); + +// Default debug messenger +// Feel free to copy-paste it into your own code, change it as needed, then call `set_debug_callback()` to use that instead +inline VKAPI_ATTR VkBool32 VKAPI_CALL default_debug_callback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, + VkDebugUtilsMessageTypeFlagsEXT messageType, + const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, + void*) { + auto ms = to_string_message_severity(messageSeverity); + auto mt = to_string_message_type(messageType); + printf("[%s: %s]\n%s\n", ms, mt, pCallbackData->pMessage); + + return VK_FALSE; // Applications must return false here +} + +class InstanceBuilder; +class PhysicalDeviceSelector; + +struct Instance { + VkInstance instance = VK_NULL_HANDLE; + VkDebugUtilsMessengerEXT debug_messenger = VK_NULL_HANDLE; + VkAllocationCallbacks* allocation_callbacks = VK_NULL_HANDLE; + PFN_vkGetInstanceProcAddr fp_vkGetInstanceProcAddr = nullptr; + PFN_vkGetDeviceProcAddr fp_vkGetDeviceProcAddr = nullptr; + + // A conversion function which allows this Instance to be used + // in places where VkInstance would have been used. + operator VkInstance() const; + + // Return a loaded instance dispatch table + InstanceDispatchTable make_table() const; + + private: + bool headless = false; + bool properties2_ext_enabled = false; + uint32_t instance_version = VKB_VK_API_VERSION_1_0; + uint32_t api_version = VKB_VK_API_VERSION_1_0; + + friend class InstanceBuilder; + friend class PhysicalDeviceSelector; +}; + +void destroy_surface(Instance const& instance, VkSurfaceKHR surface); // release surface handle +void destroy_surface(VkInstance instance, VkSurfaceKHR surface, VkAllocationCallbacks* callbacks = nullptr); // release surface handle +void destroy_instance(Instance const& instance); // release instance resources + +/* If headless mode is false, by default vk-bootstrap use the following logic to enable the windowing extensions + +#if defined(_WIN32) + VK_KHR_win32_surface +#elif defined(__linux__) + VK_KHR_xcb_surface + VK_KHR_xlib_surface + VK_KHR_wayland_surface +#elif defined(__APPLE__) + VK_EXT_metal_surface +#elif defined(__ANDROID__) + VK_KHR_android_surface +#elif defined(_DIRECT2DISPLAY) + VK_KHR_display +#endif + +Use `InstanceBuilder::enable_extension()` to add new extensions without altering the default behavior +Feel free to make a PR or raise an issue to include additional platforms. +*/ + +class InstanceBuilder { + public: + // Default constructor, will load vulkan. + explicit InstanceBuilder(); + // Optional: Can use your own PFN_vkGetInstanceProcAddr + explicit InstanceBuilder(PFN_vkGetInstanceProcAddr fp_vkGetInstanceProcAddr); + + // Create a VkInstance. Return an error if it failed. + Result build() const; + + // Sets the name of the application. Defaults to "" if none is provided. + InstanceBuilder& set_app_name(const char* app_name); + // Sets the name of the engine. Defaults to "" if none is provided. + InstanceBuilder& set_engine_name(const char* engine_name); + + // Sets the version of the application. + // Should be constructed with VK_MAKE_VERSION or VK_MAKE_API_VERSION. + InstanceBuilder& set_app_version(uint32_t app_version); + // Sets the (major, minor, patch) version of the application. + InstanceBuilder& set_app_version(uint32_t major, uint32_t minor, uint32_t patch = 0); + + // Sets the version of the engine. + // Should be constructed with VK_MAKE_VERSION or VK_MAKE_API_VERSION. + InstanceBuilder& set_engine_version(uint32_t engine_version); + // Sets the (major, minor, patch) version of the engine. + InstanceBuilder& set_engine_version(uint32_t major, uint32_t minor, uint32_t patch = 0); + + // Require a vulkan API version. Will fail to create if this version isn't available. + // Should be constructed with VK_MAKE_VERSION or VK_MAKE_API_VERSION. + InstanceBuilder& require_api_version(uint32_t required_api_version); + // Require a vulkan API version. Will fail to create if this version isn't available. + InstanceBuilder& require_api_version(uint32_t major, uint32_t minor, uint32_t patch = 0); + + // Overrides required API version for instance creation. Will fail to create if this version isn't available. + // Should be constructed with VK_MAKE_VERSION or VK_MAKE_API_VERSION. + InstanceBuilder& set_minimum_instance_version(uint32_t minimum_instance_version); + // Overrides required API version for instance creation. Will fail to create if this version isn't available. + InstanceBuilder& set_minimum_instance_version(uint32_t major, uint32_t minor, uint32_t patch = 0); + + // Prefer a vulkan instance API version. If the desired version isn't available, it will use the + // highest version available. Should be constructed with VK_MAKE_VERSION or VK_MAKE_API_VERSION. + [[deprecated("Use require_api_version + set_minimum_instance_version instead.")]] InstanceBuilder& + desire_api_version(uint32_t preferred_vulkan_version); + + // Prefer a vulkan instance API version. If the desired version isn't available, it will use the highest version available. + [[deprecated("Use require_api_version + set_minimum_instance_version instead.")]] InstanceBuilder& + desire_api_version(uint32_t major, uint32_t minor, uint32_t patch = 0); + + // Adds a layer to be enabled. Will fail to create an instance if the layer isn't available. + InstanceBuilder& enable_layer(const char* layer_name); + // Adds an extension to be enabled. Will fail to create an instance if the extension isn't available. + InstanceBuilder& enable_extension(const char* extension_name); + InstanceBuilder& enable_extensions(std::vector const& extensions); + InstanceBuilder& enable_extensions(size_t count, const char* const* extensions); + + // Headless Mode does not load the required extensions for presentation. Defaults to true. + InstanceBuilder& set_headless(bool headless = true); + + // Enables the validation layers. Will fail to create an instance if the validation layers aren't available. + InstanceBuilder& enable_validation_layers(bool require_validation = true); + // Checks if the validation layers are available and loads them if they are. + InstanceBuilder& request_validation_layers(bool enable_validation = true); + + // Use a default debug callback that prints to standard out. + InstanceBuilder& use_default_debug_messenger(); + // Provide a user defined debug callback. + InstanceBuilder& set_debug_callback(PFN_vkDebugUtilsMessengerCallbackEXT callback); + // Sets the void* to use in the debug messenger - only useful with a custom callback + InstanceBuilder& set_debug_callback_user_data_pointer(void* user_data_pointer); + // Set what message severity is needed to trigger the callback. + InstanceBuilder& set_debug_messenger_severity(VkDebugUtilsMessageSeverityFlagsEXT severity); + // Add a message severity to the list that triggers the callback. + InstanceBuilder& add_debug_messenger_severity(VkDebugUtilsMessageSeverityFlagsEXT severity); + // Set what message type triggers the callback. + InstanceBuilder& set_debug_messenger_type(VkDebugUtilsMessageTypeFlagsEXT type); + // Add a message type to the list of that triggers the callback. + InstanceBuilder& add_debug_messenger_type(VkDebugUtilsMessageTypeFlagsEXT type); + + // Disable some validation checks. + // Checks: All, and Shaders + InstanceBuilder& add_validation_disable(VkValidationCheckEXT check); + + // Enables optional parts of the validation layers. + // Parts: best practices, gpu assisted, and gpu assisted reserve binding slot. + InstanceBuilder& add_validation_feature_enable(VkValidationFeatureEnableEXT enable); + + // Disables sections of the validation layers. + // Options: All, shaders, thread safety, api parameters, object lifetimes, core checks, and unique handles. + InstanceBuilder& add_validation_feature_disable(VkValidationFeatureDisableEXT disable); + + // Provide custom allocation callbacks. + InstanceBuilder& set_allocation_callbacks(VkAllocationCallbacks* callbacks); + + private: + struct InstanceInfo { + // VkApplicationInfo + const char* app_name = nullptr; + const char* engine_name = nullptr; + uint32_t application_version = 0; + uint32_t engine_version = 0; + uint32_t minimum_instance_version = 0; + uint32_t required_api_version = VKB_VK_API_VERSION_1_0; + uint32_t desired_api_version = VKB_VK_API_VERSION_1_0; + + // VkInstanceCreateInfo + std::vector layers; + std::vector extensions; + VkInstanceCreateFlags flags = static_cast(0); + std::vector pNext_elements; + + // debug callback - use the default so it is not nullptr + PFN_vkDebugUtilsMessengerCallbackEXT debug_callback = default_debug_callback; + VkDebugUtilsMessageSeverityFlagsEXT debug_message_severity = + VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; + VkDebugUtilsMessageTypeFlagsEXT debug_message_type = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | + VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | + VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; + void* debug_user_data_pointer = nullptr; + + // validation features + std::vector disabled_validation_checks; + std::vector enabled_validation_features; + std::vector disabled_validation_features; + + // Custom allocator + VkAllocationCallbacks* allocation_callbacks = VK_NULL_HANDLE; + + bool request_validation_layers = false; + bool enable_validation_layers = false; + bool use_debug_messenger = false; + bool headless_context = false; + + PFN_vkGetInstanceProcAddr fp_vkGetInstanceProcAddr = nullptr; + } info; +}; + +VKAPI_ATTR VkBool32 VKAPI_CALL default_debug_callback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, + VkDebugUtilsMessageTypeFlagsEXT messageType, + const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, + void* pUserData); + +void destroy_debug_utils_messenger( + VkInstance const instance, VkDebugUtilsMessengerEXT const messenger, VkAllocationCallbacks* allocation_callbacks = nullptr); + +// ---- Physical Device ---- // +class PhysicalDeviceSelector; +class DeviceBuilder; + +struct PhysicalDevice { + std::string name; + VkPhysicalDevice physical_device = VK_NULL_HANDLE; + VkSurfaceKHR surface = VK_NULL_HANDLE; + + // Note that this reflects selected features carried over from required features, not all features the physical device supports. + VkPhysicalDeviceFeatures features{}; + VkPhysicalDeviceProperties properties{}; + VkPhysicalDeviceMemoryProperties memory_properties{}; + + // Has a queue family that supports compute operations but not graphics nor transfer. + bool has_dedicated_compute_queue() const; + // Has a queue family that supports transfer operations but not graphics nor compute. + bool has_dedicated_transfer_queue() const; + + // Has a queue family that supports transfer operations but not graphics. + bool has_separate_compute_queue() const; + // Has a queue family that supports transfer operations but not graphics. + bool has_separate_transfer_queue() const; + + // Advanced: Get the VkQueueFamilyProperties of the device if special queue setup is needed + std::vector get_queue_families() const; + + // Query the list of extensions which should be enabled + std::vector get_extensions() const; + + // Query the list of extensions which the physical device supports + std::vector get_available_extensions() const; + + // Returns true if an extension should be enabled on the device + bool is_extension_present(const char* extension) const; + + // Returns true if all the features are present + template bool are_extension_features_present(T const& features) const { + return is_features_node_present(detail::GenericFeaturesPNextNode(features)); + } + + // If the given extension is present, make the extension be enabled on the device. + // Returns true the extension is present. + bool enable_extension_if_present(const char* extension); + + // If all the given extensions are present, make all the extensions be enabled on the device. + // Returns true if all the extensions are present. + bool enable_extensions_if_present(const std::vector& extensions); + + // If the features from VkPhysicalDeviceFeatures are all present, make all of the features be enable on the device. + // Returns true if all the features are present. + bool enable_features_if_present(const VkPhysicalDeviceFeatures& features_to_enable); + + // If the features from the provided features struct are all present, make all of the features be enable on the + // device. Returns true if all of the features are present. + template bool enable_extension_features_if_present(T const& features_check) { + return enable_features_node_if_present(detail::GenericFeaturesPNextNode(features_check)); + } + + // A conversion function which allows this PhysicalDevice to be used + // in places where VkPhysicalDevice would have been used. + operator VkPhysicalDevice() const; + + private: + uint32_t instance_version = VKB_VK_API_VERSION_1_0; + std::vector extensions_to_enable; + std::vector available_extensions; + std::vector queue_families; + detail::GenericFeatureChain extended_features_chain; + + bool defer_surface_initialization = false; + bool properties2_ext_enabled = false; + enum class Suitable { yes, partial, no }; + Suitable suitable = Suitable::yes; + friend class PhysicalDeviceSelector; + friend class DeviceBuilder; + + bool is_features_node_present(detail::GenericFeaturesPNextNode const& node) const; + bool enable_features_node_if_present(detail::GenericFeaturesPNextNode const& node); +}; + +enum class PreferredDeviceType { other = 0, integrated = 1, discrete = 2, virtual_gpu = 3, cpu = 4 }; + +enum class DeviceSelectionMode { + // return all suitable and partially suitable devices + partially_and_fully_suitable, + // return only physical devices which are fully suitable + only_fully_suitable +}; + +// Enumerates the physical devices on the system, and based on the added criteria, returns a physical device or list of physical devies +// A device is considered suitable if it meets all the 'required' and 'desired' criteria. +// A device is considered partially suitable if it meets only the 'required' criteria. +class PhysicalDeviceSelector { + public: + // Requires a vkb::Instance to construct, needed to pass instance creation info. + explicit PhysicalDeviceSelector(Instance const& instance); + // Requires a vkb::Instance to construct, needed to pass instance creation info, optionally specify the surface here + explicit PhysicalDeviceSelector(Instance const& instance, VkSurfaceKHR surface); + + // Return the first device which is suitable + // use the `selection` parameter to configure if partially + Result select(DeviceSelectionMode selection = DeviceSelectionMode::partially_and_fully_suitable) const; + + // Return all devices which are considered suitable - intended for applications which want to let the user pick the physical device + Result> select_devices( + DeviceSelectionMode selection = DeviceSelectionMode::partially_and_fully_suitable) const; + + // Return the names of all devices which are considered suitable - intended for applications which want to let the user pick the physical device + Result> select_device_names( + DeviceSelectionMode selection = DeviceSelectionMode::partially_and_fully_suitable) const; + + // Set the surface in which the physical device should render to. + // Be sure to set it if swapchain functionality is to be used. + PhysicalDeviceSelector& set_surface(VkSurfaceKHR surface); + + // Set the name of the device to select. + PhysicalDeviceSelector& set_name(std::string const& name); + // Set the desired physical device type to select. Defaults to PreferredDeviceType::discrete. + PhysicalDeviceSelector& prefer_gpu_device_type(PreferredDeviceType type = PreferredDeviceType::discrete); + // Allow selection of a gpu device type that isn't the preferred physical device type. Defaults to true. + PhysicalDeviceSelector& allow_any_gpu_device_type(bool allow_any_type = true); + + // Require that a physical device supports presentation. Defaults to true. + PhysicalDeviceSelector& require_present(bool require = true); + + // Require a queue family that supports compute operations but not graphics nor transfer. + PhysicalDeviceSelector& require_dedicated_compute_queue(); + // Require a queue family that supports transfer operations but not graphics nor compute. + PhysicalDeviceSelector& require_dedicated_transfer_queue(); + + // Require a queue family that supports compute operations but not graphics. + PhysicalDeviceSelector& require_separate_compute_queue(); + // Require a queue family that supports transfer operations but not graphics. + PhysicalDeviceSelector& require_separate_transfer_queue(); + + // Require a memory heap from VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT with `size` memory available. + PhysicalDeviceSelector& required_device_memory_size(VkDeviceSize size); + // Prefer a memory heap from VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT with `size` memory available. + [[deprecated]] PhysicalDeviceSelector& desired_device_memory_size(VkDeviceSize size); + + // Require a physical device which supports a specific extension. + PhysicalDeviceSelector& add_required_extension(const char* extension); + // Require a physical device which supports a set of extensions. + PhysicalDeviceSelector& add_required_extensions(std::vector const& extensions); + PhysicalDeviceSelector& add_required_extensions(size_t count, const char* const* extensions); + + // Prefer a physical device which supports a specific extension. + [[deprecated("Use vkb::PhysicalDevice::enable_extension_if_present instead")]] PhysicalDeviceSelector& + add_desired_extension(const char* extension); + // Prefer a physical device which supports a set of extensions. + [[deprecated("Use vkb::PhysicalDevice::enable_extensions_if_present instead")]] PhysicalDeviceSelector& + add_desired_extensions(const std::vector& extensions); + + // Prefer a physical device that supports a (major, minor) version of vulkan. + [[deprecated("Use set_minimum_version + InstanceBuilder::require_api_version.")]] PhysicalDeviceSelector& + set_desired_version(uint32_t major, uint32_t minor); + + // Require a physical device that supports a (major, minor) version of vulkan. + PhysicalDeviceSelector& set_minimum_version(uint32_t major, uint32_t minor); + + // By default PhysicalDeviceSelector enables the portability subset if available + // This function disables that behavior + PhysicalDeviceSelector& disable_portability_subset(); + + // Require a physical device which supports a specific set of general/extension features. + // If this function is used, the user should not put their own VkPhysicalDeviceFeatures2 in + // the pNext chain of VkDeviceCreateInfo. + template PhysicalDeviceSelector& add_required_extension_features(T const& features) { + criteria.extended_features_chain.add(features); + return *this; + } + + // Require a physical device which supports the features in VkPhysicalDeviceFeatures. + PhysicalDeviceSelector& set_required_features(VkPhysicalDeviceFeatures const& features); +#if defined(VKB_VK_API_VERSION_1_2) + // Require a physical device which supports the features in VkPhysicalDeviceVulkan11Features. + // Must have vulkan version 1.2 - This is due to the VkPhysicalDeviceVulkan11Features struct being added in 1.2, not 1.1 + PhysicalDeviceSelector& set_required_features_11(VkPhysicalDeviceVulkan11Features const& features_11); + // Require a physical device which supports the features in VkPhysicalDeviceVulkan12Features. + // Must have vulkan version 1.2 + PhysicalDeviceSelector& set_required_features_12(VkPhysicalDeviceVulkan12Features const& features_12); +#endif +#if defined(VKB_VK_API_VERSION_1_3) + // Require a physical device which supports the features in VkPhysicalDeviceVulkan13Features. + // Must have vulkan version 1.3 + PhysicalDeviceSelector& set_required_features_13(VkPhysicalDeviceVulkan13Features const& features_13); +#endif + + // Used when surface creation happens after physical device selection. + // Warning: This disables checking if the physical device supports a given surface. + PhysicalDeviceSelector& defer_surface_initialization(); + + // Ignore all criteria and choose the first physical device that is available. + // Only use when: The first gpu in the list may be set by global user preferences and an application may wish to respect it. + PhysicalDeviceSelector& select_first_device_unconditionally(bool unconditionally = true); + + private: + struct InstanceInfo { + VkInstance instance = VK_NULL_HANDLE; + VkSurfaceKHR surface = VK_NULL_HANDLE; + uint32_t version = VKB_VK_API_VERSION_1_0; + bool headless = false; + bool properties2_ext_enabled = false; + } instance_info; + + // We copy the extension features stored in the selector criteria under the prose of a + // "template" to ensure that after fetching everything is compared 1:1 during a match. + + struct SelectionCriteria { + std::string name; + PreferredDeviceType preferred_type = PreferredDeviceType::discrete; + bool allow_any_type = true; + bool require_present = true; + bool require_dedicated_transfer_queue = false; + bool require_dedicated_compute_queue = false; + bool require_separate_transfer_queue = false; + bool require_separate_compute_queue = false; + VkDeviceSize required_mem_size = 0; + VkDeviceSize desired_mem_size = 0; + + std::vector required_extensions; + std::vector desired_extensions; + + uint32_t required_version = VKB_VK_API_VERSION_1_0; + uint32_t desired_version = VKB_VK_API_VERSION_1_0; + + VkPhysicalDeviceFeatures required_features{}; + VkPhysicalDeviceFeatures2 required_features2{}; + + detail::GenericFeatureChain extended_features_chain; + bool defer_surface_initialization = false; + bool use_first_gpu_unconditionally = false; + bool enable_portability_subset = true; + } criteria; + + PhysicalDevice populate_device_details( + VkPhysicalDevice phys_device, detail::GenericFeatureChain const& src_extended_features_chain) const; + + PhysicalDevice::Suitable is_device_suitable(PhysicalDevice const& phys_device) const; + + Result> select_impl(DeviceSelectionMode selection) const; +}; + +// ---- Queue ---- // +enum class QueueType { present, graphics, compute, transfer }; + +namespace detail { +// Sentinel value, used in implementation only +inline const uint32_t QUEUE_INDEX_MAX_VALUE = 65536; +} // namespace detail + +// ---- Device ---- // + +struct Device { + VkDevice device = VK_NULL_HANDLE; + PhysicalDevice physical_device; + VkSurfaceKHR surface = VK_NULL_HANDLE; + std::vector queue_families; + VkAllocationCallbacks* allocation_callbacks = VK_NULL_HANDLE; + PFN_vkGetDeviceProcAddr fp_vkGetDeviceProcAddr = nullptr; + uint32_t instance_version = VKB_VK_API_VERSION_1_0; + + Result get_queue_index(QueueType type) const; + // Only a compute or transfer queue type is valid. All other queue types do not support a 'dedicated' queue index + Result get_dedicated_queue_index(QueueType type) const; + + Result get_queue(QueueType type) const; + // Only a compute or transfer queue type is valid. All other queue types do not support a 'dedicated' queue + Result get_dedicated_queue(QueueType type) const; + + // Return a loaded dispatch table + DispatchTable make_table() const; + + // A conversion function which allows this Device to be used + // in places where VkDevice would have been used. + operator VkDevice() const; + + private: + struct { + PFN_vkGetDeviceQueue fp_vkGetDeviceQueue = nullptr; + PFN_vkDestroyDevice fp_vkDestroyDevice = nullptr; + } internal_table; + friend class DeviceBuilder; + friend void destroy_device(Device const& device); +}; + + +// For advanced device queue setup +struct CustomQueueDescription { + explicit CustomQueueDescription(uint32_t index, std::vector priorities); + uint32_t index = 0; + std::vector priorities; +}; + +void destroy_device(Device const& device); + +class DeviceBuilder { + public: + // Any features and extensions that are requested/required in PhysicalDeviceSelector are automatically enabled. + explicit DeviceBuilder(PhysicalDevice physical_device); + + Result build() const; + + // For Advanced Users: specify the exact list of VkDeviceQueueCreateInfo's needed for the application. + // If a custom queue setup is provided, getting the queues and queue indexes is up to the application. + DeviceBuilder& custom_queue_setup(std::vector queue_descriptions); + + // Add a structure to the pNext chain of VkDeviceCreateInfo. + // The structure must be valid when DeviceBuilder::build() is called. + template DeviceBuilder& add_pNext(T* structure) { + info.pNext_chain.push_back(reinterpret_cast(structure)); + return *this; + } + + // Provide custom allocation callbacks. + DeviceBuilder& set_allocation_callbacks(VkAllocationCallbacks* callbacks); + + private: + PhysicalDevice physical_device; + struct DeviceInfo { + VkDeviceCreateFlags flags = static_cast(0); + std::vector pNext_chain; + std::vector queue_descriptions; + VkAllocationCallbacks* allocation_callbacks = VK_NULL_HANDLE; + } info; +}; + +// ---- Swapchain ---- // +struct Swapchain { + VkDevice device = VK_NULL_HANDLE; + VkSwapchainKHR swapchain = VK_NULL_HANDLE; + uint32_t image_count = 0; + VkFormat image_format = VK_FORMAT_UNDEFINED; // The image format actually used when creating the swapchain. + VkColorSpaceKHR color_space = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR; // The color space actually used when creating the swapchain. + VkImageUsageFlags image_usage_flags = 0; + VkExtent2D extent = { 0, 0 }; + // The value of minImageCount actually used when creating the swapchain; note that the presentation engine is always free to create more images than that. + uint32_t requested_min_image_count = 0; + VkPresentModeKHR present_mode = VK_PRESENT_MODE_IMMEDIATE_KHR; // The present mode actually used when creating the swapchain. + uint32_t instance_version = VKB_VK_API_VERSION_1_0; + VkAllocationCallbacks* allocation_callbacks = VK_NULL_HANDLE; + + // Returns a vector of VkImage handles to the swapchain. + Result> get_images(); + + // Returns a vector of VkImageView's to the VkImage's of the swapchain. + // VkImageViews must be destroyed. The pNext chain must be a nullptr or a valid + // structure. + Result> get_image_views(); + Result> get_image_views(const void* pNext); + void destroy_image_views(std::vector const& image_views); + + // A conversion function which allows this Swapchain to be used + // in places where VkSwapchainKHR would have been used. + operator VkSwapchainKHR() const; + + private: + struct { + PFN_vkGetSwapchainImagesKHR fp_vkGetSwapchainImagesKHR = nullptr; + PFN_vkCreateImageView fp_vkCreateImageView = nullptr; + PFN_vkDestroyImageView fp_vkDestroyImageView = nullptr; + PFN_vkDestroySwapchainKHR fp_vkDestroySwapchainKHR = nullptr; + } internal_table; + friend class SwapchainBuilder; + friend void destroy_swapchain(Swapchain const& swapchain); +}; + +void destroy_swapchain(Swapchain const& swapchain); + +class SwapchainBuilder { + public: + // Construct a SwapchainBuilder with a `vkb::Device` + explicit SwapchainBuilder(Device const& device); + // Construct a SwapchainBuilder with a specific VkSurfaceKHR handle and `vkb::Device` + explicit SwapchainBuilder(Device const& device, VkSurfaceKHR const surface); + // Construct a SwapchainBuilder with Vulkan handles for the physical device, device, and surface + // Optionally can provide the uint32_t indices for the graphics and present queue + // Note: The constructor will query the graphics & present queue if the indices are not provided + explicit SwapchainBuilder(VkPhysicalDevice const physical_device, + VkDevice const device, + VkSurfaceKHR const surface, + uint32_t graphics_queue_index = detail::QUEUE_INDEX_MAX_VALUE, + uint32_t present_queue_index = detail::QUEUE_INDEX_MAX_VALUE); + + Result build() const; + + // Set the oldSwapchain member of VkSwapchainCreateInfoKHR. + // For use in rebuilding a swapchain. + SwapchainBuilder& set_old_swapchain(VkSwapchainKHR old_swapchain); + SwapchainBuilder& set_old_swapchain(Swapchain const& swapchain); + + + // Desired size of the swapchain. By default, the swapchain will use the size + // of the window being drawn to. + SwapchainBuilder& set_desired_extent(uint32_t width, uint32_t height); + + // When determining the surface format, make this the first to be used if supported. + SwapchainBuilder& set_desired_format(VkSurfaceFormatKHR format); + // Add this swapchain format to the end of the list of formats selected from. + SwapchainBuilder& add_fallback_format(VkSurfaceFormatKHR format); + // Use the default swapchain formats. This is done if no formats are provided. + // Default surface format is {VK_FORMAT_B8G8R8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR} + SwapchainBuilder& use_default_format_selection(); + + // When determining the present mode, make this the first to be used if supported. + SwapchainBuilder& set_desired_present_mode(VkPresentModeKHR present_mode); + // Add this present mode to the end of the list of present modes selected from. + SwapchainBuilder& add_fallback_present_mode(VkPresentModeKHR present_mode); + // Use the default presentation mode. This is done if no present modes are provided. + // Default present modes: VK_PRESENT_MODE_MAILBOX_KHR with fallback VK_PRESENT_MODE_FIFO_KHR + SwapchainBuilder& use_default_present_mode_selection(); + + // Set the bitmask of the image usage for acquired swapchain images. + // If the surface capabilities cannot allow it, building the swapchain will result in the `SwapchainError::required_usage_not_supported` error. + SwapchainBuilder& set_image_usage_flags(VkImageUsageFlags usage_flags); + // Add a image usage to the bitmask for acquired swapchain images. + SwapchainBuilder& add_image_usage_flags(VkImageUsageFlags usage_flags); + // Use the default image usage bitmask values. This is the default if no image usages + // are provided. The default is VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT + SwapchainBuilder& use_default_image_usage_flags(); + + // Set the number of views in for multiview/stereo surface + SwapchainBuilder& set_image_array_layer_count(uint32_t array_layer_count); + + // Convenient named constants for passing to set_desired_min_image_count(). + // Note that it is not an `enum class`, so its constants can be passed as an integer value without casting + // In other words, these might as well be `static const int`, but they benefit from being grouped together this way. + enum BufferMode { + SINGLE_BUFFERING = 1, + DOUBLE_BUFFERING = 2, + TRIPLE_BUFFERING = 3, + }; + + // Sets the desired minimum image count for the swapchain. + // Note that the presentation engine is always free to create more images than requested. + // You may pass one of the values specified in the BufferMode enum, or any integer value. + // For instance, if you pass DOUBLE_BUFFERING, the presentation engine is allowed to give you a double buffering setup, triple buffering, or more. This is up to the drivers. + SwapchainBuilder& set_desired_min_image_count(uint32_t min_image_count); + + // Sets a required minimum image count for the swapchain. + // If the surface capabilities cannot allow it, building the swapchain will result in the `SwapchainError::required_min_image_count_too_low` error. + // Otherwise, the same observations from set_desired_min_image_count() apply. + // A value of 0 is specially interpreted as meaning "no requirement", and is the behavior by default. + SwapchainBuilder& set_required_min_image_count(uint32_t required_min_image_count); + + // Set whether the Vulkan implementation is allowed to discard rendering operations that + // affect regions of the surface that are not visible. Default is true. + // Note: Applications should use the default of true if they do not expect to read back the content + // of presentable images before presenting them or after reacquiring them, and if their fragment + // shaders do not have any side effects that require them to run for all pixels in the presentable image. + SwapchainBuilder& set_clipped(bool clipped = true); + + // Set the VkSwapchainCreateFlagBitsKHR. + SwapchainBuilder& set_create_flags(VkSwapchainCreateFlagBitsKHR create_flags); + // Set the transform to be applied, like a 90 degree rotation. Default is no transform. + SwapchainBuilder& set_pre_transform_flags(VkSurfaceTransformFlagBitsKHR pre_transform_flags); + // Set the alpha channel to be used with other windows in on the system. Default is VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR. + SwapchainBuilder& set_composite_alpha_flags(VkCompositeAlphaFlagBitsKHR composite_alpha_flags); + + // Add a structure to the pNext chain of VkSwapchainCreateInfoKHR. + // The structure must be valid when SwapchainBuilder::build() is called. + template SwapchainBuilder& add_pNext(T* structure) { + info.pNext_chain.push_back(reinterpret_cast(structure)); + return *this; + } + + // Provide custom allocation callbacks. + SwapchainBuilder& set_allocation_callbacks(VkAllocationCallbacks* callbacks); + + private: + void add_desired_formats(std::vector& formats) const; + void add_desired_present_modes(std::vector& modes) const; + + struct SwapchainInfo { + VkPhysicalDevice physical_device = VK_NULL_HANDLE; + VkDevice device = VK_NULL_HANDLE; + std::vector pNext_chain; + VkSwapchainCreateFlagBitsKHR create_flags = static_cast(0); + VkSurfaceKHR surface = VK_NULL_HANDLE; + std::vector desired_formats; + uint32_t instance_version = VKB_VK_API_VERSION_1_0; + uint32_t desired_width = 256; + uint32_t desired_height = 256; + uint32_t array_layer_count = 1; + uint32_t min_image_count = 0; + uint32_t required_min_image_count = 0; + VkImageUsageFlags image_usage_flags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + uint32_t graphics_queue_index = 0; + uint32_t present_queue_index = 0; + VkSurfaceTransformFlagBitsKHR pre_transform = static_cast(0); +#if defined(__ANDROID__) + VkCompositeAlphaFlagBitsKHR composite_alpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR; +#else + VkCompositeAlphaFlagBitsKHR composite_alpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; +#endif + std::vector desired_present_modes; + bool clipped = true; + VkSwapchainKHR old_swapchain = VK_NULL_HANDLE; + VkAllocationCallbacks* allocation_callbacks = VK_NULL_HANDLE; + } info; +}; + +} // namespace vkb + + +namespace std { +template <> struct is_error_code_enum : true_type {}; +template <> struct is_error_code_enum : true_type {}; +template <> struct is_error_code_enum : true_type {}; +template <> struct is_error_code_enum : true_type {}; +template <> struct is_error_code_enum : true_type {}; +} // namespace std diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/src/VkBootstrapDispatch.h b/Ifnity/Ifnity/vendor/vk-bootstrap/src/VkBootstrapDispatch.h new file mode 100644 index 0000000..615d4e7 --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/src/VkBootstrapDispatch.h @@ -0,0 +1,7957 @@ +/* + * Copyright © 2021 Cody Goodson (contact@vibimanx.com) + * Copyright © 2022 Charles Giessen (charles@lunarg.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the “Software”), to deal in the Software without restriction, including without + * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + * of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT + * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +// This file is a part of VkBootstrap +// https://github.com/charles-lunarg/vk-bootstrap + + +#pragma once + +#include + +namespace vkb { + +struct InstanceDispatchTable { + InstanceDispatchTable() = default; + InstanceDispatchTable(VkInstance instance, PFN_vkGetInstanceProcAddr procAddr) : instance(instance), populated(true) { + fp_vkDestroyInstance = reinterpret_cast(procAddr(instance, "vkDestroyInstance")); + fp_vkEnumeratePhysicalDevices = reinterpret_cast(procAddr(instance, "vkEnumeratePhysicalDevices")); + fp_vkGetInstanceProcAddr = reinterpret_cast(procAddr(instance, "vkGetInstanceProcAddr")); + fp_vkGetPhysicalDeviceProperties = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceProperties")); + fp_vkGetPhysicalDeviceQueueFamilyProperties = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceQueueFamilyProperties")); + fp_vkGetPhysicalDeviceMemoryProperties = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceMemoryProperties")); + fp_vkGetPhysicalDeviceFeatures = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceFeatures")); + fp_vkGetPhysicalDeviceFormatProperties = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceFormatProperties")); + fp_vkGetPhysicalDeviceImageFormatProperties = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceImageFormatProperties")); + fp_vkEnumerateDeviceLayerProperties = reinterpret_cast(procAddr(instance, "vkEnumerateDeviceLayerProperties")); + fp_vkEnumerateDeviceExtensionProperties = reinterpret_cast(procAddr(instance, "vkEnumerateDeviceExtensionProperties")); + fp_vkGetPhysicalDeviceSparseImageFormatProperties = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceSparseImageFormatProperties")); +#if (defined(VK_KHR_android_surface)) + fp_vkCreateAndroidSurfaceKHR = reinterpret_cast(procAddr(instance, "vkCreateAndroidSurfaceKHR")); +#endif +#if (defined(VK_KHR_display)) + fp_vkGetPhysicalDeviceDisplayPropertiesKHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceDisplayPropertiesKHR")); +#endif +#if (defined(VK_KHR_display)) + fp_vkGetPhysicalDeviceDisplayPlanePropertiesKHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceDisplayPlanePropertiesKHR")); +#endif +#if (defined(VK_KHR_display)) + fp_vkGetDisplayPlaneSupportedDisplaysKHR = reinterpret_cast(procAddr(instance, "vkGetDisplayPlaneSupportedDisplaysKHR")); +#endif +#if (defined(VK_KHR_display)) + fp_vkGetDisplayModePropertiesKHR = reinterpret_cast(procAddr(instance, "vkGetDisplayModePropertiesKHR")); +#endif +#if (defined(VK_KHR_display)) + fp_vkCreateDisplayModeKHR = reinterpret_cast(procAddr(instance, "vkCreateDisplayModeKHR")); +#endif +#if (defined(VK_KHR_display)) + fp_vkGetDisplayPlaneCapabilitiesKHR = reinterpret_cast(procAddr(instance, "vkGetDisplayPlaneCapabilitiesKHR")); +#endif +#if (defined(VK_KHR_display)) + fp_vkCreateDisplayPlaneSurfaceKHR = reinterpret_cast(procAddr(instance, "vkCreateDisplayPlaneSurfaceKHR")); +#endif +#if (defined(VK_KHR_surface)) + fp_vkDestroySurfaceKHR = reinterpret_cast(procAddr(instance, "vkDestroySurfaceKHR")); +#endif +#if (defined(VK_KHR_surface)) + fp_vkGetPhysicalDeviceSurfaceSupportKHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceSurfaceSupportKHR")); +#endif +#if (defined(VK_KHR_surface)) + fp_vkGetPhysicalDeviceSurfaceCapabilitiesKHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceSurfaceCapabilitiesKHR")); +#endif +#if (defined(VK_KHR_surface)) + fp_vkGetPhysicalDeviceSurfaceFormatsKHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceSurfaceFormatsKHR")); +#endif +#if (defined(VK_KHR_surface)) + fp_vkGetPhysicalDeviceSurfacePresentModesKHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceSurfacePresentModesKHR")); +#endif +#if (defined(VK_NN_vi_surface)) + fp_vkCreateViSurfaceNN = reinterpret_cast(procAddr(instance, "vkCreateViSurfaceNN")); +#endif +#if (defined(VK_KHR_wayland_surface)) + fp_vkCreateWaylandSurfaceKHR = reinterpret_cast(procAddr(instance, "vkCreateWaylandSurfaceKHR")); +#endif +#if (defined(VK_KHR_wayland_surface)) + fp_vkGetPhysicalDeviceWaylandPresentationSupportKHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceWaylandPresentationSupportKHR")); +#endif +#if (defined(VK_KHR_win32_surface)) + fp_vkCreateWin32SurfaceKHR = reinterpret_cast(procAddr(instance, "vkCreateWin32SurfaceKHR")); +#endif +#if (defined(VK_KHR_win32_surface)) + fp_vkGetPhysicalDeviceWin32PresentationSupportKHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceWin32PresentationSupportKHR")); +#endif +#if (defined(VK_KHR_xlib_surface)) + fp_vkCreateXlibSurfaceKHR = reinterpret_cast(procAddr(instance, "vkCreateXlibSurfaceKHR")); +#endif +#if (defined(VK_KHR_xlib_surface)) + fp_vkGetPhysicalDeviceXlibPresentationSupportKHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceXlibPresentationSupportKHR")); +#endif +#if (defined(VK_KHR_xcb_surface)) + fp_vkCreateXcbSurfaceKHR = reinterpret_cast(procAddr(instance, "vkCreateXcbSurfaceKHR")); +#endif +#if (defined(VK_KHR_xcb_surface)) + fp_vkGetPhysicalDeviceXcbPresentationSupportKHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceXcbPresentationSupportKHR")); +#endif +#if (defined(VK_EXT_directfb_surface)) + fp_vkCreateDirectFBSurfaceEXT = reinterpret_cast(procAddr(instance, "vkCreateDirectFBSurfaceEXT")); +#endif +#if (defined(VK_EXT_directfb_surface)) + fp_vkGetPhysicalDeviceDirectFBPresentationSupportEXT = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceDirectFBPresentationSupportEXT")); +#endif +#if (defined(VK_FUCHSIA_imagepipe_surface)) + fp_vkCreateImagePipeSurfaceFUCHSIA = reinterpret_cast(procAddr(instance, "vkCreateImagePipeSurfaceFUCHSIA")); +#endif +#if (defined(VK_GGP_stream_descriptor_surface)) + fp_vkCreateStreamDescriptorSurfaceGGP = reinterpret_cast(procAddr(instance, "vkCreateStreamDescriptorSurfaceGGP")); +#endif +#if (defined(VK_QNX_screen_surface)) + fp_vkCreateScreenSurfaceQNX = reinterpret_cast(procAddr(instance, "vkCreateScreenSurfaceQNX")); +#endif +#if (defined(VK_QNX_screen_surface)) + fp_vkGetPhysicalDeviceScreenPresentationSupportQNX = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceScreenPresentationSupportQNX")); +#endif +#if (defined(VK_EXT_debug_report)) + fp_vkCreateDebugReportCallbackEXT = reinterpret_cast(procAddr(instance, "vkCreateDebugReportCallbackEXT")); +#endif +#if (defined(VK_EXT_debug_report)) + fp_vkDestroyDebugReportCallbackEXT = reinterpret_cast(procAddr(instance, "vkDestroyDebugReportCallbackEXT")); +#endif +#if (defined(VK_EXT_debug_report)) + fp_vkDebugReportMessageEXT = reinterpret_cast(procAddr(instance, "vkDebugReportMessageEXT")); +#endif +#if (defined(VK_NV_external_memory_capabilities)) + fp_vkGetPhysicalDeviceExternalImageFormatPropertiesNV = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceExternalImageFormatPropertiesNV")); +#endif +#if (defined(VK_VERSION_1_1)) + fp_vkGetPhysicalDeviceFeatures2 = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceFeatures2")); +#endif +#if (defined(VK_VERSION_1_1)) + fp_vkGetPhysicalDeviceProperties2 = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceProperties2")); +#endif +#if (defined(VK_VERSION_1_1)) + fp_vkGetPhysicalDeviceFormatProperties2 = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceFormatProperties2")); +#endif +#if (defined(VK_VERSION_1_1)) + fp_vkGetPhysicalDeviceImageFormatProperties2 = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceImageFormatProperties2")); +#endif +#if (defined(VK_VERSION_1_1)) + fp_vkGetPhysicalDeviceQueueFamilyProperties2 = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceQueueFamilyProperties2")); +#endif +#if (defined(VK_VERSION_1_1)) + fp_vkGetPhysicalDeviceMemoryProperties2 = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceMemoryProperties2")); +#endif +#if (defined(VK_VERSION_1_1)) + fp_vkGetPhysicalDeviceSparseImageFormatProperties2 = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceSparseImageFormatProperties2")); +#endif +#if (defined(VK_VERSION_1_1)) + fp_vkGetPhysicalDeviceExternalBufferProperties = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceExternalBufferProperties")); +#endif +#if (defined(VK_NV_external_memory_sci_buf)) + fp_vkGetPhysicalDeviceExternalMemorySciBufPropertiesNV = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceExternalMemorySciBufPropertiesNV")); +#endif +#if (defined(VK_NV_external_memory_sci_buf)) + fp_vkGetPhysicalDeviceSciBufAttributesNV = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceSciBufAttributesNV")); +#endif +#if (defined(VK_VERSION_1_1)) + fp_vkGetPhysicalDeviceExternalSemaphoreProperties = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceExternalSemaphoreProperties")); +#endif +#if (defined(VK_VERSION_1_1)) + fp_vkGetPhysicalDeviceExternalFenceProperties = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceExternalFenceProperties")); +#endif +#if (defined(VK_NV_external_sci_sync)) || (defined(VK_NV_external_sci_sync2)) + fp_vkGetPhysicalDeviceSciSyncAttributesNV = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceSciSyncAttributesNV")); +#endif +#if (defined(VK_EXT_direct_mode_display)) + fp_vkReleaseDisplayEXT = reinterpret_cast(procAddr(instance, "vkReleaseDisplayEXT")); +#endif +#if (defined(VK_EXT_acquire_xlib_display)) + fp_vkAcquireXlibDisplayEXT = reinterpret_cast(procAddr(instance, "vkAcquireXlibDisplayEXT")); +#endif +#if (defined(VK_EXT_acquire_xlib_display)) + fp_vkGetRandROutputDisplayEXT = reinterpret_cast(procAddr(instance, "vkGetRandROutputDisplayEXT")); +#endif +#if (defined(VK_NV_acquire_winrt_display)) + fp_vkAcquireWinrtDisplayNV = reinterpret_cast(procAddr(instance, "vkAcquireWinrtDisplayNV")); +#endif +#if (defined(VK_NV_acquire_winrt_display)) + fp_vkGetWinrtDisplayNV = reinterpret_cast(procAddr(instance, "vkGetWinrtDisplayNV")); +#endif +#if (defined(VK_EXT_display_surface_counter)) + fp_vkGetPhysicalDeviceSurfaceCapabilities2EXT = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceSurfaceCapabilities2EXT")); +#endif +#if (defined(VK_VERSION_1_1)) + fp_vkEnumeratePhysicalDeviceGroups = reinterpret_cast(procAddr(instance, "vkEnumeratePhysicalDeviceGroups")); +#endif +#if (defined(VK_KHR_swapchain)) || (defined(VK_KHR_device_group)) + fp_vkGetPhysicalDevicePresentRectanglesKHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDevicePresentRectanglesKHR")); +#endif +#if (defined(VK_MVK_ios_surface)) + fp_vkCreateIOSSurfaceMVK = reinterpret_cast(procAddr(instance, "vkCreateIOSSurfaceMVK")); +#endif +#if (defined(VK_MVK_macos_surface)) + fp_vkCreateMacOSSurfaceMVK = reinterpret_cast(procAddr(instance, "vkCreateMacOSSurfaceMVK")); +#endif +#if (defined(VK_EXT_metal_surface)) + fp_vkCreateMetalSurfaceEXT = reinterpret_cast(procAddr(instance, "vkCreateMetalSurfaceEXT")); +#endif +#if (defined(VK_EXT_sample_locations)) + fp_vkGetPhysicalDeviceMultisamplePropertiesEXT = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceMultisamplePropertiesEXT")); +#endif +#if (defined(VK_KHR_get_surface_capabilities2)) + fp_vkGetPhysicalDeviceSurfaceCapabilities2KHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceSurfaceCapabilities2KHR")); +#endif +#if (defined(VK_KHR_get_surface_capabilities2)) + fp_vkGetPhysicalDeviceSurfaceFormats2KHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceSurfaceFormats2KHR")); +#endif +#if (defined(VK_KHR_get_display_properties2)) + fp_vkGetPhysicalDeviceDisplayProperties2KHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceDisplayProperties2KHR")); +#endif +#if (defined(VK_KHR_get_display_properties2)) + fp_vkGetPhysicalDeviceDisplayPlaneProperties2KHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceDisplayPlaneProperties2KHR")); +#endif +#if (defined(VK_KHR_get_display_properties2)) + fp_vkGetDisplayModeProperties2KHR = reinterpret_cast(procAddr(instance, "vkGetDisplayModeProperties2KHR")); +#endif +#if (defined(VK_KHR_get_display_properties2)) + fp_vkGetDisplayPlaneCapabilities2KHR = reinterpret_cast(procAddr(instance, "vkGetDisplayPlaneCapabilities2KHR")); +#endif +#if (defined(VK_KHR_calibrated_timestamps)) + fp_vkGetPhysicalDeviceCalibrateableTimeDomainsKHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceCalibrateableTimeDomainsKHR")); +#endif +#if (defined(VK_EXT_debug_utils)) + fp_vkCreateDebugUtilsMessengerEXT = reinterpret_cast(procAddr(instance, "vkCreateDebugUtilsMessengerEXT")); +#endif +#if (defined(VK_EXT_debug_utils)) + fp_vkDestroyDebugUtilsMessengerEXT = reinterpret_cast(procAddr(instance, "vkDestroyDebugUtilsMessengerEXT")); +#endif +#if (defined(VK_EXT_debug_utils)) + fp_vkSubmitDebugUtilsMessageEXT = reinterpret_cast(procAddr(instance, "vkSubmitDebugUtilsMessageEXT")); +#endif +#if (defined(VK_NV_cooperative_matrix)) + fp_vkGetPhysicalDeviceCooperativeMatrixPropertiesNV = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceCooperativeMatrixPropertiesNV")); +#endif +#if (defined(VK_EXT_full_screen_exclusive)) + fp_vkGetPhysicalDeviceSurfacePresentModes2EXT = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceSurfacePresentModes2EXT")); +#endif +#if (defined(VK_KHR_performance_query)) + fp_vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR = reinterpret_cast(procAddr(instance, "vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR")); +#endif +#if (defined(VK_KHR_performance_query)) + fp_vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR")); +#endif +#if (defined(VK_EXT_headless_surface)) + fp_vkCreateHeadlessSurfaceEXT = reinterpret_cast(procAddr(instance, "vkCreateHeadlessSurfaceEXT")); +#endif +#if (defined(VK_NV_coverage_reduction_mode)) + fp_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkGetPhysicalDeviceToolProperties = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceToolProperties")); +#endif +#if (defined(VK_KHR_object_refresh)) + fp_vkGetPhysicalDeviceRefreshableObjectTypesKHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceRefreshableObjectTypesKHR")); +#endif +#if (defined(VK_KHR_fragment_shading_rate)) + fp_vkGetPhysicalDeviceFragmentShadingRatesKHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceFragmentShadingRatesKHR")); +#endif +#if (defined(VK_KHR_video_queue)) + fp_vkGetPhysicalDeviceVideoCapabilitiesKHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceVideoCapabilitiesKHR")); +#endif +#if (defined(VK_KHR_video_queue)) + fp_vkGetPhysicalDeviceVideoFormatPropertiesKHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceVideoFormatPropertiesKHR")); +#endif +#if (defined(VK_KHR_video_encode_queue)) + fp_vkGetPhysicalDeviceVideoEncodeQualityLevelPropertiesKHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceVideoEncodeQualityLevelPropertiesKHR")); +#endif +#if (defined(VK_EXT_acquire_drm_display)) + fp_vkAcquireDrmDisplayEXT = reinterpret_cast(procAddr(instance, "vkAcquireDrmDisplayEXT")); +#endif +#if (defined(VK_EXT_acquire_drm_display)) + fp_vkGetDrmDisplayEXT = reinterpret_cast(procAddr(instance, "vkGetDrmDisplayEXT")); +#endif +#if (defined(VK_NV_optical_flow)) + fp_vkGetPhysicalDeviceOpticalFlowImageFormatsNV = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceOpticalFlowImageFormatsNV")); +#endif +#if (defined(VK_KHR_cooperative_matrix)) + fp_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR")); +#endif +#if (defined(VK_KHR_get_physical_device_properties2)) + fp_vkGetPhysicalDeviceFeatures2KHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceFeatures2KHR")); +#endif +#if (defined(VK_KHR_get_physical_device_properties2)) + fp_vkGetPhysicalDeviceProperties2KHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceProperties2KHR")); +#endif +#if (defined(VK_KHR_get_physical_device_properties2)) + fp_vkGetPhysicalDeviceFormatProperties2KHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceFormatProperties2KHR")); +#endif +#if (defined(VK_KHR_get_physical_device_properties2)) + fp_vkGetPhysicalDeviceImageFormatProperties2KHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceImageFormatProperties2KHR")); +#endif +#if (defined(VK_KHR_get_physical_device_properties2)) + fp_vkGetPhysicalDeviceQueueFamilyProperties2KHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceQueueFamilyProperties2KHR")); +#endif +#if (defined(VK_KHR_get_physical_device_properties2)) + fp_vkGetPhysicalDeviceMemoryProperties2KHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceMemoryProperties2KHR")); +#endif +#if (defined(VK_KHR_get_physical_device_properties2)) + fp_vkGetPhysicalDeviceSparseImageFormatProperties2KHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceSparseImageFormatProperties2KHR")); +#endif +#if (defined(VK_KHR_external_memory_capabilities)) + fp_vkGetPhysicalDeviceExternalBufferPropertiesKHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceExternalBufferPropertiesKHR")); +#endif +#if (defined(VK_KHR_external_semaphore_capabilities)) + fp_vkGetPhysicalDeviceExternalSemaphorePropertiesKHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceExternalSemaphorePropertiesKHR")); +#endif +#if (defined(VK_KHR_external_fence_capabilities)) + fp_vkGetPhysicalDeviceExternalFencePropertiesKHR = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceExternalFencePropertiesKHR")); +#endif +#if (defined(VK_KHR_device_group_creation)) + fp_vkEnumeratePhysicalDeviceGroupsKHR = reinterpret_cast(procAddr(instance, "vkEnumeratePhysicalDeviceGroupsKHR")); +#endif +#if (defined(VK_EXT_calibrated_timestamps)) + fp_vkGetPhysicalDeviceCalibrateableTimeDomainsEXT = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceCalibrateableTimeDomainsEXT")); +#endif +#if (defined(VK_EXT_tooling_info)) + fp_vkGetPhysicalDeviceToolPropertiesEXT = reinterpret_cast(procAddr(instance, "vkGetPhysicalDeviceToolPropertiesEXT")); +#endif + } + void destroyInstance(const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyInstance(instance, pAllocator); + } + VkResult enumeratePhysicalDevices(uint32_t* pPhysicalDeviceCount, VkPhysicalDevice* pPhysicalDevices) const noexcept { + return fp_vkEnumeratePhysicalDevices(instance, pPhysicalDeviceCount, pPhysicalDevices); + } + PFN_vkVoidFunction getInstanceProcAddr(const char* pName) const noexcept { + return fp_vkGetInstanceProcAddr(instance, pName); + } + void getPhysicalDeviceProperties(VkPhysicalDevice physicalDevice, VkPhysicalDeviceProperties* pProperties) const noexcept { + fp_vkGetPhysicalDeviceProperties(physicalDevice, pProperties); + } + void getPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties* pQueueFamilyProperties) const noexcept { + fp_vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount, pQueueFamilyProperties); + } + void getPhysicalDeviceMemoryProperties(VkPhysicalDevice physicalDevice, VkPhysicalDeviceMemoryProperties* pMemoryProperties) const noexcept { + fp_vkGetPhysicalDeviceMemoryProperties(physicalDevice, pMemoryProperties); + } + void getPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) const noexcept { + fp_vkGetPhysicalDeviceFeatures(physicalDevice, pFeatures); + } + void getPhysicalDeviceFormatProperties(VkPhysicalDevice physicalDevice, VkFormat format, VkFormatProperties* pFormatProperties) const noexcept { + fp_vkGetPhysicalDeviceFormatProperties(physicalDevice, format, pFormatProperties); + } + VkResult getPhysicalDeviceImageFormatProperties(VkPhysicalDevice physicalDevice, VkFormat format, VkImageType type, VkImageTiling tiling, VkImageUsageFlags usage, VkImageCreateFlags flags, VkImageFormatProperties* pImageFormatProperties) const noexcept { + return fp_vkGetPhysicalDeviceImageFormatProperties(physicalDevice, format, type, tiling, usage, flags, pImageFormatProperties); + } + VkResult enumerateDeviceLayerProperties(VkPhysicalDevice physicalDevice, uint32_t* pPropertyCount, VkLayerProperties* pProperties) const noexcept { + return fp_vkEnumerateDeviceLayerProperties(physicalDevice, pPropertyCount, pProperties); + } + VkResult enumerateDeviceExtensionProperties(VkPhysicalDevice physicalDevice, const char* pLayerName, uint32_t* pPropertyCount, VkExtensionProperties* pProperties) const noexcept { + return fp_vkEnumerateDeviceExtensionProperties(physicalDevice, pLayerName, pPropertyCount, pProperties); + } + void getPhysicalDeviceSparseImageFormatProperties(VkPhysicalDevice physicalDevice, VkFormat format, VkImageType type, VkSampleCountFlagBits samples, VkImageUsageFlags usage, VkImageTiling tiling, uint32_t* pPropertyCount, VkSparseImageFormatProperties* pProperties) const noexcept { + fp_vkGetPhysicalDeviceSparseImageFormatProperties(physicalDevice, format, type, samples, usage, tiling, pPropertyCount, pProperties); + } +#if (defined(VK_KHR_android_surface)) + VkResult createAndroidSurfaceKHR(const VkAndroidSurfaceCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface) const noexcept { + return fp_vkCreateAndroidSurfaceKHR(instance, pCreateInfo, pAllocator, pSurface); + } +#endif +#if (defined(VK_KHR_display)) + VkResult getPhysicalDeviceDisplayPropertiesKHR(VkPhysicalDevice physicalDevice, uint32_t* pPropertyCount, VkDisplayPropertiesKHR* pProperties) const noexcept { + return fp_vkGetPhysicalDeviceDisplayPropertiesKHR(physicalDevice, pPropertyCount, pProperties); + } +#endif +#if (defined(VK_KHR_display)) + VkResult getPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice, uint32_t* pPropertyCount, VkDisplayPlanePropertiesKHR* pProperties) const noexcept { + return fp_vkGetPhysicalDeviceDisplayPlanePropertiesKHR(physicalDevice, pPropertyCount, pProperties); + } +#endif +#if (defined(VK_KHR_display)) + VkResult getDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex, uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const noexcept { + return fp_vkGetDisplayPlaneSupportedDisplaysKHR(physicalDevice, planeIndex, pDisplayCount, pDisplays); + } +#endif +#if (defined(VK_KHR_display)) + VkResult getDisplayModePropertiesKHR(VkPhysicalDevice physicalDevice, VkDisplayKHR display, uint32_t* pPropertyCount, VkDisplayModePropertiesKHR* pProperties) const noexcept { + return fp_vkGetDisplayModePropertiesKHR(physicalDevice, display, pPropertyCount, pProperties); + } +#endif +#if (defined(VK_KHR_display)) + VkResult createDisplayModeKHR(VkPhysicalDevice physicalDevice, VkDisplayKHR display, const VkDisplayModeCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDisplayModeKHR* pMode) const noexcept { + return fp_vkCreateDisplayModeKHR(physicalDevice, display, pCreateInfo, pAllocator, pMode); + } +#endif +#if (defined(VK_KHR_display)) + VkResult getDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode, uint32_t planeIndex, VkDisplayPlaneCapabilitiesKHR* pCapabilities) const noexcept { + return fp_vkGetDisplayPlaneCapabilitiesKHR(physicalDevice, mode, planeIndex, pCapabilities); + } +#endif +#if (defined(VK_KHR_display)) + VkResult createDisplayPlaneSurfaceKHR(const VkDisplaySurfaceCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface) const noexcept { + return fp_vkCreateDisplayPlaneSurfaceKHR(instance, pCreateInfo, pAllocator, pSurface); + } +#endif +#if (defined(VK_KHR_surface)) + void destroySurfaceKHR(VkSurfaceKHR surface, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroySurfaceKHR(instance, surface, pAllocator); + } +#endif +#if (defined(VK_KHR_surface)) + VkResult getPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex, VkSurfaceKHR surface, VkBool32* pSupported) const noexcept { + return fp_vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, queueFamilyIndex, surface, pSupported); + } +#endif +#if (defined(VK_KHR_surface)) + VkResult getPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, VkSurfaceCapabilitiesKHR* pSurfaceCapabilities) const noexcept { + return fp_vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice, surface, pSurfaceCapabilities); + } +#endif +#if (defined(VK_KHR_surface)) + VkResult getPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, uint32_t* pSurfaceFormatCount, VkSurfaceFormatKHR* pSurfaceFormats) const noexcept { + return fp_vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface, pSurfaceFormatCount, pSurfaceFormats); + } +#endif +#if (defined(VK_KHR_surface)) + VkResult getPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, uint32_t* pPresentModeCount, VkPresentModeKHR* pPresentModes) const noexcept { + return fp_vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface, pPresentModeCount, pPresentModes); + } +#endif +#if (defined(VK_NN_vi_surface)) + VkResult createViSurfaceNN(const VkViSurfaceCreateInfoNN* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface) const noexcept { + return fp_vkCreateViSurfaceNN(instance, pCreateInfo, pAllocator, pSurface); + } +#endif +#if (defined(VK_KHR_wayland_surface)) + VkResult createWaylandSurfaceKHR(const VkWaylandSurfaceCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface) const noexcept { + return fp_vkCreateWaylandSurfaceKHR(instance, pCreateInfo, pAllocator, pSurface); + } +#endif +#if (defined(VK_KHR_wayland_surface)) + VkBool32 getPhysicalDeviceWaylandPresentationSupportKHR(VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex, struct wl_display* display) const noexcept { + return fp_vkGetPhysicalDeviceWaylandPresentationSupportKHR(physicalDevice, queueFamilyIndex, display); + } +#endif +#if (defined(VK_KHR_win32_surface)) + VkResult createWin32SurfaceKHR(const VkWin32SurfaceCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface) const noexcept { + return fp_vkCreateWin32SurfaceKHR(instance, pCreateInfo, pAllocator, pSurface); + } +#endif +#if (defined(VK_KHR_win32_surface)) + VkBool32 getPhysicalDeviceWin32PresentationSupportKHR(VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex) const noexcept { + return fp_vkGetPhysicalDeviceWin32PresentationSupportKHR(physicalDevice, queueFamilyIndex); + } +#endif +#if (defined(VK_KHR_xlib_surface)) + VkResult createXlibSurfaceKHR(const VkXlibSurfaceCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface) const noexcept { + return fp_vkCreateXlibSurfaceKHR(instance, pCreateInfo, pAllocator, pSurface); + } +#endif +#if (defined(VK_KHR_xlib_surface)) + VkBool32 getPhysicalDeviceXlibPresentationSupportKHR(VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex, Display* dpy, VisualID visualID) const noexcept { + return fp_vkGetPhysicalDeviceXlibPresentationSupportKHR(physicalDevice, queueFamilyIndex, dpy, visualID); + } +#endif +#if (defined(VK_KHR_xcb_surface)) + VkResult createXcbSurfaceKHR(const VkXcbSurfaceCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface) const noexcept { + return fp_vkCreateXcbSurfaceKHR(instance, pCreateInfo, pAllocator, pSurface); + } +#endif +#if (defined(VK_KHR_xcb_surface)) + VkBool32 getPhysicalDeviceXcbPresentationSupportKHR(VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex, xcb_connection_t* connection, xcb_visualid_t visual_id) const noexcept { + return fp_vkGetPhysicalDeviceXcbPresentationSupportKHR(physicalDevice, queueFamilyIndex, connection, visual_id); + } +#endif +#if (defined(VK_EXT_directfb_surface)) + VkResult createDirectFBSurfaceEXT(const VkDirectFBSurfaceCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface) const noexcept { + return fp_vkCreateDirectFBSurfaceEXT(instance, pCreateInfo, pAllocator, pSurface); + } +#endif +#if (defined(VK_EXT_directfb_surface)) + VkBool32 getPhysicalDeviceDirectFBPresentationSupportEXT(VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex, IDirectFB* dfb) const noexcept { + return fp_vkGetPhysicalDeviceDirectFBPresentationSupportEXT(physicalDevice, queueFamilyIndex, dfb); + } +#endif +#if (defined(VK_FUCHSIA_imagepipe_surface)) + VkResult createImagePipeSurfaceFUCHSIA(const VkImagePipeSurfaceCreateInfoFUCHSIA* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface) const noexcept { + return fp_vkCreateImagePipeSurfaceFUCHSIA(instance, pCreateInfo, pAllocator, pSurface); + } +#endif +#if (defined(VK_GGP_stream_descriptor_surface)) + VkResult createStreamDescriptorSurfaceGGP(const VkStreamDescriptorSurfaceCreateInfoGGP* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface) const noexcept { + return fp_vkCreateStreamDescriptorSurfaceGGP(instance, pCreateInfo, pAllocator, pSurface); + } +#endif +#if (defined(VK_QNX_screen_surface)) + VkResult createScreenSurfaceQNX(const VkScreenSurfaceCreateInfoQNX* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface) const noexcept { + return fp_vkCreateScreenSurfaceQNX(instance, pCreateInfo, pAllocator, pSurface); + } +#endif +#if (defined(VK_QNX_screen_surface)) + VkBool32 getPhysicalDeviceScreenPresentationSupportQNX(VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex, struct _screen_window* window) const noexcept { + return fp_vkGetPhysicalDeviceScreenPresentationSupportQNX(physicalDevice, queueFamilyIndex, window); + } +#endif +#if (defined(VK_EXT_debug_report)) + VkResult createDebugReportCallbackEXT(const VkDebugReportCallbackCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugReportCallbackEXT* pCallback) const noexcept { + return fp_vkCreateDebugReportCallbackEXT(instance, pCreateInfo, pAllocator, pCallback); + } +#endif +#if (defined(VK_EXT_debug_report)) + void destroyDebugReportCallbackEXT(VkDebugReportCallbackEXT callback, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyDebugReportCallbackEXT(instance, callback, pAllocator); + } +#endif +#if (defined(VK_EXT_debug_report)) + void debugReportMessageEXT(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t object, size_t location, int32_t messageCode, const char* pLayerPrefix, const char* pMessage) const noexcept { + fp_vkDebugReportMessageEXT(instance, flags, objectType, object, location, messageCode, pLayerPrefix, pMessage); + } +#endif +#if (defined(VK_NV_external_memory_capabilities)) + VkResult getPhysicalDeviceExternalImageFormatPropertiesNV(VkPhysicalDevice physicalDevice, VkFormat format, VkImageType type, VkImageTiling tiling, VkImageUsageFlags usage, VkImageCreateFlags flags, VkExternalMemoryHandleTypeFlagsNV externalHandleType, VkExternalImageFormatPropertiesNV* pExternalImageFormatProperties) const noexcept { + return fp_vkGetPhysicalDeviceExternalImageFormatPropertiesNV(physicalDevice, format, type, tiling, usage, flags, externalHandleType, pExternalImageFormatProperties); + } +#endif +#if (defined(VK_VERSION_1_1)) + void getPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures2KHR* pFeatures) const noexcept { + fp_vkGetPhysicalDeviceFeatures2(physicalDevice, pFeatures); + } +#endif +#if (defined(VK_VERSION_1_1)) + void getPhysicalDeviceProperties2(VkPhysicalDevice physicalDevice, VkPhysicalDeviceProperties2KHR* pProperties) const noexcept { + fp_vkGetPhysicalDeviceProperties2(physicalDevice, pProperties); + } +#endif +#if (defined(VK_VERSION_1_1)) + void getPhysicalDeviceFormatProperties2(VkPhysicalDevice physicalDevice, VkFormat format, VkFormatProperties2KHR* pFormatProperties) const noexcept { + fp_vkGetPhysicalDeviceFormatProperties2(physicalDevice, format, pFormatProperties); + } +#endif +#if (defined(VK_VERSION_1_1)) + VkResult getPhysicalDeviceImageFormatProperties2(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceImageFormatInfo2KHR* pImageFormatInfo, VkImageFormatProperties2KHR* pImageFormatProperties) const noexcept { + return fp_vkGetPhysicalDeviceImageFormatProperties2(physicalDevice, pImageFormatInfo, pImageFormatProperties); + } +#endif +#if (defined(VK_VERSION_1_1)) + void getPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2KHR* pQueueFamilyProperties) const noexcept { + fp_vkGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount, pQueueFamilyProperties); + } +#endif +#if (defined(VK_VERSION_1_1)) + void getPhysicalDeviceMemoryProperties2(VkPhysicalDevice physicalDevice, VkPhysicalDeviceMemoryProperties2KHR* pMemoryProperties) const noexcept { + fp_vkGetPhysicalDeviceMemoryProperties2(physicalDevice, pMemoryProperties); + } +#endif +#if (defined(VK_VERSION_1_1)) + void getPhysicalDeviceSparseImageFormatProperties2(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSparseImageFormatInfo2KHR* pFormatInfo, uint32_t* pPropertyCount, VkSparseImageFormatProperties2KHR* pProperties) const noexcept { + fp_vkGetPhysicalDeviceSparseImageFormatProperties2(physicalDevice, pFormatInfo, pPropertyCount, pProperties); + } +#endif +#if (defined(VK_VERSION_1_1)) + void getPhysicalDeviceExternalBufferProperties(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceExternalBufferInfoKHR* pExternalBufferInfo, VkExternalBufferPropertiesKHR* pExternalBufferProperties) const noexcept { + fp_vkGetPhysicalDeviceExternalBufferProperties(physicalDevice, pExternalBufferInfo, pExternalBufferProperties); + } +#endif +#if (defined(VK_NV_external_memory_sci_buf)) + VkResult getPhysicalDeviceExternalMemorySciBufPropertiesNV(VkPhysicalDevice physicalDevice, VkExternalMemoryHandleTypeFlagBitsKHR handleType, NvSciBufObj handle, VkMemorySciBufPropertiesNV* pMemorySciBufProperties) const noexcept { + return fp_vkGetPhysicalDeviceExternalMemorySciBufPropertiesNV(physicalDevice, handleType, handle, pMemorySciBufProperties); + } +#endif +#if (defined(VK_NV_external_memory_sci_buf)) + VkResult getPhysicalDeviceSciBufAttributesNV(VkPhysicalDevice physicalDevice, NvSciBufAttrList pAttributes) const noexcept { + return fp_vkGetPhysicalDeviceSciBufAttributesNV(physicalDevice, pAttributes); + } +#endif +#if (defined(VK_VERSION_1_1)) + void getPhysicalDeviceExternalSemaphoreProperties(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceExternalSemaphoreInfoKHR* pExternalSemaphoreInfo, VkExternalSemaphorePropertiesKHR* pExternalSemaphoreProperties) const noexcept { + fp_vkGetPhysicalDeviceExternalSemaphoreProperties(physicalDevice, pExternalSemaphoreInfo, pExternalSemaphoreProperties); + } +#endif +#if (defined(VK_VERSION_1_1)) + void getPhysicalDeviceExternalFenceProperties(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceExternalFenceInfoKHR* pExternalFenceInfo, VkExternalFencePropertiesKHR* pExternalFenceProperties) const noexcept { + fp_vkGetPhysicalDeviceExternalFenceProperties(physicalDevice, pExternalFenceInfo, pExternalFenceProperties); + } +#endif +#if (defined(VK_NV_external_sci_sync)) || (defined(VK_NV_external_sci_sync2)) + VkResult getPhysicalDeviceSciSyncAttributesNV(VkPhysicalDevice physicalDevice, const VkSciSyncAttributesInfoNV* pSciSyncAttributesInfo, NvSciSyncAttrList pAttributes) const noexcept { + return fp_vkGetPhysicalDeviceSciSyncAttributesNV(physicalDevice, pSciSyncAttributesInfo, pAttributes); + } +#endif +#if (defined(VK_EXT_direct_mode_display)) + VkResult releaseDisplayEXT(VkPhysicalDevice physicalDevice, VkDisplayKHR display) const noexcept { + return fp_vkReleaseDisplayEXT(physicalDevice, display); + } +#endif +#if (defined(VK_EXT_acquire_xlib_display)) + VkResult acquireXlibDisplayEXT(VkPhysicalDevice physicalDevice, Display* dpy, VkDisplayKHR display) const noexcept { + return fp_vkAcquireXlibDisplayEXT(physicalDevice, dpy, display); + } +#endif +#if (defined(VK_EXT_acquire_xlib_display)) + VkResult getRandROutputDisplayEXT(VkPhysicalDevice physicalDevice, Display* dpy, RROutput rrOutput, VkDisplayKHR* pDisplay) const noexcept { + return fp_vkGetRandROutputDisplayEXT(physicalDevice, dpy, rrOutput, pDisplay); + } +#endif +#if (defined(VK_NV_acquire_winrt_display)) + VkResult acquireWinrtDisplayNV(VkPhysicalDevice physicalDevice, VkDisplayKHR display) const noexcept { + return fp_vkAcquireWinrtDisplayNV(physicalDevice, display); + } +#endif +#if (defined(VK_NV_acquire_winrt_display)) + VkResult getWinrtDisplayNV(VkPhysicalDevice physicalDevice, uint32_t deviceRelativeId, VkDisplayKHR* pDisplay) const noexcept { + return fp_vkGetWinrtDisplayNV(physicalDevice, deviceRelativeId, pDisplay); + } +#endif +#if (defined(VK_EXT_display_surface_counter)) + VkResult getPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, VkSurfaceCapabilities2EXT* pSurfaceCapabilities) const noexcept { + return fp_vkGetPhysicalDeviceSurfaceCapabilities2EXT(physicalDevice, surface, pSurfaceCapabilities); + } +#endif +#if (defined(VK_VERSION_1_1)) + VkResult enumeratePhysicalDeviceGroups(uint32_t* pPhysicalDeviceGroupCount, VkPhysicalDeviceGroupPropertiesKHR* pPhysicalDeviceGroupProperties) const noexcept { + return fp_vkEnumeratePhysicalDeviceGroups(instance, pPhysicalDeviceGroupCount, pPhysicalDeviceGroupProperties); + } +#endif +#if (defined(VK_KHR_swapchain)) || (defined(VK_KHR_device_group)) + VkResult getPhysicalDevicePresentRectanglesKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, uint32_t* pRectCount, VkRect2D* pRects) const noexcept { + return fp_vkGetPhysicalDevicePresentRectanglesKHR(physicalDevice, surface, pRectCount, pRects); + } +#endif +#if (defined(VK_MVK_ios_surface)) + VkResult createIOSSurfaceMVK(const VkIOSSurfaceCreateInfoMVK* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface) const noexcept { + return fp_vkCreateIOSSurfaceMVK(instance, pCreateInfo, pAllocator, pSurface); + } +#endif +#if (defined(VK_MVK_macos_surface)) + VkResult createMacOSSurfaceMVK(const VkMacOSSurfaceCreateInfoMVK* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface) const noexcept { + return fp_vkCreateMacOSSurfaceMVK(instance, pCreateInfo, pAllocator, pSurface); + } +#endif +#if (defined(VK_EXT_metal_surface)) + VkResult createMetalSurfaceEXT(const VkMetalSurfaceCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface) const noexcept { + return fp_vkCreateMetalSurfaceEXT(instance, pCreateInfo, pAllocator, pSurface); + } +#endif +#if (defined(VK_EXT_sample_locations)) + void getPhysicalDeviceMultisamplePropertiesEXT(VkPhysicalDevice physicalDevice, VkSampleCountFlagBits samples, VkMultisamplePropertiesEXT* pMultisampleProperties) const noexcept { + fp_vkGetPhysicalDeviceMultisamplePropertiesEXT(physicalDevice, samples, pMultisampleProperties); + } +#endif +#if (defined(VK_KHR_get_surface_capabilities2)) + VkResult getPhysicalDeviceSurfaceCapabilities2KHR(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo, VkSurfaceCapabilities2KHR* pSurfaceCapabilities) const noexcept { + return fp_vkGetPhysicalDeviceSurfaceCapabilities2KHR(physicalDevice, pSurfaceInfo, pSurfaceCapabilities); + } +#endif +#if (defined(VK_KHR_get_surface_capabilities2)) + VkResult getPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo, uint32_t* pSurfaceFormatCount, VkSurfaceFormat2KHR* pSurfaceFormats) const noexcept { + return fp_vkGetPhysicalDeviceSurfaceFormats2KHR(physicalDevice, pSurfaceInfo, pSurfaceFormatCount, pSurfaceFormats); + } +#endif +#if (defined(VK_KHR_get_display_properties2)) + VkResult getPhysicalDeviceDisplayProperties2KHR(VkPhysicalDevice physicalDevice, uint32_t* pPropertyCount, VkDisplayProperties2KHR* pProperties) const noexcept { + return fp_vkGetPhysicalDeviceDisplayProperties2KHR(physicalDevice, pPropertyCount, pProperties); + } +#endif +#if (defined(VK_KHR_get_display_properties2)) + VkResult getPhysicalDeviceDisplayPlaneProperties2KHR(VkPhysicalDevice physicalDevice, uint32_t* pPropertyCount, VkDisplayPlaneProperties2KHR* pProperties) const noexcept { + return fp_vkGetPhysicalDeviceDisplayPlaneProperties2KHR(physicalDevice, pPropertyCount, pProperties); + } +#endif +#if (defined(VK_KHR_get_display_properties2)) + VkResult getDisplayModeProperties2KHR(VkPhysicalDevice physicalDevice, VkDisplayKHR display, uint32_t* pPropertyCount, VkDisplayModeProperties2KHR* pProperties) const noexcept { + return fp_vkGetDisplayModeProperties2KHR(physicalDevice, display, pPropertyCount, pProperties); + } +#endif +#if (defined(VK_KHR_get_display_properties2)) + VkResult getDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice, const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo, VkDisplayPlaneCapabilities2KHR* pCapabilities) const noexcept { + return fp_vkGetDisplayPlaneCapabilities2KHR(physicalDevice, pDisplayPlaneInfo, pCapabilities); + } +#endif +#if (defined(VK_KHR_calibrated_timestamps)) + VkResult getPhysicalDeviceCalibrateableTimeDomainsKHR(VkPhysicalDevice physicalDevice, uint32_t* pTimeDomainCount, VkTimeDomainEXT* pTimeDomains) const noexcept { + return fp_vkGetPhysicalDeviceCalibrateableTimeDomainsKHR(physicalDevice, pTimeDomainCount, pTimeDomains); + } +#endif +#if (defined(VK_EXT_debug_utils)) + VkResult createDebugUtilsMessengerEXT(const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugUtilsMessengerEXT* pMessenger) const noexcept { + return fp_vkCreateDebugUtilsMessengerEXT(instance, pCreateInfo, pAllocator, pMessenger); + } +#endif +#if (defined(VK_EXT_debug_utils)) + void destroyDebugUtilsMessengerEXT(VkDebugUtilsMessengerEXT messenger, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyDebugUtilsMessengerEXT(instance, messenger, pAllocator); + } +#endif +#if (defined(VK_EXT_debug_utils)) + void submitDebugUtilsMessageEXT(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, VkDebugUtilsMessageTypeFlagsEXT messageTypes, const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData) const noexcept { + fp_vkSubmitDebugUtilsMessageEXT(instance, messageSeverity, messageTypes, pCallbackData); + } +#endif +#if (defined(VK_NV_cooperative_matrix)) + VkResult getPhysicalDeviceCooperativeMatrixPropertiesNV(VkPhysicalDevice physicalDevice, uint32_t* pPropertyCount, VkCooperativeMatrixPropertiesNV* pProperties) const noexcept { + return fp_vkGetPhysicalDeviceCooperativeMatrixPropertiesNV(physicalDevice, pPropertyCount, pProperties); + } +#endif +#if (defined(VK_EXT_full_screen_exclusive)) + VkResult getPhysicalDeviceSurfacePresentModes2EXT(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo, uint32_t* pPresentModeCount, VkPresentModeKHR* pPresentModes) const noexcept { + return fp_vkGetPhysicalDeviceSurfacePresentModes2EXT(physicalDevice, pSurfaceInfo, pPresentModeCount, pPresentModes); + } +#endif +#if (defined(VK_KHR_performance_query)) + VkResult enumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR(VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex, uint32_t* pCounterCount, VkPerformanceCounterKHR* pCounters, VkPerformanceCounterDescriptionKHR* pCounterDescriptions) const noexcept { + return fp_vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR(physicalDevice, queueFamilyIndex, pCounterCount, pCounters, pCounterDescriptions); + } +#endif +#if (defined(VK_KHR_performance_query)) + void getPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR(VkPhysicalDevice physicalDevice, const VkQueryPoolPerformanceCreateInfoKHR* pPerformanceQueryCreateInfo, uint32_t* pNumPasses) const noexcept { + fp_vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR(physicalDevice, pPerformanceQueryCreateInfo, pNumPasses); + } +#endif +#if (defined(VK_EXT_headless_surface)) + VkResult createHeadlessSurfaceEXT(const VkHeadlessSurfaceCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface) const noexcept { + return fp_vkCreateHeadlessSurfaceEXT(instance, pCreateInfo, pAllocator, pSurface); + } +#endif +#if (defined(VK_NV_coverage_reduction_mode)) + VkResult getPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV(VkPhysicalDevice physicalDevice, uint32_t* pCombinationCount, VkFramebufferMixedSamplesCombinationNV* pCombinations) const noexcept { + return fp_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV(physicalDevice, pCombinationCount, pCombinations); + } +#endif +#if (defined(VK_VERSION_1_3)) + VkResult getPhysicalDeviceToolProperties(VkPhysicalDevice physicalDevice, uint32_t* pToolCount, VkPhysicalDeviceToolPropertiesEXT* pToolProperties) const noexcept { + return fp_vkGetPhysicalDeviceToolProperties(physicalDevice, pToolCount, pToolProperties); + } +#endif +#if (defined(VK_KHR_object_refresh)) + VkResult getPhysicalDeviceRefreshableObjectTypesKHR(VkPhysicalDevice physicalDevice, uint32_t* pRefreshableObjectTypeCount, VkObjectType* pRefreshableObjectTypes) const noexcept { + return fp_vkGetPhysicalDeviceRefreshableObjectTypesKHR(physicalDevice, pRefreshableObjectTypeCount, pRefreshableObjectTypes); + } +#endif +#if (defined(VK_KHR_fragment_shading_rate)) + VkResult getPhysicalDeviceFragmentShadingRatesKHR(VkPhysicalDevice physicalDevice, uint32_t* pFragmentShadingRateCount, VkPhysicalDeviceFragmentShadingRateKHR* pFragmentShadingRates) const noexcept { + return fp_vkGetPhysicalDeviceFragmentShadingRatesKHR(physicalDevice, pFragmentShadingRateCount, pFragmentShadingRates); + } +#endif +#if (defined(VK_KHR_video_queue)) + VkResult getPhysicalDeviceVideoCapabilitiesKHR(VkPhysicalDevice physicalDevice, const VkVideoProfileInfoKHR* pVideoProfile, VkVideoCapabilitiesKHR* pCapabilities) const noexcept { + return fp_vkGetPhysicalDeviceVideoCapabilitiesKHR(physicalDevice, pVideoProfile, pCapabilities); + } +#endif +#if (defined(VK_KHR_video_queue)) + VkResult getPhysicalDeviceVideoFormatPropertiesKHR(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceVideoFormatInfoKHR* pVideoFormatInfo, uint32_t* pVideoFormatPropertyCount, VkVideoFormatPropertiesKHR* pVideoFormatProperties) const noexcept { + return fp_vkGetPhysicalDeviceVideoFormatPropertiesKHR(physicalDevice, pVideoFormatInfo, pVideoFormatPropertyCount, pVideoFormatProperties); + } +#endif +#if (defined(VK_KHR_video_encode_queue)) + VkResult getPhysicalDeviceVideoEncodeQualityLevelPropertiesKHR(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceVideoEncodeQualityLevelInfoKHR* pQualityLevelInfo, VkVideoEncodeQualityLevelPropertiesKHR* pQualityLevelProperties) const noexcept { + return fp_vkGetPhysicalDeviceVideoEncodeQualityLevelPropertiesKHR(physicalDevice, pQualityLevelInfo, pQualityLevelProperties); + } +#endif +#if (defined(VK_EXT_acquire_drm_display)) + VkResult acquireDrmDisplayEXT(VkPhysicalDevice physicalDevice, int32_t drmFd, VkDisplayKHR display) const noexcept { + return fp_vkAcquireDrmDisplayEXT(physicalDevice, drmFd, display); + } +#endif +#if (defined(VK_EXT_acquire_drm_display)) + VkResult getDrmDisplayEXT(VkPhysicalDevice physicalDevice, int32_t drmFd, uint32_t connectorId, VkDisplayKHR* display) const noexcept { + return fp_vkGetDrmDisplayEXT(physicalDevice, drmFd, connectorId, display); + } +#endif +#if (defined(VK_NV_optical_flow)) + VkResult getPhysicalDeviceOpticalFlowImageFormatsNV(VkPhysicalDevice physicalDevice, const VkOpticalFlowImageFormatInfoNV* pOpticalFlowImageFormatInfo, uint32_t* pFormatCount, VkOpticalFlowImageFormatPropertiesNV* pImageFormatProperties) const noexcept { + return fp_vkGetPhysicalDeviceOpticalFlowImageFormatsNV(physicalDevice, pOpticalFlowImageFormatInfo, pFormatCount, pImageFormatProperties); + } +#endif +#if (defined(VK_KHR_cooperative_matrix)) + VkResult getPhysicalDeviceCooperativeMatrixPropertiesKHR(VkPhysicalDevice physicalDevice, uint32_t* pPropertyCount, VkCooperativeMatrixPropertiesKHR* pProperties) const noexcept { + return fp_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(physicalDevice, pPropertyCount, pProperties); + } +#endif +#if (defined(VK_KHR_get_physical_device_properties2)) + void getPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures2KHR* pFeatures) const noexcept { + fp_vkGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures); + } +#endif +#if (defined(VK_KHR_get_physical_device_properties2)) + void getPhysicalDeviceProperties2KHR(VkPhysicalDevice physicalDevice, VkPhysicalDeviceProperties2KHR* pProperties) const noexcept { + fp_vkGetPhysicalDeviceProperties2KHR(physicalDevice, pProperties); + } +#endif +#if (defined(VK_KHR_get_physical_device_properties2)) + void getPhysicalDeviceFormatProperties2KHR(VkPhysicalDevice physicalDevice, VkFormat format, VkFormatProperties2KHR* pFormatProperties) const noexcept { + fp_vkGetPhysicalDeviceFormatProperties2KHR(physicalDevice, format, pFormatProperties); + } +#endif +#if (defined(VK_KHR_get_physical_device_properties2)) + VkResult getPhysicalDeviceImageFormatProperties2KHR(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceImageFormatInfo2KHR* pImageFormatInfo, VkImageFormatProperties2KHR* pImageFormatProperties) const noexcept { + return fp_vkGetPhysicalDeviceImageFormatProperties2KHR(physicalDevice, pImageFormatInfo, pImageFormatProperties); + } +#endif +#if (defined(VK_KHR_get_physical_device_properties2)) + void getPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2KHR* pQueueFamilyProperties) const noexcept { + fp_vkGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount, pQueueFamilyProperties); + } +#endif +#if (defined(VK_KHR_get_physical_device_properties2)) + void getPhysicalDeviceMemoryProperties2KHR(VkPhysicalDevice physicalDevice, VkPhysicalDeviceMemoryProperties2KHR* pMemoryProperties) const noexcept { + fp_vkGetPhysicalDeviceMemoryProperties2KHR(physicalDevice, pMemoryProperties); + } +#endif +#if (defined(VK_KHR_get_physical_device_properties2)) + void getPhysicalDeviceSparseImageFormatProperties2KHR(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSparseImageFormatInfo2KHR* pFormatInfo, uint32_t* pPropertyCount, VkSparseImageFormatProperties2KHR* pProperties) const noexcept { + fp_vkGetPhysicalDeviceSparseImageFormatProperties2KHR(physicalDevice, pFormatInfo, pPropertyCount, pProperties); + } +#endif +#if (defined(VK_KHR_external_memory_capabilities)) + void getPhysicalDeviceExternalBufferPropertiesKHR(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceExternalBufferInfoKHR* pExternalBufferInfo, VkExternalBufferPropertiesKHR* pExternalBufferProperties) const noexcept { + fp_vkGetPhysicalDeviceExternalBufferPropertiesKHR(physicalDevice, pExternalBufferInfo, pExternalBufferProperties); + } +#endif +#if (defined(VK_KHR_external_semaphore_capabilities)) + void getPhysicalDeviceExternalSemaphorePropertiesKHR(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceExternalSemaphoreInfoKHR* pExternalSemaphoreInfo, VkExternalSemaphorePropertiesKHR* pExternalSemaphoreProperties) const noexcept { + fp_vkGetPhysicalDeviceExternalSemaphorePropertiesKHR(physicalDevice, pExternalSemaphoreInfo, pExternalSemaphoreProperties); + } +#endif +#if (defined(VK_KHR_external_fence_capabilities)) + void getPhysicalDeviceExternalFencePropertiesKHR(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceExternalFenceInfoKHR* pExternalFenceInfo, VkExternalFencePropertiesKHR* pExternalFenceProperties) const noexcept { + fp_vkGetPhysicalDeviceExternalFencePropertiesKHR(physicalDevice, pExternalFenceInfo, pExternalFenceProperties); + } +#endif +#if (defined(VK_KHR_device_group_creation)) + VkResult enumeratePhysicalDeviceGroupsKHR(uint32_t* pPhysicalDeviceGroupCount, VkPhysicalDeviceGroupPropertiesKHR* pPhysicalDeviceGroupProperties) const noexcept { + return fp_vkEnumeratePhysicalDeviceGroupsKHR(instance, pPhysicalDeviceGroupCount, pPhysicalDeviceGroupProperties); + } +#endif +#if (defined(VK_EXT_calibrated_timestamps)) + VkResult getPhysicalDeviceCalibrateableTimeDomainsEXT(VkPhysicalDevice physicalDevice, uint32_t* pTimeDomainCount, VkTimeDomainEXT* pTimeDomains) const noexcept { + return fp_vkGetPhysicalDeviceCalibrateableTimeDomainsEXT(physicalDevice, pTimeDomainCount, pTimeDomains); + } +#endif +#if (defined(VK_EXT_tooling_info)) + VkResult getPhysicalDeviceToolPropertiesEXT(VkPhysicalDevice physicalDevice, uint32_t* pToolCount, VkPhysicalDeviceToolPropertiesEXT* pToolProperties) const noexcept { + return fp_vkGetPhysicalDeviceToolPropertiesEXT(physicalDevice, pToolCount, pToolProperties); + } +#endif + PFN_vkDestroyInstance fp_vkDestroyInstance = nullptr; + PFN_vkEnumeratePhysicalDevices fp_vkEnumeratePhysicalDevices = nullptr; + PFN_vkGetInstanceProcAddr fp_vkGetInstanceProcAddr = nullptr; + PFN_vkGetPhysicalDeviceProperties fp_vkGetPhysicalDeviceProperties = nullptr; + PFN_vkGetPhysicalDeviceQueueFamilyProperties fp_vkGetPhysicalDeviceQueueFamilyProperties = nullptr; + PFN_vkGetPhysicalDeviceMemoryProperties fp_vkGetPhysicalDeviceMemoryProperties = nullptr; + PFN_vkGetPhysicalDeviceFeatures fp_vkGetPhysicalDeviceFeatures = nullptr; + PFN_vkGetPhysicalDeviceFormatProperties fp_vkGetPhysicalDeviceFormatProperties = nullptr; + PFN_vkGetPhysicalDeviceImageFormatProperties fp_vkGetPhysicalDeviceImageFormatProperties = nullptr; + PFN_vkEnumerateDeviceLayerProperties fp_vkEnumerateDeviceLayerProperties = nullptr; + PFN_vkEnumerateDeviceExtensionProperties fp_vkEnumerateDeviceExtensionProperties = nullptr; + PFN_vkGetPhysicalDeviceSparseImageFormatProperties fp_vkGetPhysicalDeviceSparseImageFormatProperties = nullptr; +#if (defined(VK_KHR_android_surface)) + PFN_vkCreateAndroidSurfaceKHR fp_vkCreateAndroidSurfaceKHR = nullptr; +#else + void * fp_vkCreateAndroidSurfaceKHR{}; +#endif +#if (defined(VK_KHR_display)) + PFN_vkGetPhysicalDeviceDisplayPropertiesKHR fp_vkGetPhysicalDeviceDisplayPropertiesKHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceDisplayPropertiesKHR{}; +#endif +#if (defined(VK_KHR_display)) + PFN_vkGetPhysicalDeviceDisplayPlanePropertiesKHR fp_vkGetPhysicalDeviceDisplayPlanePropertiesKHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceDisplayPlanePropertiesKHR{}; +#endif +#if (defined(VK_KHR_display)) + PFN_vkGetDisplayPlaneSupportedDisplaysKHR fp_vkGetDisplayPlaneSupportedDisplaysKHR = nullptr; +#else + void * fp_vkGetDisplayPlaneSupportedDisplaysKHR{}; +#endif +#if (defined(VK_KHR_display)) + PFN_vkGetDisplayModePropertiesKHR fp_vkGetDisplayModePropertiesKHR = nullptr; +#else + void * fp_vkGetDisplayModePropertiesKHR{}; +#endif +#if (defined(VK_KHR_display)) + PFN_vkCreateDisplayModeKHR fp_vkCreateDisplayModeKHR = nullptr; +#else + void * fp_vkCreateDisplayModeKHR{}; +#endif +#if (defined(VK_KHR_display)) + PFN_vkGetDisplayPlaneCapabilitiesKHR fp_vkGetDisplayPlaneCapabilitiesKHR = nullptr; +#else + void * fp_vkGetDisplayPlaneCapabilitiesKHR{}; +#endif +#if (defined(VK_KHR_display)) + PFN_vkCreateDisplayPlaneSurfaceKHR fp_vkCreateDisplayPlaneSurfaceKHR = nullptr; +#else + void * fp_vkCreateDisplayPlaneSurfaceKHR{}; +#endif +#if (defined(VK_KHR_surface)) + PFN_vkDestroySurfaceKHR fp_vkDestroySurfaceKHR = nullptr; +#else + void * fp_vkDestroySurfaceKHR{}; +#endif +#if (defined(VK_KHR_surface)) + PFN_vkGetPhysicalDeviceSurfaceSupportKHR fp_vkGetPhysicalDeviceSurfaceSupportKHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceSurfaceSupportKHR{}; +#endif +#if (defined(VK_KHR_surface)) + PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR fp_vkGetPhysicalDeviceSurfaceCapabilitiesKHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceSurfaceCapabilitiesKHR{}; +#endif +#if (defined(VK_KHR_surface)) + PFN_vkGetPhysicalDeviceSurfaceFormatsKHR fp_vkGetPhysicalDeviceSurfaceFormatsKHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceSurfaceFormatsKHR{}; +#endif +#if (defined(VK_KHR_surface)) + PFN_vkGetPhysicalDeviceSurfacePresentModesKHR fp_vkGetPhysicalDeviceSurfacePresentModesKHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceSurfacePresentModesKHR{}; +#endif +#if (defined(VK_NN_vi_surface)) + PFN_vkCreateViSurfaceNN fp_vkCreateViSurfaceNN = nullptr; +#else + void * fp_vkCreateViSurfaceNN{}; +#endif +#if (defined(VK_KHR_wayland_surface)) + PFN_vkCreateWaylandSurfaceKHR fp_vkCreateWaylandSurfaceKHR = nullptr; +#else + void * fp_vkCreateWaylandSurfaceKHR{}; +#endif +#if (defined(VK_KHR_wayland_surface)) + PFN_vkGetPhysicalDeviceWaylandPresentationSupportKHR fp_vkGetPhysicalDeviceWaylandPresentationSupportKHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceWaylandPresentationSupportKHR{}; +#endif +#if (defined(VK_KHR_win32_surface)) + PFN_vkCreateWin32SurfaceKHR fp_vkCreateWin32SurfaceKHR = nullptr; +#else + void * fp_vkCreateWin32SurfaceKHR{}; +#endif +#if (defined(VK_KHR_win32_surface)) + PFN_vkGetPhysicalDeviceWin32PresentationSupportKHR fp_vkGetPhysicalDeviceWin32PresentationSupportKHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceWin32PresentationSupportKHR{}; +#endif +#if (defined(VK_KHR_xlib_surface)) + PFN_vkCreateXlibSurfaceKHR fp_vkCreateXlibSurfaceKHR = nullptr; +#else + void * fp_vkCreateXlibSurfaceKHR{}; +#endif +#if (defined(VK_KHR_xlib_surface)) + PFN_vkGetPhysicalDeviceXlibPresentationSupportKHR fp_vkGetPhysicalDeviceXlibPresentationSupportKHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceXlibPresentationSupportKHR{}; +#endif +#if (defined(VK_KHR_xcb_surface)) + PFN_vkCreateXcbSurfaceKHR fp_vkCreateXcbSurfaceKHR = nullptr; +#else + void * fp_vkCreateXcbSurfaceKHR{}; +#endif +#if (defined(VK_KHR_xcb_surface)) + PFN_vkGetPhysicalDeviceXcbPresentationSupportKHR fp_vkGetPhysicalDeviceXcbPresentationSupportKHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceXcbPresentationSupportKHR{}; +#endif +#if (defined(VK_EXT_directfb_surface)) + PFN_vkCreateDirectFBSurfaceEXT fp_vkCreateDirectFBSurfaceEXT = nullptr; +#else + void * fp_vkCreateDirectFBSurfaceEXT{}; +#endif +#if (defined(VK_EXT_directfb_surface)) + PFN_vkGetPhysicalDeviceDirectFBPresentationSupportEXT fp_vkGetPhysicalDeviceDirectFBPresentationSupportEXT = nullptr; +#else + void * fp_vkGetPhysicalDeviceDirectFBPresentationSupportEXT{}; +#endif +#if (defined(VK_FUCHSIA_imagepipe_surface)) + PFN_vkCreateImagePipeSurfaceFUCHSIA fp_vkCreateImagePipeSurfaceFUCHSIA = nullptr; +#else + void * fp_vkCreateImagePipeSurfaceFUCHSIA{}; +#endif +#if (defined(VK_GGP_stream_descriptor_surface)) + PFN_vkCreateStreamDescriptorSurfaceGGP fp_vkCreateStreamDescriptorSurfaceGGP = nullptr; +#else + void * fp_vkCreateStreamDescriptorSurfaceGGP{}; +#endif +#if (defined(VK_QNX_screen_surface)) + PFN_vkCreateScreenSurfaceQNX fp_vkCreateScreenSurfaceQNX = nullptr; +#else + void * fp_vkCreateScreenSurfaceQNX{}; +#endif +#if (defined(VK_QNX_screen_surface)) + PFN_vkGetPhysicalDeviceScreenPresentationSupportQNX fp_vkGetPhysicalDeviceScreenPresentationSupportQNX = nullptr; +#else + void * fp_vkGetPhysicalDeviceScreenPresentationSupportQNX{}; +#endif +#if (defined(VK_EXT_debug_report)) + PFN_vkCreateDebugReportCallbackEXT fp_vkCreateDebugReportCallbackEXT = nullptr; +#else + void * fp_vkCreateDebugReportCallbackEXT{}; +#endif +#if (defined(VK_EXT_debug_report)) + PFN_vkDestroyDebugReportCallbackEXT fp_vkDestroyDebugReportCallbackEXT = nullptr; +#else + void * fp_vkDestroyDebugReportCallbackEXT{}; +#endif +#if (defined(VK_EXT_debug_report)) + PFN_vkDebugReportMessageEXT fp_vkDebugReportMessageEXT = nullptr; +#else + void * fp_vkDebugReportMessageEXT{}; +#endif +#if (defined(VK_NV_external_memory_capabilities)) + PFN_vkGetPhysicalDeviceExternalImageFormatPropertiesNV fp_vkGetPhysicalDeviceExternalImageFormatPropertiesNV = nullptr; +#else + void * fp_vkGetPhysicalDeviceExternalImageFormatPropertiesNV{}; +#endif +#if (defined(VK_VERSION_1_1)) + PFN_vkGetPhysicalDeviceFeatures2 fp_vkGetPhysicalDeviceFeatures2 = nullptr; +#else + void * fp_vkGetPhysicalDeviceFeatures2{}; +#endif +#if (defined(VK_VERSION_1_1)) + PFN_vkGetPhysicalDeviceProperties2 fp_vkGetPhysicalDeviceProperties2 = nullptr; +#else + void * fp_vkGetPhysicalDeviceProperties2{}; +#endif +#if (defined(VK_VERSION_1_1)) + PFN_vkGetPhysicalDeviceFormatProperties2 fp_vkGetPhysicalDeviceFormatProperties2 = nullptr; +#else + void * fp_vkGetPhysicalDeviceFormatProperties2{}; +#endif +#if (defined(VK_VERSION_1_1)) + PFN_vkGetPhysicalDeviceImageFormatProperties2 fp_vkGetPhysicalDeviceImageFormatProperties2 = nullptr; +#else + void * fp_vkGetPhysicalDeviceImageFormatProperties2{}; +#endif +#if (defined(VK_VERSION_1_1)) + PFN_vkGetPhysicalDeviceQueueFamilyProperties2 fp_vkGetPhysicalDeviceQueueFamilyProperties2 = nullptr; +#else + void * fp_vkGetPhysicalDeviceQueueFamilyProperties2{}; +#endif +#if (defined(VK_VERSION_1_1)) + PFN_vkGetPhysicalDeviceMemoryProperties2 fp_vkGetPhysicalDeviceMemoryProperties2 = nullptr; +#else + void * fp_vkGetPhysicalDeviceMemoryProperties2{}; +#endif +#if (defined(VK_VERSION_1_1)) + PFN_vkGetPhysicalDeviceSparseImageFormatProperties2 fp_vkGetPhysicalDeviceSparseImageFormatProperties2 = nullptr; +#else + void * fp_vkGetPhysicalDeviceSparseImageFormatProperties2{}; +#endif +#if (defined(VK_VERSION_1_1)) + PFN_vkGetPhysicalDeviceExternalBufferProperties fp_vkGetPhysicalDeviceExternalBufferProperties = nullptr; +#else + void * fp_vkGetPhysicalDeviceExternalBufferProperties{}; +#endif +#if (defined(VK_NV_external_memory_sci_buf)) + PFN_vkGetPhysicalDeviceExternalMemorySciBufPropertiesNV fp_vkGetPhysicalDeviceExternalMemorySciBufPropertiesNV = nullptr; +#else + void * fp_vkGetPhysicalDeviceExternalMemorySciBufPropertiesNV{}; +#endif +#if (defined(VK_NV_external_memory_sci_buf)) + PFN_vkGetPhysicalDeviceSciBufAttributesNV fp_vkGetPhysicalDeviceSciBufAttributesNV = nullptr; +#else + void * fp_vkGetPhysicalDeviceSciBufAttributesNV{}; +#endif +#if (defined(VK_VERSION_1_1)) + PFN_vkGetPhysicalDeviceExternalSemaphoreProperties fp_vkGetPhysicalDeviceExternalSemaphoreProperties = nullptr; +#else + void * fp_vkGetPhysicalDeviceExternalSemaphoreProperties{}; +#endif +#if (defined(VK_VERSION_1_1)) + PFN_vkGetPhysicalDeviceExternalFenceProperties fp_vkGetPhysicalDeviceExternalFenceProperties = nullptr; +#else + void * fp_vkGetPhysicalDeviceExternalFenceProperties{}; +#endif +#if (defined(VK_NV_external_sci_sync)) || (defined(VK_NV_external_sci_sync2)) + PFN_vkGetPhysicalDeviceSciSyncAttributesNV fp_vkGetPhysicalDeviceSciSyncAttributesNV = nullptr; +#else + void * fp_vkGetPhysicalDeviceSciSyncAttributesNV{}; +#endif +#if (defined(VK_EXT_direct_mode_display)) + PFN_vkReleaseDisplayEXT fp_vkReleaseDisplayEXT = nullptr; +#else + void * fp_vkReleaseDisplayEXT{}; +#endif +#if (defined(VK_EXT_acquire_xlib_display)) + PFN_vkAcquireXlibDisplayEXT fp_vkAcquireXlibDisplayEXT = nullptr; +#else + void * fp_vkAcquireXlibDisplayEXT{}; +#endif +#if (defined(VK_EXT_acquire_xlib_display)) + PFN_vkGetRandROutputDisplayEXT fp_vkGetRandROutputDisplayEXT = nullptr; +#else + void * fp_vkGetRandROutputDisplayEXT{}; +#endif +#if (defined(VK_NV_acquire_winrt_display)) + PFN_vkAcquireWinrtDisplayNV fp_vkAcquireWinrtDisplayNV = nullptr; +#else + void * fp_vkAcquireWinrtDisplayNV{}; +#endif +#if (defined(VK_NV_acquire_winrt_display)) + PFN_vkGetWinrtDisplayNV fp_vkGetWinrtDisplayNV = nullptr; +#else + void * fp_vkGetWinrtDisplayNV{}; +#endif +#if (defined(VK_EXT_display_surface_counter)) + PFN_vkGetPhysicalDeviceSurfaceCapabilities2EXT fp_vkGetPhysicalDeviceSurfaceCapabilities2EXT = nullptr; +#else + void * fp_vkGetPhysicalDeviceSurfaceCapabilities2EXT{}; +#endif +#if (defined(VK_VERSION_1_1)) + PFN_vkEnumeratePhysicalDeviceGroups fp_vkEnumeratePhysicalDeviceGroups = nullptr; +#else + void * fp_vkEnumeratePhysicalDeviceGroups{}; +#endif +#if (defined(VK_KHR_swapchain)) || (defined(VK_KHR_device_group)) + PFN_vkGetPhysicalDevicePresentRectanglesKHR fp_vkGetPhysicalDevicePresentRectanglesKHR = nullptr; +#else + void * fp_vkGetPhysicalDevicePresentRectanglesKHR{}; +#endif +#if (defined(VK_MVK_ios_surface)) + PFN_vkCreateIOSSurfaceMVK fp_vkCreateIOSSurfaceMVK = nullptr; +#else + void * fp_vkCreateIOSSurfaceMVK{}; +#endif +#if (defined(VK_MVK_macos_surface)) + PFN_vkCreateMacOSSurfaceMVK fp_vkCreateMacOSSurfaceMVK = nullptr; +#else + void * fp_vkCreateMacOSSurfaceMVK{}; +#endif +#if (defined(VK_EXT_metal_surface)) + PFN_vkCreateMetalSurfaceEXT fp_vkCreateMetalSurfaceEXT = nullptr; +#else + void * fp_vkCreateMetalSurfaceEXT{}; +#endif +#if (defined(VK_EXT_sample_locations)) + PFN_vkGetPhysicalDeviceMultisamplePropertiesEXT fp_vkGetPhysicalDeviceMultisamplePropertiesEXT = nullptr; +#else + void * fp_vkGetPhysicalDeviceMultisamplePropertiesEXT{}; +#endif +#if (defined(VK_KHR_get_surface_capabilities2)) + PFN_vkGetPhysicalDeviceSurfaceCapabilities2KHR fp_vkGetPhysicalDeviceSurfaceCapabilities2KHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceSurfaceCapabilities2KHR{}; +#endif +#if (defined(VK_KHR_get_surface_capabilities2)) + PFN_vkGetPhysicalDeviceSurfaceFormats2KHR fp_vkGetPhysicalDeviceSurfaceFormats2KHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceSurfaceFormats2KHR{}; +#endif +#if (defined(VK_KHR_get_display_properties2)) + PFN_vkGetPhysicalDeviceDisplayProperties2KHR fp_vkGetPhysicalDeviceDisplayProperties2KHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceDisplayProperties2KHR{}; +#endif +#if (defined(VK_KHR_get_display_properties2)) + PFN_vkGetPhysicalDeviceDisplayPlaneProperties2KHR fp_vkGetPhysicalDeviceDisplayPlaneProperties2KHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceDisplayPlaneProperties2KHR{}; +#endif +#if (defined(VK_KHR_get_display_properties2)) + PFN_vkGetDisplayModeProperties2KHR fp_vkGetDisplayModeProperties2KHR = nullptr; +#else + void * fp_vkGetDisplayModeProperties2KHR{}; +#endif +#if (defined(VK_KHR_get_display_properties2)) + PFN_vkGetDisplayPlaneCapabilities2KHR fp_vkGetDisplayPlaneCapabilities2KHR = nullptr; +#else + void * fp_vkGetDisplayPlaneCapabilities2KHR{}; +#endif +#if (defined(VK_KHR_calibrated_timestamps)) + PFN_vkGetPhysicalDeviceCalibrateableTimeDomainsKHR fp_vkGetPhysicalDeviceCalibrateableTimeDomainsKHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceCalibrateableTimeDomainsKHR{}; +#endif +#if (defined(VK_EXT_debug_utils)) + PFN_vkCreateDebugUtilsMessengerEXT fp_vkCreateDebugUtilsMessengerEXT = nullptr; +#else + void * fp_vkCreateDebugUtilsMessengerEXT{}; +#endif +#if (defined(VK_EXT_debug_utils)) + PFN_vkDestroyDebugUtilsMessengerEXT fp_vkDestroyDebugUtilsMessengerEXT = nullptr; +#else + void * fp_vkDestroyDebugUtilsMessengerEXT{}; +#endif +#if (defined(VK_EXT_debug_utils)) + PFN_vkSubmitDebugUtilsMessageEXT fp_vkSubmitDebugUtilsMessageEXT = nullptr; +#else + void * fp_vkSubmitDebugUtilsMessageEXT{}; +#endif +#if (defined(VK_NV_cooperative_matrix)) + PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesNV fp_vkGetPhysicalDeviceCooperativeMatrixPropertiesNV = nullptr; +#else + void * fp_vkGetPhysicalDeviceCooperativeMatrixPropertiesNV{}; +#endif +#if (defined(VK_EXT_full_screen_exclusive)) + PFN_vkGetPhysicalDeviceSurfacePresentModes2EXT fp_vkGetPhysicalDeviceSurfacePresentModes2EXT = nullptr; +#else + void * fp_vkGetPhysicalDeviceSurfacePresentModes2EXT{}; +#endif +#if (defined(VK_KHR_performance_query)) + PFN_vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR fp_vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR = nullptr; +#else + void * fp_vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR{}; +#endif +#if (defined(VK_KHR_performance_query)) + PFN_vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR fp_vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR{}; +#endif +#if (defined(VK_EXT_headless_surface)) + PFN_vkCreateHeadlessSurfaceEXT fp_vkCreateHeadlessSurfaceEXT = nullptr; +#else + void * fp_vkCreateHeadlessSurfaceEXT{}; +#endif +#if (defined(VK_NV_coverage_reduction_mode)) + PFN_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV fp_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV = nullptr; +#else + void * fp_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkGetPhysicalDeviceToolProperties fp_vkGetPhysicalDeviceToolProperties = nullptr; +#else + void * fp_vkGetPhysicalDeviceToolProperties{}; +#endif +#if (defined(VK_KHR_object_refresh)) + PFN_vkGetPhysicalDeviceRefreshableObjectTypesKHR fp_vkGetPhysicalDeviceRefreshableObjectTypesKHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceRefreshableObjectTypesKHR{}; +#endif +#if (defined(VK_KHR_fragment_shading_rate)) + PFN_vkGetPhysicalDeviceFragmentShadingRatesKHR fp_vkGetPhysicalDeviceFragmentShadingRatesKHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceFragmentShadingRatesKHR{}; +#endif +#if (defined(VK_KHR_video_queue)) + PFN_vkGetPhysicalDeviceVideoCapabilitiesKHR fp_vkGetPhysicalDeviceVideoCapabilitiesKHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceVideoCapabilitiesKHR{}; +#endif +#if (defined(VK_KHR_video_queue)) + PFN_vkGetPhysicalDeviceVideoFormatPropertiesKHR fp_vkGetPhysicalDeviceVideoFormatPropertiesKHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceVideoFormatPropertiesKHR{}; +#endif +#if (defined(VK_KHR_video_encode_queue)) + PFN_vkGetPhysicalDeviceVideoEncodeQualityLevelPropertiesKHR fp_vkGetPhysicalDeviceVideoEncodeQualityLevelPropertiesKHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceVideoEncodeQualityLevelPropertiesKHR{}; +#endif +#if (defined(VK_EXT_acquire_drm_display)) + PFN_vkAcquireDrmDisplayEXT fp_vkAcquireDrmDisplayEXT = nullptr; +#else + void * fp_vkAcquireDrmDisplayEXT{}; +#endif +#if (defined(VK_EXT_acquire_drm_display)) + PFN_vkGetDrmDisplayEXT fp_vkGetDrmDisplayEXT = nullptr; +#else + void * fp_vkGetDrmDisplayEXT{}; +#endif +#if (defined(VK_NV_optical_flow)) + PFN_vkGetPhysicalDeviceOpticalFlowImageFormatsNV fp_vkGetPhysicalDeviceOpticalFlowImageFormatsNV = nullptr; +#else + void * fp_vkGetPhysicalDeviceOpticalFlowImageFormatsNV{}; +#endif +#if (defined(VK_KHR_cooperative_matrix)) + PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR fp_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR{}; +#endif +#if (defined(VK_KHR_get_physical_device_properties2)) + PFN_vkGetPhysicalDeviceFeatures2KHR fp_vkGetPhysicalDeviceFeatures2KHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceFeatures2KHR{}; +#endif +#if (defined(VK_KHR_get_physical_device_properties2)) + PFN_vkGetPhysicalDeviceProperties2KHR fp_vkGetPhysicalDeviceProperties2KHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceProperties2KHR{}; +#endif +#if (defined(VK_KHR_get_physical_device_properties2)) + PFN_vkGetPhysicalDeviceFormatProperties2KHR fp_vkGetPhysicalDeviceFormatProperties2KHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceFormatProperties2KHR{}; +#endif +#if (defined(VK_KHR_get_physical_device_properties2)) + PFN_vkGetPhysicalDeviceImageFormatProperties2KHR fp_vkGetPhysicalDeviceImageFormatProperties2KHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceImageFormatProperties2KHR{}; +#endif +#if (defined(VK_KHR_get_physical_device_properties2)) + PFN_vkGetPhysicalDeviceQueueFamilyProperties2KHR fp_vkGetPhysicalDeviceQueueFamilyProperties2KHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceQueueFamilyProperties2KHR{}; +#endif +#if (defined(VK_KHR_get_physical_device_properties2)) + PFN_vkGetPhysicalDeviceMemoryProperties2KHR fp_vkGetPhysicalDeviceMemoryProperties2KHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceMemoryProperties2KHR{}; +#endif +#if (defined(VK_KHR_get_physical_device_properties2)) + PFN_vkGetPhysicalDeviceSparseImageFormatProperties2KHR fp_vkGetPhysicalDeviceSparseImageFormatProperties2KHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceSparseImageFormatProperties2KHR{}; +#endif +#if (defined(VK_KHR_external_memory_capabilities)) + PFN_vkGetPhysicalDeviceExternalBufferPropertiesKHR fp_vkGetPhysicalDeviceExternalBufferPropertiesKHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceExternalBufferPropertiesKHR{}; +#endif +#if (defined(VK_KHR_external_semaphore_capabilities)) + PFN_vkGetPhysicalDeviceExternalSemaphorePropertiesKHR fp_vkGetPhysicalDeviceExternalSemaphorePropertiesKHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceExternalSemaphorePropertiesKHR{}; +#endif +#if (defined(VK_KHR_external_fence_capabilities)) + PFN_vkGetPhysicalDeviceExternalFencePropertiesKHR fp_vkGetPhysicalDeviceExternalFencePropertiesKHR = nullptr; +#else + void * fp_vkGetPhysicalDeviceExternalFencePropertiesKHR{}; +#endif +#if (defined(VK_KHR_device_group_creation)) + PFN_vkEnumeratePhysicalDeviceGroupsKHR fp_vkEnumeratePhysicalDeviceGroupsKHR = nullptr; +#else + void * fp_vkEnumeratePhysicalDeviceGroupsKHR{}; +#endif +#if (defined(VK_EXT_calibrated_timestamps)) + PFN_vkGetPhysicalDeviceCalibrateableTimeDomainsEXT fp_vkGetPhysicalDeviceCalibrateableTimeDomainsEXT = nullptr; +#else + void * fp_vkGetPhysicalDeviceCalibrateableTimeDomainsEXT{}; +#endif +#if (defined(VK_EXT_tooling_info)) + PFN_vkGetPhysicalDeviceToolPropertiesEXT fp_vkGetPhysicalDeviceToolPropertiesEXT = nullptr; +#else + void * fp_vkGetPhysicalDeviceToolPropertiesEXT{}; +#endif + bool is_populated() const { return populated; } + VkInstance instance = VK_NULL_HANDLE; +private: + bool populated = false; +}; + +struct DispatchTable { + DispatchTable() = default; + DispatchTable(VkDevice device, PFN_vkGetDeviceProcAddr procAddr) : device(device), populated(true) { + fp_vkGetDeviceQueue = reinterpret_cast(procAddr(device, "vkGetDeviceQueue")); + fp_vkQueueSubmit = reinterpret_cast(procAddr(device, "vkQueueSubmit")); + fp_vkQueueWaitIdle = reinterpret_cast(procAddr(device, "vkQueueWaitIdle")); + fp_vkDeviceWaitIdle = reinterpret_cast(procAddr(device, "vkDeviceWaitIdle")); + fp_vkAllocateMemory = reinterpret_cast(procAddr(device, "vkAllocateMemory")); + fp_vkFreeMemory = reinterpret_cast(procAddr(device, "vkFreeMemory")); + fp_vkMapMemory = reinterpret_cast(procAddr(device, "vkMapMemory")); + fp_vkUnmapMemory = reinterpret_cast(procAddr(device, "vkUnmapMemory")); + fp_vkFlushMappedMemoryRanges = reinterpret_cast(procAddr(device, "vkFlushMappedMemoryRanges")); + fp_vkInvalidateMappedMemoryRanges = reinterpret_cast(procAddr(device, "vkInvalidateMappedMemoryRanges")); + fp_vkGetDeviceMemoryCommitment = reinterpret_cast(procAddr(device, "vkGetDeviceMemoryCommitment")); + fp_vkGetBufferMemoryRequirements = reinterpret_cast(procAddr(device, "vkGetBufferMemoryRequirements")); + fp_vkBindBufferMemory = reinterpret_cast(procAddr(device, "vkBindBufferMemory")); + fp_vkGetImageMemoryRequirements = reinterpret_cast(procAddr(device, "vkGetImageMemoryRequirements")); + fp_vkBindImageMemory = reinterpret_cast(procAddr(device, "vkBindImageMemory")); + fp_vkGetImageSparseMemoryRequirements = reinterpret_cast(procAddr(device, "vkGetImageSparseMemoryRequirements")); + fp_vkQueueBindSparse = reinterpret_cast(procAddr(device, "vkQueueBindSparse")); + fp_vkCreateFence = reinterpret_cast(procAddr(device, "vkCreateFence")); + fp_vkDestroyFence = reinterpret_cast(procAddr(device, "vkDestroyFence")); + fp_vkResetFences = reinterpret_cast(procAddr(device, "vkResetFences")); + fp_vkGetFenceStatus = reinterpret_cast(procAddr(device, "vkGetFenceStatus")); + fp_vkWaitForFences = reinterpret_cast(procAddr(device, "vkWaitForFences")); + fp_vkCreateSemaphore = reinterpret_cast(procAddr(device, "vkCreateSemaphore")); + fp_vkDestroySemaphore = reinterpret_cast(procAddr(device, "vkDestroySemaphore")); + fp_vkCreateEvent = reinterpret_cast(procAddr(device, "vkCreateEvent")); + fp_vkDestroyEvent = reinterpret_cast(procAddr(device, "vkDestroyEvent")); + fp_vkGetEventStatus = reinterpret_cast(procAddr(device, "vkGetEventStatus")); + fp_vkSetEvent = reinterpret_cast(procAddr(device, "vkSetEvent")); + fp_vkResetEvent = reinterpret_cast(procAddr(device, "vkResetEvent")); + fp_vkCreateQueryPool = reinterpret_cast(procAddr(device, "vkCreateQueryPool")); + fp_vkDestroyQueryPool = reinterpret_cast(procAddr(device, "vkDestroyQueryPool")); + fp_vkGetQueryPoolResults = reinterpret_cast(procAddr(device, "vkGetQueryPoolResults")); +#if (defined(VK_VERSION_1_2)) + fp_vkResetQueryPool = reinterpret_cast(procAddr(device, "vkResetQueryPool")); +#endif + fp_vkCreateBuffer = reinterpret_cast(procAddr(device, "vkCreateBuffer")); + fp_vkDestroyBuffer = reinterpret_cast(procAddr(device, "vkDestroyBuffer")); + fp_vkCreateBufferView = reinterpret_cast(procAddr(device, "vkCreateBufferView")); + fp_vkDestroyBufferView = reinterpret_cast(procAddr(device, "vkDestroyBufferView")); + fp_vkCreateImage = reinterpret_cast(procAddr(device, "vkCreateImage")); + fp_vkDestroyImage = reinterpret_cast(procAddr(device, "vkDestroyImage")); + fp_vkGetImageSubresourceLayout = reinterpret_cast(procAddr(device, "vkGetImageSubresourceLayout")); + fp_vkCreateImageView = reinterpret_cast(procAddr(device, "vkCreateImageView")); + fp_vkDestroyImageView = reinterpret_cast(procAddr(device, "vkDestroyImageView")); + fp_vkCreateShaderModule = reinterpret_cast(procAddr(device, "vkCreateShaderModule")); + fp_vkDestroyShaderModule = reinterpret_cast(procAddr(device, "vkDestroyShaderModule")); + fp_vkCreatePipelineCache = reinterpret_cast(procAddr(device, "vkCreatePipelineCache")); + fp_vkDestroyPipelineCache = reinterpret_cast(procAddr(device, "vkDestroyPipelineCache")); + fp_vkGetPipelineCacheData = reinterpret_cast(procAddr(device, "vkGetPipelineCacheData")); + fp_vkMergePipelineCaches = reinterpret_cast(procAddr(device, "vkMergePipelineCaches")); +#if (defined(VK_KHR_pipeline_binary)) + fp_vkCreatePipelineBinariesKHR = reinterpret_cast(procAddr(device, "vkCreatePipelineBinariesKHR")); +#endif +#if (defined(VK_KHR_pipeline_binary)) + fp_vkDestroyPipelineBinaryKHR = reinterpret_cast(procAddr(device, "vkDestroyPipelineBinaryKHR")); +#endif +#if (defined(VK_KHR_pipeline_binary)) + fp_vkGetPipelineKeyKHR = reinterpret_cast(procAddr(device, "vkGetPipelineKeyKHR")); +#endif +#if (defined(VK_KHR_pipeline_binary)) + fp_vkGetPipelineBinaryDataKHR = reinterpret_cast(procAddr(device, "vkGetPipelineBinaryDataKHR")); +#endif +#if (defined(VK_KHR_pipeline_binary)) + fp_vkReleaseCapturedPipelineDataKHR = reinterpret_cast(procAddr(device, "vkReleaseCapturedPipelineDataKHR")); +#endif + fp_vkCreateGraphicsPipelines = reinterpret_cast(procAddr(device, "vkCreateGraphicsPipelines")); + fp_vkCreateComputePipelines = reinterpret_cast(procAddr(device, "vkCreateComputePipelines")); +#if (defined(VK_HUAWEI_subpass_shading)) + fp_vkGetDeviceSubpassShadingMaxWorkgroupSizeHUAWEI = reinterpret_cast(procAddr(device, "vkGetDeviceSubpassShadingMaxWorkgroupSizeHUAWEI")); +#endif + fp_vkDestroyPipeline = reinterpret_cast(procAddr(device, "vkDestroyPipeline")); + fp_vkCreatePipelineLayout = reinterpret_cast(procAddr(device, "vkCreatePipelineLayout")); + fp_vkDestroyPipelineLayout = reinterpret_cast(procAddr(device, "vkDestroyPipelineLayout")); + fp_vkCreateSampler = reinterpret_cast(procAddr(device, "vkCreateSampler")); + fp_vkDestroySampler = reinterpret_cast(procAddr(device, "vkDestroySampler")); + fp_vkCreateDescriptorSetLayout = reinterpret_cast(procAddr(device, "vkCreateDescriptorSetLayout")); + fp_vkDestroyDescriptorSetLayout = reinterpret_cast(procAddr(device, "vkDestroyDescriptorSetLayout")); + fp_vkCreateDescriptorPool = reinterpret_cast(procAddr(device, "vkCreateDescriptorPool")); + fp_vkDestroyDescriptorPool = reinterpret_cast(procAddr(device, "vkDestroyDescriptorPool")); + fp_vkResetDescriptorPool = reinterpret_cast(procAddr(device, "vkResetDescriptorPool")); + fp_vkAllocateDescriptorSets = reinterpret_cast(procAddr(device, "vkAllocateDescriptorSets")); + fp_vkFreeDescriptorSets = reinterpret_cast(procAddr(device, "vkFreeDescriptorSets")); + fp_vkUpdateDescriptorSets = reinterpret_cast(procAddr(device, "vkUpdateDescriptorSets")); + fp_vkCreateFramebuffer = reinterpret_cast(procAddr(device, "vkCreateFramebuffer")); + fp_vkDestroyFramebuffer = reinterpret_cast(procAddr(device, "vkDestroyFramebuffer")); + fp_vkCreateRenderPass = reinterpret_cast(procAddr(device, "vkCreateRenderPass")); + fp_vkDestroyRenderPass = reinterpret_cast(procAddr(device, "vkDestroyRenderPass")); + fp_vkGetRenderAreaGranularity = reinterpret_cast(procAddr(device, "vkGetRenderAreaGranularity")); +#if (defined(VK_KHR_maintenance5)) + fp_vkGetRenderingAreaGranularityKHR = reinterpret_cast(procAddr(device, "vkGetRenderingAreaGranularityKHR")); +#endif + fp_vkCreateCommandPool = reinterpret_cast(procAddr(device, "vkCreateCommandPool")); + fp_vkDestroyCommandPool = reinterpret_cast(procAddr(device, "vkDestroyCommandPool")); + fp_vkResetCommandPool = reinterpret_cast(procAddr(device, "vkResetCommandPool")); + fp_vkAllocateCommandBuffers = reinterpret_cast(procAddr(device, "vkAllocateCommandBuffers")); + fp_vkFreeCommandBuffers = reinterpret_cast(procAddr(device, "vkFreeCommandBuffers")); + fp_vkBeginCommandBuffer = reinterpret_cast(procAddr(device, "vkBeginCommandBuffer")); + fp_vkEndCommandBuffer = reinterpret_cast(procAddr(device, "vkEndCommandBuffer")); + fp_vkResetCommandBuffer = reinterpret_cast(procAddr(device, "vkResetCommandBuffer")); + fp_vkCmdBindPipeline = reinterpret_cast(procAddr(device, "vkCmdBindPipeline")); +#if (defined(VK_EXT_attachment_feedback_loop_dynamic_state)) + fp_vkCmdSetAttachmentFeedbackLoopEnableEXT = reinterpret_cast(procAddr(device, "vkCmdSetAttachmentFeedbackLoopEnableEXT")); +#endif + fp_vkCmdSetViewport = reinterpret_cast(procAddr(device, "vkCmdSetViewport")); + fp_vkCmdSetScissor = reinterpret_cast(procAddr(device, "vkCmdSetScissor")); + fp_vkCmdSetLineWidth = reinterpret_cast(procAddr(device, "vkCmdSetLineWidth")); + fp_vkCmdSetDepthBias = reinterpret_cast(procAddr(device, "vkCmdSetDepthBias")); + fp_vkCmdSetBlendConstants = reinterpret_cast(procAddr(device, "vkCmdSetBlendConstants")); + fp_vkCmdSetDepthBounds = reinterpret_cast(procAddr(device, "vkCmdSetDepthBounds")); + fp_vkCmdSetStencilCompareMask = reinterpret_cast(procAddr(device, "vkCmdSetStencilCompareMask")); + fp_vkCmdSetStencilWriteMask = reinterpret_cast(procAddr(device, "vkCmdSetStencilWriteMask")); + fp_vkCmdSetStencilReference = reinterpret_cast(procAddr(device, "vkCmdSetStencilReference")); + fp_vkCmdBindDescriptorSets = reinterpret_cast(procAddr(device, "vkCmdBindDescriptorSets")); + fp_vkCmdBindIndexBuffer = reinterpret_cast(procAddr(device, "vkCmdBindIndexBuffer")); + fp_vkCmdBindVertexBuffers = reinterpret_cast(procAddr(device, "vkCmdBindVertexBuffers")); + fp_vkCmdDraw = reinterpret_cast(procAddr(device, "vkCmdDraw")); + fp_vkCmdDrawIndexed = reinterpret_cast(procAddr(device, "vkCmdDrawIndexed")); +#if (defined(VK_EXT_multi_draw)) + fp_vkCmdDrawMultiEXT = reinterpret_cast(procAddr(device, "vkCmdDrawMultiEXT")); +#endif +#if (defined(VK_EXT_multi_draw)) + fp_vkCmdDrawMultiIndexedEXT = reinterpret_cast(procAddr(device, "vkCmdDrawMultiIndexedEXT")); +#endif + fp_vkCmdDrawIndirect = reinterpret_cast(procAddr(device, "vkCmdDrawIndirect")); + fp_vkCmdDrawIndexedIndirect = reinterpret_cast(procAddr(device, "vkCmdDrawIndexedIndirect")); + fp_vkCmdDispatch = reinterpret_cast(procAddr(device, "vkCmdDispatch")); + fp_vkCmdDispatchIndirect = reinterpret_cast(procAddr(device, "vkCmdDispatchIndirect")); +#if (defined(VK_HUAWEI_subpass_shading)) + fp_vkCmdSubpassShadingHUAWEI = reinterpret_cast(procAddr(device, "vkCmdSubpassShadingHUAWEI")); +#endif +#if (defined(VK_HUAWEI_cluster_culling_shader)) + fp_vkCmdDrawClusterHUAWEI = reinterpret_cast(procAddr(device, "vkCmdDrawClusterHUAWEI")); +#endif +#if (defined(VK_HUAWEI_cluster_culling_shader)) + fp_vkCmdDrawClusterIndirectHUAWEI = reinterpret_cast(procAddr(device, "vkCmdDrawClusterIndirectHUAWEI")); +#endif +#if (defined(VK_NV_device_generated_commands_compute)) + fp_vkCmdUpdatePipelineIndirectBufferNV = reinterpret_cast(procAddr(device, "vkCmdUpdatePipelineIndirectBufferNV")); +#endif + fp_vkCmdCopyBuffer = reinterpret_cast(procAddr(device, "vkCmdCopyBuffer")); + fp_vkCmdCopyImage = reinterpret_cast(procAddr(device, "vkCmdCopyImage")); + fp_vkCmdBlitImage = reinterpret_cast(procAddr(device, "vkCmdBlitImage")); + fp_vkCmdCopyBufferToImage = reinterpret_cast(procAddr(device, "vkCmdCopyBufferToImage")); + fp_vkCmdCopyImageToBuffer = reinterpret_cast(procAddr(device, "vkCmdCopyImageToBuffer")); +#if (defined(VK_NV_copy_memory_indirect)) + fp_vkCmdCopyMemoryIndirectNV = reinterpret_cast(procAddr(device, "vkCmdCopyMemoryIndirectNV")); +#endif +#if (defined(VK_NV_copy_memory_indirect)) + fp_vkCmdCopyMemoryToImageIndirectNV = reinterpret_cast(procAddr(device, "vkCmdCopyMemoryToImageIndirectNV")); +#endif + fp_vkCmdUpdateBuffer = reinterpret_cast(procAddr(device, "vkCmdUpdateBuffer")); + fp_vkCmdFillBuffer = reinterpret_cast(procAddr(device, "vkCmdFillBuffer")); + fp_vkCmdClearColorImage = reinterpret_cast(procAddr(device, "vkCmdClearColorImage")); + fp_vkCmdClearDepthStencilImage = reinterpret_cast(procAddr(device, "vkCmdClearDepthStencilImage")); + fp_vkCmdClearAttachments = reinterpret_cast(procAddr(device, "vkCmdClearAttachments")); + fp_vkCmdResolveImage = reinterpret_cast(procAddr(device, "vkCmdResolveImage")); + fp_vkCmdSetEvent = reinterpret_cast(procAddr(device, "vkCmdSetEvent")); + fp_vkCmdResetEvent = reinterpret_cast(procAddr(device, "vkCmdResetEvent")); + fp_vkCmdWaitEvents = reinterpret_cast(procAddr(device, "vkCmdWaitEvents")); + fp_vkCmdPipelineBarrier = reinterpret_cast(procAddr(device, "vkCmdPipelineBarrier")); + fp_vkCmdBeginQuery = reinterpret_cast(procAddr(device, "vkCmdBeginQuery")); + fp_vkCmdEndQuery = reinterpret_cast(procAddr(device, "vkCmdEndQuery")); +#if (defined(VK_EXT_conditional_rendering)) + fp_vkCmdBeginConditionalRenderingEXT = reinterpret_cast(procAddr(device, "vkCmdBeginConditionalRenderingEXT")); +#endif +#if (defined(VK_EXT_conditional_rendering)) + fp_vkCmdEndConditionalRenderingEXT = reinterpret_cast(procAddr(device, "vkCmdEndConditionalRenderingEXT")); +#endif + fp_vkCmdResetQueryPool = reinterpret_cast(procAddr(device, "vkCmdResetQueryPool")); + fp_vkCmdWriteTimestamp = reinterpret_cast(procAddr(device, "vkCmdWriteTimestamp")); + fp_vkCmdCopyQueryPoolResults = reinterpret_cast(procAddr(device, "vkCmdCopyQueryPoolResults")); + fp_vkCmdPushConstants = reinterpret_cast(procAddr(device, "vkCmdPushConstants")); + fp_vkCmdBeginRenderPass = reinterpret_cast(procAddr(device, "vkCmdBeginRenderPass")); + fp_vkCmdNextSubpass = reinterpret_cast(procAddr(device, "vkCmdNextSubpass")); + fp_vkCmdEndRenderPass = reinterpret_cast(procAddr(device, "vkCmdEndRenderPass")); + fp_vkCmdExecuteCommands = reinterpret_cast(procAddr(device, "vkCmdExecuteCommands")); +#if (defined(VK_KHR_display_swapchain)) + fp_vkCreateSharedSwapchainsKHR = reinterpret_cast(procAddr(device, "vkCreateSharedSwapchainsKHR")); +#endif +#if (defined(VK_KHR_swapchain)) + fp_vkCreateSwapchainKHR = reinterpret_cast(procAddr(device, "vkCreateSwapchainKHR")); +#endif +#if (defined(VK_KHR_swapchain)) + fp_vkDestroySwapchainKHR = reinterpret_cast(procAddr(device, "vkDestroySwapchainKHR")); +#endif +#if (defined(VK_KHR_swapchain)) + fp_vkGetSwapchainImagesKHR = reinterpret_cast(procAddr(device, "vkGetSwapchainImagesKHR")); +#endif +#if (defined(VK_KHR_swapchain)) + fp_vkAcquireNextImageKHR = reinterpret_cast(procAddr(device, "vkAcquireNextImageKHR")); +#endif +#if (defined(VK_KHR_swapchain)) + fp_vkQueuePresentKHR = reinterpret_cast(procAddr(device, "vkQueuePresentKHR")); +#endif +#if (defined(VK_EXT_debug_marker)) + fp_vkDebugMarkerSetObjectNameEXT = reinterpret_cast(procAddr(device, "vkDebugMarkerSetObjectNameEXT")); +#endif +#if (defined(VK_EXT_debug_marker)) + fp_vkDebugMarkerSetObjectTagEXT = reinterpret_cast(procAddr(device, "vkDebugMarkerSetObjectTagEXT")); +#endif +#if (defined(VK_EXT_debug_marker)) + fp_vkCmdDebugMarkerBeginEXT = reinterpret_cast(procAddr(device, "vkCmdDebugMarkerBeginEXT")); +#endif +#if (defined(VK_EXT_debug_marker)) + fp_vkCmdDebugMarkerEndEXT = reinterpret_cast(procAddr(device, "vkCmdDebugMarkerEndEXT")); +#endif +#if (defined(VK_EXT_debug_marker)) + fp_vkCmdDebugMarkerInsertEXT = reinterpret_cast(procAddr(device, "vkCmdDebugMarkerInsertEXT")); +#endif +#if (defined(VK_NV_external_memory_win32)) + fp_vkGetMemoryWin32HandleNV = reinterpret_cast(procAddr(device, "vkGetMemoryWin32HandleNV")); +#endif +#if (defined(VK_NV_device_generated_commands)) + fp_vkCmdExecuteGeneratedCommandsNV = reinterpret_cast(procAddr(device, "vkCmdExecuteGeneratedCommandsNV")); +#endif +#if (defined(VK_NV_device_generated_commands)) + fp_vkCmdPreprocessGeneratedCommandsNV = reinterpret_cast(procAddr(device, "vkCmdPreprocessGeneratedCommandsNV")); +#endif +#if (defined(VK_NV_device_generated_commands)) + fp_vkCmdBindPipelineShaderGroupNV = reinterpret_cast(procAddr(device, "vkCmdBindPipelineShaderGroupNV")); +#endif +#if (defined(VK_NV_device_generated_commands)) + fp_vkGetGeneratedCommandsMemoryRequirementsNV = reinterpret_cast(procAddr(device, "vkGetGeneratedCommandsMemoryRequirementsNV")); +#endif +#if (defined(VK_NV_device_generated_commands)) + fp_vkCreateIndirectCommandsLayoutNV = reinterpret_cast(procAddr(device, "vkCreateIndirectCommandsLayoutNV")); +#endif +#if (defined(VK_NV_device_generated_commands)) + fp_vkDestroyIndirectCommandsLayoutNV = reinterpret_cast(procAddr(device, "vkDestroyIndirectCommandsLayoutNV")); +#endif +#if (defined(VK_KHR_push_descriptor)) + fp_vkCmdPushDescriptorSetKHR = reinterpret_cast(procAddr(device, "vkCmdPushDescriptorSetKHR")); +#endif +#if (defined(VK_VERSION_1_1)) + fp_vkTrimCommandPool = reinterpret_cast(procAddr(device, "vkTrimCommandPool")); +#endif +#if (defined(VK_KHR_external_memory_win32)) + fp_vkGetMemoryWin32HandleKHR = reinterpret_cast(procAddr(device, "vkGetMemoryWin32HandleKHR")); +#endif +#if (defined(VK_KHR_external_memory_win32)) + fp_vkGetMemoryWin32HandlePropertiesKHR = reinterpret_cast(procAddr(device, "vkGetMemoryWin32HandlePropertiesKHR")); +#endif +#if (defined(VK_KHR_external_memory_fd)) + fp_vkGetMemoryFdKHR = reinterpret_cast(procAddr(device, "vkGetMemoryFdKHR")); +#endif +#if (defined(VK_KHR_external_memory_fd)) + fp_vkGetMemoryFdPropertiesKHR = reinterpret_cast(procAddr(device, "vkGetMemoryFdPropertiesKHR")); +#endif +#if (defined(VK_FUCHSIA_external_memory)) + fp_vkGetMemoryZirconHandleFUCHSIA = reinterpret_cast(procAddr(device, "vkGetMemoryZirconHandleFUCHSIA")); +#endif +#if (defined(VK_FUCHSIA_external_memory)) + fp_vkGetMemoryZirconHandlePropertiesFUCHSIA = reinterpret_cast(procAddr(device, "vkGetMemoryZirconHandlePropertiesFUCHSIA")); +#endif +#if (defined(VK_NV_external_memory_rdma)) + fp_vkGetMemoryRemoteAddressNV = reinterpret_cast(procAddr(device, "vkGetMemoryRemoteAddressNV")); +#endif +#if (defined(VK_NV_external_memory_sci_buf)) + fp_vkGetMemorySciBufNV = reinterpret_cast(procAddr(device, "vkGetMemorySciBufNV")); +#endif +#if (defined(VK_KHR_external_semaphore_win32)) + fp_vkGetSemaphoreWin32HandleKHR = reinterpret_cast(procAddr(device, "vkGetSemaphoreWin32HandleKHR")); +#endif +#if (defined(VK_KHR_external_semaphore_win32)) + fp_vkImportSemaphoreWin32HandleKHR = reinterpret_cast(procAddr(device, "vkImportSemaphoreWin32HandleKHR")); +#endif +#if (defined(VK_KHR_external_semaphore_fd)) + fp_vkGetSemaphoreFdKHR = reinterpret_cast(procAddr(device, "vkGetSemaphoreFdKHR")); +#endif +#if (defined(VK_KHR_external_semaphore_fd)) + fp_vkImportSemaphoreFdKHR = reinterpret_cast(procAddr(device, "vkImportSemaphoreFdKHR")); +#endif +#if (defined(VK_FUCHSIA_external_semaphore)) + fp_vkGetSemaphoreZirconHandleFUCHSIA = reinterpret_cast(procAddr(device, "vkGetSemaphoreZirconHandleFUCHSIA")); +#endif +#if (defined(VK_FUCHSIA_external_semaphore)) + fp_vkImportSemaphoreZirconHandleFUCHSIA = reinterpret_cast(procAddr(device, "vkImportSemaphoreZirconHandleFUCHSIA")); +#endif +#if (defined(VK_KHR_external_fence_win32)) + fp_vkGetFenceWin32HandleKHR = reinterpret_cast(procAddr(device, "vkGetFenceWin32HandleKHR")); +#endif +#if (defined(VK_KHR_external_fence_win32)) + fp_vkImportFenceWin32HandleKHR = reinterpret_cast(procAddr(device, "vkImportFenceWin32HandleKHR")); +#endif +#if (defined(VK_KHR_external_fence_fd)) + fp_vkGetFenceFdKHR = reinterpret_cast(procAddr(device, "vkGetFenceFdKHR")); +#endif +#if (defined(VK_KHR_external_fence_fd)) + fp_vkImportFenceFdKHR = reinterpret_cast(procAddr(device, "vkImportFenceFdKHR")); +#endif +#if (defined(VK_NV_external_sci_sync)) || (defined(VK_NV_external_sci_sync2)) + fp_vkGetFenceSciSyncFenceNV = reinterpret_cast(procAddr(device, "vkGetFenceSciSyncFenceNV")); +#endif +#if (defined(VK_NV_external_sci_sync)) || (defined(VK_NV_external_sci_sync2)) + fp_vkGetFenceSciSyncObjNV = reinterpret_cast(procAddr(device, "vkGetFenceSciSyncObjNV")); +#endif +#if (defined(VK_NV_external_sci_sync)) || (defined(VK_NV_external_sci_sync2)) + fp_vkImportFenceSciSyncFenceNV = reinterpret_cast(procAddr(device, "vkImportFenceSciSyncFenceNV")); +#endif +#if (defined(VK_NV_external_sci_sync)) || (defined(VK_NV_external_sci_sync2)) + fp_vkImportFenceSciSyncObjNV = reinterpret_cast(procAddr(device, "vkImportFenceSciSyncObjNV")); +#endif +#if (defined(VK_NV_external_sci_sync)) + fp_vkGetSemaphoreSciSyncObjNV = reinterpret_cast(procAddr(device, "vkGetSemaphoreSciSyncObjNV")); +#endif +#if (defined(VK_NV_external_sci_sync)) + fp_vkImportSemaphoreSciSyncObjNV = reinterpret_cast(procAddr(device, "vkImportSemaphoreSciSyncObjNV")); +#endif +#if (defined(VK_NV_external_sci_sync2)) + fp_vkCreateSemaphoreSciSyncPoolNV = reinterpret_cast(procAddr(device, "vkCreateSemaphoreSciSyncPoolNV")); +#endif +#if (defined(VK_NV_external_sci_sync2)) + fp_vkDestroySemaphoreSciSyncPoolNV = reinterpret_cast(procAddr(device, "vkDestroySemaphoreSciSyncPoolNV")); +#endif +#if (defined(VK_EXT_display_control)) + fp_vkDisplayPowerControlEXT = reinterpret_cast(procAddr(device, "vkDisplayPowerControlEXT")); +#endif +#if (defined(VK_EXT_display_control)) + fp_vkRegisterDeviceEventEXT = reinterpret_cast(procAddr(device, "vkRegisterDeviceEventEXT")); +#endif +#if (defined(VK_EXT_display_control)) + fp_vkRegisterDisplayEventEXT = reinterpret_cast(procAddr(device, "vkRegisterDisplayEventEXT")); +#endif +#if (defined(VK_EXT_display_control)) + fp_vkGetSwapchainCounterEXT = reinterpret_cast(procAddr(device, "vkGetSwapchainCounterEXT")); +#endif +#if (defined(VK_VERSION_1_1)) + fp_vkGetDeviceGroupPeerMemoryFeatures = reinterpret_cast(procAddr(device, "vkGetDeviceGroupPeerMemoryFeatures")); +#endif +#if (defined(VK_VERSION_1_1)) + fp_vkBindBufferMemory2 = reinterpret_cast(procAddr(device, "vkBindBufferMemory2")); +#endif +#if (defined(VK_VERSION_1_1)) + fp_vkBindImageMemory2 = reinterpret_cast(procAddr(device, "vkBindImageMemory2")); +#endif +#if (defined(VK_VERSION_1_1)) + fp_vkCmdSetDeviceMask = reinterpret_cast(procAddr(device, "vkCmdSetDeviceMask")); +#endif +#if (defined(VK_KHR_swapchain)) || (defined(VK_KHR_device_group)) + fp_vkGetDeviceGroupPresentCapabilitiesKHR = reinterpret_cast(procAddr(device, "vkGetDeviceGroupPresentCapabilitiesKHR")); +#endif +#if (defined(VK_KHR_swapchain)) || (defined(VK_KHR_device_group)) + fp_vkGetDeviceGroupSurfacePresentModesKHR = reinterpret_cast(procAddr(device, "vkGetDeviceGroupSurfacePresentModesKHR")); +#endif +#if (defined(VK_KHR_swapchain)) || (defined(VK_KHR_device_group)) + fp_vkAcquireNextImage2KHR = reinterpret_cast(procAddr(device, "vkAcquireNextImage2KHR")); +#endif +#if (defined(VK_VERSION_1_1)) + fp_vkCmdDispatchBase = reinterpret_cast(procAddr(device, "vkCmdDispatchBase")); +#endif +#if (defined(VK_VERSION_1_1)) + fp_vkCreateDescriptorUpdateTemplate = reinterpret_cast(procAddr(device, "vkCreateDescriptorUpdateTemplate")); +#endif +#if (defined(VK_VERSION_1_1)) + fp_vkDestroyDescriptorUpdateTemplate = reinterpret_cast(procAddr(device, "vkDestroyDescriptorUpdateTemplate")); +#endif +#if (defined(VK_VERSION_1_1)) + fp_vkUpdateDescriptorSetWithTemplate = reinterpret_cast(procAddr(device, "vkUpdateDescriptorSetWithTemplate")); +#endif +#if (defined(VK_KHR_push_descriptor)) || (defined(VK_KHR_descriptor_update_template)) + fp_vkCmdPushDescriptorSetWithTemplateKHR = reinterpret_cast(procAddr(device, "vkCmdPushDescriptorSetWithTemplateKHR")); +#endif +#if (defined(VK_EXT_hdr_metadata)) + fp_vkSetHdrMetadataEXT = reinterpret_cast(procAddr(device, "vkSetHdrMetadataEXT")); +#endif +#if (defined(VK_KHR_shared_presentable_image)) + fp_vkGetSwapchainStatusKHR = reinterpret_cast(procAddr(device, "vkGetSwapchainStatusKHR")); +#endif +#if (defined(VK_GOOGLE_display_timing)) + fp_vkGetRefreshCycleDurationGOOGLE = reinterpret_cast(procAddr(device, "vkGetRefreshCycleDurationGOOGLE")); +#endif +#if (defined(VK_GOOGLE_display_timing)) + fp_vkGetPastPresentationTimingGOOGLE = reinterpret_cast(procAddr(device, "vkGetPastPresentationTimingGOOGLE")); +#endif +#if (defined(VK_NV_clip_space_w_scaling)) + fp_vkCmdSetViewportWScalingNV = reinterpret_cast(procAddr(device, "vkCmdSetViewportWScalingNV")); +#endif +#if (defined(VK_EXT_discard_rectangles)) + fp_vkCmdSetDiscardRectangleEXT = reinterpret_cast(procAddr(device, "vkCmdSetDiscardRectangleEXT")); +#endif +#if ((defined(VK_EXT_discard_rectangles))) && VK_HEADER_VERSION >= 241 + fp_vkCmdSetDiscardRectangleEnableEXT = reinterpret_cast(procAddr(device, "vkCmdSetDiscardRectangleEnableEXT")); +#endif +#if ((defined(VK_EXT_discard_rectangles))) && VK_HEADER_VERSION >= 241 + fp_vkCmdSetDiscardRectangleModeEXT = reinterpret_cast(procAddr(device, "vkCmdSetDiscardRectangleModeEXT")); +#endif +#if (defined(VK_EXT_sample_locations)) + fp_vkCmdSetSampleLocationsEXT = reinterpret_cast(procAddr(device, "vkCmdSetSampleLocationsEXT")); +#endif +#if (defined(VK_VERSION_1_1)) + fp_vkGetBufferMemoryRequirements2 = reinterpret_cast(procAddr(device, "vkGetBufferMemoryRequirements2")); +#endif +#if (defined(VK_VERSION_1_1)) + fp_vkGetImageMemoryRequirements2 = reinterpret_cast(procAddr(device, "vkGetImageMemoryRequirements2")); +#endif +#if (defined(VK_VERSION_1_1)) + fp_vkGetImageSparseMemoryRequirements2 = reinterpret_cast(procAddr(device, "vkGetImageSparseMemoryRequirements2")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkGetDeviceBufferMemoryRequirements = reinterpret_cast(procAddr(device, "vkGetDeviceBufferMemoryRequirements")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkGetDeviceImageMemoryRequirements = reinterpret_cast(procAddr(device, "vkGetDeviceImageMemoryRequirements")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkGetDeviceImageSparseMemoryRequirements = reinterpret_cast(procAddr(device, "vkGetDeviceImageSparseMemoryRequirements")); +#endif +#if (defined(VK_VERSION_1_1)) + fp_vkCreateSamplerYcbcrConversion = reinterpret_cast(procAddr(device, "vkCreateSamplerYcbcrConversion")); +#endif +#if (defined(VK_VERSION_1_1)) + fp_vkDestroySamplerYcbcrConversion = reinterpret_cast(procAddr(device, "vkDestroySamplerYcbcrConversion")); +#endif +#if (defined(VK_VERSION_1_1)) + fp_vkGetDeviceQueue2 = reinterpret_cast(procAddr(device, "vkGetDeviceQueue2")); +#endif +#if (defined(VK_EXT_validation_cache)) + fp_vkCreateValidationCacheEXT = reinterpret_cast(procAddr(device, "vkCreateValidationCacheEXT")); +#endif +#if (defined(VK_EXT_validation_cache)) + fp_vkDestroyValidationCacheEXT = reinterpret_cast(procAddr(device, "vkDestroyValidationCacheEXT")); +#endif +#if (defined(VK_EXT_validation_cache)) + fp_vkGetValidationCacheDataEXT = reinterpret_cast(procAddr(device, "vkGetValidationCacheDataEXT")); +#endif +#if (defined(VK_EXT_validation_cache)) + fp_vkMergeValidationCachesEXT = reinterpret_cast(procAddr(device, "vkMergeValidationCachesEXT")); +#endif +#if (defined(VK_VERSION_1_1)) + fp_vkGetDescriptorSetLayoutSupport = reinterpret_cast(procAddr(device, "vkGetDescriptorSetLayoutSupport")); +#endif +#if (defined(VK_ANDROID_native_buffer)) + fp_vkGetSwapchainGrallocUsageANDROID = reinterpret_cast(procAddr(device, "vkGetSwapchainGrallocUsageANDROID")); +#endif +#if (defined(VK_ANDROID_native_buffer)) + fp_vkGetSwapchainGrallocUsage2ANDROID = reinterpret_cast(procAddr(device, "vkGetSwapchainGrallocUsage2ANDROID")); +#endif +#if (defined(VK_ANDROID_native_buffer)) + fp_vkAcquireImageANDROID = reinterpret_cast(procAddr(device, "vkAcquireImageANDROID")); +#endif +#if (defined(VK_ANDROID_native_buffer)) + fp_vkQueueSignalReleaseImageANDROID = reinterpret_cast(procAddr(device, "vkQueueSignalReleaseImageANDROID")); +#endif +#if (defined(VK_AMD_shader_info)) + fp_vkGetShaderInfoAMD = reinterpret_cast(procAddr(device, "vkGetShaderInfoAMD")); +#endif +#if (defined(VK_AMD_display_native_hdr)) + fp_vkSetLocalDimmingAMD = reinterpret_cast(procAddr(device, "vkSetLocalDimmingAMD")); +#endif +#if (defined(VK_KHR_calibrated_timestamps)) + fp_vkGetCalibratedTimestampsKHR = reinterpret_cast(procAddr(device, "vkGetCalibratedTimestampsKHR")); +#endif +#if (defined(VK_EXT_debug_utils)) + fp_vkSetDebugUtilsObjectNameEXT = reinterpret_cast(procAddr(device, "vkSetDebugUtilsObjectNameEXT")); +#endif +#if (defined(VK_EXT_debug_utils)) + fp_vkSetDebugUtilsObjectTagEXT = reinterpret_cast(procAddr(device, "vkSetDebugUtilsObjectTagEXT")); +#endif +#if (defined(VK_EXT_debug_utils)) + fp_vkQueueBeginDebugUtilsLabelEXT = reinterpret_cast(procAddr(device, "vkQueueBeginDebugUtilsLabelEXT")); +#endif +#if (defined(VK_EXT_debug_utils)) + fp_vkQueueEndDebugUtilsLabelEXT = reinterpret_cast(procAddr(device, "vkQueueEndDebugUtilsLabelEXT")); +#endif +#if (defined(VK_EXT_debug_utils)) + fp_vkQueueInsertDebugUtilsLabelEXT = reinterpret_cast(procAddr(device, "vkQueueInsertDebugUtilsLabelEXT")); +#endif +#if (defined(VK_EXT_debug_utils)) + fp_vkCmdBeginDebugUtilsLabelEXT = reinterpret_cast(procAddr(device, "vkCmdBeginDebugUtilsLabelEXT")); +#endif +#if (defined(VK_EXT_debug_utils)) + fp_vkCmdEndDebugUtilsLabelEXT = reinterpret_cast(procAddr(device, "vkCmdEndDebugUtilsLabelEXT")); +#endif +#if (defined(VK_EXT_debug_utils)) + fp_vkCmdInsertDebugUtilsLabelEXT = reinterpret_cast(procAddr(device, "vkCmdInsertDebugUtilsLabelEXT")); +#endif +#if (defined(VK_EXT_external_memory_host)) + fp_vkGetMemoryHostPointerPropertiesEXT = reinterpret_cast(procAddr(device, "vkGetMemoryHostPointerPropertiesEXT")); +#endif +#if (defined(VK_AMD_buffer_marker)) + fp_vkCmdWriteBufferMarkerAMD = reinterpret_cast(procAddr(device, "vkCmdWriteBufferMarkerAMD")); +#endif +#if (defined(VK_VERSION_1_2)) + fp_vkCreateRenderPass2 = reinterpret_cast(procAddr(device, "vkCreateRenderPass2")); +#endif +#if (defined(VK_VERSION_1_2)) + fp_vkCmdBeginRenderPass2 = reinterpret_cast(procAddr(device, "vkCmdBeginRenderPass2")); +#endif +#if (defined(VK_VERSION_1_2)) + fp_vkCmdNextSubpass2 = reinterpret_cast(procAddr(device, "vkCmdNextSubpass2")); +#endif +#if (defined(VK_VERSION_1_2)) + fp_vkCmdEndRenderPass2 = reinterpret_cast(procAddr(device, "vkCmdEndRenderPass2")); +#endif +#if (defined(VK_VERSION_1_2)) + fp_vkGetSemaphoreCounterValue = reinterpret_cast(procAddr(device, "vkGetSemaphoreCounterValue")); +#endif +#if (defined(VK_VERSION_1_2)) + fp_vkWaitSemaphores = reinterpret_cast(procAddr(device, "vkWaitSemaphores")); +#endif +#if (defined(VK_VERSION_1_2)) + fp_vkSignalSemaphore = reinterpret_cast(procAddr(device, "vkSignalSemaphore")); +#endif +#if (defined(VK_ANDROID_external_memory_android_hardware_buffer)) + fp_vkGetAndroidHardwareBufferPropertiesANDROID = reinterpret_cast(procAddr(device, "vkGetAndroidHardwareBufferPropertiesANDROID")); +#endif +#if (defined(VK_ANDROID_external_memory_android_hardware_buffer)) + fp_vkGetMemoryAndroidHardwareBufferANDROID = reinterpret_cast(procAddr(device, "vkGetMemoryAndroidHardwareBufferANDROID")); +#endif +#if (defined(VK_VERSION_1_2)) + fp_vkCmdDrawIndirectCount = reinterpret_cast(procAddr(device, "vkCmdDrawIndirectCount")); +#endif +#if (defined(VK_VERSION_1_2)) + fp_vkCmdDrawIndexedIndirectCount = reinterpret_cast(procAddr(device, "vkCmdDrawIndexedIndirectCount")); +#endif +#if (defined(VK_NV_device_diagnostic_checkpoints)) + fp_vkCmdSetCheckpointNV = reinterpret_cast(procAddr(device, "vkCmdSetCheckpointNV")); +#endif +#if (defined(VK_NV_device_diagnostic_checkpoints)) + fp_vkGetQueueCheckpointDataNV = reinterpret_cast(procAddr(device, "vkGetQueueCheckpointDataNV")); +#endif +#if (defined(VK_EXT_transform_feedback)) + fp_vkCmdBindTransformFeedbackBuffersEXT = reinterpret_cast(procAddr(device, "vkCmdBindTransformFeedbackBuffersEXT")); +#endif +#if (defined(VK_EXT_transform_feedback)) + fp_vkCmdBeginTransformFeedbackEXT = reinterpret_cast(procAddr(device, "vkCmdBeginTransformFeedbackEXT")); +#endif +#if (defined(VK_EXT_transform_feedback)) + fp_vkCmdEndTransformFeedbackEXT = reinterpret_cast(procAddr(device, "vkCmdEndTransformFeedbackEXT")); +#endif +#if (defined(VK_EXT_transform_feedback)) + fp_vkCmdBeginQueryIndexedEXT = reinterpret_cast(procAddr(device, "vkCmdBeginQueryIndexedEXT")); +#endif +#if (defined(VK_EXT_transform_feedback)) + fp_vkCmdEndQueryIndexedEXT = reinterpret_cast(procAddr(device, "vkCmdEndQueryIndexedEXT")); +#endif +#if (defined(VK_EXT_transform_feedback)) + fp_vkCmdDrawIndirectByteCountEXT = reinterpret_cast(procAddr(device, "vkCmdDrawIndirectByteCountEXT")); +#endif +#if (defined(VK_NV_scissor_exclusive)) + fp_vkCmdSetExclusiveScissorNV = reinterpret_cast(procAddr(device, "vkCmdSetExclusiveScissorNV")); +#endif +#if ((defined(VK_NV_scissor_exclusive))) && VK_HEADER_VERSION >= 241 + fp_vkCmdSetExclusiveScissorEnableNV = reinterpret_cast(procAddr(device, "vkCmdSetExclusiveScissorEnableNV")); +#endif +#if (defined(VK_NV_shading_rate_image)) + fp_vkCmdBindShadingRateImageNV = reinterpret_cast(procAddr(device, "vkCmdBindShadingRateImageNV")); +#endif +#if (defined(VK_NV_shading_rate_image)) + fp_vkCmdSetViewportShadingRatePaletteNV = reinterpret_cast(procAddr(device, "vkCmdSetViewportShadingRatePaletteNV")); +#endif +#if (defined(VK_NV_shading_rate_image)) + fp_vkCmdSetCoarseSampleOrderNV = reinterpret_cast(procAddr(device, "vkCmdSetCoarseSampleOrderNV")); +#endif +#if (defined(VK_NV_mesh_shader)) + fp_vkCmdDrawMeshTasksNV = reinterpret_cast(procAddr(device, "vkCmdDrawMeshTasksNV")); +#endif +#if (defined(VK_NV_mesh_shader)) + fp_vkCmdDrawMeshTasksIndirectNV = reinterpret_cast(procAddr(device, "vkCmdDrawMeshTasksIndirectNV")); +#endif +#if (defined(VK_NV_mesh_shader)) + fp_vkCmdDrawMeshTasksIndirectCountNV = reinterpret_cast(procAddr(device, "vkCmdDrawMeshTasksIndirectCountNV")); +#endif +#if (defined(VK_EXT_mesh_shader)) + fp_vkCmdDrawMeshTasksEXT = reinterpret_cast(procAddr(device, "vkCmdDrawMeshTasksEXT")); +#endif +#if (defined(VK_EXT_mesh_shader)) + fp_vkCmdDrawMeshTasksIndirectEXT = reinterpret_cast(procAddr(device, "vkCmdDrawMeshTasksIndirectEXT")); +#endif +#if (defined(VK_EXT_mesh_shader)) + fp_vkCmdDrawMeshTasksIndirectCountEXT = reinterpret_cast(procAddr(device, "vkCmdDrawMeshTasksIndirectCountEXT")); +#endif +#if (defined(VK_NV_ray_tracing)) + fp_vkCompileDeferredNV = reinterpret_cast(procAddr(device, "vkCompileDeferredNV")); +#endif +#if (defined(VK_NV_ray_tracing)) + fp_vkCreateAccelerationStructureNV = reinterpret_cast(procAddr(device, "vkCreateAccelerationStructureNV")); +#endif +#if (defined(VK_HUAWEI_invocation_mask)) + fp_vkCmdBindInvocationMaskHUAWEI = reinterpret_cast(procAddr(device, "vkCmdBindInvocationMaskHUAWEI")); +#endif +#if (defined(VK_KHR_acceleration_structure)) + fp_vkDestroyAccelerationStructureKHR = reinterpret_cast(procAddr(device, "vkDestroyAccelerationStructureKHR")); +#endif +#if (defined(VK_NV_ray_tracing)) + fp_vkDestroyAccelerationStructureNV = reinterpret_cast(procAddr(device, "vkDestroyAccelerationStructureNV")); +#endif +#if (defined(VK_NV_ray_tracing)) + fp_vkGetAccelerationStructureMemoryRequirementsNV = reinterpret_cast(procAddr(device, "vkGetAccelerationStructureMemoryRequirementsNV")); +#endif +#if (defined(VK_NV_ray_tracing)) + fp_vkBindAccelerationStructureMemoryNV = reinterpret_cast(procAddr(device, "vkBindAccelerationStructureMemoryNV")); +#endif +#if (defined(VK_NV_ray_tracing)) + fp_vkCmdCopyAccelerationStructureNV = reinterpret_cast(procAddr(device, "vkCmdCopyAccelerationStructureNV")); +#endif +#if (defined(VK_KHR_acceleration_structure)) + fp_vkCmdCopyAccelerationStructureKHR = reinterpret_cast(procAddr(device, "vkCmdCopyAccelerationStructureKHR")); +#endif +#if (defined(VK_KHR_acceleration_structure)) + fp_vkCopyAccelerationStructureKHR = reinterpret_cast(procAddr(device, "vkCopyAccelerationStructureKHR")); +#endif +#if (defined(VK_KHR_acceleration_structure)) + fp_vkCmdCopyAccelerationStructureToMemoryKHR = reinterpret_cast(procAddr(device, "vkCmdCopyAccelerationStructureToMemoryKHR")); +#endif +#if (defined(VK_KHR_acceleration_structure)) + fp_vkCopyAccelerationStructureToMemoryKHR = reinterpret_cast(procAddr(device, "vkCopyAccelerationStructureToMemoryKHR")); +#endif +#if (defined(VK_KHR_acceleration_structure)) + fp_vkCmdCopyMemoryToAccelerationStructureKHR = reinterpret_cast(procAddr(device, "vkCmdCopyMemoryToAccelerationStructureKHR")); +#endif +#if (defined(VK_KHR_acceleration_structure)) + fp_vkCopyMemoryToAccelerationStructureKHR = reinterpret_cast(procAddr(device, "vkCopyMemoryToAccelerationStructureKHR")); +#endif +#if (defined(VK_KHR_acceleration_structure)) + fp_vkCmdWriteAccelerationStructuresPropertiesKHR = reinterpret_cast(procAddr(device, "vkCmdWriteAccelerationStructuresPropertiesKHR")); +#endif +#if (defined(VK_NV_ray_tracing)) + fp_vkCmdWriteAccelerationStructuresPropertiesNV = reinterpret_cast(procAddr(device, "vkCmdWriteAccelerationStructuresPropertiesNV")); +#endif +#if (defined(VK_NV_ray_tracing)) + fp_vkCmdBuildAccelerationStructureNV = reinterpret_cast(procAddr(device, "vkCmdBuildAccelerationStructureNV")); +#endif +#if (defined(VK_KHR_acceleration_structure)) + fp_vkWriteAccelerationStructuresPropertiesKHR = reinterpret_cast(procAddr(device, "vkWriteAccelerationStructuresPropertiesKHR")); +#endif +#if (defined(VK_KHR_ray_tracing_pipeline)) + fp_vkCmdTraceRaysKHR = reinterpret_cast(procAddr(device, "vkCmdTraceRaysKHR")); +#endif +#if (defined(VK_NV_ray_tracing)) + fp_vkCmdTraceRaysNV = reinterpret_cast(procAddr(device, "vkCmdTraceRaysNV")); +#endif +#if (defined(VK_KHR_ray_tracing_pipeline)) + fp_vkGetRayTracingShaderGroupHandlesKHR = reinterpret_cast(procAddr(device, "vkGetRayTracingShaderGroupHandlesKHR")); +#endif +#if (defined(VK_KHR_ray_tracing_pipeline)) + fp_vkGetRayTracingCaptureReplayShaderGroupHandlesKHR = reinterpret_cast(procAddr(device, "vkGetRayTracingCaptureReplayShaderGroupHandlesKHR")); +#endif +#if (defined(VK_NV_ray_tracing)) + fp_vkGetAccelerationStructureHandleNV = reinterpret_cast(procAddr(device, "vkGetAccelerationStructureHandleNV")); +#endif +#if (defined(VK_NV_ray_tracing)) + fp_vkCreateRayTracingPipelinesNV = reinterpret_cast(procAddr(device, "vkCreateRayTracingPipelinesNV")); +#endif +#if (defined(VK_KHR_ray_tracing_pipeline)) + fp_vkCreateRayTracingPipelinesKHR = reinterpret_cast(procAddr(device, "vkCreateRayTracingPipelinesKHR")); +#endif +#if (defined(VK_KHR_ray_tracing_pipeline)) + fp_vkCmdTraceRaysIndirectKHR = reinterpret_cast(procAddr(device, "vkCmdTraceRaysIndirectKHR")); +#endif +#if (defined(VK_KHR_ray_tracing_maintenance1)) + fp_vkCmdTraceRaysIndirect2KHR = reinterpret_cast(procAddr(device, "vkCmdTraceRaysIndirect2KHR")); +#endif +#if (defined(VK_KHR_acceleration_structure)) + fp_vkGetDeviceAccelerationStructureCompatibilityKHR = reinterpret_cast(procAddr(device, "vkGetDeviceAccelerationStructureCompatibilityKHR")); +#endif +#if (defined(VK_KHR_ray_tracing_pipeline)) + fp_vkGetRayTracingShaderGroupStackSizeKHR = reinterpret_cast(procAddr(device, "vkGetRayTracingShaderGroupStackSizeKHR")); +#endif +#if (defined(VK_KHR_ray_tracing_pipeline)) + fp_vkCmdSetRayTracingPipelineStackSizeKHR = reinterpret_cast(procAddr(device, "vkCmdSetRayTracingPipelineStackSizeKHR")); +#endif +#if (defined(VK_EXT_full_screen_exclusive)) + fp_vkGetDeviceGroupSurfacePresentModes2EXT = reinterpret_cast(procAddr(device, "vkGetDeviceGroupSurfacePresentModes2EXT")); +#endif +#if (defined(VK_EXT_full_screen_exclusive)) + fp_vkAcquireFullScreenExclusiveModeEXT = reinterpret_cast(procAddr(device, "vkAcquireFullScreenExclusiveModeEXT")); +#endif +#if (defined(VK_EXT_full_screen_exclusive)) + fp_vkReleaseFullScreenExclusiveModeEXT = reinterpret_cast(procAddr(device, "vkReleaseFullScreenExclusiveModeEXT")); +#endif +#if (defined(VK_KHR_performance_query)) + fp_vkAcquireProfilingLockKHR = reinterpret_cast(procAddr(device, "vkAcquireProfilingLockKHR")); +#endif +#if (defined(VK_KHR_performance_query)) + fp_vkReleaseProfilingLockKHR = reinterpret_cast(procAddr(device, "vkReleaseProfilingLockKHR")); +#endif +#if (defined(VK_EXT_image_drm_format_modifier)) + fp_vkGetImageDrmFormatModifierPropertiesEXT = reinterpret_cast(procAddr(device, "vkGetImageDrmFormatModifierPropertiesEXT")); +#endif +#if (defined(VK_VERSION_1_2)) + fp_vkGetBufferOpaqueCaptureAddress = reinterpret_cast(procAddr(device, "vkGetBufferOpaqueCaptureAddress")); +#endif +#if (defined(VK_VERSION_1_2)) + fp_vkGetBufferDeviceAddress = reinterpret_cast(procAddr(device, "vkGetBufferDeviceAddress")); +#endif +#if (defined(VK_INTEL_performance_query)) + fp_vkInitializePerformanceApiINTEL = reinterpret_cast(procAddr(device, "vkInitializePerformanceApiINTEL")); +#endif +#if (defined(VK_INTEL_performance_query)) + fp_vkUninitializePerformanceApiINTEL = reinterpret_cast(procAddr(device, "vkUninitializePerformanceApiINTEL")); +#endif +#if (defined(VK_INTEL_performance_query)) + fp_vkCmdSetPerformanceMarkerINTEL = reinterpret_cast(procAddr(device, "vkCmdSetPerformanceMarkerINTEL")); +#endif +#if (defined(VK_INTEL_performance_query)) + fp_vkCmdSetPerformanceStreamMarkerINTEL = reinterpret_cast(procAddr(device, "vkCmdSetPerformanceStreamMarkerINTEL")); +#endif +#if (defined(VK_INTEL_performance_query)) + fp_vkCmdSetPerformanceOverrideINTEL = reinterpret_cast(procAddr(device, "vkCmdSetPerformanceOverrideINTEL")); +#endif +#if (defined(VK_INTEL_performance_query)) + fp_vkAcquirePerformanceConfigurationINTEL = reinterpret_cast(procAddr(device, "vkAcquirePerformanceConfigurationINTEL")); +#endif +#if (defined(VK_INTEL_performance_query)) + fp_vkReleasePerformanceConfigurationINTEL = reinterpret_cast(procAddr(device, "vkReleasePerformanceConfigurationINTEL")); +#endif +#if (defined(VK_INTEL_performance_query)) + fp_vkQueueSetPerformanceConfigurationINTEL = reinterpret_cast(procAddr(device, "vkQueueSetPerformanceConfigurationINTEL")); +#endif +#if (defined(VK_INTEL_performance_query)) + fp_vkGetPerformanceParameterINTEL = reinterpret_cast(procAddr(device, "vkGetPerformanceParameterINTEL")); +#endif +#if (defined(VK_VERSION_1_2)) + fp_vkGetDeviceMemoryOpaqueCaptureAddress = reinterpret_cast(procAddr(device, "vkGetDeviceMemoryOpaqueCaptureAddress")); +#endif +#if (defined(VK_KHR_pipeline_executable_properties)) + fp_vkGetPipelineExecutablePropertiesKHR = reinterpret_cast(procAddr(device, "vkGetPipelineExecutablePropertiesKHR")); +#endif +#if (defined(VK_KHR_pipeline_executable_properties)) + fp_vkGetPipelineExecutableStatisticsKHR = reinterpret_cast(procAddr(device, "vkGetPipelineExecutableStatisticsKHR")); +#endif +#if (defined(VK_KHR_pipeline_executable_properties)) + fp_vkGetPipelineExecutableInternalRepresentationsKHR = reinterpret_cast(procAddr(device, "vkGetPipelineExecutableInternalRepresentationsKHR")); +#endif +#if (defined(VK_KHR_line_rasterization)) + fp_vkCmdSetLineStippleKHR = reinterpret_cast(procAddr(device, "vkCmdSetLineStippleKHR")); +#endif +#if (defined(VKSC_VERSION_1_0)) + fp_vkGetFaultData = reinterpret_cast(procAddr(device, "vkGetFaultData")); +#endif +#if (defined(VK_KHR_acceleration_structure)) + fp_vkCreateAccelerationStructureKHR = reinterpret_cast(procAddr(device, "vkCreateAccelerationStructureKHR")); +#endif +#if (defined(VK_KHR_acceleration_structure)) + fp_vkCmdBuildAccelerationStructuresKHR = reinterpret_cast(procAddr(device, "vkCmdBuildAccelerationStructuresKHR")); +#endif +#if (defined(VK_KHR_acceleration_structure)) + fp_vkCmdBuildAccelerationStructuresIndirectKHR = reinterpret_cast(procAddr(device, "vkCmdBuildAccelerationStructuresIndirectKHR")); +#endif +#if (defined(VK_KHR_acceleration_structure)) + fp_vkBuildAccelerationStructuresKHR = reinterpret_cast(procAddr(device, "vkBuildAccelerationStructuresKHR")); +#endif +#if (defined(VK_KHR_acceleration_structure)) + fp_vkGetAccelerationStructureDeviceAddressKHR = reinterpret_cast(procAddr(device, "vkGetAccelerationStructureDeviceAddressKHR")); +#endif +#if (defined(VK_KHR_deferred_host_operations)) + fp_vkCreateDeferredOperationKHR = reinterpret_cast(procAddr(device, "vkCreateDeferredOperationKHR")); +#endif +#if (defined(VK_KHR_deferred_host_operations)) + fp_vkDestroyDeferredOperationKHR = reinterpret_cast(procAddr(device, "vkDestroyDeferredOperationKHR")); +#endif +#if (defined(VK_KHR_deferred_host_operations)) + fp_vkGetDeferredOperationMaxConcurrencyKHR = reinterpret_cast(procAddr(device, "vkGetDeferredOperationMaxConcurrencyKHR")); +#endif +#if (defined(VK_KHR_deferred_host_operations)) + fp_vkGetDeferredOperationResultKHR = reinterpret_cast(procAddr(device, "vkGetDeferredOperationResultKHR")); +#endif +#if (defined(VK_KHR_deferred_host_operations)) + fp_vkDeferredOperationJoinKHR = reinterpret_cast(procAddr(device, "vkDeferredOperationJoinKHR")); +#endif +#if (defined(VK_NV_device_generated_commands_compute)) + fp_vkGetPipelineIndirectMemoryRequirementsNV = reinterpret_cast(procAddr(device, "vkGetPipelineIndirectMemoryRequirementsNV")); +#endif +#if (defined(VK_NV_device_generated_commands_compute)) + fp_vkGetPipelineIndirectDeviceAddressNV = reinterpret_cast(procAddr(device, "vkGetPipelineIndirectDeviceAddressNV")); +#endif +#if (defined(VK_AMD_anti_lag)) + fp_vkAntiLagUpdateAMD = reinterpret_cast(procAddr(device, "vkAntiLagUpdateAMD")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdSetCullMode = reinterpret_cast(procAddr(device, "vkCmdSetCullMode")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdSetFrontFace = reinterpret_cast(procAddr(device, "vkCmdSetFrontFace")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdSetPrimitiveTopology = reinterpret_cast(procAddr(device, "vkCmdSetPrimitiveTopology")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdSetViewportWithCount = reinterpret_cast(procAddr(device, "vkCmdSetViewportWithCount")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdSetScissorWithCount = reinterpret_cast(procAddr(device, "vkCmdSetScissorWithCount")); +#endif +#if (defined(VK_KHR_maintenance5)) + fp_vkCmdBindIndexBuffer2KHR = reinterpret_cast(procAddr(device, "vkCmdBindIndexBuffer2KHR")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdBindVertexBuffers2 = reinterpret_cast(procAddr(device, "vkCmdBindVertexBuffers2")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdSetDepthTestEnable = reinterpret_cast(procAddr(device, "vkCmdSetDepthTestEnable")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdSetDepthWriteEnable = reinterpret_cast(procAddr(device, "vkCmdSetDepthWriteEnable")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdSetDepthCompareOp = reinterpret_cast(procAddr(device, "vkCmdSetDepthCompareOp")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdSetDepthBoundsTestEnable = reinterpret_cast(procAddr(device, "vkCmdSetDepthBoundsTestEnable")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdSetStencilTestEnable = reinterpret_cast(procAddr(device, "vkCmdSetStencilTestEnable")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdSetStencilOp = reinterpret_cast(procAddr(device, "vkCmdSetStencilOp")); +#endif +#if (defined(VK_EXT_extended_dynamic_state2)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetPatchControlPointsEXT = reinterpret_cast(procAddr(device, "vkCmdSetPatchControlPointsEXT")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdSetRasterizerDiscardEnable = reinterpret_cast(procAddr(device, "vkCmdSetRasterizerDiscardEnable")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdSetDepthBiasEnable = reinterpret_cast(procAddr(device, "vkCmdSetDepthBiasEnable")); +#endif +#if (defined(VK_EXT_extended_dynamic_state2)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetLogicOpEXT = reinterpret_cast(procAddr(device, "vkCmdSetLogicOpEXT")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdSetPrimitiveRestartEnable = reinterpret_cast(procAddr(device, "vkCmdSetPrimitiveRestartEnable")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetTessellationDomainOriginEXT = reinterpret_cast(procAddr(device, "vkCmdSetTessellationDomainOriginEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetDepthClampEnableEXT = reinterpret_cast(procAddr(device, "vkCmdSetDepthClampEnableEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetPolygonModeEXT = reinterpret_cast(procAddr(device, "vkCmdSetPolygonModeEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetRasterizationSamplesEXT = reinterpret_cast(procAddr(device, "vkCmdSetRasterizationSamplesEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetSampleMaskEXT = reinterpret_cast(procAddr(device, "vkCmdSetSampleMaskEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetAlphaToCoverageEnableEXT = reinterpret_cast(procAddr(device, "vkCmdSetAlphaToCoverageEnableEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetAlphaToOneEnableEXT = reinterpret_cast(procAddr(device, "vkCmdSetAlphaToOneEnableEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetLogicOpEnableEXT = reinterpret_cast(procAddr(device, "vkCmdSetLogicOpEnableEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetColorBlendEnableEXT = reinterpret_cast(procAddr(device, "vkCmdSetColorBlendEnableEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetColorBlendEquationEXT = reinterpret_cast(procAddr(device, "vkCmdSetColorBlendEquationEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetColorWriteMaskEXT = reinterpret_cast(procAddr(device, "vkCmdSetColorWriteMaskEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetRasterizationStreamEXT = reinterpret_cast(procAddr(device, "vkCmdSetRasterizationStreamEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetConservativeRasterizationModeEXT = reinterpret_cast(procAddr(device, "vkCmdSetConservativeRasterizationModeEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetExtraPrimitiveOverestimationSizeEXT = reinterpret_cast(procAddr(device, "vkCmdSetExtraPrimitiveOverestimationSizeEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetDepthClipEnableEXT = reinterpret_cast(procAddr(device, "vkCmdSetDepthClipEnableEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetSampleLocationsEnableEXT = reinterpret_cast(procAddr(device, "vkCmdSetSampleLocationsEnableEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetColorBlendAdvancedEXT = reinterpret_cast(procAddr(device, "vkCmdSetColorBlendAdvancedEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetProvokingVertexModeEXT = reinterpret_cast(procAddr(device, "vkCmdSetProvokingVertexModeEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetLineRasterizationModeEXT = reinterpret_cast(procAddr(device, "vkCmdSetLineRasterizationModeEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetLineStippleEnableEXT = reinterpret_cast(procAddr(device, "vkCmdSetLineStippleEnableEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetDepthClipNegativeOneToOneEXT = reinterpret_cast(procAddr(device, "vkCmdSetDepthClipNegativeOneToOneEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetViewportWScalingEnableNV = reinterpret_cast(procAddr(device, "vkCmdSetViewportWScalingEnableNV")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetViewportSwizzleNV = reinterpret_cast(procAddr(device, "vkCmdSetViewportSwizzleNV")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetCoverageToColorEnableNV = reinterpret_cast(procAddr(device, "vkCmdSetCoverageToColorEnableNV")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetCoverageToColorLocationNV = reinterpret_cast(procAddr(device, "vkCmdSetCoverageToColorLocationNV")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetCoverageModulationModeNV = reinterpret_cast(procAddr(device, "vkCmdSetCoverageModulationModeNV")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetCoverageModulationTableEnableNV = reinterpret_cast(procAddr(device, "vkCmdSetCoverageModulationTableEnableNV")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetCoverageModulationTableNV = reinterpret_cast(procAddr(device, "vkCmdSetCoverageModulationTableNV")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetShadingRateImageEnableNV = reinterpret_cast(procAddr(device, "vkCmdSetShadingRateImageEnableNV")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetCoverageReductionModeNV = reinterpret_cast(procAddr(device, "vkCmdSetCoverageReductionModeNV")); +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetRepresentativeFragmentTestEnableNV = reinterpret_cast(procAddr(device, "vkCmdSetRepresentativeFragmentTestEnableNV")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCreatePrivateDataSlot = reinterpret_cast(procAddr(device, "vkCreatePrivateDataSlot")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkDestroyPrivateDataSlot = reinterpret_cast(procAddr(device, "vkDestroyPrivateDataSlot")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkSetPrivateData = reinterpret_cast(procAddr(device, "vkSetPrivateData")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkGetPrivateData = reinterpret_cast(procAddr(device, "vkGetPrivateData")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdCopyBuffer2 = reinterpret_cast(procAddr(device, "vkCmdCopyBuffer2")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdCopyImage2 = reinterpret_cast(procAddr(device, "vkCmdCopyImage2")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdBlitImage2 = reinterpret_cast(procAddr(device, "vkCmdBlitImage2")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdCopyBufferToImage2 = reinterpret_cast(procAddr(device, "vkCmdCopyBufferToImage2")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdCopyImageToBuffer2 = reinterpret_cast(procAddr(device, "vkCmdCopyImageToBuffer2")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdResolveImage2 = reinterpret_cast(procAddr(device, "vkCmdResolveImage2")); +#endif +#if (defined(VK_KHR_object_refresh)) + fp_vkCmdRefreshObjectsKHR = reinterpret_cast(procAddr(device, "vkCmdRefreshObjectsKHR")); +#endif +#if (defined(VK_KHR_fragment_shading_rate)) + fp_vkCmdSetFragmentShadingRateKHR = reinterpret_cast(procAddr(device, "vkCmdSetFragmentShadingRateKHR")); +#endif +#if (defined(VK_NV_fragment_shading_rate_enums)) + fp_vkCmdSetFragmentShadingRateEnumNV = reinterpret_cast(procAddr(device, "vkCmdSetFragmentShadingRateEnumNV")); +#endif +#if (defined(VK_KHR_acceleration_structure)) + fp_vkGetAccelerationStructureBuildSizesKHR = reinterpret_cast(procAddr(device, "vkGetAccelerationStructureBuildSizesKHR")); +#endif +#if (defined(VK_EXT_vertex_input_dynamic_state)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetVertexInputEXT = reinterpret_cast(procAddr(device, "vkCmdSetVertexInputEXT")); +#endif +#if (defined(VK_EXT_color_write_enable)) + fp_vkCmdSetColorWriteEnableEXT = reinterpret_cast(procAddr(device, "vkCmdSetColorWriteEnableEXT")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdSetEvent2 = reinterpret_cast(procAddr(device, "vkCmdSetEvent2")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdResetEvent2 = reinterpret_cast(procAddr(device, "vkCmdResetEvent2")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdWaitEvents2 = reinterpret_cast(procAddr(device, "vkCmdWaitEvents2")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdPipelineBarrier2 = reinterpret_cast(procAddr(device, "vkCmdPipelineBarrier2")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkQueueSubmit2 = reinterpret_cast(procAddr(device, "vkQueueSubmit2")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdWriteTimestamp2 = reinterpret_cast(procAddr(device, "vkCmdWriteTimestamp2")); +#endif +#if (defined(VK_KHR_synchronization2)) + fp_vkCmdWriteBufferMarker2AMD = reinterpret_cast(procAddr(device, "vkCmdWriteBufferMarker2AMD")); +#endif +#if (defined(VK_KHR_synchronization2)) + fp_vkGetQueueCheckpointData2NV = reinterpret_cast(procAddr(device, "vkGetQueueCheckpointData2NV")); +#endif +#if (defined(VK_EXT_host_image_copy)) + fp_vkCopyMemoryToImageEXT = reinterpret_cast(procAddr(device, "vkCopyMemoryToImageEXT")); +#endif +#if (defined(VK_EXT_host_image_copy)) + fp_vkCopyImageToMemoryEXT = reinterpret_cast(procAddr(device, "vkCopyImageToMemoryEXT")); +#endif +#if (defined(VK_EXT_host_image_copy)) + fp_vkCopyImageToImageEXT = reinterpret_cast(procAddr(device, "vkCopyImageToImageEXT")); +#endif +#if (defined(VK_EXT_host_image_copy)) + fp_vkTransitionImageLayoutEXT = reinterpret_cast(procAddr(device, "vkTransitionImageLayoutEXT")); +#endif +#if (defined(VKSC_VERSION_1_0)) + fp_vkGetCommandPoolMemoryConsumption = reinterpret_cast(procAddr(device, "vkGetCommandPoolMemoryConsumption")); +#endif +#if (defined(VK_KHR_video_queue)) + fp_vkCreateVideoSessionKHR = reinterpret_cast(procAddr(device, "vkCreateVideoSessionKHR")); +#endif +#if (defined(VK_KHR_video_queue)) + fp_vkDestroyVideoSessionKHR = reinterpret_cast(procAddr(device, "vkDestroyVideoSessionKHR")); +#endif +#if (defined(VK_KHR_video_queue)) + fp_vkCreateVideoSessionParametersKHR = reinterpret_cast(procAddr(device, "vkCreateVideoSessionParametersKHR")); +#endif +#if (defined(VK_KHR_video_queue)) + fp_vkUpdateVideoSessionParametersKHR = reinterpret_cast(procAddr(device, "vkUpdateVideoSessionParametersKHR")); +#endif +#if (defined(VK_KHR_video_encode_queue)) + fp_vkGetEncodedVideoSessionParametersKHR = reinterpret_cast(procAddr(device, "vkGetEncodedVideoSessionParametersKHR")); +#endif +#if (defined(VK_KHR_video_queue)) + fp_vkDestroyVideoSessionParametersKHR = reinterpret_cast(procAddr(device, "vkDestroyVideoSessionParametersKHR")); +#endif +#if (defined(VK_KHR_video_queue)) + fp_vkGetVideoSessionMemoryRequirementsKHR = reinterpret_cast(procAddr(device, "vkGetVideoSessionMemoryRequirementsKHR")); +#endif +#if (defined(VK_KHR_video_queue)) + fp_vkBindVideoSessionMemoryKHR = reinterpret_cast(procAddr(device, "vkBindVideoSessionMemoryKHR")); +#endif +#if (defined(VK_KHR_video_decode_queue)) + fp_vkCmdDecodeVideoKHR = reinterpret_cast(procAddr(device, "vkCmdDecodeVideoKHR")); +#endif +#if (defined(VK_KHR_video_queue)) + fp_vkCmdBeginVideoCodingKHR = reinterpret_cast(procAddr(device, "vkCmdBeginVideoCodingKHR")); +#endif +#if (defined(VK_KHR_video_queue)) + fp_vkCmdControlVideoCodingKHR = reinterpret_cast(procAddr(device, "vkCmdControlVideoCodingKHR")); +#endif +#if (defined(VK_KHR_video_queue)) + fp_vkCmdEndVideoCodingKHR = reinterpret_cast(procAddr(device, "vkCmdEndVideoCodingKHR")); +#endif +#if (defined(VK_KHR_video_encode_queue)) + fp_vkCmdEncodeVideoKHR = reinterpret_cast(procAddr(device, "vkCmdEncodeVideoKHR")); +#endif +#if (defined(VK_NV_memory_decompression)) + fp_vkCmdDecompressMemoryNV = reinterpret_cast(procAddr(device, "vkCmdDecompressMemoryNV")); +#endif +#if (defined(VK_NV_memory_decompression)) + fp_vkCmdDecompressMemoryIndirectCountNV = reinterpret_cast(procAddr(device, "vkCmdDecompressMemoryIndirectCountNV")); +#endif +#if (defined(VK_EXT_descriptor_buffer)) + fp_vkGetDescriptorSetLayoutSizeEXT = reinterpret_cast(procAddr(device, "vkGetDescriptorSetLayoutSizeEXT")); +#endif +#if (defined(VK_EXT_descriptor_buffer)) + fp_vkGetDescriptorSetLayoutBindingOffsetEXT = reinterpret_cast(procAddr(device, "vkGetDescriptorSetLayoutBindingOffsetEXT")); +#endif +#if (defined(VK_EXT_descriptor_buffer)) + fp_vkGetDescriptorEXT = reinterpret_cast(procAddr(device, "vkGetDescriptorEXT")); +#endif +#if (defined(VK_EXT_descriptor_buffer)) + fp_vkCmdBindDescriptorBuffersEXT = reinterpret_cast(procAddr(device, "vkCmdBindDescriptorBuffersEXT")); +#endif +#if (defined(VK_EXT_descriptor_buffer)) + fp_vkCmdSetDescriptorBufferOffsetsEXT = reinterpret_cast(procAddr(device, "vkCmdSetDescriptorBufferOffsetsEXT")); +#endif +#if (defined(VK_EXT_descriptor_buffer)) + fp_vkCmdBindDescriptorBufferEmbeddedSamplersEXT = reinterpret_cast(procAddr(device, "vkCmdBindDescriptorBufferEmbeddedSamplersEXT")); +#endif +#if (defined(VK_EXT_descriptor_buffer)) + fp_vkGetBufferOpaqueCaptureDescriptorDataEXT = reinterpret_cast(procAddr(device, "vkGetBufferOpaqueCaptureDescriptorDataEXT")); +#endif +#if (defined(VK_EXT_descriptor_buffer)) + fp_vkGetImageOpaqueCaptureDescriptorDataEXT = reinterpret_cast(procAddr(device, "vkGetImageOpaqueCaptureDescriptorDataEXT")); +#endif +#if (defined(VK_EXT_descriptor_buffer)) + fp_vkGetImageViewOpaqueCaptureDescriptorDataEXT = reinterpret_cast(procAddr(device, "vkGetImageViewOpaqueCaptureDescriptorDataEXT")); +#endif +#if (defined(VK_EXT_descriptor_buffer)) + fp_vkGetSamplerOpaqueCaptureDescriptorDataEXT = reinterpret_cast(procAddr(device, "vkGetSamplerOpaqueCaptureDescriptorDataEXT")); +#endif +#if (defined(VK_EXT_descriptor_buffer)) + fp_vkGetAccelerationStructureOpaqueCaptureDescriptorDataEXT = reinterpret_cast(procAddr(device, "vkGetAccelerationStructureOpaqueCaptureDescriptorDataEXT")); +#endif +#if (defined(VK_EXT_pageable_device_local_memory)) + fp_vkSetDeviceMemoryPriorityEXT = reinterpret_cast(procAddr(device, "vkSetDeviceMemoryPriorityEXT")); +#endif +#if (defined(VK_KHR_present_wait)) + fp_vkWaitForPresentKHR = reinterpret_cast(procAddr(device, "vkWaitForPresentKHR")); +#endif +#if (defined(VK_FUCHSIA_buffer_collection)) + fp_vkCreateBufferCollectionFUCHSIA = reinterpret_cast(procAddr(device, "vkCreateBufferCollectionFUCHSIA")); +#endif +#if (defined(VK_FUCHSIA_buffer_collection)) + fp_vkSetBufferCollectionBufferConstraintsFUCHSIA = reinterpret_cast(procAddr(device, "vkSetBufferCollectionBufferConstraintsFUCHSIA")); +#endif +#if (defined(VK_FUCHSIA_buffer_collection)) + fp_vkSetBufferCollectionImageConstraintsFUCHSIA = reinterpret_cast(procAddr(device, "vkSetBufferCollectionImageConstraintsFUCHSIA")); +#endif +#if (defined(VK_FUCHSIA_buffer_collection)) + fp_vkDestroyBufferCollectionFUCHSIA = reinterpret_cast(procAddr(device, "vkDestroyBufferCollectionFUCHSIA")); +#endif +#if (defined(VK_FUCHSIA_buffer_collection)) + fp_vkGetBufferCollectionPropertiesFUCHSIA = reinterpret_cast(procAddr(device, "vkGetBufferCollectionPropertiesFUCHSIA")); +#endif +#if (defined(VK_NV_cuda_kernel_launch)) + fp_vkCreateCudaModuleNV = reinterpret_cast(procAddr(device, "vkCreateCudaModuleNV")); +#endif +#if (defined(VK_NV_cuda_kernel_launch)) + fp_vkGetCudaModuleCacheNV = reinterpret_cast(procAddr(device, "vkGetCudaModuleCacheNV")); +#endif +#if (defined(VK_NV_cuda_kernel_launch)) + fp_vkCreateCudaFunctionNV = reinterpret_cast(procAddr(device, "vkCreateCudaFunctionNV")); +#endif +#if (defined(VK_NV_cuda_kernel_launch)) + fp_vkDestroyCudaModuleNV = reinterpret_cast(procAddr(device, "vkDestroyCudaModuleNV")); +#endif +#if (defined(VK_NV_cuda_kernel_launch)) + fp_vkDestroyCudaFunctionNV = reinterpret_cast(procAddr(device, "vkDestroyCudaFunctionNV")); +#endif +#if (defined(VK_NV_cuda_kernel_launch)) + fp_vkCmdCudaLaunchKernelNV = reinterpret_cast(procAddr(device, "vkCmdCudaLaunchKernelNV")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdBeginRendering = reinterpret_cast(procAddr(device, "vkCmdBeginRendering")); +#endif +#if (defined(VK_VERSION_1_3)) + fp_vkCmdEndRendering = reinterpret_cast(procAddr(device, "vkCmdEndRendering")); +#endif +#if (defined(VK_VALVE_descriptor_set_host_mapping)) + fp_vkGetDescriptorSetLayoutHostMappingInfoVALVE = reinterpret_cast(procAddr(device, "vkGetDescriptorSetLayoutHostMappingInfoVALVE")); +#endif +#if (defined(VK_VALVE_descriptor_set_host_mapping)) + fp_vkGetDescriptorSetHostMappingVALVE = reinterpret_cast(procAddr(device, "vkGetDescriptorSetHostMappingVALVE")); +#endif +#if (defined(VK_EXT_opacity_micromap)) + fp_vkCreateMicromapEXT = reinterpret_cast(procAddr(device, "vkCreateMicromapEXT")); +#endif +#if (defined(VK_EXT_opacity_micromap)) + fp_vkCmdBuildMicromapsEXT = reinterpret_cast(procAddr(device, "vkCmdBuildMicromapsEXT")); +#endif +#if (defined(VK_EXT_opacity_micromap)) + fp_vkBuildMicromapsEXT = reinterpret_cast(procAddr(device, "vkBuildMicromapsEXT")); +#endif +#if (defined(VK_EXT_opacity_micromap)) + fp_vkDestroyMicromapEXT = reinterpret_cast(procAddr(device, "vkDestroyMicromapEXT")); +#endif +#if (defined(VK_EXT_opacity_micromap)) + fp_vkCmdCopyMicromapEXT = reinterpret_cast(procAddr(device, "vkCmdCopyMicromapEXT")); +#endif +#if (defined(VK_EXT_opacity_micromap)) + fp_vkCopyMicromapEXT = reinterpret_cast(procAddr(device, "vkCopyMicromapEXT")); +#endif +#if (defined(VK_EXT_opacity_micromap)) + fp_vkCmdCopyMicromapToMemoryEXT = reinterpret_cast(procAddr(device, "vkCmdCopyMicromapToMemoryEXT")); +#endif +#if (defined(VK_EXT_opacity_micromap)) + fp_vkCopyMicromapToMemoryEXT = reinterpret_cast(procAddr(device, "vkCopyMicromapToMemoryEXT")); +#endif +#if (defined(VK_EXT_opacity_micromap)) + fp_vkCmdCopyMemoryToMicromapEXT = reinterpret_cast(procAddr(device, "vkCmdCopyMemoryToMicromapEXT")); +#endif +#if (defined(VK_EXT_opacity_micromap)) + fp_vkCopyMemoryToMicromapEXT = reinterpret_cast(procAddr(device, "vkCopyMemoryToMicromapEXT")); +#endif +#if (defined(VK_EXT_opacity_micromap)) + fp_vkCmdWriteMicromapsPropertiesEXT = reinterpret_cast(procAddr(device, "vkCmdWriteMicromapsPropertiesEXT")); +#endif +#if (defined(VK_EXT_opacity_micromap)) + fp_vkWriteMicromapsPropertiesEXT = reinterpret_cast(procAddr(device, "vkWriteMicromapsPropertiesEXT")); +#endif +#if (defined(VK_EXT_opacity_micromap)) + fp_vkGetDeviceMicromapCompatibilityEXT = reinterpret_cast(procAddr(device, "vkGetDeviceMicromapCompatibilityEXT")); +#endif +#if (defined(VK_EXT_opacity_micromap)) + fp_vkGetMicromapBuildSizesEXT = reinterpret_cast(procAddr(device, "vkGetMicromapBuildSizesEXT")); +#endif +#if (defined(VK_EXT_shader_module_identifier)) + fp_vkGetShaderModuleIdentifierEXT = reinterpret_cast(procAddr(device, "vkGetShaderModuleIdentifierEXT")); +#endif +#if (defined(VK_EXT_shader_module_identifier)) + fp_vkGetShaderModuleCreateInfoIdentifierEXT = reinterpret_cast(procAddr(device, "vkGetShaderModuleCreateInfoIdentifierEXT")); +#endif +#if (defined(VK_KHR_maintenance5)) + fp_vkGetImageSubresourceLayout2KHR = reinterpret_cast(procAddr(device, "vkGetImageSubresourceLayout2KHR")); +#endif +#if (defined(VK_EXT_pipeline_properties)) + fp_vkGetPipelinePropertiesEXT = reinterpret_cast(procAddr(device, "vkGetPipelinePropertiesEXT")); +#endif +#if (defined(VK_EXT_metal_objects)) + fp_vkExportMetalObjectsEXT = reinterpret_cast(procAddr(device, "vkExportMetalObjectsEXT")); +#endif +#if (defined(VK_QCOM_tile_properties)) + fp_vkGetFramebufferTilePropertiesQCOM = reinterpret_cast(procAddr(device, "vkGetFramebufferTilePropertiesQCOM")); +#endif +#if (defined(VK_QCOM_tile_properties)) + fp_vkGetDynamicRenderingTilePropertiesQCOM = reinterpret_cast(procAddr(device, "vkGetDynamicRenderingTilePropertiesQCOM")); +#endif +#if (defined(VK_NV_optical_flow)) + fp_vkCreateOpticalFlowSessionNV = reinterpret_cast(procAddr(device, "vkCreateOpticalFlowSessionNV")); +#endif +#if (defined(VK_NV_optical_flow)) + fp_vkDestroyOpticalFlowSessionNV = reinterpret_cast(procAddr(device, "vkDestroyOpticalFlowSessionNV")); +#endif +#if (defined(VK_NV_optical_flow)) + fp_vkBindOpticalFlowSessionImageNV = reinterpret_cast(procAddr(device, "vkBindOpticalFlowSessionImageNV")); +#endif +#if (defined(VK_NV_optical_flow)) + fp_vkCmdOpticalFlowExecuteNV = reinterpret_cast(procAddr(device, "vkCmdOpticalFlowExecuteNV")); +#endif +#if (defined(VK_EXT_device_fault)) + fp_vkGetDeviceFaultInfoEXT = reinterpret_cast(procAddr(device, "vkGetDeviceFaultInfoEXT")); +#endif +#if (defined(VK_EXT_depth_bias_control)) + fp_vkCmdSetDepthBias2EXT = reinterpret_cast(procAddr(device, "vkCmdSetDepthBias2EXT")); +#endif +#if (defined(VK_EXT_swapchain_maintenance1)) + fp_vkReleaseSwapchainImagesEXT = reinterpret_cast(procAddr(device, "vkReleaseSwapchainImagesEXT")); +#endif +#if (defined(VK_KHR_maintenance5)) + fp_vkGetDeviceImageSubresourceLayoutKHR = reinterpret_cast(procAddr(device, "vkGetDeviceImageSubresourceLayoutKHR")); +#endif +#if (defined(VK_KHR_map_memory2)) + fp_vkMapMemory2KHR = reinterpret_cast(procAddr(device, "vkMapMemory2KHR")); +#endif +#if (defined(VK_KHR_map_memory2)) + fp_vkUnmapMemory2KHR = reinterpret_cast(procAddr(device, "vkUnmapMemory2KHR")); +#endif +#if (defined(VK_EXT_shader_object)) + fp_vkCreateShadersEXT = reinterpret_cast(procAddr(device, "vkCreateShadersEXT")); +#endif +#if (defined(VK_EXT_shader_object)) + fp_vkDestroyShaderEXT = reinterpret_cast(procAddr(device, "vkDestroyShaderEXT")); +#endif +#if (defined(VK_EXT_shader_object)) + fp_vkGetShaderBinaryDataEXT = reinterpret_cast(procAddr(device, "vkGetShaderBinaryDataEXT")); +#endif +#if (defined(VK_EXT_shader_object)) + fp_vkCmdBindShadersEXT = reinterpret_cast(procAddr(device, "vkCmdBindShadersEXT")); +#endif +#if (defined(VK_QNX_external_memory_screen_buffer)) + fp_vkGetScreenBufferPropertiesQNX = reinterpret_cast(procAddr(device, "vkGetScreenBufferPropertiesQNX")); +#endif +#if (defined(VK_AMDX_shader_enqueue)) + fp_vkGetExecutionGraphPipelineScratchSizeAMDX = reinterpret_cast(procAddr(device, "vkGetExecutionGraphPipelineScratchSizeAMDX")); +#endif +#if (defined(VK_AMDX_shader_enqueue)) + fp_vkGetExecutionGraphPipelineNodeIndexAMDX = reinterpret_cast(procAddr(device, "vkGetExecutionGraphPipelineNodeIndexAMDX")); +#endif +#if (defined(VK_AMDX_shader_enqueue)) + fp_vkCreateExecutionGraphPipelinesAMDX = reinterpret_cast(procAddr(device, "vkCreateExecutionGraphPipelinesAMDX")); +#endif +#if (defined(VK_AMDX_shader_enqueue)) + fp_vkCmdInitializeGraphScratchMemoryAMDX = reinterpret_cast(procAddr(device, "vkCmdInitializeGraphScratchMemoryAMDX")); +#endif +#if (defined(VK_AMDX_shader_enqueue)) + fp_vkCmdDispatchGraphAMDX = reinterpret_cast(procAddr(device, "vkCmdDispatchGraphAMDX")); +#endif +#if (defined(VK_AMDX_shader_enqueue)) + fp_vkCmdDispatchGraphIndirectAMDX = reinterpret_cast(procAddr(device, "vkCmdDispatchGraphIndirectAMDX")); +#endif +#if (defined(VK_AMDX_shader_enqueue)) + fp_vkCmdDispatchGraphIndirectCountAMDX = reinterpret_cast(procAddr(device, "vkCmdDispatchGraphIndirectCountAMDX")); +#endif +#if (defined(VK_KHR_maintenance6)) + fp_vkCmdBindDescriptorSets2KHR = reinterpret_cast(procAddr(device, "vkCmdBindDescriptorSets2KHR")); +#endif +#if (defined(VK_KHR_maintenance6)) + fp_vkCmdPushConstants2KHR = reinterpret_cast(procAddr(device, "vkCmdPushConstants2KHR")); +#endif +#if (defined(VK_KHR_maintenance6)) + fp_vkCmdPushDescriptorSet2KHR = reinterpret_cast(procAddr(device, "vkCmdPushDescriptorSet2KHR")); +#endif +#if (defined(VK_KHR_maintenance6)) + fp_vkCmdPushDescriptorSetWithTemplate2KHR = reinterpret_cast(procAddr(device, "vkCmdPushDescriptorSetWithTemplate2KHR")); +#endif +#if (defined(VK_KHR_maintenance6)) + fp_vkCmdSetDescriptorBufferOffsets2EXT = reinterpret_cast(procAddr(device, "vkCmdSetDescriptorBufferOffsets2EXT")); +#endif +#if (defined(VK_KHR_maintenance6)) + fp_vkCmdBindDescriptorBufferEmbeddedSamplers2EXT = reinterpret_cast(procAddr(device, "vkCmdBindDescriptorBufferEmbeddedSamplers2EXT")); +#endif +#if (defined(VK_NV_low_latency2)) + fp_vkSetLatencySleepModeNV = reinterpret_cast(procAddr(device, "vkSetLatencySleepModeNV")); +#endif +#if (defined(VK_NV_low_latency2)) + fp_vkLatencySleepNV = reinterpret_cast(procAddr(device, "vkLatencySleepNV")); +#endif +#if (defined(VK_NV_low_latency2)) + fp_vkSetLatencyMarkerNV = reinterpret_cast(procAddr(device, "vkSetLatencyMarkerNV")); +#endif +#if ((defined(VK_NV_low_latency2))) && VK_HEADER_VERSION >= 271 + fp_vkGetLatencyTimingsNV = reinterpret_cast(procAddr(device, "vkGetLatencyTimingsNV")); +#endif +#if (defined(VK_NV_low_latency2)) + fp_vkQueueNotifyOutOfBandNV = reinterpret_cast(procAddr(device, "vkQueueNotifyOutOfBandNV")); +#endif +#if (defined(VK_KHR_dynamic_rendering_local_read)) + fp_vkCmdSetRenderingAttachmentLocationsKHR = reinterpret_cast(procAddr(device, "vkCmdSetRenderingAttachmentLocationsKHR")); +#endif +#if (defined(VK_KHR_dynamic_rendering_local_read)) + fp_vkCmdSetRenderingInputAttachmentIndicesKHR = reinterpret_cast(procAddr(device, "vkCmdSetRenderingInputAttachmentIndicesKHR")); +#endif +#if (defined(VK_EXT_host_query_reset)) + fp_vkResetQueryPoolEXT = reinterpret_cast(procAddr(device, "vkResetQueryPoolEXT")); +#endif +#if (defined(VK_KHR_maintenance1)) + fp_vkTrimCommandPoolKHR = reinterpret_cast(procAddr(device, "vkTrimCommandPoolKHR")); +#endif +#if (defined(VK_KHR_device_group)) + fp_vkGetDeviceGroupPeerMemoryFeaturesKHR = reinterpret_cast(procAddr(device, "vkGetDeviceGroupPeerMemoryFeaturesKHR")); +#endif +#if (defined(VK_KHR_bind_memory2)) + fp_vkBindBufferMemory2KHR = reinterpret_cast(procAddr(device, "vkBindBufferMemory2KHR")); +#endif +#if (defined(VK_KHR_bind_memory2)) + fp_vkBindImageMemory2KHR = reinterpret_cast(procAddr(device, "vkBindImageMemory2KHR")); +#endif +#if (defined(VK_KHR_device_group)) + fp_vkCmdSetDeviceMaskKHR = reinterpret_cast(procAddr(device, "vkCmdSetDeviceMaskKHR")); +#endif +#if (defined(VK_KHR_device_group)) + fp_vkCmdDispatchBaseKHR = reinterpret_cast(procAddr(device, "vkCmdDispatchBaseKHR")); +#endif +#if (defined(VK_KHR_descriptor_update_template)) + fp_vkCreateDescriptorUpdateTemplateKHR = reinterpret_cast(procAddr(device, "vkCreateDescriptorUpdateTemplateKHR")); +#endif +#if (defined(VK_KHR_descriptor_update_template)) + fp_vkDestroyDescriptorUpdateTemplateKHR = reinterpret_cast(procAddr(device, "vkDestroyDescriptorUpdateTemplateKHR")); +#endif +#if (defined(VK_KHR_descriptor_update_template)) + fp_vkUpdateDescriptorSetWithTemplateKHR = reinterpret_cast(procAddr(device, "vkUpdateDescriptorSetWithTemplateKHR")); +#endif +#if (defined(VK_KHR_get_memory_requirements2)) + fp_vkGetBufferMemoryRequirements2KHR = reinterpret_cast(procAddr(device, "vkGetBufferMemoryRequirements2KHR")); +#endif +#if (defined(VK_KHR_get_memory_requirements2)) + fp_vkGetImageMemoryRequirements2KHR = reinterpret_cast(procAddr(device, "vkGetImageMemoryRequirements2KHR")); +#endif +#if (defined(VK_KHR_get_memory_requirements2)) + fp_vkGetImageSparseMemoryRequirements2KHR = reinterpret_cast(procAddr(device, "vkGetImageSparseMemoryRequirements2KHR")); +#endif +#if (defined(VK_KHR_maintenance4)) + fp_vkGetDeviceBufferMemoryRequirementsKHR = reinterpret_cast(procAddr(device, "vkGetDeviceBufferMemoryRequirementsKHR")); +#endif +#if (defined(VK_KHR_maintenance4)) + fp_vkGetDeviceImageMemoryRequirementsKHR = reinterpret_cast(procAddr(device, "vkGetDeviceImageMemoryRequirementsKHR")); +#endif +#if (defined(VK_KHR_maintenance4)) + fp_vkGetDeviceImageSparseMemoryRequirementsKHR = reinterpret_cast(procAddr(device, "vkGetDeviceImageSparseMemoryRequirementsKHR")); +#endif +#if (defined(VK_KHR_sampler_ycbcr_conversion)) + fp_vkCreateSamplerYcbcrConversionKHR = reinterpret_cast(procAddr(device, "vkCreateSamplerYcbcrConversionKHR")); +#endif +#if (defined(VK_KHR_sampler_ycbcr_conversion)) + fp_vkDestroySamplerYcbcrConversionKHR = reinterpret_cast(procAddr(device, "vkDestroySamplerYcbcrConversionKHR")); +#endif +#if (defined(VK_KHR_maintenance3)) + fp_vkGetDescriptorSetLayoutSupportKHR = reinterpret_cast(procAddr(device, "vkGetDescriptorSetLayoutSupportKHR")); +#endif +#if (defined(VK_EXT_calibrated_timestamps)) + fp_vkGetCalibratedTimestampsEXT = reinterpret_cast(procAddr(device, "vkGetCalibratedTimestampsEXT")); +#endif +#if (defined(VK_KHR_create_renderpass2)) + fp_vkCreateRenderPass2KHR = reinterpret_cast(procAddr(device, "vkCreateRenderPass2KHR")); +#endif +#if (defined(VK_KHR_create_renderpass2)) + fp_vkCmdBeginRenderPass2KHR = reinterpret_cast(procAddr(device, "vkCmdBeginRenderPass2KHR")); +#endif +#if (defined(VK_KHR_create_renderpass2)) + fp_vkCmdNextSubpass2KHR = reinterpret_cast(procAddr(device, "vkCmdNextSubpass2KHR")); +#endif +#if (defined(VK_KHR_create_renderpass2)) + fp_vkCmdEndRenderPass2KHR = reinterpret_cast(procAddr(device, "vkCmdEndRenderPass2KHR")); +#endif +#if (defined(VK_KHR_timeline_semaphore)) + fp_vkGetSemaphoreCounterValueKHR = reinterpret_cast(procAddr(device, "vkGetSemaphoreCounterValueKHR")); +#endif +#if (defined(VK_KHR_timeline_semaphore)) + fp_vkWaitSemaphoresKHR = reinterpret_cast(procAddr(device, "vkWaitSemaphoresKHR")); +#endif +#if (defined(VK_KHR_timeline_semaphore)) + fp_vkSignalSemaphoreKHR = reinterpret_cast(procAddr(device, "vkSignalSemaphoreKHR")); +#endif +#if (defined(VK_AMD_draw_indirect_count)) + fp_vkCmdDrawIndirectCountAMD = reinterpret_cast(procAddr(device, "vkCmdDrawIndirectCountAMD")); +#endif +#if (defined(VK_AMD_draw_indirect_count)) + fp_vkCmdDrawIndexedIndirectCountAMD = reinterpret_cast(procAddr(device, "vkCmdDrawIndexedIndirectCountAMD")); +#endif +#if (defined(VK_NV_ray_tracing)) + fp_vkGetRayTracingShaderGroupHandlesNV = reinterpret_cast(procAddr(device, "vkGetRayTracingShaderGroupHandlesNV")); +#endif +#if (defined(VK_KHR_buffer_device_address)) + fp_vkGetBufferOpaqueCaptureAddressKHR = reinterpret_cast(procAddr(device, "vkGetBufferOpaqueCaptureAddressKHR")); +#endif +#if (defined(VK_EXT_buffer_device_address)) + fp_vkGetBufferDeviceAddressEXT = reinterpret_cast(procAddr(device, "vkGetBufferDeviceAddressEXT")); +#endif +#if (defined(VK_KHR_buffer_device_address)) + fp_vkGetDeviceMemoryOpaqueCaptureAddressKHR = reinterpret_cast(procAddr(device, "vkGetDeviceMemoryOpaqueCaptureAddressKHR")); +#endif +#if (defined(VK_EXT_line_rasterization)) + fp_vkCmdSetLineStippleEXT = reinterpret_cast(procAddr(device, "vkCmdSetLineStippleEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetCullModeEXT = reinterpret_cast(procAddr(device, "vkCmdSetCullModeEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetFrontFaceEXT = reinterpret_cast(procAddr(device, "vkCmdSetFrontFaceEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetPrimitiveTopologyEXT = reinterpret_cast(procAddr(device, "vkCmdSetPrimitiveTopologyEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetViewportWithCountEXT = reinterpret_cast(procAddr(device, "vkCmdSetViewportWithCountEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetScissorWithCountEXT = reinterpret_cast(procAddr(device, "vkCmdSetScissorWithCountEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + fp_vkCmdBindVertexBuffers2EXT = reinterpret_cast(procAddr(device, "vkCmdBindVertexBuffers2EXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetDepthTestEnableEXT = reinterpret_cast(procAddr(device, "vkCmdSetDepthTestEnableEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetDepthWriteEnableEXT = reinterpret_cast(procAddr(device, "vkCmdSetDepthWriteEnableEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetDepthCompareOpEXT = reinterpret_cast(procAddr(device, "vkCmdSetDepthCompareOpEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetDepthBoundsTestEnableEXT = reinterpret_cast(procAddr(device, "vkCmdSetDepthBoundsTestEnableEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetStencilTestEnableEXT = reinterpret_cast(procAddr(device, "vkCmdSetStencilTestEnableEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetStencilOpEXT = reinterpret_cast(procAddr(device, "vkCmdSetStencilOpEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state2)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetRasterizerDiscardEnableEXT = reinterpret_cast(procAddr(device, "vkCmdSetRasterizerDiscardEnableEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state2)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetDepthBiasEnableEXT = reinterpret_cast(procAddr(device, "vkCmdSetDepthBiasEnableEXT")); +#endif +#if (defined(VK_EXT_extended_dynamic_state2)) || (defined(VK_EXT_shader_object)) + fp_vkCmdSetPrimitiveRestartEnableEXT = reinterpret_cast(procAddr(device, "vkCmdSetPrimitiveRestartEnableEXT")); +#endif +#if (defined(VK_EXT_private_data)) + fp_vkCreatePrivateDataSlotEXT = reinterpret_cast(procAddr(device, "vkCreatePrivateDataSlotEXT")); +#endif +#if (defined(VK_EXT_private_data)) + fp_vkDestroyPrivateDataSlotEXT = reinterpret_cast(procAddr(device, "vkDestroyPrivateDataSlotEXT")); +#endif +#if (defined(VK_EXT_private_data)) + fp_vkSetPrivateDataEXT = reinterpret_cast(procAddr(device, "vkSetPrivateDataEXT")); +#endif +#if (defined(VK_EXT_private_data)) + fp_vkGetPrivateDataEXT = reinterpret_cast(procAddr(device, "vkGetPrivateDataEXT")); +#endif +#if (defined(VK_KHR_copy_commands2)) + fp_vkCmdCopyBuffer2KHR = reinterpret_cast(procAddr(device, "vkCmdCopyBuffer2KHR")); +#endif +#if (defined(VK_KHR_copy_commands2)) + fp_vkCmdCopyImage2KHR = reinterpret_cast(procAddr(device, "vkCmdCopyImage2KHR")); +#endif +#if (defined(VK_KHR_copy_commands2)) + fp_vkCmdBlitImage2KHR = reinterpret_cast(procAddr(device, "vkCmdBlitImage2KHR")); +#endif +#if (defined(VK_KHR_copy_commands2)) + fp_vkCmdCopyBufferToImage2KHR = reinterpret_cast(procAddr(device, "vkCmdCopyBufferToImage2KHR")); +#endif +#if (defined(VK_KHR_copy_commands2)) + fp_vkCmdCopyImageToBuffer2KHR = reinterpret_cast(procAddr(device, "vkCmdCopyImageToBuffer2KHR")); +#endif +#if (defined(VK_KHR_copy_commands2)) + fp_vkCmdResolveImage2KHR = reinterpret_cast(procAddr(device, "vkCmdResolveImage2KHR")); +#endif +#if (defined(VK_KHR_synchronization2)) + fp_vkCmdSetEvent2KHR = reinterpret_cast(procAddr(device, "vkCmdSetEvent2KHR")); +#endif +#if (defined(VK_KHR_synchronization2)) + fp_vkCmdResetEvent2KHR = reinterpret_cast(procAddr(device, "vkCmdResetEvent2KHR")); +#endif +#if (defined(VK_KHR_synchronization2)) + fp_vkCmdWaitEvents2KHR = reinterpret_cast(procAddr(device, "vkCmdWaitEvents2KHR")); +#endif +#if (defined(VK_KHR_synchronization2)) + fp_vkCmdPipelineBarrier2KHR = reinterpret_cast(procAddr(device, "vkCmdPipelineBarrier2KHR")); +#endif +#if (defined(VK_KHR_synchronization2)) + fp_vkQueueSubmit2KHR = reinterpret_cast(procAddr(device, "vkQueueSubmit2KHR")); +#endif +#if (defined(VK_KHR_synchronization2)) + fp_vkCmdWriteTimestamp2KHR = reinterpret_cast(procAddr(device, "vkCmdWriteTimestamp2KHR")); +#endif +#if (defined(VK_KHR_dynamic_rendering)) + fp_vkCmdBeginRenderingKHR = reinterpret_cast(procAddr(device, "vkCmdBeginRenderingKHR")); +#endif +#if (defined(VK_KHR_dynamic_rendering)) + fp_vkCmdEndRenderingKHR = reinterpret_cast(procAddr(device, "vkCmdEndRenderingKHR")); +#endif +#if (defined(VK_EXT_host_image_copy)) || (defined(VK_EXT_image_compression_control)) + fp_vkGetImageSubresourceLayout2EXT = reinterpret_cast(procAddr(device, "vkGetImageSubresourceLayout2EXT")); +#endif + } + void getDeviceQueue(uint32_t queueFamilyIndex, uint32_t queueIndex, VkQueue* pQueue) const noexcept { + fp_vkGetDeviceQueue(device, queueFamilyIndex, queueIndex, pQueue); + } + VkResult queueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence) const noexcept { + return fp_vkQueueSubmit(queue, submitCount, pSubmits, fence); + } + VkResult queueWaitIdle(VkQueue queue) const noexcept { + return fp_vkQueueWaitIdle(queue); + } + VkResult deviceWaitIdle() const noexcept { + return fp_vkDeviceWaitIdle(device); + } + VkResult allocateMemory(const VkMemoryAllocateInfo* pAllocateInfo, const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const noexcept { + return fp_vkAllocateMemory(device, pAllocateInfo, pAllocator, pMemory); + } + void freeMemory(VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkFreeMemory(device, memory, pAllocator); + } + VkResult mapMemory(VkDeviceMemory memory, VkDeviceSize offset, VkDeviceSize size, VkMemoryMapFlags flags, void** ppData) const noexcept { + return fp_vkMapMemory(device, memory, offset, size, flags, ppData); + } + void unmapMemory(VkDeviceMemory memory) const noexcept { + fp_vkUnmapMemory(device, memory); + } + VkResult flushMappedMemoryRanges(uint32_t memoryRangeCount, const VkMappedMemoryRange* pMemoryRanges) const noexcept { + return fp_vkFlushMappedMemoryRanges(device, memoryRangeCount, pMemoryRanges); + } + VkResult invalidateMappedMemoryRanges(uint32_t memoryRangeCount, const VkMappedMemoryRange* pMemoryRanges) const noexcept { + return fp_vkInvalidateMappedMemoryRanges(device, memoryRangeCount, pMemoryRanges); + } + void getDeviceMemoryCommitment(VkDeviceMemory memory, VkDeviceSize* pCommittedMemoryInBytes) const noexcept { + fp_vkGetDeviceMemoryCommitment(device, memory, pCommittedMemoryInBytes); + } + void getBufferMemoryRequirements(VkBuffer buffer, VkMemoryRequirements* pMemoryRequirements) const noexcept { + fp_vkGetBufferMemoryRequirements(device, buffer, pMemoryRequirements); + } + VkResult bindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, VkDeviceSize memoryOffset) const noexcept { + return fp_vkBindBufferMemory(device, buffer, memory, memoryOffset); + } + void getImageMemoryRequirements(VkImage image, VkMemoryRequirements* pMemoryRequirements) const noexcept { + fp_vkGetImageMemoryRequirements(device, image, pMemoryRequirements); + } + VkResult bindImageMemory(VkImage image, VkDeviceMemory memory, VkDeviceSize memoryOffset) const noexcept { + return fp_vkBindImageMemory(device, image, memory, memoryOffset); + } + void getImageSparseMemoryRequirements(VkImage image, uint32_t* pSparseMemoryRequirementCount, VkSparseImageMemoryRequirements* pSparseMemoryRequirements) const noexcept { + fp_vkGetImageSparseMemoryRequirements(device, image, pSparseMemoryRequirementCount, pSparseMemoryRequirements); + } + VkResult queueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo, VkFence fence) const noexcept { + return fp_vkQueueBindSparse(queue, bindInfoCount, pBindInfo, fence); + } + VkResult createFence(const VkFenceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkFence* pFence) const noexcept { + return fp_vkCreateFence(device, pCreateInfo, pAllocator, pFence); + } + void destroyFence(VkFence fence, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyFence(device, fence, pAllocator); + } + VkResult resetFences(uint32_t fenceCount, const VkFence* pFences) const noexcept { + return fp_vkResetFences(device, fenceCount, pFences); + } + VkResult getFenceStatus(VkFence fence) const noexcept { + return fp_vkGetFenceStatus(device, fence); + } + VkResult waitForFences(uint32_t fenceCount, const VkFence* pFences, VkBool32 waitAll, uint64_t timeout) const noexcept { + return fp_vkWaitForFences(device, fenceCount, pFences, waitAll, timeout); + } + VkResult createSemaphore(const VkSemaphoreCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSemaphore* pSemaphore) const noexcept { + return fp_vkCreateSemaphore(device, pCreateInfo, pAllocator, pSemaphore); + } + void destroySemaphore(VkSemaphore semaphore, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroySemaphore(device, semaphore, pAllocator); + } + VkResult createEvent(const VkEventCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkEvent* pEvent) const noexcept { + return fp_vkCreateEvent(device, pCreateInfo, pAllocator, pEvent); + } + void destroyEvent(VkEvent event, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyEvent(device, event, pAllocator); + } + VkResult getEventStatus(VkEvent event) const noexcept { + return fp_vkGetEventStatus(device, event); + } + VkResult setEvent(VkEvent event) const noexcept { + return fp_vkSetEvent(device, event); + } + VkResult resetEvent(VkEvent event) const noexcept { + return fp_vkResetEvent(device, event); + } + VkResult createQueryPool(const VkQueryPoolCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkQueryPool* pQueryPool) const noexcept { + return fp_vkCreateQueryPool(device, pCreateInfo, pAllocator, pQueryPool); + } + void destroyQueryPool(VkQueryPool queryPool, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyQueryPool(device, queryPool, pAllocator); + } + VkResult getQueryPoolResults(VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount, size_t dataSize, void* pData, VkDeviceSize stride, VkQueryResultFlags flags) const noexcept { + return fp_vkGetQueryPoolResults(device, queryPool, firstQuery, queryCount, dataSize, pData, stride, flags); + } +#if (defined(VK_VERSION_1_2)) + void resetQueryPool(VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount) const noexcept { + fp_vkResetQueryPool(device, queryPool, firstQuery, queryCount); + } +#endif + VkResult createBuffer(const VkBufferCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const noexcept { + return fp_vkCreateBuffer(device, pCreateInfo, pAllocator, pBuffer); + } + void destroyBuffer(VkBuffer buffer, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyBuffer(device, buffer, pAllocator); + } + VkResult createBufferView(const VkBufferViewCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkBufferView* pView) const noexcept { + return fp_vkCreateBufferView(device, pCreateInfo, pAllocator, pView); + } + void destroyBufferView(VkBufferView bufferView, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyBufferView(device, bufferView, pAllocator); + } + VkResult createImage(const VkImageCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkImage* pImage) const noexcept { + return fp_vkCreateImage(device, pCreateInfo, pAllocator, pImage); + } + void destroyImage(VkImage image, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyImage(device, image, pAllocator); + } + void getImageSubresourceLayout(VkImage image, const VkImageSubresource* pSubresource, VkSubresourceLayout* pLayout) const noexcept { + fp_vkGetImageSubresourceLayout(device, image, pSubresource, pLayout); + } + VkResult createImageView(const VkImageViewCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkImageView* pView) const noexcept { + return fp_vkCreateImageView(device, pCreateInfo, pAllocator, pView); + } + void destroyImageView(VkImageView imageView, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyImageView(device, imageView, pAllocator); + } + VkResult createShaderModule(const VkShaderModuleCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkShaderModule* pShaderModule) const noexcept { + return fp_vkCreateShaderModule(device, pCreateInfo, pAllocator, pShaderModule); + } + void destroyShaderModule(VkShaderModule shaderModule, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyShaderModule(device, shaderModule, pAllocator); + } + VkResult createPipelineCache(const VkPipelineCacheCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkPipelineCache* pPipelineCache) const noexcept { + return fp_vkCreatePipelineCache(device, pCreateInfo, pAllocator, pPipelineCache); + } + void destroyPipelineCache(VkPipelineCache pipelineCache, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyPipelineCache(device, pipelineCache, pAllocator); + } + VkResult getPipelineCacheData(VkPipelineCache pipelineCache, size_t* pDataSize, void* pData) const noexcept { + return fp_vkGetPipelineCacheData(device, pipelineCache, pDataSize, pData); + } + VkResult mergePipelineCaches(VkPipelineCache dstCache, uint32_t srcCacheCount, const VkPipelineCache* pSrcCaches) const noexcept { + return fp_vkMergePipelineCaches(device, dstCache, srcCacheCount, pSrcCaches); + } +#if (defined(VK_KHR_pipeline_binary)) + VkResult createPipelineBinariesKHR(const VkPipelineBinaryCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkPipelineBinaryHandlesInfoKHR* pBinaries) const noexcept { + return fp_vkCreatePipelineBinariesKHR(device, pCreateInfo, pAllocator, pBinaries); + } +#endif +#if (defined(VK_KHR_pipeline_binary)) + void destroyPipelineBinaryKHR(VkPipelineBinaryKHR pipelineBinary, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyPipelineBinaryKHR(device, pipelineBinary, pAllocator); + } +#endif +#if (defined(VK_KHR_pipeline_binary)) + VkResult getPipelineKeyKHR(const VkPipelineCreateInfoKHR* pPipelineCreateInfo, VkPipelineBinaryKeyKHR* pPipelineKey) const noexcept { + return fp_vkGetPipelineKeyKHR(device, pPipelineCreateInfo, pPipelineKey); + } +#endif +#if (defined(VK_KHR_pipeline_binary)) + VkResult getPipelineBinaryDataKHR(const VkPipelineBinaryDataInfoKHR* pInfo, VkPipelineBinaryKeyKHR* pPipelineBinaryKey, size_t* pPipelineBinaryDataSize, void* pPipelineBinaryData) const noexcept { + return fp_vkGetPipelineBinaryDataKHR(device, pInfo, pPipelineBinaryKey, pPipelineBinaryDataSize, pPipelineBinaryData); + } +#endif +#if (defined(VK_KHR_pipeline_binary)) + VkResult releaseCapturedPipelineDataKHR(const VkReleaseCapturedPipelineDataInfoKHR* pInfo, const VkAllocationCallbacks* pAllocator) const noexcept { + return fp_vkReleaseCapturedPipelineDataKHR(device, pInfo, pAllocator); + } +#endif + VkResult createGraphicsPipelines(VkPipelineCache pipelineCache, uint32_t createInfoCount, const VkGraphicsPipelineCreateInfo* pCreateInfos, const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines) const noexcept { + return fp_vkCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos, pAllocator, pPipelines); + } + VkResult createComputePipelines(VkPipelineCache pipelineCache, uint32_t createInfoCount, const VkComputePipelineCreateInfo* pCreateInfos, const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines) const noexcept { + return fp_vkCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos, pAllocator, pPipelines); + } +#if (defined(VK_HUAWEI_subpass_shading)) + VkResult getDeviceSubpassShadingMaxWorkgroupSizeHUAWEI(VkRenderPass renderpass, VkExtent2D* pMaxWorkgroupSize) const noexcept { + return fp_vkGetDeviceSubpassShadingMaxWorkgroupSizeHUAWEI(device, renderpass, pMaxWorkgroupSize); + } +#endif + void destroyPipeline(VkPipeline pipeline, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyPipeline(device, pipeline, pAllocator); + } + VkResult createPipelineLayout(const VkPipelineLayoutCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkPipelineLayout* pPipelineLayout) const noexcept { + return fp_vkCreatePipelineLayout(device, pCreateInfo, pAllocator, pPipelineLayout); + } + void destroyPipelineLayout(VkPipelineLayout pipelineLayout, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyPipelineLayout(device, pipelineLayout, pAllocator); + } + VkResult createSampler(const VkSamplerCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const noexcept { + return fp_vkCreateSampler(device, pCreateInfo, pAllocator, pSampler); + } + void destroySampler(VkSampler sampler, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroySampler(device, sampler, pAllocator); + } + VkResult createDescriptorSetLayout(const VkDescriptorSetLayoutCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDescriptorSetLayout* pSetLayout) const noexcept { + return fp_vkCreateDescriptorSetLayout(device, pCreateInfo, pAllocator, pSetLayout); + } + void destroyDescriptorSetLayout(VkDescriptorSetLayout descriptorSetLayout, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyDescriptorSetLayout(device, descriptorSetLayout, pAllocator); + } + VkResult createDescriptorPool(const VkDescriptorPoolCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDescriptorPool* pDescriptorPool) const noexcept { + return fp_vkCreateDescriptorPool(device, pCreateInfo, pAllocator, pDescriptorPool); + } + void destroyDescriptorPool(VkDescriptorPool descriptorPool, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyDescriptorPool(device, descriptorPool, pAllocator); + } + VkResult resetDescriptorPool(VkDescriptorPool descriptorPool, VkDescriptorPoolResetFlags flags) const noexcept { + return fp_vkResetDescriptorPool(device, descriptorPool, flags); + } + VkResult allocateDescriptorSets(const VkDescriptorSetAllocateInfo* pAllocateInfo, VkDescriptorSet* pDescriptorSets) const noexcept { + return fp_vkAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets); + } + VkResult freeDescriptorSets(VkDescriptorPool descriptorPool, uint32_t descriptorSetCount, const VkDescriptorSet* pDescriptorSets) const noexcept { + return fp_vkFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets); + } + void updateDescriptorSets(uint32_t descriptorWriteCount, const VkWriteDescriptorSet* pDescriptorWrites, uint32_t descriptorCopyCount, const VkCopyDescriptorSet* pDescriptorCopies) const noexcept { + fp_vkUpdateDescriptorSets(device, descriptorWriteCount, pDescriptorWrites, descriptorCopyCount, pDescriptorCopies); + } + VkResult createFramebuffer(const VkFramebufferCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const noexcept { + return fp_vkCreateFramebuffer(device, pCreateInfo, pAllocator, pFramebuffer); + } + void destroyFramebuffer(VkFramebuffer framebuffer, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyFramebuffer(device, framebuffer, pAllocator); + } + VkResult createRenderPass(const VkRenderPassCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const noexcept { + return fp_vkCreateRenderPass(device, pCreateInfo, pAllocator, pRenderPass); + } + void destroyRenderPass(VkRenderPass renderPass, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyRenderPass(device, renderPass, pAllocator); + } + void getRenderAreaGranularity(VkRenderPass renderPass, VkExtent2D* pGranularity) const noexcept { + fp_vkGetRenderAreaGranularity(device, renderPass, pGranularity); + } +#if (defined(VK_KHR_maintenance5)) + void getRenderingAreaGranularityKHR(const VkRenderingAreaInfoKHR* pRenderingAreaInfo, VkExtent2D* pGranularity) const noexcept { + fp_vkGetRenderingAreaGranularityKHR(device, pRenderingAreaInfo, pGranularity); + } +#endif + VkResult createCommandPool(const VkCommandPoolCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const noexcept { + return fp_vkCreateCommandPool(device, pCreateInfo, pAllocator, pCommandPool); + } + void destroyCommandPool(VkCommandPool commandPool, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyCommandPool(device, commandPool, pAllocator); + } + VkResult resetCommandPool(VkCommandPool commandPool, VkCommandPoolResetFlags flags) const noexcept { + return fp_vkResetCommandPool(device, commandPool, flags); + } + VkResult allocateCommandBuffers(const VkCommandBufferAllocateInfo* pAllocateInfo, VkCommandBuffer* pCommandBuffers) const noexcept { + return fp_vkAllocateCommandBuffers(device, pAllocateInfo, pCommandBuffers); + } + void freeCommandBuffers(VkCommandPool commandPool, uint32_t commandBufferCount, const VkCommandBuffer* pCommandBuffers) const noexcept { + fp_vkFreeCommandBuffers(device, commandPool, commandBufferCount, pCommandBuffers); + } + VkResult beginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo* pBeginInfo) const noexcept { + return fp_vkBeginCommandBuffer(commandBuffer, pBeginInfo); + } + VkResult endCommandBuffer(VkCommandBuffer commandBuffer) const noexcept { + return fp_vkEndCommandBuffer(commandBuffer); + } + VkResult resetCommandBuffer(VkCommandBuffer commandBuffer, VkCommandBufferResetFlags flags) const noexcept { + return fp_vkResetCommandBuffer(commandBuffer, flags); + } + void cmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipeline pipeline) const noexcept { + fp_vkCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline); + } +#if (defined(VK_EXT_attachment_feedback_loop_dynamic_state)) + void cmdSetAttachmentFeedbackLoopEnableEXT(VkCommandBuffer commandBuffer, VkImageAspectFlags aspectMask) const noexcept { + fp_vkCmdSetAttachmentFeedbackLoopEnableEXT(commandBuffer, aspectMask); + } +#endif + void cmdSetViewport(VkCommandBuffer commandBuffer, uint32_t firstViewport, uint32_t viewportCount, const VkViewport* pViewports) const noexcept { + fp_vkCmdSetViewport(commandBuffer, firstViewport, viewportCount, pViewports); + } + void cmdSetScissor(VkCommandBuffer commandBuffer, uint32_t firstScissor, uint32_t scissorCount, const VkRect2D* pScissors) const noexcept { + fp_vkCmdSetScissor(commandBuffer, firstScissor, scissorCount, pScissors); + } + void cmdSetLineWidth(VkCommandBuffer commandBuffer, float lineWidth) const noexcept { + fp_vkCmdSetLineWidth(commandBuffer, lineWidth); + } + void cmdSetDepthBias(VkCommandBuffer commandBuffer, float depthBiasConstantFactor, float depthBiasClamp, float depthBiasSlopeFactor) const noexcept { + fp_vkCmdSetDepthBias(commandBuffer, depthBiasConstantFactor, depthBiasClamp, depthBiasSlopeFactor); + } + void cmdSetBlendConstants(VkCommandBuffer commandBuffer, const float blendConstants[4]) const noexcept { + fp_vkCmdSetBlendConstants(commandBuffer, blendConstants); + } + void cmdSetDepthBounds(VkCommandBuffer commandBuffer, float minDepthBounds, float maxDepthBounds) const noexcept { + fp_vkCmdSetDepthBounds(commandBuffer, minDepthBounds, maxDepthBounds); + } + void cmdSetStencilCompareMask(VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask, uint32_t compareMask) const noexcept { + fp_vkCmdSetStencilCompareMask(commandBuffer, faceMask, compareMask); + } + void cmdSetStencilWriteMask(VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask, uint32_t writeMask) const noexcept { + fp_vkCmdSetStencilWriteMask(commandBuffer, faceMask, writeMask); + } + void cmdSetStencilReference(VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask, uint32_t reference) const noexcept { + fp_vkCmdSetStencilReference(commandBuffer, faceMask, reference); + } + void cmdBindDescriptorSets(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipelineLayout layout, uint32_t firstSet, uint32_t descriptorSetCount, const VkDescriptorSet* pDescriptorSets, uint32_t dynamicOffsetCount, const uint32_t* pDynamicOffsets) const noexcept { + fp_vkCmdBindDescriptorSets(commandBuffer, pipelineBindPoint, layout, firstSet, descriptorSetCount, pDescriptorSets, dynamicOffsetCount, pDynamicOffsets); + } + void cmdBindIndexBuffer(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkIndexType indexType) const noexcept { + fp_vkCmdBindIndexBuffer(commandBuffer, buffer, offset, indexType); + } + void cmdBindVertexBuffers(VkCommandBuffer commandBuffer, uint32_t firstBinding, uint32_t bindingCount, const VkBuffer* pBuffers, const VkDeviceSize* pOffsets) const noexcept { + fp_vkCmdBindVertexBuffers(commandBuffer, firstBinding, bindingCount, pBuffers, pOffsets); + } + void cmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount, uint32_t firstVertex, uint32_t firstInstance) const noexcept { + fp_vkCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance); + } + void cmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount, uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const noexcept { + fp_vkCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance); + } +#if (defined(VK_EXT_multi_draw)) + void cmdDrawMultiEXT(VkCommandBuffer commandBuffer, uint32_t drawCount, const VkMultiDrawInfoEXT* pVertexInfo, uint32_t instanceCount, uint32_t firstInstance, uint32_t stride) const noexcept { + fp_vkCmdDrawMultiEXT(commandBuffer, drawCount, pVertexInfo, instanceCount, firstInstance, stride); + } +#endif +#if (defined(VK_EXT_multi_draw)) + void cmdDrawMultiIndexedEXT(VkCommandBuffer commandBuffer, uint32_t drawCount, const VkMultiDrawIndexedInfoEXT* pIndexInfo, uint32_t instanceCount, uint32_t firstInstance, uint32_t stride, const int32_t* pVertexOffset) const noexcept { + fp_vkCmdDrawMultiIndexedEXT(commandBuffer, drawCount, pIndexInfo, instanceCount, firstInstance, stride, pVertexOffset); + } +#endif + void cmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, uint32_t drawCount, uint32_t stride) const noexcept { + fp_vkCmdDrawIndirect(commandBuffer, buffer, offset, drawCount, stride); + } + void cmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, uint32_t drawCount, uint32_t stride) const noexcept { + fp_vkCmdDrawIndexedIndirect(commandBuffer, buffer, offset, drawCount, stride); + } + void cmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY, uint32_t groupCountZ) const noexcept { + fp_vkCmdDispatch(commandBuffer, groupCountX, groupCountY, groupCountZ); + } + void cmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) const noexcept { + fp_vkCmdDispatchIndirect(commandBuffer, buffer, offset); + } +#if (defined(VK_HUAWEI_subpass_shading)) + void cmdSubpassShadingHUAWEI(VkCommandBuffer commandBuffer) const noexcept { + fp_vkCmdSubpassShadingHUAWEI(commandBuffer); + } +#endif +#if (defined(VK_HUAWEI_cluster_culling_shader)) + void cmdDrawClusterHUAWEI(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY, uint32_t groupCountZ) const noexcept { + fp_vkCmdDrawClusterHUAWEI(commandBuffer, groupCountX, groupCountY, groupCountZ); + } +#endif +#if (defined(VK_HUAWEI_cluster_culling_shader)) + void cmdDrawClusterIndirectHUAWEI(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) const noexcept { + fp_vkCmdDrawClusterIndirectHUAWEI(commandBuffer, buffer, offset); + } +#endif +#if (defined(VK_NV_device_generated_commands_compute)) + void cmdUpdatePipelineIndirectBufferNV(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipeline pipeline) const noexcept { + fp_vkCmdUpdatePipelineIndirectBufferNV(commandBuffer, pipelineBindPoint, pipeline); + } +#endif + void cmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer, uint32_t regionCount, const VkBufferCopy* pRegions) const noexcept { + fp_vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, regionCount, pRegions); + } + void cmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkImageCopy* pRegions) const noexcept { + fp_vkCmdCopyImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions); + } + void cmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkImageBlit* pRegions, VkFilter filter) const noexcept { + fp_vkCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter); + } + void cmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkBufferImageCopy* pRegions) const noexcept { + fp_vkCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions); + } + void cmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions) const noexcept { + fp_vkCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions); + } +#if (defined(VK_NV_copy_memory_indirect)) + void cmdCopyMemoryIndirectNV(VkCommandBuffer commandBuffer, VkDeviceAddress copyBufferAddress, uint32_t copyCount, uint32_t stride) const noexcept { + fp_vkCmdCopyMemoryIndirectNV(commandBuffer, copyBufferAddress, copyCount, stride); + } +#endif +#if (defined(VK_NV_copy_memory_indirect)) + void cmdCopyMemoryToImageIndirectNV(VkCommandBuffer commandBuffer, VkDeviceAddress copyBufferAddress, uint32_t copyCount, uint32_t stride, VkImage dstImage, VkImageLayout dstImageLayout, const VkImageSubresourceLayers* pImageSubresources) const noexcept { + fp_vkCmdCopyMemoryToImageIndirectNV(commandBuffer, copyBufferAddress, copyCount, stride, dstImage, dstImageLayout, pImageSubresources); + } +#endif + void cmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize dataSize, const void* pData) const noexcept { + fp_vkCmdUpdateBuffer(commandBuffer, dstBuffer, dstOffset, dataSize, pData); + } + void cmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize size, uint32_t data) const noexcept { + fp_vkCmdFillBuffer(commandBuffer, dstBuffer, dstOffset, size, data); + } + void cmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout, const VkClearColorValue* pColor, uint32_t rangeCount, const VkImageSubresourceRange* pRanges) const noexcept { + fp_vkCmdClearColorImage(commandBuffer, image, imageLayout, pColor, rangeCount, pRanges); + } + void cmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout, const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount, const VkImageSubresourceRange* pRanges) const noexcept { + fp_vkCmdClearDepthStencilImage(commandBuffer, image, imageLayout, pDepthStencil, rangeCount, pRanges); + } + void cmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount, const VkClearAttachment* pAttachments, uint32_t rectCount, const VkClearRect* pRects) const noexcept { + fp_vkCmdClearAttachments(commandBuffer, attachmentCount, pAttachments, rectCount, pRects); + } + void cmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkImageResolve* pRegions) const noexcept { + fp_vkCmdResolveImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions); + } + void cmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const noexcept { + fp_vkCmdSetEvent(commandBuffer, event, stageMask); + } + void cmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const noexcept { + fp_vkCmdResetEvent(commandBuffer, event, stageMask); + } + void cmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask, uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers, uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier* pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier* pImageMemoryBarriers) const noexcept { + fp_vkCmdWaitEvents(commandBuffer, eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers); + } + void cmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers, uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier* pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier* pImageMemoryBarriers) const noexcept { + fp_vkCmdPipelineBarrier(commandBuffer, srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers); + } + void cmdBeginQuery(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t query, VkQueryControlFlags flags) const noexcept { + fp_vkCmdBeginQuery(commandBuffer, queryPool, query, flags); + } + void cmdEndQuery(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t query) const noexcept { + fp_vkCmdEndQuery(commandBuffer, queryPool, query); + } +#if (defined(VK_EXT_conditional_rendering)) + void cmdBeginConditionalRenderingEXT(VkCommandBuffer commandBuffer, const VkConditionalRenderingBeginInfoEXT* pConditionalRenderingBegin) const noexcept { + fp_vkCmdBeginConditionalRenderingEXT(commandBuffer, pConditionalRenderingBegin); + } +#endif +#if (defined(VK_EXT_conditional_rendering)) + void cmdEndConditionalRenderingEXT(VkCommandBuffer commandBuffer) const noexcept { + fp_vkCmdEndConditionalRenderingEXT(commandBuffer); + } +#endif + void cmdResetQueryPool(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount) const noexcept { + fp_vkCmdResetQueryPool(commandBuffer, queryPool, firstQuery, queryCount); + } + void cmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage, VkQueryPool queryPool, uint32_t query) const noexcept { + fp_vkCmdWriteTimestamp(commandBuffer, pipelineStage, queryPool, query); + } + void cmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize stride, VkQueryResultFlags flags) const noexcept { + fp_vkCmdCopyQueryPoolResults(commandBuffer, queryPool, firstQuery, queryCount, dstBuffer, dstOffset, stride, flags); + } + void cmdPushConstants(VkCommandBuffer commandBuffer, VkPipelineLayout layout, VkShaderStageFlags stageFlags, uint32_t offset, uint32_t size, const void* pValues) const noexcept { + fp_vkCmdPushConstants(commandBuffer, layout, stageFlags, offset, size, pValues); + } + void cmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin, VkSubpassContents contents) const noexcept { + fp_vkCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents); + } + void cmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) const noexcept { + fp_vkCmdNextSubpass(commandBuffer, contents); + } + void cmdEndRenderPass(VkCommandBuffer commandBuffer) const noexcept { + fp_vkCmdEndRenderPass(commandBuffer); + } + void cmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount, const VkCommandBuffer* pCommandBuffers) const noexcept { + fp_vkCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers); + } +#if (defined(VK_KHR_display_swapchain)) + VkResult createSharedSwapchainsKHR(uint32_t swapchainCount, const VkSwapchainCreateInfoKHR* pCreateInfos, const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchains) const noexcept { + return fp_vkCreateSharedSwapchainsKHR(device, swapchainCount, pCreateInfos, pAllocator, pSwapchains); + } +#endif +#if (defined(VK_KHR_swapchain)) + VkResult createSwapchainKHR(const VkSwapchainCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const noexcept { + return fp_vkCreateSwapchainKHR(device, pCreateInfo, pAllocator, pSwapchain); + } +#endif +#if (defined(VK_KHR_swapchain)) + void destroySwapchainKHR(VkSwapchainKHR swapchain, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroySwapchainKHR(device, swapchain, pAllocator); + } +#endif +#if (defined(VK_KHR_swapchain)) + VkResult getSwapchainImagesKHR(VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages) const noexcept { + return fp_vkGetSwapchainImagesKHR(device, swapchain, pSwapchainImageCount, pSwapchainImages); + } +#endif +#if (defined(VK_KHR_swapchain)) + VkResult acquireNextImageKHR(VkSwapchainKHR swapchain, uint64_t timeout, VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const noexcept { + return fp_vkAcquireNextImageKHR(device, swapchain, timeout, semaphore, fence, pImageIndex); + } +#endif +#if (defined(VK_KHR_swapchain)) + VkResult queuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo) const noexcept { + return fp_vkQueuePresentKHR(queue, pPresentInfo); + } +#endif +#if (defined(VK_EXT_debug_marker)) + VkResult debugMarkerSetObjectNameEXT(const VkDebugMarkerObjectNameInfoEXT* pNameInfo) const noexcept { + return fp_vkDebugMarkerSetObjectNameEXT(device, pNameInfo); + } +#endif +#if (defined(VK_EXT_debug_marker)) + VkResult debugMarkerSetObjectTagEXT(const VkDebugMarkerObjectTagInfoEXT* pTagInfo) const noexcept { + return fp_vkDebugMarkerSetObjectTagEXT(device, pTagInfo); + } +#endif +#if (defined(VK_EXT_debug_marker)) + void cmdDebugMarkerBeginEXT(VkCommandBuffer commandBuffer, const VkDebugMarkerMarkerInfoEXT* pMarkerInfo) const noexcept { + fp_vkCmdDebugMarkerBeginEXT(commandBuffer, pMarkerInfo); + } +#endif +#if (defined(VK_EXT_debug_marker)) + void cmdDebugMarkerEndEXT(VkCommandBuffer commandBuffer) const noexcept { + fp_vkCmdDebugMarkerEndEXT(commandBuffer); + } +#endif +#if (defined(VK_EXT_debug_marker)) + void cmdDebugMarkerInsertEXT(VkCommandBuffer commandBuffer, const VkDebugMarkerMarkerInfoEXT* pMarkerInfo) const noexcept { + fp_vkCmdDebugMarkerInsertEXT(commandBuffer, pMarkerInfo); + } +#endif +#if (defined(VK_NV_external_memory_win32)) + VkResult getMemoryWin32HandleNV(VkDeviceMemory memory, VkExternalMemoryHandleTypeFlagsNV handleType, HANDLE* pHandle) const noexcept { + return fp_vkGetMemoryWin32HandleNV(device, memory, handleType, pHandle); + } +#endif +#if (defined(VK_NV_device_generated_commands)) + void cmdExecuteGeneratedCommandsNV(VkCommandBuffer commandBuffer, VkBool32 isPreprocessed, const VkGeneratedCommandsInfoNV* pGeneratedCommandsInfo) const noexcept { + fp_vkCmdExecuteGeneratedCommandsNV(commandBuffer, isPreprocessed, pGeneratedCommandsInfo); + } +#endif +#if (defined(VK_NV_device_generated_commands)) + void cmdPreprocessGeneratedCommandsNV(VkCommandBuffer commandBuffer, const VkGeneratedCommandsInfoNV* pGeneratedCommandsInfo) const noexcept { + fp_vkCmdPreprocessGeneratedCommandsNV(commandBuffer, pGeneratedCommandsInfo); + } +#endif +#if (defined(VK_NV_device_generated_commands)) + void cmdBindPipelineShaderGroupNV(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipeline pipeline, uint32_t groupIndex) const noexcept { + fp_vkCmdBindPipelineShaderGroupNV(commandBuffer, pipelineBindPoint, pipeline, groupIndex); + } +#endif +#if (defined(VK_NV_device_generated_commands)) + void getGeneratedCommandsMemoryRequirementsNV(const VkGeneratedCommandsMemoryRequirementsInfoNV* pInfo, VkMemoryRequirements2KHR* pMemoryRequirements) const noexcept { + fp_vkGetGeneratedCommandsMemoryRequirementsNV(device, pInfo, pMemoryRequirements); + } +#endif +#if (defined(VK_NV_device_generated_commands)) + VkResult createIndirectCommandsLayoutNV(const VkIndirectCommandsLayoutCreateInfoNV* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkIndirectCommandsLayoutNV* pIndirectCommandsLayout) const noexcept { + return fp_vkCreateIndirectCommandsLayoutNV(device, pCreateInfo, pAllocator, pIndirectCommandsLayout); + } +#endif +#if (defined(VK_NV_device_generated_commands)) + void destroyIndirectCommandsLayoutNV(VkIndirectCommandsLayoutNV indirectCommandsLayout, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyIndirectCommandsLayoutNV(device, indirectCommandsLayout, pAllocator); + } +#endif +#if (defined(VK_KHR_push_descriptor)) + void cmdPushDescriptorSetKHR(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipelineLayout layout, uint32_t set, uint32_t descriptorWriteCount, const VkWriteDescriptorSet* pDescriptorWrites) const noexcept { + fp_vkCmdPushDescriptorSetKHR(commandBuffer, pipelineBindPoint, layout, set, descriptorWriteCount, pDescriptorWrites); + } +#endif +#if (defined(VK_VERSION_1_1)) + void trimCommandPool(VkCommandPool commandPool, VkCommandPoolTrimFlagsKHR flags) const noexcept { + fp_vkTrimCommandPool(device, commandPool, flags); + } +#endif +#if (defined(VK_KHR_external_memory_win32)) + VkResult getMemoryWin32HandleKHR(const VkMemoryGetWin32HandleInfoKHR* pGetWin32HandleInfo, HANDLE* pHandle) const noexcept { + return fp_vkGetMemoryWin32HandleKHR(device, pGetWin32HandleInfo, pHandle); + } +#endif +#if (defined(VK_KHR_external_memory_win32)) + VkResult getMemoryWin32HandlePropertiesKHR(VkExternalMemoryHandleTypeFlagBitsKHR handleType, HANDLE handle, VkMemoryWin32HandlePropertiesKHR* pMemoryWin32HandleProperties) const noexcept { + return fp_vkGetMemoryWin32HandlePropertiesKHR(device, handleType, handle, pMemoryWin32HandleProperties); + } +#endif +#if (defined(VK_KHR_external_memory_fd)) + VkResult getMemoryFdKHR(const VkMemoryGetFdInfoKHR* pGetFdInfo, int* pFd) const noexcept { + return fp_vkGetMemoryFdKHR(device, pGetFdInfo, pFd); + } +#endif +#if (defined(VK_KHR_external_memory_fd)) + VkResult getMemoryFdPropertiesKHR(VkExternalMemoryHandleTypeFlagBitsKHR handleType, int fd, VkMemoryFdPropertiesKHR* pMemoryFdProperties) const noexcept { + return fp_vkGetMemoryFdPropertiesKHR(device, handleType, fd, pMemoryFdProperties); + } +#endif +#if (defined(VK_FUCHSIA_external_memory)) + VkResult getMemoryZirconHandleFUCHSIA(const VkMemoryGetZirconHandleInfoFUCHSIA* pGetZirconHandleInfo, zx_handle_t* pZirconHandle) const noexcept { + return fp_vkGetMemoryZirconHandleFUCHSIA(device, pGetZirconHandleInfo, pZirconHandle); + } +#endif +#if (defined(VK_FUCHSIA_external_memory)) + VkResult getMemoryZirconHandlePropertiesFUCHSIA(VkExternalMemoryHandleTypeFlagBitsKHR handleType, zx_handle_t zirconHandle, VkMemoryZirconHandlePropertiesFUCHSIA* pMemoryZirconHandleProperties) const noexcept { + return fp_vkGetMemoryZirconHandlePropertiesFUCHSIA(device, handleType, zirconHandle, pMemoryZirconHandleProperties); + } +#endif +#if (defined(VK_NV_external_memory_rdma)) + VkResult getMemoryRemoteAddressNV(const VkMemoryGetRemoteAddressInfoNV* pMemoryGetRemoteAddressInfo, VkRemoteAddressNV* pAddress) const noexcept { + return fp_vkGetMemoryRemoteAddressNV(device, pMemoryGetRemoteAddressInfo, pAddress); + } +#endif +#if (defined(VK_NV_external_memory_sci_buf)) + VkResult getMemorySciBufNV(const VkMemoryGetSciBufInfoNV* pGetSciBufInfo, NvSciBufObj* pHandle) const noexcept { + return fp_vkGetMemorySciBufNV(device, pGetSciBufInfo, pHandle); + } +#endif +#if (defined(VK_KHR_external_semaphore_win32)) + VkResult getSemaphoreWin32HandleKHR(const VkSemaphoreGetWin32HandleInfoKHR* pGetWin32HandleInfo, HANDLE* pHandle) const noexcept { + return fp_vkGetSemaphoreWin32HandleKHR(device, pGetWin32HandleInfo, pHandle); + } +#endif +#if (defined(VK_KHR_external_semaphore_win32)) + VkResult importSemaphoreWin32HandleKHR(const VkImportSemaphoreWin32HandleInfoKHR* pImportSemaphoreWin32HandleInfo) const noexcept { + return fp_vkImportSemaphoreWin32HandleKHR(device, pImportSemaphoreWin32HandleInfo); + } +#endif +#if (defined(VK_KHR_external_semaphore_fd)) + VkResult getSemaphoreFdKHR(const VkSemaphoreGetFdInfoKHR* pGetFdInfo, int* pFd) const noexcept { + return fp_vkGetSemaphoreFdKHR(device, pGetFdInfo, pFd); + } +#endif +#if (defined(VK_KHR_external_semaphore_fd)) + VkResult importSemaphoreFdKHR(const VkImportSemaphoreFdInfoKHR* pImportSemaphoreFdInfo) const noexcept { + return fp_vkImportSemaphoreFdKHR(device, pImportSemaphoreFdInfo); + } +#endif +#if (defined(VK_FUCHSIA_external_semaphore)) + VkResult getSemaphoreZirconHandleFUCHSIA(const VkSemaphoreGetZirconHandleInfoFUCHSIA* pGetZirconHandleInfo, zx_handle_t* pZirconHandle) const noexcept { + return fp_vkGetSemaphoreZirconHandleFUCHSIA(device, pGetZirconHandleInfo, pZirconHandle); + } +#endif +#if (defined(VK_FUCHSIA_external_semaphore)) + VkResult importSemaphoreZirconHandleFUCHSIA(const VkImportSemaphoreZirconHandleInfoFUCHSIA* pImportSemaphoreZirconHandleInfo) const noexcept { + return fp_vkImportSemaphoreZirconHandleFUCHSIA(device, pImportSemaphoreZirconHandleInfo); + } +#endif +#if (defined(VK_KHR_external_fence_win32)) + VkResult getFenceWin32HandleKHR(const VkFenceGetWin32HandleInfoKHR* pGetWin32HandleInfo, HANDLE* pHandle) const noexcept { + return fp_vkGetFenceWin32HandleKHR(device, pGetWin32HandleInfo, pHandle); + } +#endif +#if (defined(VK_KHR_external_fence_win32)) + VkResult importFenceWin32HandleKHR(const VkImportFenceWin32HandleInfoKHR* pImportFenceWin32HandleInfo) const noexcept { + return fp_vkImportFenceWin32HandleKHR(device, pImportFenceWin32HandleInfo); + } +#endif +#if (defined(VK_KHR_external_fence_fd)) + VkResult getFenceFdKHR(const VkFenceGetFdInfoKHR* pGetFdInfo, int* pFd) const noexcept { + return fp_vkGetFenceFdKHR(device, pGetFdInfo, pFd); + } +#endif +#if (defined(VK_KHR_external_fence_fd)) + VkResult importFenceFdKHR(const VkImportFenceFdInfoKHR* pImportFenceFdInfo) const noexcept { + return fp_vkImportFenceFdKHR(device, pImportFenceFdInfo); + } +#endif +#if (defined(VK_NV_external_sci_sync)) || (defined(VK_NV_external_sci_sync2)) + VkResult getFenceSciSyncFenceNV(const VkFenceGetSciSyncInfoNV* pGetSciSyncHandleInfo, void* pHandle) const noexcept { + return fp_vkGetFenceSciSyncFenceNV(device, pGetSciSyncHandleInfo, pHandle); + } +#endif +#if (defined(VK_NV_external_sci_sync)) || (defined(VK_NV_external_sci_sync2)) + VkResult getFenceSciSyncObjNV(const VkFenceGetSciSyncInfoNV* pGetSciSyncHandleInfo, void* pHandle) const noexcept { + return fp_vkGetFenceSciSyncObjNV(device, pGetSciSyncHandleInfo, pHandle); + } +#endif +#if (defined(VK_NV_external_sci_sync)) || (defined(VK_NV_external_sci_sync2)) + VkResult importFenceSciSyncFenceNV(const VkImportFenceSciSyncInfoNV* pImportFenceSciSyncInfo) const noexcept { + return fp_vkImportFenceSciSyncFenceNV(device, pImportFenceSciSyncInfo); + } +#endif +#if (defined(VK_NV_external_sci_sync)) || (defined(VK_NV_external_sci_sync2)) + VkResult importFenceSciSyncObjNV(const VkImportFenceSciSyncInfoNV* pImportFenceSciSyncInfo) const noexcept { + return fp_vkImportFenceSciSyncObjNV(device, pImportFenceSciSyncInfo); + } +#endif +#if (defined(VK_NV_external_sci_sync)) + VkResult getSemaphoreSciSyncObjNV(const VkSemaphoreGetSciSyncInfoNV* pGetSciSyncInfo, void* pHandle) const noexcept { + return fp_vkGetSemaphoreSciSyncObjNV(device, pGetSciSyncInfo, pHandle); + } +#endif +#if (defined(VK_NV_external_sci_sync)) + VkResult importSemaphoreSciSyncObjNV(const VkImportSemaphoreSciSyncInfoNV* pImportSemaphoreSciSyncInfo) const noexcept { + return fp_vkImportSemaphoreSciSyncObjNV(device, pImportSemaphoreSciSyncInfo); + } +#endif +#if (defined(VK_NV_external_sci_sync2)) + VkResult createSemaphoreSciSyncPoolNV(const VkSemaphoreSciSyncPoolCreateInfoNV* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSemaphoreSciSyncPoolNV* pSemaphorePool) const noexcept { + return fp_vkCreateSemaphoreSciSyncPoolNV(device, pCreateInfo, pAllocator, pSemaphorePool); + } +#endif +#if (defined(VK_NV_external_sci_sync2)) + void destroySemaphoreSciSyncPoolNV(VkSemaphoreSciSyncPoolNV semaphorePool, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroySemaphoreSciSyncPoolNV(device, semaphorePool, pAllocator); + } +#endif +#if (defined(VK_EXT_display_control)) + VkResult displayPowerControlEXT(VkDisplayKHR display, const VkDisplayPowerInfoEXT* pDisplayPowerInfo) const noexcept { + return fp_vkDisplayPowerControlEXT(device, display, pDisplayPowerInfo); + } +#endif +#if (defined(VK_EXT_display_control)) + VkResult registerDeviceEventEXT(const VkDeviceEventInfoEXT* pDeviceEventInfo, const VkAllocationCallbacks* pAllocator, VkFence* pFence) const noexcept { + return fp_vkRegisterDeviceEventEXT(device, pDeviceEventInfo, pAllocator, pFence); + } +#endif +#if (defined(VK_EXT_display_control)) + VkResult registerDisplayEventEXT(VkDisplayKHR display, const VkDisplayEventInfoEXT* pDisplayEventInfo, const VkAllocationCallbacks* pAllocator, VkFence* pFence) const noexcept { + return fp_vkRegisterDisplayEventEXT(device, display, pDisplayEventInfo, pAllocator, pFence); + } +#endif +#if (defined(VK_EXT_display_control)) + VkResult getSwapchainCounterEXT(VkSwapchainKHR swapchain, VkSurfaceCounterFlagBitsEXT counter, uint64_t* pCounterValue) const noexcept { + return fp_vkGetSwapchainCounterEXT(device, swapchain, counter, pCounterValue); + } +#endif +#if (defined(VK_VERSION_1_1)) + void getDeviceGroupPeerMemoryFeatures(uint32_t heapIndex, uint32_t localDeviceIndex, uint32_t remoteDeviceIndex, VkPeerMemoryFeatureFlagsKHR* pPeerMemoryFeatures) const noexcept { + fp_vkGetDeviceGroupPeerMemoryFeatures(device, heapIndex, localDeviceIndex, remoteDeviceIndex, pPeerMemoryFeatures); + } +#endif +#if (defined(VK_VERSION_1_1)) + VkResult bindBufferMemory2(uint32_t bindInfoCount, const VkBindBufferMemoryInfoKHR* pBindInfos) const noexcept { + return fp_vkBindBufferMemory2(device, bindInfoCount, pBindInfos); + } +#endif +#if (defined(VK_VERSION_1_1)) + VkResult bindImageMemory2(uint32_t bindInfoCount, const VkBindImageMemoryInfoKHR* pBindInfos) const noexcept { + return fp_vkBindImageMemory2(device, bindInfoCount, pBindInfos); + } +#endif +#if (defined(VK_VERSION_1_1)) + void cmdSetDeviceMask(VkCommandBuffer commandBuffer, uint32_t deviceMask) const noexcept { + fp_vkCmdSetDeviceMask(commandBuffer, deviceMask); + } +#endif +#if (defined(VK_KHR_swapchain)) || (defined(VK_KHR_device_group)) + VkResult getDeviceGroupPresentCapabilitiesKHR(VkDeviceGroupPresentCapabilitiesKHR* pDeviceGroupPresentCapabilities) const noexcept { + return fp_vkGetDeviceGroupPresentCapabilitiesKHR(device, pDeviceGroupPresentCapabilities); + } +#endif +#if (defined(VK_KHR_swapchain)) || (defined(VK_KHR_device_group)) + VkResult getDeviceGroupSurfacePresentModesKHR(VkSurfaceKHR surface, VkDeviceGroupPresentModeFlagsKHR* pModes) const noexcept { + return fp_vkGetDeviceGroupSurfacePresentModesKHR(device, surface, pModes); + } +#endif +#if (defined(VK_KHR_swapchain)) || (defined(VK_KHR_device_group)) + VkResult acquireNextImage2KHR(const VkAcquireNextImageInfoKHR* pAcquireInfo, uint32_t* pImageIndex) const noexcept { + return fp_vkAcquireNextImage2KHR(device, pAcquireInfo, pImageIndex); + } +#endif +#if (defined(VK_VERSION_1_1)) + void cmdDispatchBase(VkCommandBuffer commandBuffer, uint32_t baseGroupX, uint32_t baseGroupY, uint32_t baseGroupZ, uint32_t groupCountX, uint32_t groupCountY, uint32_t groupCountZ) const noexcept { + fp_vkCmdDispatchBase(commandBuffer, baseGroupX, baseGroupY, baseGroupZ, groupCountX, groupCountY, groupCountZ); + } +#endif +#if (defined(VK_VERSION_1_1)) + VkResult createDescriptorUpdateTemplate(const VkDescriptorUpdateTemplateCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDescriptorUpdateTemplateKHR* pDescriptorUpdateTemplate) const noexcept { + return fp_vkCreateDescriptorUpdateTemplate(device, pCreateInfo, pAllocator, pDescriptorUpdateTemplate); + } +#endif +#if (defined(VK_VERSION_1_1)) + void destroyDescriptorUpdateTemplate(VkDescriptorUpdateTemplateKHR descriptorUpdateTemplate, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyDescriptorUpdateTemplate(device, descriptorUpdateTemplate, pAllocator); + } +#endif +#if (defined(VK_VERSION_1_1)) + void updateDescriptorSetWithTemplate(VkDescriptorSet descriptorSet, VkDescriptorUpdateTemplateKHR descriptorUpdateTemplate, const void* pData) const noexcept { + fp_vkUpdateDescriptorSetWithTemplate(device, descriptorSet, descriptorUpdateTemplate, pData); + } +#endif +#if (defined(VK_KHR_push_descriptor)) || (defined(VK_KHR_descriptor_update_template)) + void cmdPushDescriptorSetWithTemplateKHR(VkCommandBuffer commandBuffer, VkDescriptorUpdateTemplateKHR descriptorUpdateTemplate, VkPipelineLayout layout, uint32_t set, const void* pData) const noexcept { + fp_vkCmdPushDescriptorSetWithTemplateKHR(commandBuffer, descriptorUpdateTemplate, layout, set, pData); + } +#endif +#if (defined(VK_EXT_hdr_metadata)) + void setHdrMetadataEXT(uint32_t swapchainCount, const VkSwapchainKHR* pSwapchains, const VkHdrMetadataEXT* pMetadata) const noexcept { + fp_vkSetHdrMetadataEXT(device, swapchainCount, pSwapchains, pMetadata); + } +#endif +#if (defined(VK_KHR_shared_presentable_image)) + VkResult getSwapchainStatusKHR(VkSwapchainKHR swapchain) const noexcept { + return fp_vkGetSwapchainStatusKHR(device, swapchain); + } +#endif +#if (defined(VK_GOOGLE_display_timing)) + VkResult getRefreshCycleDurationGOOGLE(VkSwapchainKHR swapchain, VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties) const noexcept { + return fp_vkGetRefreshCycleDurationGOOGLE(device, swapchain, pDisplayTimingProperties); + } +#endif +#if (defined(VK_GOOGLE_display_timing)) + VkResult getPastPresentationTimingGOOGLE(VkSwapchainKHR swapchain, uint32_t* pPresentationTimingCount, VkPastPresentationTimingGOOGLE* pPresentationTimings) const noexcept { + return fp_vkGetPastPresentationTimingGOOGLE(device, swapchain, pPresentationTimingCount, pPresentationTimings); + } +#endif +#if (defined(VK_NV_clip_space_w_scaling)) + void cmdSetViewportWScalingNV(VkCommandBuffer commandBuffer, uint32_t firstViewport, uint32_t viewportCount, const VkViewportWScalingNV* pViewportWScalings) const noexcept { + fp_vkCmdSetViewportWScalingNV(commandBuffer, firstViewport, viewportCount, pViewportWScalings); + } +#endif +#if (defined(VK_EXT_discard_rectangles)) + void cmdSetDiscardRectangleEXT(VkCommandBuffer commandBuffer, uint32_t firstDiscardRectangle, uint32_t discardRectangleCount, const VkRect2D* pDiscardRectangles) const noexcept { + fp_vkCmdSetDiscardRectangleEXT(commandBuffer, firstDiscardRectangle, discardRectangleCount, pDiscardRectangles); + } +#endif +#if ((defined(VK_EXT_discard_rectangles))) && VK_HEADER_VERSION >= 241 + void cmdSetDiscardRectangleEnableEXT(VkCommandBuffer commandBuffer, VkBool32 discardRectangleEnable) const noexcept { + fp_vkCmdSetDiscardRectangleEnableEXT(commandBuffer, discardRectangleEnable); + } +#endif +#if ((defined(VK_EXT_discard_rectangles))) && VK_HEADER_VERSION >= 241 + void cmdSetDiscardRectangleModeEXT(VkCommandBuffer commandBuffer, VkDiscardRectangleModeEXT discardRectangleMode) const noexcept { + fp_vkCmdSetDiscardRectangleModeEXT(commandBuffer, discardRectangleMode); + } +#endif +#if (defined(VK_EXT_sample_locations)) + void cmdSetSampleLocationsEXT(VkCommandBuffer commandBuffer, const VkSampleLocationsInfoEXT* pSampleLocationsInfo) const noexcept { + fp_vkCmdSetSampleLocationsEXT(commandBuffer, pSampleLocationsInfo); + } +#endif +#if (defined(VK_VERSION_1_1)) + void getBufferMemoryRequirements2(const VkBufferMemoryRequirementsInfo2KHR* pInfo, VkMemoryRequirements2KHR* pMemoryRequirements) const noexcept { + fp_vkGetBufferMemoryRequirements2(device, pInfo, pMemoryRequirements); + } +#endif +#if (defined(VK_VERSION_1_1)) + void getImageMemoryRequirements2(const VkImageMemoryRequirementsInfo2KHR* pInfo, VkMemoryRequirements2KHR* pMemoryRequirements) const noexcept { + fp_vkGetImageMemoryRequirements2(device, pInfo, pMemoryRequirements); + } +#endif +#if (defined(VK_VERSION_1_1)) + void getImageSparseMemoryRequirements2(const VkImageSparseMemoryRequirementsInfo2KHR* pInfo, uint32_t* pSparseMemoryRequirementCount, VkSparseImageMemoryRequirements2KHR* pSparseMemoryRequirements) const noexcept { + fp_vkGetImageSparseMemoryRequirements2(device, pInfo, pSparseMemoryRequirementCount, pSparseMemoryRequirements); + } +#endif +#if (defined(VK_VERSION_1_3)) + void getDeviceBufferMemoryRequirements(const VkDeviceBufferMemoryRequirementsKHR* pInfo, VkMemoryRequirements2KHR* pMemoryRequirements) const noexcept { + fp_vkGetDeviceBufferMemoryRequirements(device, pInfo, pMemoryRequirements); + } +#endif +#if (defined(VK_VERSION_1_3)) + void getDeviceImageMemoryRequirements(const VkDeviceImageMemoryRequirementsKHR* pInfo, VkMemoryRequirements2KHR* pMemoryRequirements) const noexcept { + fp_vkGetDeviceImageMemoryRequirements(device, pInfo, pMemoryRequirements); + } +#endif +#if (defined(VK_VERSION_1_3)) + void getDeviceImageSparseMemoryRequirements(const VkDeviceImageMemoryRequirementsKHR* pInfo, uint32_t* pSparseMemoryRequirementCount, VkSparseImageMemoryRequirements2KHR* pSparseMemoryRequirements) const noexcept { + fp_vkGetDeviceImageSparseMemoryRequirements(device, pInfo, pSparseMemoryRequirementCount, pSparseMemoryRequirements); + } +#endif +#if (defined(VK_VERSION_1_1)) + VkResult createSamplerYcbcrConversion(const VkSamplerYcbcrConversionCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSamplerYcbcrConversionKHR* pYcbcrConversion) const noexcept { + return fp_vkCreateSamplerYcbcrConversion(device, pCreateInfo, pAllocator, pYcbcrConversion); + } +#endif +#if (defined(VK_VERSION_1_1)) + void destroySamplerYcbcrConversion(VkSamplerYcbcrConversionKHR ycbcrConversion, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroySamplerYcbcrConversion(device, ycbcrConversion, pAllocator); + } +#endif +#if (defined(VK_VERSION_1_1)) + void getDeviceQueue2(const VkDeviceQueueInfo2* pQueueInfo, VkQueue* pQueue) const noexcept { + fp_vkGetDeviceQueue2(device, pQueueInfo, pQueue); + } +#endif +#if (defined(VK_EXT_validation_cache)) + VkResult createValidationCacheEXT(const VkValidationCacheCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkValidationCacheEXT* pValidationCache) const noexcept { + return fp_vkCreateValidationCacheEXT(device, pCreateInfo, pAllocator, pValidationCache); + } +#endif +#if (defined(VK_EXT_validation_cache)) + void destroyValidationCacheEXT(VkValidationCacheEXT validationCache, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyValidationCacheEXT(device, validationCache, pAllocator); + } +#endif +#if (defined(VK_EXT_validation_cache)) + VkResult getValidationCacheDataEXT(VkValidationCacheEXT validationCache, size_t* pDataSize, void* pData) const noexcept { + return fp_vkGetValidationCacheDataEXT(device, validationCache, pDataSize, pData); + } +#endif +#if (defined(VK_EXT_validation_cache)) + VkResult mergeValidationCachesEXT(VkValidationCacheEXT dstCache, uint32_t srcCacheCount, const VkValidationCacheEXT* pSrcCaches) const noexcept { + return fp_vkMergeValidationCachesEXT(device, dstCache, srcCacheCount, pSrcCaches); + } +#endif +#if (defined(VK_VERSION_1_1)) + void getDescriptorSetLayoutSupport(const VkDescriptorSetLayoutCreateInfo* pCreateInfo, VkDescriptorSetLayoutSupportKHR* pSupport) const noexcept { + fp_vkGetDescriptorSetLayoutSupport(device, pCreateInfo, pSupport); + } +#endif +#if (defined(VK_ANDROID_native_buffer)) + VkResult getSwapchainGrallocUsageANDROID(VkFormat format, VkImageUsageFlags imageUsage, int* grallocUsage) const noexcept { + return fp_vkGetSwapchainGrallocUsageANDROID(device, format, imageUsage, grallocUsage); + } +#endif +#if (defined(VK_ANDROID_native_buffer)) + VkResult getSwapchainGrallocUsage2ANDROID(VkFormat format, VkImageUsageFlags imageUsage, VkSwapchainImageUsageFlagsANDROID swapchainImageUsage, uint64_t* grallocConsumerUsage, uint64_t* grallocProducerUsage) const noexcept { + return fp_vkGetSwapchainGrallocUsage2ANDROID(device, format, imageUsage, swapchainImageUsage, grallocConsumerUsage, grallocProducerUsage); + } +#endif +#if (defined(VK_ANDROID_native_buffer)) + VkResult acquireImageANDROID(VkImage image, int nativeFenceFd, VkSemaphore semaphore, VkFence fence) const noexcept { + return fp_vkAcquireImageANDROID(device, image, nativeFenceFd, semaphore, fence); + } +#endif +#if (defined(VK_ANDROID_native_buffer)) + VkResult queueSignalReleaseImageANDROID(VkQueue queue, uint32_t waitSemaphoreCount, const VkSemaphore* pWaitSemaphores, VkImage image, int* pNativeFenceFd) const noexcept { + return fp_vkQueueSignalReleaseImageANDROID(queue, waitSemaphoreCount, pWaitSemaphores, image, pNativeFenceFd); + } +#endif +#if (defined(VK_AMD_shader_info)) + VkResult getShaderInfoAMD(VkPipeline pipeline, VkShaderStageFlagBits shaderStage, VkShaderInfoTypeAMD infoType, size_t* pInfoSize, void* pInfo) const noexcept { + return fp_vkGetShaderInfoAMD(device, pipeline, shaderStage, infoType, pInfoSize, pInfo); + } +#endif +#if (defined(VK_AMD_display_native_hdr)) + void setLocalDimmingAMD(VkSwapchainKHR swapChain, VkBool32 localDimmingEnable) const noexcept { + fp_vkSetLocalDimmingAMD(device, swapChain, localDimmingEnable); + } +#endif +#if (defined(VK_KHR_calibrated_timestamps)) + VkResult getCalibratedTimestampsKHR(uint32_t timestampCount, const VkCalibratedTimestampInfoEXT* pTimestampInfos, uint64_t* pTimestamps, uint64_t* pMaxDeviation) const noexcept { + return fp_vkGetCalibratedTimestampsKHR(device, timestampCount, pTimestampInfos, pTimestamps, pMaxDeviation); + } +#endif +#if (defined(VK_EXT_debug_utils)) + VkResult setDebugUtilsObjectNameEXT(const VkDebugUtilsObjectNameInfoEXT* pNameInfo) const noexcept { + return fp_vkSetDebugUtilsObjectNameEXT(device, pNameInfo); + } +#endif +#if (defined(VK_EXT_debug_utils)) + VkResult setDebugUtilsObjectTagEXT(const VkDebugUtilsObjectTagInfoEXT* pTagInfo) const noexcept { + return fp_vkSetDebugUtilsObjectTagEXT(device, pTagInfo); + } +#endif +#if (defined(VK_EXT_debug_utils)) + void queueBeginDebugUtilsLabelEXT(VkQueue queue, const VkDebugUtilsLabelEXT* pLabelInfo) const noexcept { + fp_vkQueueBeginDebugUtilsLabelEXT(queue, pLabelInfo); + } +#endif +#if (defined(VK_EXT_debug_utils)) + void queueEndDebugUtilsLabelEXT(VkQueue queue) const noexcept { + fp_vkQueueEndDebugUtilsLabelEXT(queue); + } +#endif +#if (defined(VK_EXT_debug_utils)) + void queueInsertDebugUtilsLabelEXT(VkQueue queue, const VkDebugUtilsLabelEXT* pLabelInfo) const noexcept { + fp_vkQueueInsertDebugUtilsLabelEXT(queue, pLabelInfo); + } +#endif +#if (defined(VK_EXT_debug_utils)) + void cmdBeginDebugUtilsLabelEXT(VkCommandBuffer commandBuffer, const VkDebugUtilsLabelEXT* pLabelInfo) const noexcept { + fp_vkCmdBeginDebugUtilsLabelEXT(commandBuffer, pLabelInfo); + } +#endif +#if (defined(VK_EXT_debug_utils)) + void cmdEndDebugUtilsLabelEXT(VkCommandBuffer commandBuffer) const noexcept { + fp_vkCmdEndDebugUtilsLabelEXT(commandBuffer); + } +#endif +#if (defined(VK_EXT_debug_utils)) + void cmdInsertDebugUtilsLabelEXT(VkCommandBuffer commandBuffer, const VkDebugUtilsLabelEXT* pLabelInfo) const noexcept { + fp_vkCmdInsertDebugUtilsLabelEXT(commandBuffer, pLabelInfo); + } +#endif +#if (defined(VK_EXT_external_memory_host)) + VkResult getMemoryHostPointerPropertiesEXT(VkExternalMemoryHandleTypeFlagBitsKHR handleType, const void* pHostPointer, VkMemoryHostPointerPropertiesEXT* pMemoryHostPointerProperties) const noexcept { + return fp_vkGetMemoryHostPointerPropertiesEXT(device, handleType, pHostPointer, pMemoryHostPointerProperties); + } +#endif +#if (defined(VK_AMD_buffer_marker)) + void cmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage, VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const noexcept { + fp_vkCmdWriteBufferMarkerAMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker); + } +#endif +#if (defined(VK_VERSION_1_2)) + VkResult createRenderPass2(const VkRenderPassCreateInfo2KHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const noexcept { + return fp_vkCreateRenderPass2(device, pCreateInfo, pAllocator, pRenderPass); + } +#endif +#if (defined(VK_VERSION_1_2)) + void cmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin, const VkSubpassBeginInfoKHR* pSubpassBeginInfo) const noexcept { + fp_vkCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo); + } +#endif +#if (defined(VK_VERSION_1_2)) + void cmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfoKHR* pSubpassBeginInfo, const VkSubpassEndInfoKHR* pSubpassEndInfo) const noexcept { + fp_vkCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo); + } +#endif +#if (defined(VK_VERSION_1_2)) + void cmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR* pSubpassEndInfo) const noexcept { + fp_vkCmdEndRenderPass2(commandBuffer, pSubpassEndInfo); + } +#endif +#if (defined(VK_VERSION_1_2)) + VkResult getSemaphoreCounterValue(VkSemaphore semaphore, uint64_t* pValue) const noexcept { + return fp_vkGetSemaphoreCounterValue(device, semaphore, pValue); + } +#endif +#if (defined(VK_VERSION_1_2)) + VkResult waitSemaphores(const VkSemaphoreWaitInfoKHR* pWaitInfo, uint64_t timeout) const noexcept { + return fp_vkWaitSemaphores(device, pWaitInfo, timeout); + } +#endif +#if (defined(VK_VERSION_1_2)) + VkResult signalSemaphore(const VkSemaphoreSignalInfoKHR* pSignalInfo) const noexcept { + return fp_vkSignalSemaphore(device, pSignalInfo); + } +#endif +#if (defined(VK_ANDROID_external_memory_android_hardware_buffer)) + VkResult getAndroidHardwareBufferPropertiesANDROID(const struct AHardwareBuffer* buffer, VkAndroidHardwareBufferPropertiesANDROID* pProperties) const noexcept { + return fp_vkGetAndroidHardwareBufferPropertiesANDROID(device, buffer, pProperties); + } +#endif +#if (defined(VK_ANDROID_external_memory_android_hardware_buffer)) + VkResult getMemoryAndroidHardwareBufferANDROID(const VkMemoryGetAndroidHardwareBufferInfoANDROID* pInfo, struct AHardwareBuffer** pBuffer) const noexcept { + return fp_vkGetMemoryAndroidHardwareBufferANDROID(device, pInfo, pBuffer); + } +#endif +#if (defined(VK_VERSION_1_2)) + void cmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount, uint32_t stride) const noexcept { + fp_vkCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride); + } +#endif +#if (defined(VK_VERSION_1_2)) + void cmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount, uint32_t stride) const noexcept { + fp_vkCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride); + } +#endif +#if (defined(VK_NV_device_diagnostic_checkpoints)) + void cmdSetCheckpointNV(VkCommandBuffer commandBuffer, const void* pCheckpointMarker) const noexcept { + fp_vkCmdSetCheckpointNV(commandBuffer, pCheckpointMarker); + } +#endif +#if (defined(VK_NV_device_diagnostic_checkpoints)) + void getQueueCheckpointDataNV(VkQueue queue, uint32_t* pCheckpointDataCount, VkCheckpointDataNV* pCheckpointData) const noexcept { + fp_vkGetQueueCheckpointDataNV(queue, pCheckpointDataCount, pCheckpointData); + } +#endif +#if (defined(VK_EXT_transform_feedback)) + void cmdBindTransformFeedbackBuffersEXT(VkCommandBuffer commandBuffer, uint32_t firstBinding, uint32_t bindingCount, const VkBuffer* pBuffers, const VkDeviceSize* pOffsets, const VkDeviceSize* pSizes) const noexcept { + fp_vkCmdBindTransformFeedbackBuffersEXT(commandBuffer, firstBinding, bindingCount, pBuffers, pOffsets, pSizes); + } +#endif +#if (defined(VK_EXT_transform_feedback)) + void cmdBeginTransformFeedbackEXT(VkCommandBuffer commandBuffer, uint32_t firstCounterBuffer, uint32_t counterBufferCount, const VkBuffer* pCounterBuffers, const VkDeviceSize* pCounterBufferOffsets) const noexcept { + fp_vkCmdBeginTransformFeedbackEXT(commandBuffer, firstCounterBuffer, counterBufferCount, pCounterBuffers, pCounterBufferOffsets); + } +#endif +#if (defined(VK_EXT_transform_feedback)) + void cmdEndTransformFeedbackEXT(VkCommandBuffer commandBuffer, uint32_t firstCounterBuffer, uint32_t counterBufferCount, const VkBuffer* pCounterBuffers, const VkDeviceSize* pCounterBufferOffsets) const noexcept { + fp_vkCmdEndTransformFeedbackEXT(commandBuffer, firstCounterBuffer, counterBufferCount, pCounterBuffers, pCounterBufferOffsets); + } +#endif +#if (defined(VK_EXT_transform_feedback)) + void cmdBeginQueryIndexedEXT(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t query, VkQueryControlFlags flags, uint32_t index) const noexcept { + fp_vkCmdBeginQueryIndexedEXT(commandBuffer, queryPool, query, flags, index); + } +#endif +#if (defined(VK_EXT_transform_feedback)) + void cmdEndQueryIndexedEXT(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t query, uint32_t index) const noexcept { + fp_vkCmdEndQueryIndexedEXT(commandBuffer, queryPool, query, index); + } +#endif +#if (defined(VK_EXT_transform_feedback)) + void cmdDrawIndirectByteCountEXT(VkCommandBuffer commandBuffer, uint32_t instanceCount, uint32_t firstInstance, VkBuffer counterBuffer, VkDeviceSize counterBufferOffset, uint32_t counterOffset, uint32_t vertexStride) const noexcept { + fp_vkCmdDrawIndirectByteCountEXT(commandBuffer, instanceCount, firstInstance, counterBuffer, counterBufferOffset, counterOffset, vertexStride); + } +#endif +#if (defined(VK_NV_scissor_exclusive)) + void cmdSetExclusiveScissorNV(VkCommandBuffer commandBuffer, uint32_t firstExclusiveScissor, uint32_t exclusiveScissorCount, const VkRect2D* pExclusiveScissors) const noexcept { + fp_vkCmdSetExclusiveScissorNV(commandBuffer, firstExclusiveScissor, exclusiveScissorCount, pExclusiveScissors); + } +#endif +#if ((defined(VK_NV_scissor_exclusive))) && VK_HEADER_VERSION >= 241 + void cmdSetExclusiveScissorEnableNV(VkCommandBuffer commandBuffer, uint32_t firstExclusiveScissor, uint32_t exclusiveScissorCount, const VkBool32* pExclusiveScissorEnables) const noexcept { + fp_vkCmdSetExclusiveScissorEnableNV(commandBuffer, firstExclusiveScissor, exclusiveScissorCount, pExclusiveScissorEnables); + } +#endif +#if (defined(VK_NV_shading_rate_image)) + void cmdBindShadingRateImageNV(VkCommandBuffer commandBuffer, VkImageView imageView, VkImageLayout imageLayout) const noexcept { + fp_vkCmdBindShadingRateImageNV(commandBuffer, imageView, imageLayout); + } +#endif +#if (defined(VK_NV_shading_rate_image)) + void cmdSetViewportShadingRatePaletteNV(VkCommandBuffer commandBuffer, uint32_t firstViewport, uint32_t viewportCount, const VkShadingRatePaletteNV* pShadingRatePalettes) const noexcept { + fp_vkCmdSetViewportShadingRatePaletteNV(commandBuffer, firstViewport, viewportCount, pShadingRatePalettes); + } +#endif +#if (defined(VK_NV_shading_rate_image)) + void cmdSetCoarseSampleOrderNV(VkCommandBuffer commandBuffer, VkCoarseSampleOrderTypeNV sampleOrderType, uint32_t customSampleOrderCount, const VkCoarseSampleOrderCustomNV* pCustomSampleOrders) const noexcept { + fp_vkCmdSetCoarseSampleOrderNV(commandBuffer, sampleOrderType, customSampleOrderCount, pCustomSampleOrders); + } +#endif +#if (defined(VK_NV_mesh_shader)) + void cmdDrawMeshTasksNV(VkCommandBuffer commandBuffer, uint32_t taskCount, uint32_t firstTask) const noexcept { + fp_vkCmdDrawMeshTasksNV(commandBuffer, taskCount, firstTask); + } +#endif +#if (defined(VK_NV_mesh_shader)) + void cmdDrawMeshTasksIndirectNV(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, uint32_t drawCount, uint32_t stride) const noexcept { + fp_vkCmdDrawMeshTasksIndirectNV(commandBuffer, buffer, offset, drawCount, stride); + } +#endif +#if (defined(VK_NV_mesh_shader)) + void cmdDrawMeshTasksIndirectCountNV(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount, uint32_t stride) const noexcept { + fp_vkCmdDrawMeshTasksIndirectCountNV(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride); + } +#endif +#if (defined(VK_EXT_mesh_shader)) + void cmdDrawMeshTasksEXT(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY, uint32_t groupCountZ) const noexcept { + fp_vkCmdDrawMeshTasksEXT(commandBuffer, groupCountX, groupCountY, groupCountZ); + } +#endif +#if (defined(VK_EXT_mesh_shader)) + void cmdDrawMeshTasksIndirectEXT(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, uint32_t drawCount, uint32_t stride) const noexcept { + fp_vkCmdDrawMeshTasksIndirectEXT(commandBuffer, buffer, offset, drawCount, stride); + } +#endif +#if (defined(VK_EXT_mesh_shader)) + void cmdDrawMeshTasksIndirectCountEXT(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount, uint32_t stride) const noexcept { + fp_vkCmdDrawMeshTasksIndirectCountEXT(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride); + } +#endif +#if (defined(VK_NV_ray_tracing)) + VkResult compileDeferredNV(VkPipeline pipeline, uint32_t shader) const noexcept { + return fp_vkCompileDeferredNV(device, pipeline, shader); + } +#endif +#if (defined(VK_NV_ray_tracing)) + VkResult createAccelerationStructureNV(const VkAccelerationStructureCreateInfoNV* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkAccelerationStructureNV* pAccelerationStructure) const noexcept { + return fp_vkCreateAccelerationStructureNV(device, pCreateInfo, pAllocator, pAccelerationStructure); + } +#endif +#if (defined(VK_HUAWEI_invocation_mask)) + void cmdBindInvocationMaskHUAWEI(VkCommandBuffer commandBuffer, VkImageView imageView, VkImageLayout imageLayout) const noexcept { + fp_vkCmdBindInvocationMaskHUAWEI(commandBuffer, imageView, imageLayout); + } +#endif +#if (defined(VK_KHR_acceleration_structure)) + void destroyAccelerationStructureKHR(VkAccelerationStructureKHR accelerationStructure, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyAccelerationStructureKHR(device, accelerationStructure, pAllocator); + } +#endif +#if (defined(VK_NV_ray_tracing)) + void destroyAccelerationStructureNV(VkAccelerationStructureNV accelerationStructure, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyAccelerationStructureNV(device, accelerationStructure, pAllocator); + } +#endif +#if (defined(VK_NV_ray_tracing)) + void getAccelerationStructureMemoryRequirementsNV(const VkAccelerationStructureMemoryRequirementsInfoNV* pInfo, VkMemoryRequirements2KHR* pMemoryRequirements) const noexcept { + fp_vkGetAccelerationStructureMemoryRequirementsNV(device, pInfo, pMemoryRequirements); + } +#endif +#if (defined(VK_NV_ray_tracing)) + VkResult bindAccelerationStructureMemoryNV(uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const noexcept { + return fp_vkBindAccelerationStructureMemoryNV(device, bindInfoCount, pBindInfos); + } +#endif +#if (defined(VK_NV_ray_tracing)) + void cmdCopyAccelerationStructureNV(VkCommandBuffer commandBuffer, VkAccelerationStructureNV dst, VkAccelerationStructureNV src, VkCopyAccelerationStructureModeNV mode) const noexcept { + fp_vkCmdCopyAccelerationStructureNV(commandBuffer, dst, src, mode); + } +#endif +#if (defined(VK_KHR_acceleration_structure)) + void cmdCopyAccelerationStructureKHR(VkCommandBuffer commandBuffer, const VkCopyAccelerationStructureInfoKHR* pInfo) const noexcept { + fp_vkCmdCopyAccelerationStructureKHR(commandBuffer, pInfo); + } +#endif +#if (defined(VK_KHR_acceleration_structure)) + VkResult copyAccelerationStructureKHR(VkDeferredOperationKHR deferredOperation, const VkCopyAccelerationStructureInfoKHR* pInfo) const noexcept { + return fp_vkCopyAccelerationStructureKHR(device, deferredOperation, pInfo); + } +#endif +#if (defined(VK_KHR_acceleration_structure)) + void cmdCopyAccelerationStructureToMemoryKHR(VkCommandBuffer commandBuffer, const VkCopyAccelerationStructureToMemoryInfoKHR* pInfo) const noexcept { + fp_vkCmdCopyAccelerationStructureToMemoryKHR(commandBuffer, pInfo); + } +#endif +#if (defined(VK_KHR_acceleration_structure)) + VkResult copyAccelerationStructureToMemoryKHR(VkDeferredOperationKHR deferredOperation, const VkCopyAccelerationStructureToMemoryInfoKHR* pInfo) const noexcept { + return fp_vkCopyAccelerationStructureToMemoryKHR(device, deferredOperation, pInfo); + } +#endif +#if (defined(VK_KHR_acceleration_structure)) + void cmdCopyMemoryToAccelerationStructureKHR(VkCommandBuffer commandBuffer, const VkCopyMemoryToAccelerationStructureInfoKHR* pInfo) const noexcept { + fp_vkCmdCopyMemoryToAccelerationStructureKHR(commandBuffer, pInfo); + } +#endif +#if (defined(VK_KHR_acceleration_structure)) + VkResult copyMemoryToAccelerationStructureKHR(VkDeferredOperationKHR deferredOperation, const VkCopyMemoryToAccelerationStructureInfoKHR* pInfo) const noexcept { + return fp_vkCopyMemoryToAccelerationStructureKHR(device, deferredOperation, pInfo); + } +#endif +#if (defined(VK_KHR_acceleration_structure)) + void cmdWriteAccelerationStructuresPropertiesKHR(VkCommandBuffer commandBuffer, uint32_t accelerationStructureCount, const VkAccelerationStructureKHR* pAccelerationStructures, VkQueryType queryType, VkQueryPool queryPool, uint32_t firstQuery) const noexcept { + fp_vkCmdWriteAccelerationStructuresPropertiesKHR(commandBuffer, accelerationStructureCount, pAccelerationStructures, queryType, queryPool, firstQuery); + } +#endif +#if (defined(VK_NV_ray_tracing)) + void cmdWriteAccelerationStructuresPropertiesNV(VkCommandBuffer commandBuffer, uint32_t accelerationStructureCount, const VkAccelerationStructureNV* pAccelerationStructures, VkQueryType queryType, VkQueryPool queryPool, uint32_t firstQuery) const noexcept { + fp_vkCmdWriteAccelerationStructuresPropertiesNV(commandBuffer, accelerationStructureCount, pAccelerationStructures, queryType, queryPool, firstQuery); + } +#endif +#if (defined(VK_NV_ray_tracing)) + void cmdBuildAccelerationStructureNV(VkCommandBuffer commandBuffer, const VkAccelerationStructureInfoNV* pInfo, VkBuffer instanceData, VkDeviceSize instanceOffset, VkBool32 update, VkAccelerationStructureNV dst, VkAccelerationStructureNV src, VkBuffer scratch, VkDeviceSize scratchOffset) const noexcept { + fp_vkCmdBuildAccelerationStructureNV(commandBuffer, pInfo, instanceData, instanceOffset, update, dst, src, scratch, scratchOffset); + } +#endif +#if (defined(VK_KHR_acceleration_structure)) + VkResult writeAccelerationStructuresPropertiesKHR(uint32_t accelerationStructureCount, const VkAccelerationStructureKHR* pAccelerationStructures, VkQueryType queryType, size_t dataSize, void* pData, size_t stride) const noexcept { + return fp_vkWriteAccelerationStructuresPropertiesKHR(device, accelerationStructureCount, pAccelerationStructures, queryType, dataSize, pData, stride); + } +#endif +#if (defined(VK_KHR_ray_tracing_pipeline)) + void cmdTraceRaysKHR(VkCommandBuffer commandBuffer, const VkStridedDeviceAddressRegionKHR* pRaygenShaderBindingTable, const VkStridedDeviceAddressRegionKHR* pMissShaderBindingTable, const VkStridedDeviceAddressRegionKHR* pHitShaderBindingTable, const VkStridedDeviceAddressRegionKHR* pCallableShaderBindingTable, uint32_t width, uint32_t height, uint32_t depth) const noexcept { + fp_vkCmdTraceRaysKHR(commandBuffer, pRaygenShaderBindingTable, pMissShaderBindingTable, pHitShaderBindingTable, pCallableShaderBindingTable, width, height, depth); + } +#endif +#if (defined(VK_NV_ray_tracing)) + void cmdTraceRaysNV(VkCommandBuffer commandBuffer, VkBuffer raygenShaderBindingTableBuffer, VkDeviceSize raygenShaderBindingOffset, VkBuffer missShaderBindingTableBuffer, VkDeviceSize missShaderBindingOffset, VkDeviceSize missShaderBindingStride, VkBuffer hitShaderBindingTableBuffer, VkDeviceSize hitShaderBindingOffset, VkDeviceSize hitShaderBindingStride, VkBuffer callableShaderBindingTableBuffer, VkDeviceSize callableShaderBindingOffset, VkDeviceSize callableShaderBindingStride, uint32_t width, uint32_t height, uint32_t depth) const noexcept { + fp_vkCmdTraceRaysNV(commandBuffer, raygenShaderBindingTableBuffer, raygenShaderBindingOffset, missShaderBindingTableBuffer, missShaderBindingOffset, missShaderBindingStride, hitShaderBindingTableBuffer, hitShaderBindingOffset, hitShaderBindingStride, callableShaderBindingTableBuffer, callableShaderBindingOffset, callableShaderBindingStride, width, height, depth); + } +#endif +#if (defined(VK_KHR_ray_tracing_pipeline)) + VkResult getRayTracingShaderGroupHandlesKHR(VkPipeline pipeline, uint32_t firstGroup, uint32_t groupCount, size_t dataSize, void* pData) const noexcept { + return fp_vkGetRayTracingShaderGroupHandlesKHR(device, pipeline, firstGroup, groupCount, dataSize, pData); + } +#endif +#if (defined(VK_KHR_ray_tracing_pipeline)) + VkResult getRayTracingCaptureReplayShaderGroupHandlesKHR(VkPipeline pipeline, uint32_t firstGroup, uint32_t groupCount, size_t dataSize, void* pData) const noexcept { + return fp_vkGetRayTracingCaptureReplayShaderGroupHandlesKHR(device, pipeline, firstGroup, groupCount, dataSize, pData); + } +#endif +#if (defined(VK_NV_ray_tracing)) + VkResult getAccelerationStructureHandleNV(VkAccelerationStructureNV accelerationStructure, size_t dataSize, void* pData) const noexcept { + return fp_vkGetAccelerationStructureHandleNV(device, accelerationStructure, dataSize, pData); + } +#endif +#if (defined(VK_NV_ray_tracing)) + VkResult createRayTracingPipelinesNV(VkPipelineCache pipelineCache, uint32_t createInfoCount, const VkRayTracingPipelineCreateInfoNV* pCreateInfos, const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines) const noexcept { + return fp_vkCreateRayTracingPipelinesNV(device, pipelineCache, createInfoCount, pCreateInfos, pAllocator, pPipelines); + } +#endif +#if (defined(VK_KHR_ray_tracing_pipeline)) + VkResult createRayTracingPipelinesKHR(VkDeferredOperationKHR deferredOperation, VkPipelineCache pipelineCache, uint32_t createInfoCount, const VkRayTracingPipelineCreateInfoKHR* pCreateInfos, const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines) const noexcept { + return fp_vkCreateRayTracingPipelinesKHR(device, deferredOperation, pipelineCache, createInfoCount, pCreateInfos, pAllocator, pPipelines); + } +#endif +#if (defined(VK_KHR_ray_tracing_pipeline)) + void cmdTraceRaysIndirectKHR(VkCommandBuffer commandBuffer, const VkStridedDeviceAddressRegionKHR* pRaygenShaderBindingTable, const VkStridedDeviceAddressRegionKHR* pMissShaderBindingTable, const VkStridedDeviceAddressRegionKHR* pHitShaderBindingTable, const VkStridedDeviceAddressRegionKHR* pCallableShaderBindingTable, VkDeviceAddress indirectDeviceAddress) const noexcept { + fp_vkCmdTraceRaysIndirectKHR(commandBuffer, pRaygenShaderBindingTable, pMissShaderBindingTable, pHitShaderBindingTable, pCallableShaderBindingTable, indirectDeviceAddress); + } +#endif +#if (defined(VK_KHR_ray_tracing_maintenance1)) + void cmdTraceRaysIndirect2KHR(VkCommandBuffer commandBuffer, VkDeviceAddress indirectDeviceAddress) const noexcept { + fp_vkCmdTraceRaysIndirect2KHR(commandBuffer, indirectDeviceAddress); + } +#endif +#if (defined(VK_KHR_acceleration_structure)) + void getDeviceAccelerationStructureCompatibilityKHR(const VkAccelerationStructureVersionInfoKHR* pVersionInfo, VkAccelerationStructureCompatibilityKHR* pCompatibility) const noexcept { + fp_vkGetDeviceAccelerationStructureCompatibilityKHR(device, pVersionInfo, pCompatibility); + } +#endif +#if (defined(VK_KHR_ray_tracing_pipeline)) + VkDeviceSize getRayTracingShaderGroupStackSizeKHR(VkPipeline pipeline, uint32_t group, VkShaderGroupShaderKHR groupShader) const noexcept { + return fp_vkGetRayTracingShaderGroupStackSizeKHR(device, pipeline, group, groupShader); + } +#endif +#if (defined(VK_KHR_ray_tracing_pipeline)) + void cmdSetRayTracingPipelineStackSizeKHR(VkCommandBuffer commandBuffer, uint32_t pipelineStackSize) const noexcept { + fp_vkCmdSetRayTracingPipelineStackSizeKHR(commandBuffer, pipelineStackSize); + } +#endif +#if (defined(VK_EXT_full_screen_exclusive)) + VkResult getDeviceGroupSurfacePresentModes2EXT(const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo, VkDeviceGroupPresentModeFlagsKHR* pModes) const noexcept { + return fp_vkGetDeviceGroupSurfacePresentModes2EXT(device, pSurfaceInfo, pModes); + } +#endif +#if (defined(VK_EXT_full_screen_exclusive)) + VkResult acquireFullScreenExclusiveModeEXT(VkSwapchainKHR swapchain) const noexcept { + return fp_vkAcquireFullScreenExclusiveModeEXT(device, swapchain); + } +#endif +#if (defined(VK_EXT_full_screen_exclusive)) + VkResult releaseFullScreenExclusiveModeEXT(VkSwapchainKHR swapchain) const noexcept { + return fp_vkReleaseFullScreenExclusiveModeEXT(device, swapchain); + } +#endif +#if (defined(VK_KHR_performance_query)) + VkResult acquireProfilingLockKHR(const VkAcquireProfilingLockInfoKHR* pInfo) const noexcept { + return fp_vkAcquireProfilingLockKHR(device, pInfo); + } +#endif +#if (defined(VK_KHR_performance_query)) + void releaseProfilingLockKHR() const noexcept { + fp_vkReleaseProfilingLockKHR(device); + } +#endif +#if (defined(VK_EXT_image_drm_format_modifier)) + VkResult getImageDrmFormatModifierPropertiesEXT(VkImage image, VkImageDrmFormatModifierPropertiesEXT* pProperties) const noexcept { + return fp_vkGetImageDrmFormatModifierPropertiesEXT(device, image, pProperties); + } +#endif +#if (defined(VK_VERSION_1_2)) + uint64_t getBufferOpaqueCaptureAddress(const VkBufferDeviceAddressInfoEXT* pInfo) const noexcept { + return fp_vkGetBufferOpaqueCaptureAddress(device, pInfo); + } +#endif +#if (defined(VK_VERSION_1_2)) + VkDeviceAddress getBufferDeviceAddress(const VkBufferDeviceAddressInfoEXT* pInfo) const noexcept { + return fp_vkGetBufferDeviceAddress(device, pInfo); + } +#endif +#if (defined(VK_INTEL_performance_query)) + VkResult initializePerformanceApiINTEL(const VkInitializePerformanceApiInfoINTEL* pInitializeInfo) const noexcept { + return fp_vkInitializePerformanceApiINTEL(device, pInitializeInfo); + } +#endif +#if (defined(VK_INTEL_performance_query)) + void uninitializePerformanceApiINTEL() const noexcept { + fp_vkUninitializePerformanceApiINTEL(device); + } +#endif +#if (defined(VK_INTEL_performance_query)) + VkResult cmdSetPerformanceMarkerINTEL(VkCommandBuffer commandBuffer, const VkPerformanceMarkerInfoINTEL* pMarkerInfo) const noexcept { + return fp_vkCmdSetPerformanceMarkerINTEL(commandBuffer, pMarkerInfo); + } +#endif +#if (defined(VK_INTEL_performance_query)) + VkResult cmdSetPerformanceStreamMarkerINTEL(VkCommandBuffer commandBuffer, const VkPerformanceStreamMarkerInfoINTEL* pMarkerInfo) const noexcept { + return fp_vkCmdSetPerformanceStreamMarkerINTEL(commandBuffer, pMarkerInfo); + } +#endif +#if (defined(VK_INTEL_performance_query)) + VkResult cmdSetPerformanceOverrideINTEL(VkCommandBuffer commandBuffer, const VkPerformanceOverrideInfoINTEL* pOverrideInfo) const noexcept { + return fp_vkCmdSetPerformanceOverrideINTEL(commandBuffer, pOverrideInfo); + } +#endif +#if (defined(VK_INTEL_performance_query)) + VkResult acquirePerformanceConfigurationINTEL(const VkPerformanceConfigurationAcquireInfoINTEL* pAcquireInfo, VkPerformanceConfigurationINTEL* pConfiguration) const noexcept { + return fp_vkAcquirePerformanceConfigurationINTEL(device, pAcquireInfo, pConfiguration); + } +#endif +#if (defined(VK_INTEL_performance_query)) + VkResult releasePerformanceConfigurationINTEL(VkPerformanceConfigurationINTEL configuration) const noexcept { + return fp_vkReleasePerformanceConfigurationINTEL(device, configuration); + } +#endif +#if (defined(VK_INTEL_performance_query)) + VkResult queueSetPerformanceConfigurationINTEL(VkQueue queue, VkPerformanceConfigurationINTEL configuration) const noexcept { + return fp_vkQueueSetPerformanceConfigurationINTEL(queue, configuration); + } +#endif +#if (defined(VK_INTEL_performance_query)) + VkResult getPerformanceParameterINTEL(VkPerformanceParameterTypeINTEL parameter, VkPerformanceValueINTEL* pValue) const noexcept { + return fp_vkGetPerformanceParameterINTEL(device, parameter, pValue); + } +#endif +#if (defined(VK_VERSION_1_2)) + uint64_t getDeviceMemoryOpaqueCaptureAddress(const VkDeviceMemoryOpaqueCaptureAddressInfoKHR* pInfo) const noexcept { + return fp_vkGetDeviceMemoryOpaqueCaptureAddress(device, pInfo); + } +#endif +#if (defined(VK_KHR_pipeline_executable_properties)) + VkResult getPipelineExecutablePropertiesKHR(const VkPipelineInfoKHR* pPipelineInfo, uint32_t* pExecutableCount, VkPipelineExecutablePropertiesKHR* pProperties) const noexcept { + return fp_vkGetPipelineExecutablePropertiesKHR(device, pPipelineInfo, pExecutableCount, pProperties); + } +#endif +#if (defined(VK_KHR_pipeline_executable_properties)) + VkResult getPipelineExecutableStatisticsKHR(const VkPipelineExecutableInfoKHR* pExecutableInfo, uint32_t* pStatisticCount, VkPipelineExecutableStatisticKHR* pStatistics) const noexcept { + return fp_vkGetPipelineExecutableStatisticsKHR(device, pExecutableInfo, pStatisticCount, pStatistics); + } +#endif +#if (defined(VK_KHR_pipeline_executable_properties)) + VkResult getPipelineExecutableInternalRepresentationsKHR(const VkPipelineExecutableInfoKHR* pExecutableInfo, uint32_t* pInternalRepresentationCount, VkPipelineExecutableInternalRepresentationKHR* pInternalRepresentations) const noexcept { + return fp_vkGetPipelineExecutableInternalRepresentationsKHR(device, pExecutableInfo, pInternalRepresentationCount, pInternalRepresentations); + } +#endif +#if (defined(VK_KHR_line_rasterization)) + void cmdSetLineStippleKHR(VkCommandBuffer commandBuffer, uint32_t lineStippleFactor, uint16_t lineStipplePattern) const noexcept { + fp_vkCmdSetLineStippleKHR(commandBuffer, lineStippleFactor, lineStipplePattern); + } +#endif +#if (defined(VKSC_VERSION_1_0)) + VkResult getFaultData(VkFaultQueryBehavior faultQueryBehavior, VkBool32* pUnrecordedFaults, uint32_t* pFaultCount, VkFaultData* pFaults) const noexcept { + return fp_vkGetFaultData(device, faultQueryBehavior, pUnrecordedFaults, pFaultCount, pFaults); + } +#endif +#if (defined(VK_KHR_acceleration_structure)) + VkResult createAccelerationStructureKHR(const VkAccelerationStructureCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkAccelerationStructureKHR* pAccelerationStructure) const noexcept { + return fp_vkCreateAccelerationStructureKHR(device, pCreateInfo, pAllocator, pAccelerationStructure); + } +#endif +#if (defined(VK_KHR_acceleration_structure)) + void cmdBuildAccelerationStructuresKHR(VkCommandBuffer commandBuffer, uint32_t infoCount, const VkAccelerationStructureBuildGeometryInfoKHR* pInfos, const VkAccelerationStructureBuildRangeInfoKHR* const* ppBuildRangeInfos) const noexcept { + fp_vkCmdBuildAccelerationStructuresKHR(commandBuffer, infoCount, pInfos, ppBuildRangeInfos); + } +#endif +#if (defined(VK_KHR_acceleration_structure)) + void cmdBuildAccelerationStructuresIndirectKHR(VkCommandBuffer commandBuffer, uint32_t infoCount, const VkAccelerationStructureBuildGeometryInfoKHR* pInfos, const VkDeviceAddress* pIndirectDeviceAddresses, const uint32_t* pIndirectStrides, const uint32_t* const* ppMaxPrimitiveCounts) const noexcept { + fp_vkCmdBuildAccelerationStructuresIndirectKHR(commandBuffer, infoCount, pInfos, pIndirectDeviceAddresses, pIndirectStrides, ppMaxPrimitiveCounts); + } +#endif +#if (defined(VK_KHR_acceleration_structure)) + VkResult buildAccelerationStructuresKHR(VkDeferredOperationKHR deferredOperation, uint32_t infoCount, const VkAccelerationStructureBuildGeometryInfoKHR* pInfos, const VkAccelerationStructureBuildRangeInfoKHR* const* ppBuildRangeInfos) const noexcept { + return fp_vkBuildAccelerationStructuresKHR(device, deferredOperation, infoCount, pInfos, ppBuildRangeInfos); + } +#endif +#if (defined(VK_KHR_acceleration_structure)) + VkDeviceAddress getAccelerationStructureDeviceAddressKHR(const VkAccelerationStructureDeviceAddressInfoKHR* pInfo) const noexcept { + return fp_vkGetAccelerationStructureDeviceAddressKHR(device, pInfo); + } +#endif +#if (defined(VK_KHR_deferred_host_operations)) + VkResult createDeferredOperationKHR(const VkAllocationCallbacks* pAllocator, VkDeferredOperationKHR* pDeferredOperation) const noexcept { + return fp_vkCreateDeferredOperationKHR(device, pAllocator, pDeferredOperation); + } +#endif +#if (defined(VK_KHR_deferred_host_operations)) + void destroyDeferredOperationKHR(VkDeferredOperationKHR operation, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyDeferredOperationKHR(device, operation, pAllocator); + } +#endif +#if (defined(VK_KHR_deferred_host_operations)) + uint32_t getDeferredOperationMaxConcurrencyKHR(VkDeferredOperationKHR operation) const noexcept { + return fp_vkGetDeferredOperationMaxConcurrencyKHR(device, operation); + } +#endif +#if (defined(VK_KHR_deferred_host_operations)) + VkResult getDeferredOperationResultKHR(VkDeferredOperationKHR operation) const noexcept { + return fp_vkGetDeferredOperationResultKHR(device, operation); + } +#endif +#if (defined(VK_KHR_deferred_host_operations)) + VkResult deferredOperationJoinKHR(VkDeferredOperationKHR operation) const noexcept { + return fp_vkDeferredOperationJoinKHR(device, operation); + } +#endif +#if (defined(VK_NV_device_generated_commands_compute)) + void getPipelineIndirectMemoryRequirementsNV(const VkComputePipelineCreateInfo* pCreateInfo, VkMemoryRequirements2KHR* pMemoryRequirements) const noexcept { + fp_vkGetPipelineIndirectMemoryRequirementsNV(device, pCreateInfo, pMemoryRequirements); + } +#endif +#if (defined(VK_NV_device_generated_commands_compute)) + VkDeviceAddress getPipelineIndirectDeviceAddressNV(const VkPipelineIndirectDeviceAddressInfoNV* pInfo) const noexcept { + return fp_vkGetPipelineIndirectDeviceAddressNV(device, pInfo); + } +#endif +#if (defined(VK_AMD_anti_lag)) + void antiLagUpdateAMD(const VkAntiLagDataAMD* pData) const noexcept { + fp_vkAntiLagUpdateAMD(device, pData); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdSetCullMode(VkCommandBuffer commandBuffer, VkCullModeFlags cullMode) const noexcept { + fp_vkCmdSetCullMode(commandBuffer, cullMode); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdSetFrontFace(VkCommandBuffer commandBuffer, VkFrontFace frontFace) const noexcept { + fp_vkCmdSetFrontFace(commandBuffer, frontFace); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdSetPrimitiveTopology(VkCommandBuffer commandBuffer, VkPrimitiveTopology primitiveTopology) const noexcept { + fp_vkCmdSetPrimitiveTopology(commandBuffer, primitiveTopology); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdSetViewportWithCount(VkCommandBuffer commandBuffer, uint32_t viewportCount, const VkViewport* pViewports) const noexcept { + fp_vkCmdSetViewportWithCount(commandBuffer, viewportCount, pViewports); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdSetScissorWithCount(VkCommandBuffer commandBuffer, uint32_t scissorCount, const VkRect2D* pScissors) const noexcept { + fp_vkCmdSetScissorWithCount(commandBuffer, scissorCount, pScissors); + } +#endif +#if (defined(VK_KHR_maintenance5)) + void cmdBindIndexBuffer2KHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkDeviceSize size, VkIndexType indexType) const noexcept { + fp_vkCmdBindIndexBuffer2KHR(commandBuffer, buffer, offset, size, indexType); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdBindVertexBuffers2(VkCommandBuffer commandBuffer, uint32_t firstBinding, uint32_t bindingCount, const VkBuffer* pBuffers, const VkDeviceSize* pOffsets, const VkDeviceSize* pSizes, const VkDeviceSize* pStrides) const noexcept { + fp_vkCmdBindVertexBuffers2(commandBuffer, firstBinding, bindingCount, pBuffers, pOffsets, pSizes, pStrides); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdSetDepthTestEnable(VkCommandBuffer commandBuffer, VkBool32 depthTestEnable) const noexcept { + fp_vkCmdSetDepthTestEnable(commandBuffer, depthTestEnable); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdSetDepthWriteEnable(VkCommandBuffer commandBuffer, VkBool32 depthWriteEnable) const noexcept { + fp_vkCmdSetDepthWriteEnable(commandBuffer, depthWriteEnable); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdSetDepthCompareOp(VkCommandBuffer commandBuffer, VkCompareOp depthCompareOp) const noexcept { + fp_vkCmdSetDepthCompareOp(commandBuffer, depthCompareOp); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdSetDepthBoundsTestEnable(VkCommandBuffer commandBuffer, VkBool32 depthBoundsTestEnable) const noexcept { + fp_vkCmdSetDepthBoundsTestEnable(commandBuffer, depthBoundsTestEnable); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdSetStencilTestEnable(VkCommandBuffer commandBuffer, VkBool32 stencilTestEnable) const noexcept { + fp_vkCmdSetStencilTestEnable(commandBuffer, stencilTestEnable); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdSetStencilOp(VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask, VkStencilOp failOp, VkStencilOp passOp, VkStencilOp depthFailOp, VkCompareOp compareOp) const noexcept { + fp_vkCmdSetStencilOp(commandBuffer, faceMask, failOp, passOp, depthFailOp, compareOp); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state2)) || (defined(VK_EXT_shader_object)) + void cmdSetPatchControlPointsEXT(VkCommandBuffer commandBuffer, uint32_t patchControlPoints) const noexcept { + fp_vkCmdSetPatchControlPointsEXT(commandBuffer, patchControlPoints); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdSetRasterizerDiscardEnable(VkCommandBuffer commandBuffer, VkBool32 rasterizerDiscardEnable) const noexcept { + fp_vkCmdSetRasterizerDiscardEnable(commandBuffer, rasterizerDiscardEnable); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdSetDepthBiasEnable(VkCommandBuffer commandBuffer, VkBool32 depthBiasEnable) const noexcept { + fp_vkCmdSetDepthBiasEnable(commandBuffer, depthBiasEnable); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state2)) || (defined(VK_EXT_shader_object)) + void cmdSetLogicOpEXT(VkCommandBuffer commandBuffer, VkLogicOp logicOp) const noexcept { + fp_vkCmdSetLogicOpEXT(commandBuffer, logicOp); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdSetPrimitiveRestartEnable(VkCommandBuffer commandBuffer, VkBool32 primitiveRestartEnable) const noexcept { + fp_vkCmdSetPrimitiveRestartEnable(commandBuffer, primitiveRestartEnable); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetTessellationDomainOriginEXT(VkCommandBuffer commandBuffer, VkTessellationDomainOriginKHR domainOrigin) const noexcept { + fp_vkCmdSetTessellationDomainOriginEXT(commandBuffer, domainOrigin); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetDepthClampEnableEXT(VkCommandBuffer commandBuffer, VkBool32 depthClampEnable) const noexcept { + fp_vkCmdSetDepthClampEnableEXT(commandBuffer, depthClampEnable); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetPolygonModeEXT(VkCommandBuffer commandBuffer, VkPolygonMode polygonMode) const noexcept { + fp_vkCmdSetPolygonModeEXT(commandBuffer, polygonMode); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetRasterizationSamplesEXT(VkCommandBuffer commandBuffer, VkSampleCountFlagBits rasterizationSamples) const noexcept { + fp_vkCmdSetRasterizationSamplesEXT(commandBuffer, rasterizationSamples); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetSampleMaskEXT(VkCommandBuffer commandBuffer, VkSampleCountFlagBits samples, const VkSampleMask* pSampleMask) const noexcept { + fp_vkCmdSetSampleMaskEXT(commandBuffer, samples, pSampleMask); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetAlphaToCoverageEnableEXT(VkCommandBuffer commandBuffer, VkBool32 alphaToCoverageEnable) const noexcept { + fp_vkCmdSetAlphaToCoverageEnableEXT(commandBuffer, alphaToCoverageEnable); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetAlphaToOneEnableEXT(VkCommandBuffer commandBuffer, VkBool32 alphaToOneEnable) const noexcept { + fp_vkCmdSetAlphaToOneEnableEXT(commandBuffer, alphaToOneEnable); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetLogicOpEnableEXT(VkCommandBuffer commandBuffer, VkBool32 logicOpEnable) const noexcept { + fp_vkCmdSetLogicOpEnableEXT(commandBuffer, logicOpEnable); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetColorBlendEnableEXT(VkCommandBuffer commandBuffer, uint32_t firstAttachment, uint32_t attachmentCount, const VkBool32* pColorBlendEnables) const noexcept { + fp_vkCmdSetColorBlendEnableEXT(commandBuffer, firstAttachment, attachmentCount, pColorBlendEnables); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetColorBlendEquationEXT(VkCommandBuffer commandBuffer, uint32_t firstAttachment, uint32_t attachmentCount, const VkColorBlendEquationEXT* pColorBlendEquations) const noexcept { + fp_vkCmdSetColorBlendEquationEXT(commandBuffer, firstAttachment, attachmentCount, pColorBlendEquations); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetColorWriteMaskEXT(VkCommandBuffer commandBuffer, uint32_t firstAttachment, uint32_t attachmentCount, const VkColorComponentFlags* pColorWriteMasks) const noexcept { + fp_vkCmdSetColorWriteMaskEXT(commandBuffer, firstAttachment, attachmentCount, pColorWriteMasks); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetRasterizationStreamEXT(VkCommandBuffer commandBuffer, uint32_t rasterizationStream) const noexcept { + fp_vkCmdSetRasterizationStreamEXT(commandBuffer, rasterizationStream); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetConservativeRasterizationModeEXT(VkCommandBuffer commandBuffer, VkConservativeRasterizationModeEXT conservativeRasterizationMode) const noexcept { + fp_vkCmdSetConservativeRasterizationModeEXT(commandBuffer, conservativeRasterizationMode); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetExtraPrimitiveOverestimationSizeEXT(VkCommandBuffer commandBuffer, float extraPrimitiveOverestimationSize) const noexcept { + fp_vkCmdSetExtraPrimitiveOverestimationSizeEXT(commandBuffer, extraPrimitiveOverestimationSize); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetDepthClipEnableEXT(VkCommandBuffer commandBuffer, VkBool32 depthClipEnable) const noexcept { + fp_vkCmdSetDepthClipEnableEXT(commandBuffer, depthClipEnable); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetSampleLocationsEnableEXT(VkCommandBuffer commandBuffer, VkBool32 sampleLocationsEnable) const noexcept { + fp_vkCmdSetSampleLocationsEnableEXT(commandBuffer, sampleLocationsEnable); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetColorBlendAdvancedEXT(VkCommandBuffer commandBuffer, uint32_t firstAttachment, uint32_t attachmentCount, const VkColorBlendAdvancedEXT* pColorBlendAdvanced) const noexcept { + fp_vkCmdSetColorBlendAdvancedEXT(commandBuffer, firstAttachment, attachmentCount, pColorBlendAdvanced); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetProvokingVertexModeEXT(VkCommandBuffer commandBuffer, VkProvokingVertexModeEXT provokingVertexMode) const noexcept { + fp_vkCmdSetProvokingVertexModeEXT(commandBuffer, provokingVertexMode); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetLineRasterizationModeEXT(VkCommandBuffer commandBuffer, VkLineRasterizationModeEXT lineRasterizationMode) const noexcept { + fp_vkCmdSetLineRasterizationModeEXT(commandBuffer, lineRasterizationMode); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetLineStippleEnableEXT(VkCommandBuffer commandBuffer, VkBool32 stippledLineEnable) const noexcept { + fp_vkCmdSetLineStippleEnableEXT(commandBuffer, stippledLineEnable); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetDepthClipNegativeOneToOneEXT(VkCommandBuffer commandBuffer, VkBool32 negativeOneToOne) const noexcept { + fp_vkCmdSetDepthClipNegativeOneToOneEXT(commandBuffer, negativeOneToOne); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetViewportWScalingEnableNV(VkCommandBuffer commandBuffer, VkBool32 viewportWScalingEnable) const noexcept { + fp_vkCmdSetViewportWScalingEnableNV(commandBuffer, viewportWScalingEnable); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetViewportSwizzleNV(VkCommandBuffer commandBuffer, uint32_t firstViewport, uint32_t viewportCount, const VkViewportSwizzleNV* pViewportSwizzles) const noexcept { + fp_vkCmdSetViewportSwizzleNV(commandBuffer, firstViewport, viewportCount, pViewportSwizzles); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetCoverageToColorEnableNV(VkCommandBuffer commandBuffer, VkBool32 coverageToColorEnable) const noexcept { + fp_vkCmdSetCoverageToColorEnableNV(commandBuffer, coverageToColorEnable); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetCoverageToColorLocationNV(VkCommandBuffer commandBuffer, uint32_t coverageToColorLocation) const noexcept { + fp_vkCmdSetCoverageToColorLocationNV(commandBuffer, coverageToColorLocation); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetCoverageModulationModeNV(VkCommandBuffer commandBuffer, VkCoverageModulationModeNV coverageModulationMode) const noexcept { + fp_vkCmdSetCoverageModulationModeNV(commandBuffer, coverageModulationMode); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetCoverageModulationTableEnableNV(VkCommandBuffer commandBuffer, VkBool32 coverageModulationTableEnable) const noexcept { + fp_vkCmdSetCoverageModulationTableEnableNV(commandBuffer, coverageModulationTableEnable); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetCoverageModulationTableNV(VkCommandBuffer commandBuffer, uint32_t coverageModulationTableCount, const float* pCoverageModulationTable) const noexcept { + fp_vkCmdSetCoverageModulationTableNV(commandBuffer, coverageModulationTableCount, pCoverageModulationTable); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetShadingRateImageEnableNV(VkCommandBuffer commandBuffer, VkBool32 shadingRateImageEnable) const noexcept { + fp_vkCmdSetShadingRateImageEnableNV(commandBuffer, shadingRateImageEnable); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetCoverageReductionModeNV(VkCommandBuffer commandBuffer, VkCoverageReductionModeNV coverageReductionMode) const noexcept { + fp_vkCmdSetCoverageReductionModeNV(commandBuffer, coverageReductionMode); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + void cmdSetRepresentativeFragmentTestEnableNV(VkCommandBuffer commandBuffer, VkBool32 representativeFragmentTestEnable) const noexcept { + fp_vkCmdSetRepresentativeFragmentTestEnableNV(commandBuffer, representativeFragmentTestEnable); + } +#endif +#if (defined(VK_VERSION_1_3)) + VkResult createPrivateDataSlot(const VkPrivateDataSlotCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkPrivateDataSlotEXT* pPrivateDataSlot) const noexcept { + return fp_vkCreatePrivateDataSlot(device, pCreateInfo, pAllocator, pPrivateDataSlot); + } +#endif +#if (defined(VK_VERSION_1_3)) + void destroyPrivateDataSlot(VkPrivateDataSlotEXT privateDataSlot, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyPrivateDataSlot(device, privateDataSlot, pAllocator); + } +#endif +#if (defined(VK_VERSION_1_3)) + VkResult setPrivateData(VkObjectType objectType, uint64_t objectHandle, VkPrivateDataSlotEXT privateDataSlot, uint64_t data) const noexcept { + return fp_vkSetPrivateData(device, objectType, objectHandle, privateDataSlot, data); + } +#endif +#if (defined(VK_VERSION_1_3)) + void getPrivateData(VkObjectType objectType, uint64_t objectHandle, VkPrivateDataSlotEXT privateDataSlot, uint64_t* pData) const noexcept { + fp_vkGetPrivateData(device, objectType, objectHandle, privateDataSlot, pData); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR* pCopyBufferInfo) const noexcept { + fp_vkCmdCopyBuffer2(commandBuffer, pCopyBufferInfo); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR* pCopyImageInfo) const noexcept { + fp_vkCmdCopyImage2(commandBuffer, pCopyImageInfo); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdBlitImage2(VkCommandBuffer commandBuffer, const VkBlitImageInfo2KHR* pBlitImageInfo) const noexcept { + fp_vkCmdBlitImage2(commandBuffer, pBlitImageInfo); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdCopyBufferToImage2(VkCommandBuffer commandBuffer, const VkCopyBufferToImageInfo2KHR* pCopyBufferToImageInfo) const noexcept { + fp_vkCmdCopyBufferToImage2(commandBuffer, pCopyBufferToImageInfo); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdCopyImageToBuffer2(VkCommandBuffer commandBuffer, const VkCopyImageToBufferInfo2KHR* pCopyImageToBufferInfo) const noexcept { + fp_vkCmdCopyImageToBuffer2(commandBuffer, pCopyImageToBufferInfo); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR* pResolveImageInfo) const noexcept { + fp_vkCmdResolveImage2(commandBuffer, pResolveImageInfo); + } +#endif +#if (defined(VK_KHR_object_refresh)) + void cmdRefreshObjectsKHR(VkCommandBuffer commandBuffer, const VkRefreshObjectListKHR* pRefreshObjects) const noexcept { + fp_vkCmdRefreshObjectsKHR(commandBuffer, pRefreshObjects); + } +#endif +#if (defined(VK_KHR_fragment_shading_rate)) + void cmdSetFragmentShadingRateKHR(VkCommandBuffer commandBuffer, const VkExtent2D* pFragmentSize, const VkFragmentShadingRateCombinerOpKHR combinerOps[2]) const noexcept { + fp_vkCmdSetFragmentShadingRateKHR(commandBuffer, pFragmentSize, combinerOps); + } +#endif +#if (defined(VK_NV_fragment_shading_rate_enums)) + void cmdSetFragmentShadingRateEnumNV(VkCommandBuffer commandBuffer, VkFragmentShadingRateNV shadingRate, const VkFragmentShadingRateCombinerOpKHR combinerOps[2]) const noexcept { + fp_vkCmdSetFragmentShadingRateEnumNV(commandBuffer, shadingRate, combinerOps); + } +#endif +#if (defined(VK_KHR_acceleration_structure)) + void getAccelerationStructureBuildSizesKHR(VkAccelerationStructureBuildTypeKHR buildType, const VkAccelerationStructureBuildGeometryInfoKHR* pBuildInfo, const uint32_t* pMaxPrimitiveCounts, VkAccelerationStructureBuildSizesInfoKHR* pSizeInfo) const noexcept { + fp_vkGetAccelerationStructureBuildSizesKHR(device, buildType, pBuildInfo, pMaxPrimitiveCounts, pSizeInfo); + } +#endif +#if (defined(VK_EXT_vertex_input_dynamic_state)) || (defined(VK_EXT_shader_object)) + void cmdSetVertexInputEXT(VkCommandBuffer commandBuffer, uint32_t vertexBindingDescriptionCount, const VkVertexInputBindingDescription2EXT* pVertexBindingDescriptions, uint32_t vertexAttributeDescriptionCount, const VkVertexInputAttributeDescription2EXT* pVertexAttributeDescriptions) const noexcept { + fp_vkCmdSetVertexInputEXT(commandBuffer, vertexBindingDescriptionCount, pVertexBindingDescriptions, vertexAttributeDescriptionCount, pVertexAttributeDescriptions); + } +#endif +#if (defined(VK_EXT_color_write_enable)) + void cmdSetColorWriteEnableEXT(VkCommandBuffer commandBuffer, uint32_t attachmentCount, const VkBool32* pColorWriteEnables) const noexcept { + fp_vkCmdSetColorWriteEnableEXT(commandBuffer, attachmentCount, pColorWriteEnables); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event, const VkDependencyInfoKHR* pDependencyInfo) const noexcept { + fp_vkCmdSetEvent2(commandBuffer, event, pDependencyInfo); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags2KHR stageMask) const noexcept { + fp_vkCmdResetEvent2(commandBuffer, event, stageMask); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents, const VkDependencyInfoKHR* pDependencyInfos) const noexcept { + fp_vkCmdWaitEvents2(commandBuffer, eventCount, pEvents, pDependencyInfos); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdPipelineBarrier2(VkCommandBuffer commandBuffer, const VkDependencyInfoKHR* pDependencyInfo) const noexcept { + fp_vkCmdPipelineBarrier2(commandBuffer, pDependencyInfo); + } +#endif +#if (defined(VK_VERSION_1_3)) + VkResult queueSubmit2(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits, VkFence fence) const noexcept { + return fp_vkQueueSubmit2(queue, submitCount, pSubmits, fence); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdWriteTimestamp2(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR stage, VkQueryPool queryPool, uint32_t query) const noexcept { + fp_vkCmdWriteTimestamp2(commandBuffer, stage, queryPool, query); + } +#endif +#if (defined(VK_KHR_synchronization2)) + void cmdWriteBufferMarker2AMD(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR stage, VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const noexcept { + fp_vkCmdWriteBufferMarker2AMD(commandBuffer, stage, dstBuffer, dstOffset, marker); + } +#endif +#if (defined(VK_KHR_synchronization2)) + void getQueueCheckpointData2NV(VkQueue queue, uint32_t* pCheckpointDataCount, VkCheckpointData2NV* pCheckpointData) const noexcept { + fp_vkGetQueueCheckpointData2NV(queue, pCheckpointDataCount, pCheckpointData); + } +#endif +#if (defined(VK_EXT_host_image_copy)) + VkResult copyMemoryToImageEXT(const VkCopyMemoryToImageInfoEXT* pCopyMemoryToImageInfo) const noexcept { + return fp_vkCopyMemoryToImageEXT(device, pCopyMemoryToImageInfo); + } +#endif +#if (defined(VK_EXT_host_image_copy)) + VkResult copyImageToMemoryEXT(const VkCopyImageToMemoryInfoEXT* pCopyImageToMemoryInfo) const noexcept { + return fp_vkCopyImageToMemoryEXT(device, pCopyImageToMemoryInfo); + } +#endif +#if (defined(VK_EXT_host_image_copy)) + VkResult copyImageToImageEXT(const VkCopyImageToImageInfoEXT* pCopyImageToImageInfo) const noexcept { + return fp_vkCopyImageToImageEXT(device, pCopyImageToImageInfo); + } +#endif +#if (defined(VK_EXT_host_image_copy)) + VkResult transitionImageLayoutEXT(uint32_t transitionCount, const VkHostImageLayoutTransitionInfoEXT* pTransitions) const noexcept { + return fp_vkTransitionImageLayoutEXT(device, transitionCount, pTransitions); + } +#endif +#if (defined(VKSC_VERSION_1_0)) + void getCommandPoolMemoryConsumption(VkCommandPool commandPool, VkCommandBuffer commandBuffer, VkCommandPoolMemoryConsumption* pConsumption) const noexcept { + fp_vkGetCommandPoolMemoryConsumption(device, commandPool, commandBuffer, pConsumption); + } +#endif +#if (defined(VK_KHR_video_queue)) + VkResult createVideoSessionKHR(const VkVideoSessionCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkVideoSessionKHR* pVideoSession) const noexcept { + return fp_vkCreateVideoSessionKHR(device, pCreateInfo, pAllocator, pVideoSession); + } +#endif +#if (defined(VK_KHR_video_queue)) + void destroyVideoSessionKHR(VkVideoSessionKHR videoSession, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyVideoSessionKHR(device, videoSession, pAllocator); + } +#endif +#if (defined(VK_KHR_video_queue)) + VkResult createVideoSessionParametersKHR(const VkVideoSessionParametersCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkVideoSessionParametersKHR* pVideoSessionParameters) const noexcept { + return fp_vkCreateVideoSessionParametersKHR(device, pCreateInfo, pAllocator, pVideoSessionParameters); + } +#endif +#if (defined(VK_KHR_video_queue)) + VkResult updateVideoSessionParametersKHR(VkVideoSessionParametersKHR videoSessionParameters, const VkVideoSessionParametersUpdateInfoKHR* pUpdateInfo) const noexcept { + return fp_vkUpdateVideoSessionParametersKHR(device, videoSessionParameters, pUpdateInfo); + } +#endif +#if (defined(VK_KHR_video_encode_queue)) + VkResult getEncodedVideoSessionParametersKHR(const VkVideoEncodeSessionParametersGetInfoKHR* pVideoSessionParametersInfo, VkVideoEncodeSessionParametersFeedbackInfoKHR* pFeedbackInfo, size_t* pDataSize, void* pData) const noexcept { + return fp_vkGetEncodedVideoSessionParametersKHR(device, pVideoSessionParametersInfo, pFeedbackInfo, pDataSize, pData); + } +#endif +#if (defined(VK_KHR_video_queue)) + void destroyVideoSessionParametersKHR(VkVideoSessionParametersKHR videoSessionParameters, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyVideoSessionParametersKHR(device, videoSessionParameters, pAllocator); + } +#endif +#if (defined(VK_KHR_video_queue)) + VkResult getVideoSessionMemoryRequirementsKHR(VkVideoSessionKHR videoSession, uint32_t* pMemoryRequirementsCount, VkVideoSessionMemoryRequirementsKHR* pMemoryRequirements) const noexcept { + return fp_vkGetVideoSessionMemoryRequirementsKHR(device, videoSession, pMemoryRequirementsCount, pMemoryRequirements); + } +#endif +#if (defined(VK_KHR_video_queue)) + VkResult bindVideoSessionMemoryKHR(VkVideoSessionKHR videoSession, uint32_t bindSessionMemoryInfoCount, const VkBindVideoSessionMemoryInfoKHR* pBindSessionMemoryInfos) const noexcept { + return fp_vkBindVideoSessionMemoryKHR(device, videoSession, bindSessionMemoryInfoCount, pBindSessionMemoryInfos); + } +#endif +#if (defined(VK_KHR_video_decode_queue)) + void cmdDecodeVideoKHR(VkCommandBuffer commandBuffer, const VkVideoDecodeInfoKHR* pDecodeInfo) const noexcept { + fp_vkCmdDecodeVideoKHR(commandBuffer, pDecodeInfo); + } +#endif +#if (defined(VK_KHR_video_queue)) + void cmdBeginVideoCodingKHR(VkCommandBuffer commandBuffer, const VkVideoBeginCodingInfoKHR* pBeginInfo) const noexcept { + fp_vkCmdBeginVideoCodingKHR(commandBuffer, pBeginInfo); + } +#endif +#if (defined(VK_KHR_video_queue)) + void cmdControlVideoCodingKHR(VkCommandBuffer commandBuffer, const VkVideoCodingControlInfoKHR* pCodingControlInfo) const noexcept { + fp_vkCmdControlVideoCodingKHR(commandBuffer, pCodingControlInfo); + } +#endif +#if (defined(VK_KHR_video_queue)) + void cmdEndVideoCodingKHR(VkCommandBuffer commandBuffer, const VkVideoEndCodingInfoKHR* pEndCodingInfo) const noexcept { + fp_vkCmdEndVideoCodingKHR(commandBuffer, pEndCodingInfo); + } +#endif +#if (defined(VK_KHR_video_encode_queue)) + void cmdEncodeVideoKHR(VkCommandBuffer commandBuffer, const VkVideoEncodeInfoKHR* pEncodeInfo) const noexcept { + fp_vkCmdEncodeVideoKHR(commandBuffer, pEncodeInfo); + } +#endif +#if (defined(VK_NV_memory_decompression)) + void cmdDecompressMemoryNV(VkCommandBuffer commandBuffer, uint32_t decompressRegionCount, const VkDecompressMemoryRegionNV* pDecompressMemoryRegions) const noexcept { + fp_vkCmdDecompressMemoryNV(commandBuffer, decompressRegionCount, pDecompressMemoryRegions); + } +#endif +#if (defined(VK_NV_memory_decompression)) + void cmdDecompressMemoryIndirectCountNV(VkCommandBuffer commandBuffer, VkDeviceAddress indirectCommandsAddress, VkDeviceAddress indirectCommandsCountAddress, uint32_t stride) const noexcept { + fp_vkCmdDecompressMemoryIndirectCountNV(commandBuffer, indirectCommandsAddress, indirectCommandsCountAddress, stride); + } +#endif +#if (defined(VK_EXT_descriptor_buffer)) + void getDescriptorSetLayoutSizeEXT(VkDescriptorSetLayout layout, VkDeviceSize* pLayoutSizeInBytes) const noexcept { + fp_vkGetDescriptorSetLayoutSizeEXT(device, layout, pLayoutSizeInBytes); + } +#endif +#if (defined(VK_EXT_descriptor_buffer)) + void getDescriptorSetLayoutBindingOffsetEXT(VkDescriptorSetLayout layout, uint32_t binding, VkDeviceSize* pOffset) const noexcept { + fp_vkGetDescriptorSetLayoutBindingOffsetEXT(device, layout, binding, pOffset); + } +#endif +#if (defined(VK_EXT_descriptor_buffer)) + void getDescriptorEXT(const VkDescriptorGetInfoEXT* pDescriptorInfo, size_t dataSize, void* pDescriptor) const noexcept { + fp_vkGetDescriptorEXT(device, pDescriptorInfo, dataSize, pDescriptor); + } +#endif +#if (defined(VK_EXT_descriptor_buffer)) + void cmdBindDescriptorBuffersEXT(VkCommandBuffer commandBuffer, uint32_t bufferCount, const VkDescriptorBufferBindingInfoEXT* pBindingInfos) const noexcept { + fp_vkCmdBindDescriptorBuffersEXT(commandBuffer, bufferCount, pBindingInfos); + } +#endif +#if (defined(VK_EXT_descriptor_buffer)) + void cmdSetDescriptorBufferOffsetsEXT(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipelineLayout layout, uint32_t firstSet, uint32_t setCount, const uint32_t* pBufferIndices, const VkDeviceSize* pOffsets) const noexcept { + fp_vkCmdSetDescriptorBufferOffsetsEXT(commandBuffer, pipelineBindPoint, layout, firstSet, setCount, pBufferIndices, pOffsets); + } +#endif +#if (defined(VK_EXT_descriptor_buffer)) + void cmdBindDescriptorBufferEmbeddedSamplersEXT(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipelineLayout layout, uint32_t set) const noexcept { + fp_vkCmdBindDescriptorBufferEmbeddedSamplersEXT(commandBuffer, pipelineBindPoint, layout, set); + } +#endif +#if (defined(VK_EXT_descriptor_buffer)) + VkResult getBufferOpaqueCaptureDescriptorDataEXT(const VkBufferCaptureDescriptorDataInfoEXT* pInfo, void* pData) const noexcept { + return fp_vkGetBufferOpaqueCaptureDescriptorDataEXT(device, pInfo, pData); + } +#endif +#if (defined(VK_EXT_descriptor_buffer)) + VkResult getImageOpaqueCaptureDescriptorDataEXT(const VkImageCaptureDescriptorDataInfoEXT* pInfo, void* pData) const noexcept { + return fp_vkGetImageOpaqueCaptureDescriptorDataEXT(device, pInfo, pData); + } +#endif +#if (defined(VK_EXT_descriptor_buffer)) + VkResult getImageViewOpaqueCaptureDescriptorDataEXT(const VkImageViewCaptureDescriptorDataInfoEXT* pInfo, void* pData) const noexcept { + return fp_vkGetImageViewOpaqueCaptureDescriptorDataEXT(device, pInfo, pData); + } +#endif +#if (defined(VK_EXT_descriptor_buffer)) + VkResult getSamplerOpaqueCaptureDescriptorDataEXT(const VkSamplerCaptureDescriptorDataInfoEXT* pInfo, void* pData) const noexcept { + return fp_vkGetSamplerOpaqueCaptureDescriptorDataEXT(device, pInfo, pData); + } +#endif +#if (defined(VK_EXT_descriptor_buffer)) + VkResult getAccelerationStructureOpaqueCaptureDescriptorDataEXT(const VkAccelerationStructureCaptureDescriptorDataInfoEXT* pInfo, void* pData) const noexcept { + return fp_vkGetAccelerationStructureOpaqueCaptureDescriptorDataEXT(device, pInfo, pData); + } +#endif +#if (defined(VK_EXT_pageable_device_local_memory)) + void setDeviceMemoryPriorityEXT(VkDeviceMemory memory, float priority) const noexcept { + fp_vkSetDeviceMemoryPriorityEXT(device, memory, priority); + } +#endif +#if (defined(VK_KHR_present_wait)) + VkResult waitForPresentKHR(VkSwapchainKHR swapchain, uint64_t presentId, uint64_t timeout) const noexcept { + return fp_vkWaitForPresentKHR(device, swapchain, presentId, timeout); + } +#endif +#if (defined(VK_FUCHSIA_buffer_collection)) + VkResult createBufferCollectionFUCHSIA(const VkBufferCollectionCreateInfoFUCHSIA* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkBufferCollectionFUCHSIA* pCollection) const noexcept { + return fp_vkCreateBufferCollectionFUCHSIA(device, pCreateInfo, pAllocator, pCollection); + } +#endif +#if (defined(VK_FUCHSIA_buffer_collection)) + VkResult setBufferCollectionBufferConstraintsFUCHSIA(VkBufferCollectionFUCHSIA collection, const VkBufferConstraintsInfoFUCHSIA* pBufferConstraintsInfo) const noexcept { + return fp_vkSetBufferCollectionBufferConstraintsFUCHSIA(device, collection, pBufferConstraintsInfo); + } +#endif +#if (defined(VK_FUCHSIA_buffer_collection)) + VkResult setBufferCollectionImageConstraintsFUCHSIA(VkBufferCollectionFUCHSIA collection, const VkImageConstraintsInfoFUCHSIA* pImageConstraintsInfo) const noexcept { + return fp_vkSetBufferCollectionImageConstraintsFUCHSIA(device, collection, pImageConstraintsInfo); + } +#endif +#if (defined(VK_FUCHSIA_buffer_collection)) + void destroyBufferCollectionFUCHSIA(VkBufferCollectionFUCHSIA collection, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyBufferCollectionFUCHSIA(device, collection, pAllocator); + } +#endif +#if (defined(VK_FUCHSIA_buffer_collection)) + VkResult getBufferCollectionPropertiesFUCHSIA(VkBufferCollectionFUCHSIA collection, VkBufferCollectionPropertiesFUCHSIA* pProperties) const noexcept { + return fp_vkGetBufferCollectionPropertiesFUCHSIA(device, collection, pProperties); + } +#endif +#if (defined(VK_NV_cuda_kernel_launch)) + VkResult createCudaModuleNV(const VkCudaModuleCreateInfoNV* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkCudaModuleNV* pModule) const noexcept { + return fp_vkCreateCudaModuleNV(device, pCreateInfo, pAllocator, pModule); + } +#endif +#if (defined(VK_NV_cuda_kernel_launch)) + VkResult getCudaModuleCacheNV(VkCudaModuleNV module, size_t* pCacheSize, void* pCacheData) const noexcept { + return fp_vkGetCudaModuleCacheNV(device, module, pCacheSize, pCacheData); + } +#endif +#if (defined(VK_NV_cuda_kernel_launch)) + VkResult createCudaFunctionNV(const VkCudaFunctionCreateInfoNV* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkCudaFunctionNV* pFunction) const noexcept { + return fp_vkCreateCudaFunctionNV(device, pCreateInfo, pAllocator, pFunction); + } +#endif +#if (defined(VK_NV_cuda_kernel_launch)) + void destroyCudaModuleNV(VkCudaModuleNV module, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyCudaModuleNV(device, module, pAllocator); + } +#endif +#if (defined(VK_NV_cuda_kernel_launch)) + void destroyCudaFunctionNV(VkCudaFunctionNV function, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyCudaFunctionNV(device, function, pAllocator); + } +#endif +#if (defined(VK_NV_cuda_kernel_launch)) + void cmdCudaLaunchKernelNV(VkCommandBuffer commandBuffer, const VkCudaLaunchInfoNV* pLaunchInfo) const noexcept { + fp_vkCmdCudaLaunchKernelNV(commandBuffer, pLaunchInfo); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdBeginRendering(VkCommandBuffer commandBuffer, const VkRenderingInfoKHR* pRenderingInfo) const noexcept { + fp_vkCmdBeginRendering(commandBuffer, pRenderingInfo); + } +#endif +#if (defined(VK_VERSION_1_3)) + void cmdEndRendering(VkCommandBuffer commandBuffer) const noexcept { + fp_vkCmdEndRendering(commandBuffer); + } +#endif +#if (defined(VK_VALVE_descriptor_set_host_mapping)) + void getDescriptorSetLayoutHostMappingInfoVALVE(const VkDescriptorSetBindingReferenceVALVE* pBindingReference, VkDescriptorSetLayoutHostMappingInfoVALVE* pHostMapping) const noexcept { + fp_vkGetDescriptorSetLayoutHostMappingInfoVALVE(device, pBindingReference, pHostMapping); + } +#endif +#if (defined(VK_VALVE_descriptor_set_host_mapping)) + void getDescriptorSetHostMappingVALVE(VkDescriptorSet descriptorSet, void** ppData) const noexcept { + fp_vkGetDescriptorSetHostMappingVALVE(device, descriptorSet, ppData); + } +#endif +#if (defined(VK_EXT_opacity_micromap)) + VkResult createMicromapEXT(const VkMicromapCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkMicromapEXT* pMicromap) const noexcept { + return fp_vkCreateMicromapEXT(device, pCreateInfo, pAllocator, pMicromap); + } +#endif +#if (defined(VK_EXT_opacity_micromap)) + void cmdBuildMicromapsEXT(VkCommandBuffer commandBuffer, uint32_t infoCount, const VkMicromapBuildInfoEXT* pInfos) const noexcept { + fp_vkCmdBuildMicromapsEXT(commandBuffer, infoCount, pInfos); + } +#endif +#if (defined(VK_EXT_opacity_micromap)) + VkResult buildMicromapsEXT(VkDeferredOperationKHR deferredOperation, uint32_t infoCount, const VkMicromapBuildInfoEXT* pInfos) const noexcept { + return fp_vkBuildMicromapsEXT(device, deferredOperation, infoCount, pInfos); + } +#endif +#if (defined(VK_EXT_opacity_micromap)) + void destroyMicromapEXT(VkMicromapEXT micromap, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyMicromapEXT(device, micromap, pAllocator); + } +#endif +#if (defined(VK_EXT_opacity_micromap)) + void cmdCopyMicromapEXT(VkCommandBuffer commandBuffer, const VkCopyMicromapInfoEXT* pInfo) const noexcept { + fp_vkCmdCopyMicromapEXT(commandBuffer, pInfo); + } +#endif +#if (defined(VK_EXT_opacity_micromap)) + VkResult copyMicromapEXT(VkDeferredOperationKHR deferredOperation, const VkCopyMicromapInfoEXT* pInfo) const noexcept { + return fp_vkCopyMicromapEXT(device, deferredOperation, pInfo); + } +#endif +#if (defined(VK_EXT_opacity_micromap)) + void cmdCopyMicromapToMemoryEXT(VkCommandBuffer commandBuffer, const VkCopyMicromapToMemoryInfoEXT* pInfo) const noexcept { + fp_vkCmdCopyMicromapToMemoryEXT(commandBuffer, pInfo); + } +#endif +#if (defined(VK_EXT_opacity_micromap)) + VkResult copyMicromapToMemoryEXT(VkDeferredOperationKHR deferredOperation, const VkCopyMicromapToMemoryInfoEXT* pInfo) const noexcept { + return fp_vkCopyMicromapToMemoryEXT(device, deferredOperation, pInfo); + } +#endif +#if (defined(VK_EXT_opacity_micromap)) + void cmdCopyMemoryToMicromapEXT(VkCommandBuffer commandBuffer, const VkCopyMemoryToMicromapInfoEXT* pInfo) const noexcept { + fp_vkCmdCopyMemoryToMicromapEXT(commandBuffer, pInfo); + } +#endif +#if (defined(VK_EXT_opacity_micromap)) + VkResult copyMemoryToMicromapEXT(VkDeferredOperationKHR deferredOperation, const VkCopyMemoryToMicromapInfoEXT* pInfo) const noexcept { + return fp_vkCopyMemoryToMicromapEXT(device, deferredOperation, pInfo); + } +#endif +#if (defined(VK_EXT_opacity_micromap)) + void cmdWriteMicromapsPropertiesEXT(VkCommandBuffer commandBuffer, uint32_t micromapCount, const VkMicromapEXT* pMicromaps, VkQueryType queryType, VkQueryPool queryPool, uint32_t firstQuery) const noexcept { + fp_vkCmdWriteMicromapsPropertiesEXT(commandBuffer, micromapCount, pMicromaps, queryType, queryPool, firstQuery); + } +#endif +#if (defined(VK_EXT_opacity_micromap)) + VkResult writeMicromapsPropertiesEXT(uint32_t micromapCount, const VkMicromapEXT* pMicromaps, VkQueryType queryType, size_t dataSize, void* pData, size_t stride) const noexcept { + return fp_vkWriteMicromapsPropertiesEXT(device, micromapCount, pMicromaps, queryType, dataSize, pData, stride); + } +#endif +#if (defined(VK_EXT_opacity_micromap)) + void getDeviceMicromapCompatibilityEXT(const VkMicromapVersionInfoEXT* pVersionInfo, VkAccelerationStructureCompatibilityKHR* pCompatibility) const noexcept { + fp_vkGetDeviceMicromapCompatibilityEXT(device, pVersionInfo, pCompatibility); + } +#endif +#if (defined(VK_EXT_opacity_micromap)) + void getMicromapBuildSizesEXT(VkAccelerationStructureBuildTypeKHR buildType, const VkMicromapBuildInfoEXT* pBuildInfo, VkMicromapBuildSizesInfoEXT* pSizeInfo) const noexcept { + fp_vkGetMicromapBuildSizesEXT(device, buildType, pBuildInfo, pSizeInfo); + } +#endif +#if (defined(VK_EXT_shader_module_identifier)) + void getShaderModuleIdentifierEXT(VkShaderModule shaderModule, VkShaderModuleIdentifierEXT* pIdentifier) const noexcept { + fp_vkGetShaderModuleIdentifierEXT(device, shaderModule, pIdentifier); + } +#endif +#if (defined(VK_EXT_shader_module_identifier)) + void getShaderModuleCreateInfoIdentifierEXT(const VkShaderModuleCreateInfo* pCreateInfo, VkShaderModuleIdentifierEXT* pIdentifier) const noexcept { + fp_vkGetShaderModuleCreateInfoIdentifierEXT(device, pCreateInfo, pIdentifier); + } +#endif +#if (defined(VK_KHR_maintenance5)) + void getImageSubresourceLayout2KHR(VkImage image, const VkImageSubresource2EXT* pSubresource, VkSubresourceLayout2EXT* pLayout) const noexcept { + fp_vkGetImageSubresourceLayout2KHR(device, image, pSubresource, pLayout); + } +#endif +#if (defined(VK_EXT_pipeline_properties)) + VkResult getPipelinePropertiesEXT(const VkPipelineInfoEXT* pPipelineInfo, VkBaseOutStructure* pPipelineProperties) const noexcept { + return fp_vkGetPipelinePropertiesEXT(device, pPipelineInfo, pPipelineProperties); + } +#endif +#if (defined(VK_EXT_metal_objects)) + void exportMetalObjectsEXT(VkExportMetalObjectsInfoEXT* pMetalObjectsInfo) const noexcept { + fp_vkExportMetalObjectsEXT(device, pMetalObjectsInfo); + } +#endif +#if (defined(VK_QCOM_tile_properties)) + VkResult getFramebufferTilePropertiesQCOM(VkFramebuffer framebuffer, uint32_t* pPropertiesCount, VkTilePropertiesQCOM* pProperties) const noexcept { + return fp_vkGetFramebufferTilePropertiesQCOM(device, framebuffer, pPropertiesCount, pProperties); + } +#endif +#if (defined(VK_QCOM_tile_properties)) + VkResult getDynamicRenderingTilePropertiesQCOM(const VkRenderingInfoKHR* pRenderingInfo, VkTilePropertiesQCOM* pProperties) const noexcept { + return fp_vkGetDynamicRenderingTilePropertiesQCOM(device, pRenderingInfo, pProperties); + } +#endif +#if (defined(VK_NV_optical_flow)) + VkResult createOpticalFlowSessionNV(const VkOpticalFlowSessionCreateInfoNV* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkOpticalFlowSessionNV* pSession) const noexcept { + return fp_vkCreateOpticalFlowSessionNV(device, pCreateInfo, pAllocator, pSession); + } +#endif +#if (defined(VK_NV_optical_flow)) + void destroyOpticalFlowSessionNV(VkOpticalFlowSessionNV session, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyOpticalFlowSessionNV(device, session, pAllocator); + } +#endif +#if (defined(VK_NV_optical_flow)) + VkResult bindOpticalFlowSessionImageNV(VkOpticalFlowSessionNV session, VkOpticalFlowSessionBindingPointNV bindingPoint, VkImageView view, VkImageLayout layout) const noexcept { + return fp_vkBindOpticalFlowSessionImageNV(device, session, bindingPoint, view, layout); + } +#endif +#if (defined(VK_NV_optical_flow)) + void cmdOpticalFlowExecuteNV(VkCommandBuffer commandBuffer, VkOpticalFlowSessionNV session, const VkOpticalFlowExecuteInfoNV* pExecuteInfo) const noexcept { + fp_vkCmdOpticalFlowExecuteNV(commandBuffer, session, pExecuteInfo); + } +#endif +#if (defined(VK_EXT_device_fault)) + VkResult getDeviceFaultInfoEXT(VkDeviceFaultCountsEXT* pFaultCounts, VkDeviceFaultInfoEXT* pFaultInfo) const noexcept { + return fp_vkGetDeviceFaultInfoEXT(device, pFaultCounts, pFaultInfo); + } +#endif +#if (defined(VK_EXT_depth_bias_control)) + void cmdSetDepthBias2EXT(VkCommandBuffer commandBuffer, const VkDepthBiasInfoEXT* pDepthBiasInfo) const noexcept { + fp_vkCmdSetDepthBias2EXT(commandBuffer, pDepthBiasInfo); + } +#endif +#if (defined(VK_EXT_swapchain_maintenance1)) + VkResult releaseSwapchainImagesEXT(const VkReleaseSwapchainImagesInfoEXT* pReleaseInfo) const noexcept { + return fp_vkReleaseSwapchainImagesEXT(device, pReleaseInfo); + } +#endif +#if (defined(VK_KHR_maintenance5)) + void getDeviceImageSubresourceLayoutKHR(const VkDeviceImageSubresourceInfoKHR* pInfo, VkSubresourceLayout2EXT* pLayout) const noexcept { + fp_vkGetDeviceImageSubresourceLayoutKHR(device, pInfo, pLayout); + } +#endif +#if (defined(VK_KHR_map_memory2)) + VkResult mapMemory2KHR(const VkMemoryMapInfoKHR* pMemoryMapInfo, void** ppData) const noexcept { + return fp_vkMapMemory2KHR(device, pMemoryMapInfo, ppData); + } +#endif +#if (defined(VK_KHR_map_memory2)) + VkResult unmapMemory2KHR(const VkMemoryUnmapInfoKHR* pMemoryUnmapInfo) const noexcept { + return fp_vkUnmapMemory2KHR(device, pMemoryUnmapInfo); + } +#endif +#if (defined(VK_EXT_shader_object)) + VkResult createShadersEXT(uint32_t createInfoCount, const VkShaderCreateInfoEXT* pCreateInfos, const VkAllocationCallbacks* pAllocator, VkShaderEXT* pShaders) const noexcept { + return fp_vkCreateShadersEXT(device, createInfoCount, pCreateInfos, pAllocator, pShaders); + } +#endif +#if (defined(VK_EXT_shader_object)) + void destroyShaderEXT(VkShaderEXT shader, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyShaderEXT(device, shader, pAllocator); + } +#endif +#if (defined(VK_EXT_shader_object)) + VkResult getShaderBinaryDataEXT(VkShaderEXT shader, size_t* pDataSize, void* pData) const noexcept { + return fp_vkGetShaderBinaryDataEXT(device, shader, pDataSize, pData); + } +#endif +#if (defined(VK_EXT_shader_object)) + void cmdBindShadersEXT(VkCommandBuffer commandBuffer, uint32_t stageCount, const VkShaderStageFlagBits* pStages, const VkShaderEXT* pShaders) const noexcept { + fp_vkCmdBindShadersEXT(commandBuffer, stageCount, pStages, pShaders); + } +#endif +#if (defined(VK_QNX_external_memory_screen_buffer)) + VkResult getScreenBufferPropertiesQNX(const struct _screen_buffer* buffer, VkScreenBufferPropertiesQNX* pProperties) const noexcept { + return fp_vkGetScreenBufferPropertiesQNX(device, buffer, pProperties); + } +#endif +#if (defined(VK_AMDX_shader_enqueue)) + VkResult getExecutionGraphPipelineScratchSizeAMDX(VkPipeline executionGraph, VkExecutionGraphPipelineScratchSizeAMDX* pSizeInfo) const noexcept { + return fp_vkGetExecutionGraphPipelineScratchSizeAMDX(device, executionGraph, pSizeInfo); + } +#endif +#if (defined(VK_AMDX_shader_enqueue)) + VkResult getExecutionGraphPipelineNodeIndexAMDX(VkPipeline executionGraph, const VkPipelineShaderStageNodeCreateInfoAMDX* pNodeInfo, uint32_t* pNodeIndex) const noexcept { + return fp_vkGetExecutionGraphPipelineNodeIndexAMDX(device, executionGraph, pNodeInfo, pNodeIndex); + } +#endif +#if (defined(VK_AMDX_shader_enqueue)) + VkResult createExecutionGraphPipelinesAMDX(VkPipelineCache pipelineCache, uint32_t createInfoCount, const VkExecutionGraphPipelineCreateInfoAMDX* pCreateInfos, const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines) const noexcept { + return fp_vkCreateExecutionGraphPipelinesAMDX(device, pipelineCache, createInfoCount, pCreateInfos, pAllocator, pPipelines); + } +#endif +#if (defined(VK_AMDX_shader_enqueue)) + void cmdInitializeGraphScratchMemoryAMDX(VkCommandBuffer commandBuffer, VkDeviceAddress scratch) const noexcept { + fp_vkCmdInitializeGraphScratchMemoryAMDX(commandBuffer, scratch); + } +#endif +#if (defined(VK_AMDX_shader_enqueue)) + void cmdDispatchGraphAMDX(VkCommandBuffer commandBuffer, VkDeviceAddress scratch, const VkDispatchGraphCountInfoAMDX* pCountInfo) const noexcept { + fp_vkCmdDispatchGraphAMDX(commandBuffer, scratch, pCountInfo); + } +#endif +#if (defined(VK_AMDX_shader_enqueue)) + void cmdDispatchGraphIndirectAMDX(VkCommandBuffer commandBuffer, VkDeviceAddress scratch, const VkDispatchGraphCountInfoAMDX* pCountInfo) const noexcept { + fp_vkCmdDispatchGraphIndirectAMDX(commandBuffer, scratch, pCountInfo); + } +#endif +#if (defined(VK_AMDX_shader_enqueue)) + void cmdDispatchGraphIndirectCountAMDX(VkCommandBuffer commandBuffer, VkDeviceAddress scratch, VkDeviceAddress countInfo) const noexcept { + fp_vkCmdDispatchGraphIndirectCountAMDX(commandBuffer, scratch, countInfo); + } +#endif +#if (defined(VK_KHR_maintenance6)) + void cmdBindDescriptorSets2KHR(VkCommandBuffer commandBuffer, const VkBindDescriptorSetsInfoKHR* pBindDescriptorSetsInfo) const noexcept { + fp_vkCmdBindDescriptorSets2KHR(commandBuffer, pBindDescriptorSetsInfo); + } +#endif +#if (defined(VK_KHR_maintenance6)) + void cmdPushConstants2KHR(VkCommandBuffer commandBuffer, const VkPushConstantsInfoKHR* pPushConstantsInfo) const noexcept { + fp_vkCmdPushConstants2KHR(commandBuffer, pPushConstantsInfo); + } +#endif +#if (defined(VK_KHR_maintenance6)) + void cmdPushDescriptorSet2KHR(VkCommandBuffer commandBuffer, const VkPushDescriptorSetInfoKHR* pPushDescriptorSetInfo) const noexcept { + fp_vkCmdPushDescriptorSet2KHR(commandBuffer, pPushDescriptorSetInfo); + } +#endif +#if (defined(VK_KHR_maintenance6)) + void cmdPushDescriptorSetWithTemplate2KHR(VkCommandBuffer commandBuffer, const VkPushDescriptorSetWithTemplateInfoKHR* pPushDescriptorSetWithTemplateInfo) const noexcept { + fp_vkCmdPushDescriptorSetWithTemplate2KHR(commandBuffer, pPushDescriptorSetWithTemplateInfo); + } +#endif +#if (defined(VK_KHR_maintenance6)) + void cmdSetDescriptorBufferOffsets2EXT(VkCommandBuffer commandBuffer, const VkSetDescriptorBufferOffsetsInfoEXT* pSetDescriptorBufferOffsetsInfo) const noexcept { + fp_vkCmdSetDescriptorBufferOffsets2EXT(commandBuffer, pSetDescriptorBufferOffsetsInfo); + } +#endif +#if (defined(VK_KHR_maintenance6)) + void cmdBindDescriptorBufferEmbeddedSamplers2EXT(VkCommandBuffer commandBuffer, const VkBindDescriptorBufferEmbeddedSamplersInfoEXT* pBindDescriptorBufferEmbeddedSamplersInfo) const noexcept { + fp_vkCmdBindDescriptorBufferEmbeddedSamplers2EXT(commandBuffer, pBindDescriptorBufferEmbeddedSamplersInfo); + } +#endif +#if (defined(VK_NV_low_latency2)) + VkResult setLatencySleepModeNV(VkSwapchainKHR swapchain, const VkLatencySleepModeInfoNV* pSleepModeInfo) const noexcept { + return fp_vkSetLatencySleepModeNV(device, swapchain, pSleepModeInfo); + } +#endif +#if (defined(VK_NV_low_latency2)) + VkResult latencySleepNV(VkSwapchainKHR swapchain, const VkLatencySleepInfoNV* pSleepInfo) const noexcept { + return fp_vkLatencySleepNV(device, swapchain, pSleepInfo); + } +#endif +#if (defined(VK_NV_low_latency2)) + void setLatencyMarkerNV(VkSwapchainKHR swapchain, const VkSetLatencyMarkerInfoNV* pLatencyMarkerInfo) const noexcept { + fp_vkSetLatencyMarkerNV(device, swapchain, pLatencyMarkerInfo); + } +#endif +#if ((defined(VK_NV_low_latency2))) && VK_HEADER_VERSION >= 271 + void getLatencyTimingsNV(VkSwapchainKHR swapchain, VkGetLatencyMarkerInfoNV* pLatencyMarkerInfo) const noexcept { + fp_vkGetLatencyTimingsNV(device, swapchain, pLatencyMarkerInfo); + } +#endif +#if (defined(VK_NV_low_latency2)) + void queueNotifyOutOfBandNV(VkQueue queue, const VkOutOfBandQueueTypeInfoNV* pQueueTypeInfo) const noexcept { + fp_vkQueueNotifyOutOfBandNV(queue, pQueueTypeInfo); + } +#endif +#if (defined(VK_KHR_dynamic_rendering_local_read)) + void cmdSetRenderingAttachmentLocationsKHR(VkCommandBuffer commandBuffer, const VkRenderingAttachmentLocationInfoKHR* pLocationInfo) const noexcept { + fp_vkCmdSetRenderingAttachmentLocationsKHR(commandBuffer, pLocationInfo); + } +#endif +#if (defined(VK_KHR_dynamic_rendering_local_read)) + void cmdSetRenderingInputAttachmentIndicesKHR(VkCommandBuffer commandBuffer, const VkRenderingInputAttachmentIndexInfoKHR* pInputAttachmentIndexInfo) const noexcept { + fp_vkCmdSetRenderingInputAttachmentIndicesKHR(commandBuffer, pInputAttachmentIndexInfo); + } +#endif +#if (defined(VK_EXT_host_query_reset)) + void resetQueryPoolEXT(VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount) const noexcept { + fp_vkResetQueryPoolEXT(device, queryPool, firstQuery, queryCount); + } +#endif +#if (defined(VK_KHR_maintenance1)) + void trimCommandPoolKHR(VkCommandPool commandPool, VkCommandPoolTrimFlagsKHR flags) const noexcept { + fp_vkTrimCommandPoolKHR(device, commandPool, flags); + } +#endif +#if (defined(VK_KHR_device_group)) + void getDeviceGroupPeerMemoryFeaturesKHR(uint32_t heapIndex, uint32_t localDeviceIndex, uint32_t remoteDeviceIndex, VkPeerMemoryFeatureFlagsKHR* pPeerMemoryFeatures) const noexcept { + fp_vkGetDeviceGroupPeerMemoryFeaturesKHR(device, heapIndex, localDeviceIndex, remoteDeviceIndex, pPeerMemoryFeatures); + } +#endif +#if (defined(VK_KHR_bind_memory2)) + VkResult bindBufferMemory2KHR(uint32_t bindInfoCount, const VkBindBufferMemoryInfoKHR* pBindInfos) const noexcept { + return fp_vkBindBufferMemory2KHR(device, bindInfoCount, pBindInfos); + } +#endif +#if (defined(VK_KHR_bind_memory2)) + VkResult bindImageMemory2KHR(uint32_t bindInfoCount, const VkBindImageMemoryInfoKHR* pBindInfos) const noexcept { + return fp_vkBindImageMemory2KHR(device, bindInfoCount, pBindInfos); + } +#endif +#if (defined(VK_KHR_device_group)) + void cmdSetDeviceMaskKHR(VkCommandBuffer commandBuffer, uint32_t deviceMask) const noexcept { + fp_vkCmdSetDeviceMaskKHR(commandBuffer, deviceMask); + } +#endif +#if (defined(VK_KHR_device_group)) + void cmdDispatchBaseKHR(VkCommandBuffer commandBuffer, uint32_t baseGroupX, uint32_t baseGroupY, uint32_t baseGroupZ, uint32_t groupCountX, uint32_t groupCountY, uint32_t groupCountZ) const noexcept { + fp_vkCmdDispatchBaseKHR(commandBuffer, baseGroupX, baseGroupY, baseGroupZ, groupCountX, groupCountY, groupCountZ); + } +#endif +#if (defined(VK_KHR_descriptor_update_template)) + VkResult createDescriptorUpdateTemplateKHR(const VkDescriptorUpdateTemplateCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDescriptorUpdateTemplateKHR* pDescriptorUpdateTemplate) const noexcept { + return fp_vkCreateDescriptorUpdateTemplateKHR(device, pCreateInfo, pAllocator, pDescriptorUpdateTemplate); + } +#endif +#if (defined(VK_KHR_descriptor_update_template)) + void destroyDescriptorUpdateTemplateKHR(VkDescriptorUpdateTemplateKHR descriptorUpdateTemplate, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyDescriptorUpdateTemplateKHR(device, descriptorUpdateTemplate, pAllocator); + } +#endif +#if (defined(VK_KHR_descriptor_update_template)) + void updateDescriptorSetWithTemplateKHR(VkDescriptorSet descriptorSet, VkDescriptorUpdateTemplateKHR descriptorUpdateTemplate, const void* pData) const noexcept { + fp_vkUpdateDescriptorSetWithTemplateKHR(device, descriptorSet, descriptorUpdateTemplate, pData); + } +#endif +#if (defined(VK_KHR_get_memory_requirements2)) + void getBufferMemoryRequirements2KHR(const VkBufferMemoryRequirementsInfo2KHR* pInfo, VkMemoryRequirements2KHR* pMemoryRequirements) const noexcept { + fp_vkGetBufferMemoryRequirements2KHR(device, pInfo, pMemoryRequirements); + } +#endif +#if (defined(VK_KHR_get_memory_requirements2)) + void getImageMemoryRequirements2KHR(const VkImageMemoryRequirementsInfo2KHR* pInfo, VkMemoryRequirements2KHR* pMemoryRequirements) const noexcept { + fp_vkGetImageMemoryRequirements2KHR(device, pInfo, pMemoryRequirements); + } +#endif +#if (defined(VK_KHR_get_memory_requirements2)) + void getImageSparseMemoryRequirements2KHR(const VkImageSparseMemoryRequirementsInfo2KHR* pInfo, uint32_t* pSparseMemoryRequirementCount, VkSparseImageMemoryRequirements2KHR* pSparseMemoryRequirements) const noexcept { + fp_vkGetImageSparseMemoryRequirements2KHR(device, pInfo, pSparseMemoryRequirementCount, pSparseMemoryRequirements); + } +#endif +#if (defined(VK_KHR_maintenance4)) + void getDeviceBufferMemoryRequirementsKHR(const VkDeviceBufferMemoryRequirementsKHR* pInfo, VkMemoryRequirements2KHR* pMemoryRequirements) const noexcept { + fp_vkGetDeviceBufferMemoryRequirementsKHR(device, pInfo, pMemoryRequirements); + } +#endif +#if (defined(VK_KHR_maintenance4)) + void getDeviceImageMemoryRequirementsKHR(const VkDeviceImageMemoryRequirementsKHR* pInfo, VkMemoryRequirements2KHR* pMemoryRequirements) const noexcept { + fp_vkGetDeviceImageMemoryRequirementsKHR(device, pInfo, pMemoryRequirements); + } +#endif +#if (defined(VK_KHR_maintenance4)) + void getDeviceImageSparseMemoryRequirementsKHR(const VkDeviceImageMemoryRequirementsKHR* pInfo, uint32_t* pSparseMemoryRequirementCount, VkSparseImageMemoryRequirements2KHR* pSparseMemoryRequirements) const noexcept { + fp_vkGetDeviceImageSparseMemoryRequirementsKHR(device, pInfo, pSparseMemoryRequirementCount, pSparseMemoryRequirements); + } +#endif +#if (defined(VK_KHR_sampler_ycbcr_conversion)) + VkResult createSamplerYcbcrConversionKHR(const VkSamplerYcbcrConversionCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSamplerYcbcrConversionKHR* pYcbcrConversion) const noexcept { + return fp_vkCreateSamplerYcbcrConversionKHR(device, pCreateInfo, pAllocator, pYcbcrConversion); + } +#endif +#if (defined(VK_KHR_sampler_ycbcr_conversion)) + void destroySamplerYcbcrConversionKHR(VkSamplerYcbcrConversionKHR ycbcrConversion, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroySamplerYcbcrConversionKHR(device, ycbcrConversion, pAllocator); + } +#endif +#if (defined(VK_KHR_maintenance3)) + void getDescriptorSetLayoutSupportKHR(const VkDescriptorSetLayoutCreateInfo* pCreateInfo, VkDescriptorSetLayoutSupportKHR* pSupport) const noexcept { + fp_vkGetDescriptorSetLayoutSupportKHR(device, pCreateInfo, pSupport); + } +#endif +#if (defined(VK_EXT_calibrated_timestamps)) + VkResult getCalibratedTimestampsEXT(uint32_t timestampCount, const VkCalibratedTimestampInfoEXT* pTimestampInfos, uint64_t* pTimestamps, uint64_t* pMaxDeviation) const noexcept { + return fp_vkGetCalibratedTimestampsEXT(device, timestampCount, pTimestampInfos, pTimestamps, pMaxDeviation); + } +#endif +#if (defined(VK_KHR_create_renderpass2)) + VkResult createRenderPass2KHR(const VkRenderPassCreateInfo2KHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const noexcept { + return fp_vkCreateRenderPass2KHR(device, pCreateInfo, pAllocator, pRenderPass); + } +#endif +#if (defined(VK_KHR_create_renderpass2)) + void cmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin, const VkSubpassBeginInfoKHR* pSubpassBeginInfo) const noexcept { + fp_vkCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo); + } +#endif +#if (defined(VK_KHR_create_renderpass2)) + void cmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfoKHR* pSubpassBeginInfo, const VkSubpassEndInfoKHR* pSubpassEndInfo) const noexcept { + fp_vkCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo); + } +#endif +#if (defined(VK_KHR_create_renderpass2)) + void cmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR* pSubpassEndInfo) const noexcept { + fp_vkCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo); + } +#endif +#if (defined(VK_KHR_timeline_semaphore)) + VkResult getSemaphoreCounterValueKHR(VkSemaphore semaphore, uint64_t* pValue) const noexcept { + return fp_vkGetSemaphoreCounterValueKHR(device, semaphore, pValue); + } +#endif +#if (defined(VK_KHR_timeline_semaphore)) + VkResult waitSemaphoresKHR(const VkSemaphoreWaitInfoKHR* pWaitInfo, uint64_t timeout) const noexcept { + return fp_vkWaitSemaphoresKHR(device, pWaitInfo, timeout); + } +#endif +#if (defined(VK_KHR_timeline_semaphore)) + VkResult signalSemaphoreKHR(const VkSemaphoreSignalInfoKHR* pSignalInfo) const noexcept { + return fp_vkSignalSemaphoreKHR(device, pSignalInfo); + } +#endif +#if (defined(VK_AMD_draw_indirect_count)) + void cmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount, uint32_t stride) const noexcept { + fp_vkCmdDrawIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride); + } +#endif +#if (defined(VK_AMD_draw_indirect_count)) + void cmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount, uint32_t stride) const noexcept { + fp_vkCmdDrawIndexedIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride); + } +#endif +#if (defined(VK_NV_ray_tracing)) + VkResult getRayTracingShaderGroupHandlesNV(VkPipeline pipeline, uint32_t firstGroup, uint32_t groupCount, size_t dataSize, void* pData) const noexcept { + return fp_vkGetRayTracingShaderGroupHandlesNV(device, pipeline, firstGroup, groupCount, dataSize, pData); + } +#endif +#if (defined(VK_KHR_buffer_device_address)) + uint64_t getBufferOpaqueCaptureAddressKHR(const VkBufferDeviceAddressInfoEXT* pInfo) const noexcept { + return fp_vkGetBufferOpaqueCaptureAddressKHR(device, pInfo); + } +#endif +#if (defined(VK_EXT_buffer_device_address)) + VkDeviceAddress getBufferDeviceAddressEXT(const VkBufferDeviceAddressInfoEXT* pInfo) const noexcept { + return fp_vkGetBufferDeviceAddressEXT(device, pInfo); + } +#endif +#if (defined(VK_KHR_buffer_device_address)) + uint64_t getDeviceMemoryOpaqueCaptureAddressKHR(const VkDeviceMemoryOpaqueCaptureAddressInfoKHR* pInfo) const noexcept { + return fp_vkGetDeviceMemoryOpaqueCaptureAddressKHR(device, pInfo); + } +#endif +#if (defined(VK_EXT_line_rasterization)) + void cmdSetLineStippleEXT(VkCommandBuffer commandBuffer, uint32_t lineStippleFactor, uint16_t lineStipplePattern) const noexcept { + fp_vkCmdSetLineStippleEXT(commandBuffer, lineStippleFactor, lineStipplePattern); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + void cmdSetCullModeEXT(VkCommandBuffer commandBuffer, VkCullModeFlags cullMode) const noexcept { + fp_vkCmdSetCullModeEXT(commandBuffer, cullMode); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + void cmdSetFrontFaceEXT(VkCommandBuffer commandBuffer, VkFrontFace frontFace) const noexcept { + fp_vkCmdSetFrontFaceEXT(commandBuffer, frontFace); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + void cmdSetPrimitiveTopologyEXT(VkCommandBuffer commandBuffer, VkPrimitiveTopology primitiveTopology) const noexcept { + fp_vkCmdSetPrimitiveTopologyEXT(commandBuffer, primitiveTopology); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + void cmdSetViewportWithCountEXT(VkCommandBuffer commandBuffer, uint32_t viewportCount, const VkViewport* pViewports) const noexcept { + fp_vkCmdSetViewportWithCountEXT(commandBuffer, viewportCount, pViewports); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + void cmdSetScissorWithCountEXT(VkCommandBuffer commandBuffer, uint32_t scissorCount, const VkRect2D* pScissors) const noexcept { + fp_vkCmdSetScissorWithCountEXT(commandBuffer, scissorCount, pScissors); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + void cmdBindVertexBuffers2EXT(VkCommandBuffer commandBuffer, uint32_t firstBinding, uint32_t bindingCount, const VkBuffer* pBuffers, const VkDeviceSize* pOffsets, const VkDeviceSize* pSizes, const VkDeviceSize* pStrides) const noexcept { + fp_vkCmdBindVertexBuffers2EXT(commandBuffer, firstBinding, bindingCount, pBuffers, pOffsets, pSizes, pStrides); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + void cmdSetDepthTestEnableEXT(VkCommandBuffer commandBuffer, VkBool32 depthTestEnable) const noexcept { + fp_vkCmdSetDepthTestEnableEXT(commandBuffer, depthTestEnable); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + void cmdSetDepthWriteEnableEXT(VkCommandBuffer commandBuffer, VkBool32 depthWriteEnable) const noexcept { + fp_vkCmdSetDepthWriteEnableEXT(commandBuffer, depthWriteEnable); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + void cmdSetDepthCompareOpEXT(VkCommandBuffer commandBuffer, VkCompareOp depthCompareOp) const noexcept { + fp_vkCmdSetDepthCompareOpEXT(commandBuffer, depthCompareOp); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + void cmdSetDepthBoundsTestEnableEXT(VkCommandBuffer commandBuffer, VkBool32 depthBoundsTestEnable) const noexcept { + fp_vkCmdSetDepthBoundsTestEnableEXT(commandBuffer, depthBoundsTestEnable); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + void cmdSetStencilTestEnableEXT(VkCommandBuffer commandBuffer, VkBool32 stencilTestEnable) const noexcept { + fp_vkCmdSetStencilTestEnableEXT(commandBuffer, stencilTestEnable); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + void cmdSetStencilOpEXT(VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask, VkStencilOp failOp, VkStencilOp passOp, VkStencilOp depthFailOp, VkCompareOp compareOp) const noexcept { + fp_vkCmdSetStencilOpEXT(commandBuffer, faceMask, failOp, passOp, depthFailOp, compareOp); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state2)) || (defined(VK_EXT_shader_object)) + void cmdSetRasterizerDiscardEnableEXT(VkCommandBuffer commandBuffer, VkBool32 rasterizerDiscardEnable) const noexcept { + fp_vkCmdSetRasterizerDiscardEnableEXT(commandBuffer, rasterizerDiscardEnable); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state2)) || (defined(VK_EXT_shader_object)) + void cmdSetDepthBiasEnableEXT(VkCommandBuffer commandBuffer, VkBool32 depthBiasEnable) const noexcept { + fp_vkCmdSetDepthBiasEnableEXT(commandBuffer, depthBiasEnable); + } +#endif +#if (defined(VK_EXT_extended_dynamic_state2)) || (defined(VK_EXT_shader_object)) + void cmdSetPrimitiveRestartEnableEXT(VkCommandBuffer commandBuffer, VkBool32 primitiveRestartEnable) const noexcept { + fp_vkCmdSetPrimitiveRestartEnableEXT(commandBuffer, primitiveRestartEnable); + } +#endif +#if (defined(VK_EXT_private_data)) + VkResult createPrivateDataSlotEXT(const VkPrivateDataSlotCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkPrivateDataSlotEXT* pPrivateDataSlot) const noexcept { + return fp_vkCreatePrivateDataSlotEXT(device, pCreateInfo, pAllocator, pPrivateDataSlot); + } +#endif +#if (defined(VK_EXT_private_data)) + void destroyPrivateDataSlotEXT(VkPrivateDataSlotEXT privateDataSlot, const VkAllocationCallbacks* pAllocator) const noexcept { + fp_vkDestroyPrivateDataSlotEXT(device, privateDataSlot, pAllocator); + } +#endif +#if (defined(VK_EXT_private_data)) + VkResult setPrivateDataEXT(VkObjectType objectType, uint64_t objectHandle, VkPrivateDataSlotEXT privateDataSlot, uint64_t data) const noexcept { + return fp_vkSetPrivateDataEXT(device, objectType, objectHandle, privateDataSlot, data); + } +#endif +#if (defined(VK_EXT_private_data)) + void getPrivateDataEXT(VkObjectType objectType, uint64_t objectHandle, VkPrivateDataSlotEXT privateDataSlot, uint64_t* pData) const noexcept { + fp_vkGetPrivateDataEXT(device, objectType, objectHandle, privateDataSlot, pData); + } +#endif +#if (defined(VK_KHR_copy_commands2)) + void cmdCopyBuffer2KHR(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR* pCopyBufferInfo) const noexcept { + fp_vkCmdCopyBuffer2KHR(commandBuffer, pCopyBufferInfo); + } +#endif +#if (defined(VK_KHR_copy_commands2)) + void cmdCopyImage2KHR(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR* pCopyImageInfo) const noexcept { + fp_vkCmdCopyImage2KHR(commandBuffer, pCopyImageInfo); + } +#endif +#if (defined(VK_KHR_copy_commands2)) + void cmdBlitImage2KHR(VkCommandBuffer commandBuffer, const VkBlitImageInfo2KHR* pBlitImageInfo) const noexcept { + fp_vkCmdBlitImage2KHR(commandBuffer, pBlitImageInfo); + } +#endif +#if (defined(VK_KHR_copy_commands2)) + void cmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer, const VkCopyBufferToImageInfo2KHR* pCopyBufferToImageInfo) const noexcept { + fp_vkCmdCopyBufferToImage2KHR(commandBuffer, pCopyBufferToImageInfo); + } +#endif +#if (defined(VK_KHR_copy_commands2)) + void cmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer, const VkCopyImageToBufferInfo2KHR* pCopyImageToBufferInfo) const noexcept { + fp_vkCmdCopyImageToBuffer2KHR(commandBuffer, pCopyImageToBufferInfo); + } +#endif +#if (defined(VK_KHR_copy_commands2)) + void cmdResolveImage2KHR(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR* pResolveImageInfo) const noexcept { + fp_vkCmdResolveImage2KHR(commandBuffer, pResolveImageInfo); + } +#endif +#if (defined(VK_KHR_synchronization2)) + void cmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event, const VkDependencyInfoKHR* pDependencyInfo) const noexcept { + fp_vkCmdSetEvent2KHR(commandBuffer, event, pDependencyInfo); + } +#endif +#if (defined(VK_KHR_synchronization2)) + void cmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags2KHR stageMask) const noexcept { + fp_vkCmdResetEvent2KHR(commandBuffer, event, stageMask); + } +#endif +#if (defined(VK_KHR_synchronization2)) + void cmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents, const VkDependencyInfoKHR* pDependencyInfos) const noexcept { + fp_vkCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos); + } +#endif +#if (defined(VK_KHR_synchronization2)) + void cmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer, const VkDependencyInfoKHR* pDependencyInfo) const noexcept { + fp_vkCmdPipelineBarrier2KHR(commandBuffer, pDependencyInfo); + } +#endif +#if (defined(VK_KHR_synchronization2)) + VkResult queueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits, VkFence fence) const noexcept { + return fp_vkQueueSubmit2KHR(queue, submitCount, pSubmits, fence); + } +#endif +#if (defined(VK_KHR_synchronization2)) + void cmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR stage, VkQueryPool queryPool, uint32_t query) const noexcept { + fp_vkCmdWriteTimestamp2KHR(commandBuffer, stage, queryPool, query); + } +#endif +#if (defined(VK_KHR_dynamic_rendering)) + void cmdBeginRenderingKHR(VkCommandBuffer commandBuffer, const VkRenderingInfoKHR* pRenderingInfo) const noexcept { + fp_vkCmdBeginRenderingKHR(commandBuffer, pRenderingInfo); + } +#endif +#if (defined(VK_KHR_dynamic_rendering)) + void cmdEndRenderingKHR(VkCommandBuffer commandBuffer) const noexcept { + fp_vkCmdEndRenderingKHR(commandBuffer); + } +#endif +#if (defined(VK_EXT_host_image_copy)) || (defined(VK_EXT_image_compression_control)) + void getImageSubresourceLayout2EXT(VkImage image, const VkImageSubresource2EXT* pSubresource, VkSubresourceLayout2EXT* pLayout) const noexcept { + fp_vkGetImageSubresourceLayout2EXT(device, image, pSubresource, pLayout); + } +#endif + PFN_vkGetDeviceQueue fp_vkGetDeviceQueue = nullptr; + PFN_vkQueueSubmit fp_vkQueueSubmit = nullptr; + PFN_vkQueueWaitIdle fp_vkQueueWaitIdle = nullptr; + PFN_vkDeviceWaitIdle fp_vkDeviceWaitIdle = nullptr; + PFN_vkAllocateMemory fp_vkAllocateMemory = nullptr; + PFN_vkFreeMemory fp_vkFreeMemory = nullptr; + PFN_vkMapMemory fp_vkMapMemory = nullptr; + PFN_vkUnmapMemory fp_vkUnmapMemory = nullptr; + PFN_vkFlushMappedMemoryRanges fp_vkFlushMappedMemoryRanges = nullptr; + PFN_vkInvalidateMappedMemoryRanges fp_vkInvalidateMappedMemoryRanges = nullptr; + PFN_vkGetDeviceMemoryCommitment fp_vkGetDeviceMemoryCommitment = nullptr; + PFN_vkGetBufferMemoryRequirements fp_vkGetBufferMemoryRequirements = nullptr; + PFN_vkBindBufferMemory fp_vkBindBufferMemory = nullptr; + PFN_vkGetImageMemoryRequirements fp_vkGetImageMemoryRequirements = nullptr; + PFN_vkBindImageMemory fp_vkBindImageMemory = nullptr; + PFN_vkGetImageSparseMemoryRequirements fp_vkGetImageSparseMemoryRequirements = nullptr; + PFN_vkQueueBindSparse fp_vkQueueBindSparse = nullptr; + PFN_vkCreateFence fp_vkCreateFence = nullptr; + PFN_vkDestroyFence fp_vkDestroyFence = nullptr; + PFN_vkResetFences fp_vkResetFences = nullptr; + PFN_vkGetFenceStatus fp_vkGetFenceStatus = nullptr; + PFN_vkWaitForFences fp_vkWaitForFences = nullptr; + PFN_vkCreateSemaphore fp_vkCreateSemaphore = nullptr; + PFN_vkDestroySemaphore fp_vkDestroySemaphore = nullptr; + PFN_vkCreateEvent fp_vkCreateEvent = nullptr; + PFN_vkDestroyEvent fp_vkDestroyEvent = nullptr; + PFN_vkGetEventStatus fp_vkGetEventStatus = nullptr; + PFN_vkSetEvent fp_vkSetEvent = nullptr; + PFN_vkResetEvent fp_vkResetEvent = nullptr; + PFN_vkCreateQueryPool fp_vkCreateQueryPool = nullptr; + PFN_vkDestroyQueryPool fp_vkDestroyQueryPool = nullptr; + PFN_vkGetQueryPoolResults fp_vkGetQueryPoolResults = nullptr; +#if (defined(VK_VERSION_1_2)) + PFN_vkResetQueryPool fp_vkResetQueryPool = nullptr; +#else + void * fp_vkResetQueryPool{}; +#endif + PFN_vkCreateBuffer fp_vkCreateBuffer = nullptr; + PFN_vkDestroyBuffer fp_vkDestroyBuffer = nullptr; + PFN_vkCreateBufferView fp_vkCreateBufferView = nullptr; + PFN_vkDestroyBufferView fp_vkDestroyBufferView = nullptr; + PFN_vkCreateImage fp_vkCreateImage = nullptr; + PFN_vkDestroyImage fp_vkDestroyImage = nullptr; + PFN_vkGetImageSubresourceLayout fp_vkGetImageSubresourceLayout = nullptr; + PFN_vkCreateImageView fp_vkCreateImageView = nullptr; + PFN_vkDestroyImageView fp_vkDestroyImageView = nullptr; + PFN_vkCreateShaderModule fp_vkCreateShaderModule = nullptr; + PFN_vkDestroyShaderModule fp_vkDestroyShaderModule = nullptr; + PFN_vkCreatePipelineCache fp_vkCreatePipelineCache = nullptr; + PFN_vkDestroyPipelineCache fp_vkDestroyPipelineCache = nullptr; + PFN_vkGetPipelineCacheData fp_vkGetPipelineCacheData = nullptr; + PFN_vkMergePipelineCaches fp_vkMergePipelineCaches = nullptr; +#if (defined(VK_KHR_pipeline_binary)) + PFN_vkCreatePipelineBinariesKHR fp_vkCreatePipelineBinariesKHR = nullptr; +#else + void * fp_vkCreatePipelineBinariesKHR{}; +#endif +#if (defined(VK_KHR_pipeline_binary)) + PFN_vkDestroyPipelineBinaryKHR fp_vkDestroyPipelineBinaryKHR = nullptr; +#else + void * fp_vkDestroyPipelineBinaryKHR{}; +#endif +#if (defined(VK_KHR_pipeline_binary)) + PFN_vkGetPipelineKeyKHR fp_vkGetPipelineKeyKHR = nullptr; +#else + void * fp_vkGetPipelineKeyKHR{}; +#endif +#if (defined(VK_KHR_pipeline_binary)) + PFN_vkGetPipelineBinaryDataKHR fp_vkGetPipelineBinaryDataKHR = nullptr; +#else + void * fp_vkGetPipelineBinaryDataKHR{}; +#endif +#if (defined(VK_KHR_pipeline_binary)) + PFN_vkReleaseCapturedPipelineDataKHR fp_vkReleaseCapturedPipelineDataKHR = nullptr; +#else + void * fp_vkReleaseCapturedPipelineDataKHR{}; +#endif + PFN_vkCreateGraphicsPipelines fp_vkCreateGraphicsPipelines = nullptr; + PFN_vkCreateComputePipelines fp_vkCreateComputePipelines = nullptr; +#if (defined(VK_HUAWEI_subpass_shading)) + PFN_vkGetDeviceSubpassShadingMaxWorkgroupSizeHUAWEI fp_vkGetDeviceSubpassShadingMaxWorkgroupSizeHUAWEI = nullptr; +#else + void * fp_vkGetDeviceSubpassShadingMaxWorkgroupSizeHUAWEI{}; +#endif + PFN_vkDestroyPipeline fp_vkDestroyPipeline = nullptr; + PFN_vkCreatePipelineLayout fp_vkCreatePipelineLayout = nullptr; + PFN_vkDestroyPipelineLayout fp_vkDestroyPipelineLayout = nullptr; + PFN_vkCreateSampler fp_vkCreateSampler = nullptr; + PFN_vkDestroySampler fp_vkDestroySampler = nullptr; + PFN_vkCreateDescriptorSetLayout fp_vkCreateDescriptorSetLayout = nullptr; + PFN_vkDestroyDescriptorSetLayout fp_vkDestroyDescriptorSetLayout = nullptr; + PFN_vkCreateDescriptorPool fp_vkCreateDescriptorPool = nullptr; + PFN_vkDestroyDescriptorPool fp_vkDestroyDescriptorPool = nullptr; + PFN_vkResetDescriptorPool fp_vkResetDescriptorPool = nullptr; + PFN_vkAllocateDescriptorSets fp_vkAllocateDescriptorSets = nullptr; + PFN_vkFreeDescriptorSets fp_vkFreeDescriptorSets = nullptr; + PFN_vkUpdateDescriptorSets fp_vkUpdateDescriptorSets = nullptr; + PFN_vkCreateFramebuffer fp_vkCreateFramebuffer = nullptr; + PFN_vkDestroyFramebuffer fp_vkDestroyFramebuffer = nullptr; + PFN_vkCreateRenderPass fp_vkCreateRenderPass = nullptr; + PFN_vkDestroyRenderPass fp_vkDestroyRenderPass = nullptr; + PFN_vkGetRenderAreaGranularity fp_vkGetRenderAreaGranularity = nullptr; +#if (defined(VK_KHR_maintenance5)) + PFN_vkGetRenderingAreaGranularityKHR fp_vkGetRenderingAreaGranularityKHR = nullptr; +#else + void * fp_vkGetRenderingAreaGranularityKHR{}; +#endif + PFN_vkCreateCommandPool fp_vkCreateCommandPool = nullptr; + PFN_vkDestroyCommandPool fp_vkDestroyCommandPool = nullptr; + PFN_vkResetCommandPool fp_vkResetCommandPool = nullptr; + PFN_vkAllocateCommandBuffers fp_vkAllocateCommandBuffers = nullptr; + PFN_vkFreeCommandBuffers fp_vkFreeCommandBuffers = nullptr; + PFN_vkBeginCommandBuffer fp_vkBeginCommandBuffer = nullptr; + PFN_vkEndCommandBuffer fp_vkEndCommandBuffer = nullptr; + PFN_vkResetCommandBuffer fp_vkResetCommandBuffer = nullptr; + PFN_vkCmdBindPipeline fp_vkCmdBindPipeline = nullptr; +#if (defined(VK_EXT_attachment_feedback_loop_dynamic_state)) + PFN_vkCmdSetAttachmentFeedbackLoopEnableEXT fp_vkCmdSetAttachmentFeedbackLoopEnableEXT = nullptr; +#else + void * fp_vkCmdSetAttachmentFeedbackLoopEnableEXT{}; +#endif + PFN_vkCmdSetViewport fp_vkCmdSetViewport = nullptr; + PFN_vkCmdSetScissor fp_vkCmdSetScissor = nullptr; + PFN_vkCmdSetLineWidth fp_vkCmdSetLineWidth = nullptr; + PFN_vkCmdSetDepthBias fp_vkCmdSetDepthBias = nullptr; + PFN_vkCmdSetBlendConstants fp_vkCmdSetBlendConstants = nullptr; + PFN_vkCmdSetDepthBounds fp_vkCmdSetDepthBounds = nullptr; + PFN_vkCmdSetStencilCompareMask fp_vkCmdSetStencilCompareMask = nullptr; + PFN_vkCmdSetStencilWriteMask fp_vkCmdSetStencilWriteMask = nullptr; + PFN_vkCmdSetStencilReference fp_vkCmdSetStencilReference = nullptr; + PFN_vkCmdBindDescriptorSets fp_vkCmdBindDescriptorSets = nullptr; + PFN_vkCmdBindIndexBuffer fp_vkCmdBindIndexBuffer = nullptr; + PFN_vkCmdBindVertexBuffers fp_vkCmdBindVertexBuffers = nullptr; + PFN_vkCmdDraw fp_vkCmdDraw = nullptr; + PFN_vkCmdDrawIndexed fp_vkCmdDrawIndexed = nullptr; +#if (defined(VK_EXT_multi_draw)) + PFN_vkCmdDrawMultiEXT fp_vkCmdDrawMultiEXT = nullptr; +#else + void * fp_vkCmdDrawMultiEXT{}; +#endif +#if (defined(VK_EXT_multi_draw)) + PFN_vkCmdDrawMultiIndexedEXT fp_vkCmdDrawMultiIndexedEXT = nullptr; +#else + void * fp_vkCmdDrawMultiIndexedEXT{}; +#endif + PFN_vkCmdDrawIndirect fp_vkCmdDrawIndirect = nullptr; + PFN_vkCmdDrawIndexedIndirect fp_vkCmdDrawIndexedIndirect = nullptr; + PFN_vkCmdDispatch fp_vkCmdDispatch = nullptr; + PFN_vkCmdDispatchIndirect fp_vkCmdDispatchIndirect = nullptr; +#if (defined(VK_HUAWEI_subpass_shading)) + PFN_vkCmdSubpassShadingHUAWEI fp_vkCmdSubpassShadingHUAWEI = nullptr; +#else + void * fp_vkCmdSubpassShadingHUAWEI{}; +#endif +#if (defined(VK_HUAWEI_cluster_culling_shader)) + PFN_vkCmdDrawClusterHUAWEI fp_vkCmdDrawClusterHUAWEI = nullptr; +#else + void * fp_vkCmdDrawClusterHUAWEI{}; +#endif +#if (defined(VK_HUAWEI_cluster_culling_shader)) + PFN_vkCmdDrawClusterIndirectHUAWEI fp_vkCmdDrawClusterIndirectHUAWEI = nullptr; +#else + void * fp_vkCmdDrawClusterIndirectHUAWEI{}; +#endif +#if (defined(VK_NV_device_generated_commands_compute)) + PFN_vkCmdUpdatePipelineIndirectBufferNV fp_vkCmdUpdatePipelineIndirectBufferNV = nullptr; +#else + void * fp_vkCmdUpdatePipelineIndirectBufferNV{}; +#endif + PFN_vkCmdCopyBuffer fp_vkCmdCopyBuffer = nullptr; + PFN_vkCmdCopyImage fp_vkCmdCopyImage = nullptr; + PFN_vkCmdBlitImage fp_vkCmdBlitImage = nullptr; + PFN_vkCmdCopyBufferToImage fp_vkCmdCopyBufferToImage = nullptr; + PFN_vkCmdCopyImageToBuffer fp_vkCmdCopyImageToBuffer = nullptr; +#if (defined(VK_NV_copy_memory_indirect)) + PFN_vkCmdCopyMemoryIndirectNV fp_vkCmdCopyMemoryIndirectNV = nullptr; +#else + void * fp_vkCmdCopyMemoryIndirectNV{}; +#endif +#if (defined(VK_NV_copy_memory_indirect)) + PFN_vkCmdCopyMemoryToImageIndirectNV fp_vkCmdCopyMemoryToImageIndirectNV = nullptr; +#else + void * fp_vkCmdCopyMemoryToImageIndirectNV{}; +#endif + PFN_vkCmdUpdateBuffer fp_vkCmdUpdateBuffer = nullptr; + PFN_vkCmdFillBuffer fp_vkCmdFillBuffer = nullptr; + PFN_vkCmdClearColorImage fp_vkCmdClearColorImage = nullptr; + PFN_vkCmdClearDepthStencilImage fp_vkCmdClearDepthStencilImage = nullptr; + PFN_vkCmdClearAttachments fp_vkCmdClearAttachments = nullptr; + PFN_vkCmdResolveImage fp_vkCmdResolveImage = nullptr; + PFN_vkCmdSetEvent fp_vkCmdSetEvent = nullptr; + PFN_vkCmdResetEvent fp_vkCmdResetEvent = nullptr; + PFN_vkCmdWaitEvents fp_vkCmdWaitEvents = nullptr; + PFN_vkCmdPipelineBarrier fp_vkCmdPipelineBarrier = nullptr; + PFN_vkCmdBeginQuery fp_vkCmdBeginQuery = nullptr; + PFN_vkCmdEndQuery fp_vkCmdEndQuery = nullptr; +#if (defined(VK_EXT_conditional_rendering)) + PFN_vkCmdBeginConditionalRenderingEXT fp_vkCmdBeginConditionalRenderingEXT = nullptr; +#else + void * fp_vkCmdBeginConditionalRenderingEXT{}; +#endif +#if (defined(VK_EXT_conditional_rendering)) + PFN_vkCmdEndConditionalRenderingEXT fp_vkCmdEndConditionalRenderingEXT = nullptr; +#else + void * fp_vkCmdEndConditionalRenderingEXT{}; +#endif + PFN_vkCmdResetQueryPool fp_vkCmdResetQueryPool = nullptr; + PFN_vkCmdWriteTimestamp fp_vkCmdWriteTimestamp = nullptr; + PFN_vkCmdCopyQueryPoolResults fp_vkCmdCopyQueryPoolResults = nullptr; + PFN_vkCmdPushConstants fp_vkCmdPushConstants = nullptr; + PFN_vkCmdBeginRenderPass fp_vkCmdBeginRenderPass = nullptr; + PFN_vkCmdNextSubpass fp_vkCmdNextSubpass = nullptr; + PFN_vkCmdEndRenderPass fp_vkCmdEndRenderPass = nullptr; + PFN_vkCmdExecuteCommands fp_vkCmdExecuteCommands = nullptr; +#if (defined(VK_KHR_display_swapchain)) + PFN_vkCreateSharedSwapchainsKHR fp_vkCreateSharedSwapchainsKHR = nullptr; +#else + void * fp_vkCreateSharedSwapchainsKHR{}; +#endif +#if (defined(VK_KHR_swapchain)) + PFN_vkCreateSwapchainKHR fp_vkCreateSwapchainKHR = nullptr; +#else + void * fp_vkCreateSwapchainKHR{}; +#endif +#if (defined(VK_KHR_swapchain)) + PFN_vkDestroySwapchainKHR fp_vkDestroySwapchainKHR = nullptr; +#else + void * fp_vkDestroySwapchainKHR{}; +#endif +#if (defined(VK_KHR_swapchain)) + PFN_vkGetSwapchainImagesKHR fp_vkGetSwapchainImagesKHR = nullptr; +#else + void * fp_vkGetSwapchainImagesKHR{}; +#endif +#if (defined(VK_KHR_swapchain)) + PFN_vkAcquireNextImageKHR fp_vkAcquireNextImageKHR = nullptr; +#else + void * fp_vkAcquireNextImageKHR{}; +#endif +#if (defined(VK_KHR_swapchain)) + PFN_vkQueuePresentKHR fp_vkQueuePresentKHR = nullptr; +#else + void * fp_vkQueuePresentKHR{}; +#endif +#if (defined(VK_EXT_debug_marker)) + PFN_vkDebugMarkerSetObjectNameEXT fp_vkDebugMarkerSetObjectNameEXT = nullptr; +#else + void * fp_vkDebugMarkerSetObjectNameEXT{}; +#endif +#if (defined(VK_EXT_debug_marker)) + PFN_vkDebugMarkerSetObjectTagEXT fp_vkDebugMarkerSetObjectTagEXT = nullptr; +#else + void * fp_vkDebugMarkerSetObjectTagEXT{}; +#endif +#if (defined(VK_EXT_debug_marker)) + PFN_vkCmdDebugMarkerBeginEXT fp_vkCmdDebugMarkerBeginEXT = nullptr; +#else + void * fp_vkCmdDebugMarkerBeginEXT{}; +#endif +#if (defined(VK_EXT_debug_marker)) + PFN_vkCmdDebugMarkerEndEXT fp_vkCmdDebugMarkerEndEXT = nullptr; +#else + void * fp_vkCmdDebugMarkerEndEXT{}; +#endif +#if (defined(VK_EXT_debug_marker)) + PFN_vkCmdDebugMarkerInsertEXT fp_vkCmdDebugMarkerInsertEXT = nullptr; +#else + void * fp_vkCmdDebugMarkerInsertEXT{}; +#endif +#if (defined(VK_NV_external_memory_win32)) + PFN_vkGetMemoryWin32HandleNV fp_vkGetMemoryWin32HandleNV = nullptr; +#else + void * fp_vkGetMemoryWin32HandleNV{}; +#endif +#if (defined(VK_NV_device_generated_commands)) + PFN_vkCmdExecuteGeneratedCommandsNV fp_vkCmdExecuteGeneratedCommandsNV = nullptr; +#else + void * fp_vkCmdExecuteGeneratedCommandsNV{}; +#endif +#if (defined(VK_NV_device_generated_commands)) + PFN_vkCmdPreprocessGeneratedCommandsNV fp_vkCmdPreprocessGeneratedCommandsNV = nullptr; +#else + void * fp_vkCmdPreprocessGeneratedCommandsNV{}; +#endif +#if (defined(VK_NV_device_generated_commands)) + PFN_vkCmdBindPipelineShaderGroupNV fp_vkCmdBindPipelineShaderGroupNV = nullptr; +#else + void * fp_vkCmdBindPipelineShaderGroupNV{}; +#endif +#if (defined(VK_NV_device_generated_commands)) + PFN_vkGetGeneratedCommandsMemoryRequirementsNV fp_vkGetGeneratedCommandsMemoryRequirementsNV = nullptr; +#else + void * fp_vkGetGeneratedCommandsMemoryRequirementsNV{}; +#endif +#if (defined(VK_NV_device_generated_commands)) + PFN_vkCreateIndirectCommandsLayoutNV fp_vkCreateIndirectCommandsLayoutNV = nullptr; +#else + void * fp_vkCreateIndirectCommandsLayoutNV{}; +#endif +#if (defined(VK_NV_device_generated_commands)) + PFN_vkDestroyIndirectCommandsLayoutNV fp_vkDestroyIndirectCommandsLayoutNV = nullptr; +#else + void * fp_vkDestroyIndirectCommandsLayoutNV{}; +#endif +#if (defined(VK_KHR_push_descriptor)) + PFN_vkCmdPushDescriptorSetKHR fp_vkCmdPushDescriptorSetKHR = nullptr; +#else + void * fp_vkCmdPushDescriptorSetKHR{}; +#endif +#if (defined(VK_VERSION_1_1)) + PFN_vkTrimCommandPool fp_vkTrimCommandPool = nullptr; +#else + void * fp_vkTrimCommandPool{}; +#endif +#if (defined(VK_KHR_external_memory_win32)) + PFN_vkGetMemoryWin32HandleKHR fp_vkGetMemoryWin32HandleKHR = nullptr; +#else + void * fp_vkGetMemoryWin32HandleKHR{}; +#endif +#if (defined(VK_KHR_external_memory_win32)) + PFN_vkGetMemoryWin32HandlePropertiesKHR fp_vkGetMemoryWin32HandlePropertiesKHR = nullptr; +#else + void * fp_vkGetMemoryWin32HandlePropertiesKHR{}; +#endif +#if (defined(VK_KHR_external_memory_fd)) + PFN_vkGetMemoryFdKHR fp_vkGetMemoryFdKHR = nullptr; +#else + void * fp_vkGetMemoryFdKHR{}; +#endif +#if (defined(VK_KHR_external_memory_fd)) + PFN_vkGetMemoryFdPropertiesKHR fp_vkGetMemoryFdPropertiesKHR = nullptr; +#else + void * fp_vkGetMemoryFdPropertiesKHR{}; +#endif +#if (defined(VK_FUCHSIA_external_memory)) + PFN_vkGetMemoryZirconHandleFUCHSIA fp_vkGetMemoryZirconHandleFUCHSIA = nullptr; +#else + void * fp_vkGetMemoryZirconHandleFUCHSIA{}; +#endif +#if (defined(VK_FUCHSIA_external_memory)) + PFN_vkGetMemoryZirconHandlePropertiesFUCHSIA fp_vkGetMemoryZirconHandlePropertiesFUCHSIA = nullptr; +#else + void * fp_vkGetMemoryZirconHandlePropertiesFUCHSIA{}; +#endif +#if (defined(VK_NV_external_memory_rdma)) + PFN_vkGetMemoryRemoteAddressNV fp_vkGetMemoryRemoteAddressNV = nullptr; +#else + void * fp_vkGetMemoryRemoteAddressNV{}; +#endif +#if (defined(VK_NV_external_memory_sci_buf)) + PFN_vkGetMemorySciBufNV fp_vkGetMemorySciBufNV = nullptr; +#else + void * fp_vkGetMemorySciBufNV{}; +#endif +#if (defined(VK_KHR_external_semaphore_win32)) + PFN_vkGetSemaphoreWin32HandleKHR fp_vkGetSemaphoreWin32HandleKHR = nullptr; +#else + void * fp_vkGetSemaphoreWin32HandleKHR{}; +#endif +#if (defined(VK_KHR_external_semaphore_win32)) + PFN_vkImportSemaphoreWin32HandleKHR fp_vkImportSemaphoreWin32HandleKHR = nullptr; +#else + void * fp_vkImportSemaphoreWin32HandleKHR{}; +#endif +#if (defined(VK_KHR_external_semaphore_fd)) + PFN_vkGetSemaphoreFdKHR fp_vkGetSemaphoreFdKHR = nullptr; +#else + void * fp_vkGetSemaphoreFdKHR{}; +#endif +#if (defined(VK_KHR_external_semaphore_fd)) + PFN_vkImportSemaphoreFdKHR fp_vkImportSemaphoreFdKHR = nullptr; +#else + void * fp_vkImportSemaphoreFdKHR{}; +#endif +#if (defined(VK_FUCHSIA_external_semaphore)) + PFN_vkGetSemaphoreZirconHandleFUCHSIA fp_vkGetSemaphoreZirconHandleFUCHSIA = nullptr; +#else + void * fp_vkGetSemaphoreZirconHandleFUCHSIA{}; +#endif +#if (defined(VK_FUCHSIA_external_semaphore)) + PFN_vkImportSemaphoreZirconHandleFUCHSIA fp_vkImportSemaphoreZirconHandleFUCHSIA = nullptr; +#else + void * fp_vkImportSemaphoreZirconHandleFUCHSIA{}; +#endif +#if (defined(VK_KHR_external_fence_win32)) + PFN_vkGetFenceWin32HandleKHR fp_vkGetFenceWin32HandleKHR = nullptr; +#else + void * fp_vkGetFenceWin32HandleKHR{}; +#endif +#if (defined(VK_KHR_external_fence_win32)) + PFN_vkImportFenceWin32HandleKHR fp_vkImportFenceWin32HandleKHR = nullptr; +#else + void * fp_vkImportFenceWin32HandleKHR{}; +#endif +#if (defined(VK_KHR_external_fence_fd)) + PFN_vkGetFenceFdKHR fp_vkGetFenceFdKHR = nullptr; +#else + void * fp_vkGetFenceFdKHR{}; +#endif +#if (defined(VK_KHR_external_fence_fd)) + PFN_vkImportFenceFdKHR fp_vkImportFenceFdKHR = nullptr; +#else + void * fp_vkImportFenceFdKHR{}; +#endif +#if (defined(VK_NV_external_sci_sync)) || (defined(VK_NV_external_sci_sync2)) + PFN_vkGetFenceSciSyncFenceNV fp_vkGetFenceSciSyncFenceNV = nullptr; +#else + void * fp_vkGetFenceSciSyncFenceNV{}; +#endif +#if (defined(VK_NV_external_sci_sync)) || (defined(VK_NV_external_sci_sync2)) + PFN_vkGetFenceSciSyncObjNV fp_vkGetFenceSciSyncObjNV = nullptr; +#else + void * fp_vkGetFenceSciSyncObjNV{}; +#endif +#if (defined(VK_NV_external_sci_sync)) || (defined(VK_NV_external_sci_sync2)) + PFN_vkImportFenceSciSyncFenceNV fp_vkImportFenceSciSyncFenceNV = nullptr; +#else + void * fp_vkImportFenceSciSyncFenceNV{}; +#endif +#if (defined(VK_NV_external_sci_sync)) || (defined(VK_NV_external_sci_sync2)) + PFN_vkImportFenceSciSyncObjNV fp_vkImportFenceSciSyncObjNV = nullptr; +#else + void * fp_vkImportFenceSciSyncObjNV{}; +#endif +#if (defined(VK_NV_external_sci_sync)) + PFN_vkGetSemaphoreSciSyncObjNV fp_vkGetSemaphoreSciSyncObjNV = nullptr; +#else + void * fp_vkGetSemaphoreSciSyncObjNV{}; +#endif +#if (defined(VK_NV_external_sci_sync)) + PFN_vkImportSemaphoreSciSyncObjNV fp_vkImportSemaphoreSciSyncObjNV = nullptr; +#else + void * fp_vkImportSemaphoreSciSyncObjNV{}; +#endif +#if (defined(VK_NV_external_sci_sync2)) + PFN_vkCreateSemaphoreSciSyncPoolNV fp_vkCreateSemaphoreSciSyncPoolNV = nullptr; +#else + void * fp_vkCreateSemaphoreSciSyncPoolNV{}; +#endif +#if (defined(VK_NV_external_sci_sync2)) + PFN_vkDestroySemaphoreSciSyncPoolNV fp_vkDestroySemaphoreSciSyncPoolNV = nullptr; +#else + void * fp_vkDestroySemaphoreSciSyncPoolNV{}; +#endif +#if (defined(VK_EXT_display_control)) + PFN_vkDisplayPowerControlEXT fp_vkDisplayPowerControlEXT = nullptr; +#else + void * fp_vkDisplayPowerControlEXT{}; +#endif +#if (defined(VK_EXT_display_control)) + PFN_vkRegisterDeviceEventEXT fp_vkRegisterDeviceEventEXT = nullptr; +#else + void * fp_vkRegisterDeviceEventEXT{}; +#endif +#if (defined(VK_EXT_display_control)) + PFN_vkRegisterDisplayEventEXT fp_vkRegisterDisplayEventEXT = nullptr; +#else + void * fp_vkRegisterDisplayEventEXT{}; +#endif +#if (defined(VK_EXT_display_control)) + PFN_vkGetSwapchainCounterEXT fp_vkGetSwapchainCounterEXT = nullptr; +#else + void * fp_vkGetSwapchainCounterEXT{}; +#endif +#if (defined(VK_VERSION_1_1)) + PFN_vkGetDeviceGroupPeerMemoryFeatures fp_vkGetDeviceGroupPeerMemoryFeatures = nullptr; +#else + void * fp_vkGetDeviceGroupPeerMemoryFeatures{}; +#endif +#if (defined(VK_VERSION_1_1)) + PFN_vkBindBufferMemory2 fp_vkBindBufferMemory2 = nullptr; +#else + void * fp_vkBindBufferMemory2{}; +#endif +#if (defined(VK_VERSION_1_1)) + PFN_vkBindImageMemory2 fp_vkBindImageMemory2 = nullptr; +#else + void * fp_vkBindImageMemory2{}; +#endif +#if (defined(VK_VERSION_1_1)) + PFN_vkCmdSetDeviceMask fp_vkCmdSetDeviceMask = nullptr; +#else + void * fp_vkCmdSetDeviceMask{}; +#endif +#if (defined(VK_KHR_swapchain)) || (defined(VK_KHR_device_group)) + PFN_vkGetDeviceGroupPresentCapabilitiesKHR fp_vkGetDeviceGroupPresentCapabilitiesKHR = nullptr; +#else + void * fp_vkGetDeviceGroupPresentCapabilitiesKHR{}; +#endif +#if (defined(VK_KHR_swapchain)) || (defined(VK_KHR_device_group)) + PFN_vkGetDeviceGroupSurfacePresentModesKHR fp_vkGetDeviceGroupSurfacePresentModesKHR = nullptr; +#else + void * fp_vkGetDeviceGroupSurfacePresentModesKHR{}; +#endif +#if (defined(VK_KHR_swapchain)) || (defined(VK_KHR_device_group)) + PFN_vkAcquireNextImage2KHR fp_vkAcquireNextImage2KHR = nullptr; +#else + void * fp_vkAcquireNextImage2KHR{}; +#endif +#if (defined(VK_VERSION_1_1)) + PFN_vkCmdDispatchBase fp_vkCmdDispatchBase = nullptr; +#else + void * fp_vkCmdDispatchBase{}; +#endif +#if (defined(VK_VERSION_1_1)) + PFN_vkCreateDescriptorUpdateTemplate fp_vkCreateDescriptorUpdateTemplate = nullptr; +#else + void * fp_vkCreateDescriptorUpdateTemplate{}; +#endif +#if (defined(VK_VERSION_1_1)) + PFN_vkDestroyDescriptorUpdateTemplate fp_vkDestroyDescriptorUpdateTemplate = nullptr; +#else + void * fp_vkDestroyDescriptorUpdateTemplate{}; +#endif +#if (defined(VK_VERSION_1_1)) + PFN_vkUpdateDescriptorSetWithTemplate fp_vkUpdateDescriptorSetWithTemplate = nullptr; +#else + void * fp_vkUpdateDescriptorSetWithTemplate{}; +#endif +#if (defined(VK_KHR_push_descriptor)) || (defined(VK_KHR_descriptor_update_template)) + PFN_vkCmdPushDescriptorSetWithTemplateKHR fp_vkCmdPushDescriptorSetWithTemplateKHR = nullptr; +#else + void * fp_vkCmdPushDescriptorSetWithTemplateKHR{}; +#endif +#if (defined(VK_EXT_hdr_metadata)) + PFN_vkSetHdrMetadataEXT fp_vkSetHdrMetadataEXT = nullptr; +#else + void * fp_vkSetHdrMetadataEXT{}; +#endif +#if (defined(VK_KHR_shared_presentable_image)) + PFN_vkGetSwapchainStatusKHR fp_vkGetSwapchainStatusKHR = nullptr; +#else + void * fp_vkGetSwapchainStatusKHR{}; +#endif +#if (defined(VK_GOOGLE_display_timing)) + PFN_vkGetRefreshCycleDurationGOOGLE fp_vkGetRefreshCycleDurationGOOGLE = nullptr; +#else + void * fp_vkGetRefreshCycleDurationGOOGLE{}; +#endif +#if (defined(VK_GOOGLE_display_timing)) + PFN_vkGetPastPresentationTimingGOOGLE fp_vkGetPastPresentationTimingGOOGLE = nullptr; +#else + void * fp_vkGetPastPresentationTimingGOOGLE{}; +#endif +#if (defined(VK_NV_clip_space_w_scaling)) + PFN_vkCmdSetViewportWScalingNV fp_vkCmdSetViewportWScalingNV = nullptr; +#else + void * fp_vkCmdSetViewportWScalingNV{}; +#endif +#if (defined(VK_EXT_discard_rectangles)) + PFN_vkCmdSetDiscardRectangleEXT fp_vkCmdSetDiscardRectangleEXT = nullptr; +#else + void * fp_vkCmdSetDiscardRectangleEXT{}; +#endif +#if ((defined(VK_EXT_discard_rectangles))) && VK_HEADER_VERSION >= 241 + PFN_vkCmdSetDiscardRectangleEnableEXT fp_vkCmdSetDiscardRectangleEnableEXT = nullptr; +#else + void * fp_vkCmdSetDiscardRectangleEnableEXT{}; +#endif +#if ((defined(VK_EXT_discard_rectangles))) && VK_HEADER_VERSION >= 241 + PFN_vkCmdSetDiscardRectangleModeEXT fp_vkCmdSetDiscardRectangleModeEXT = nullptr; +#else + void * fp_vkCmdSetDiscardRectangleModeEXT{}; +#endif +#if (defined(VK_EXT_sample_locations)) + PFN_vkCmdSetSampleLocationsEXT fp_vkCmdSetSampleLocationsEXT = nullptr; +#else + void * fp_vkCmdSetSampleLocationsEXT{}; +#endif +#if (defined(VK_VERSION_1_1)) + PFN_vkGetBufferMemoryRequirements2 fp_vkGetBufferMemoryRequirements2 = nullptr; +#else + void * fp_vkGetBufferMemoryRequirements2{}; +#endif +#if (defined(VK_VERSION_1_1)) + PFN_vkGetImageMemoryRequirements2 fp_vkGetImageMemoryRequirements2 = nullptr; +#else + void * fp_vkGetImageMemoryRequirements2{}; +#endif +#if (defined(VK_VERSION_1_1)) + PFN_vkGetImageSparseMemoryRequirements2 fp_vkGetImageSparseMemoryRequirements2 = nullptr; +#else + void * fp_vkGetImageSparseMemoryRequirements2{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkGetDeviceBufferMemoryRequirements fp_vkGetDeviceBufferMemoryRequirements = nullptr; +#else + void * fp_vkGetDeviceBufferMemoryRequirements{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkGetDeviceImageMemoryRequirements fp_vkGetDeviceImageMemoryRequirements = nullptr; +#else + void * fp_vkGetDeviceImageMemoryRequirements{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkGetDeviceImageSparseMemoryRequirements fp_vkGetDeviceImageSparseMemoryRequirements = nullptr; +#else + void * fp_vkGetDeviceImageSparseMemoryRequirements{}; +#endif +#if (defined(VK_VERSION_1_1)) + PFN_vkCreateSamplerYcbcrConversion fp_vkCreateSamplerYcbcrConversion = nullptr; +#else + void * fp_vkCreateSamplerYcbcrConversion{}; +#endif +#if (defined(VK_VERSION_1_1)) + PFN_vkDestroySamplerYcbcrConversion fp_vkDestroySamplerYcbcrConversion = nullptr; +#else + void * fp_vkDestroySamplerYcbcrConversion{}; +#endif +#if (defined(VK_VERSION_1_1)) + PFN_vkGetDeviceQueue2 fp_vkGetDeviceQueue2 = nullptr; +#else + void * fp_vkGetDeviceQueue2{}; +#endif +#if (defined(VK_EXT_validation_cache)) + PFN_vkCreateValidationCacheEXT fp_vkCreateValidationCacheEXT = nullptr; +#else + void * fp_vkCreateValidationCacheEXT{}; +#endif +#if (defined(VK_EXT_validation_cache)) + PFN_vkDestroyValidationCacheEXT fp_vkDestroyValidationCacheEXT = nullptr; +#else + void * fp_vkDestroyValidationCacheEXT{}; +#endif +#if (defined(VK_EXT_validation_cache)) + PFN_vkGetValidationCacheDataEXT fp_vkGetValidationCacheDataEXT = nullptr; +#else + void * fp_vkGetValidationCacheDataEXT{}; +#endif +#if (defined(VK_EXT_validation_cache)) + PFN_vkMergeValidationCachesEXT fp_vkMergeValidationCachesEXT = nullptr; +#else + void * fp_vkMergeValidationCachesEXT{}; +#endif +#if (defined(VK_VERSION_1_1)) + PFN_vkGetDescriptorSetLayoutSupport fp_vkGetDescriptorSetLayoutSupport = nullptr; +#else + void * fp_vkGetDescriptorSetLayoutSupport{}; +#endif +#if (defined(VK_ANDROID_native_buffer)) + PFN_vkGetSwapchainGrallocUsageANDROID fp_vkGetSwapchainGrallocUsageANDROID = nullptr; +#else + void * fp_vkGetSwapchainGrallocUsageANDROID{}; +#endif +#if (defined(VK_ANDROID_native_buffer)) + PFN_vkGetSwapchainGrallocUsage2ANDROID fp_vkGetSwapchainGrallocUsage2ANDROID = nullptr; +#else + void * fp_vkGetSwapchainGrallocUsage2ANDROID{}; +#endif +#if (defined(VK_ANDROID_native_buffer)) + PFN_vkAcquireImageANDROID fp_vkAcquireImageANDROID = nullptr; +#else + void * fp_vkAcquireImageANDROID{}; +#endif +#if (defined(VK_ANDROID_native_buffer)) + PFN_vkQueueSignalReleaseImageANDROID fp_vkQueueSignalReleaseImageANDROID = nullptr; +#else + void * fp_vkQueueSignalReleaseImageANDROID{}; +#endif +#if (defined(VK_AMD_shader_info)) + PFN_vkGetShaderInfoAMD fp_vkGetShaderInfoAMD = nullptr; +#else + void * fp_vkGetShaderInfoAMD{}; +#endif +#if (defined(VK_AMD_display_native_hdr)) + PFN_vkSetLocalDimmingAMD fp_vkSetLocalDimmingAMD = nullptr; +#else + void * fp_vkSetLocalDimmingAMD{}; +#endif +#if (defined(VK_KHR_calibrated_timestamps)) + PFN_vkGetCalibratedTimestampsKHR fp_vkGetCalibratedTimestampsKHR = nullptr; +#else + void * fp_vkGetCalibratedTimestampsKHR{}; +#endif +#if (defined(VK_EXT_debug_utils)) + PFN_vkSetDebugUtilsObjectNameEXT fp_vkSetDebugUtilsObjectNameEXT = nullptr; +#else + void * fp_vkSetDebugUtilsObjectNameEXT{}; +#endif +#if (defined(VK_EXT_debug_utils)) + PFN_vkSetDebugUtilsObjectTagEXT fp_vkSetDebugUtilsObjectTagEXT = nullptr; +#else + void * fp_vkSetDebugUtilsObjectTagEXT{}; +#endif +#if (defined(VK_EXT_debug_utils)) + PFN_vkQueueBeginDebugUtilsLabelEXT fp_vkQueueBeginDebugUtilsLabelEXT = nullptr; +#else + void * fp_vkQueueBeginDebugUtilsLabelEXT{}; +#endif +#if (defined(VK_EXT_debug_utils)) + PFN_vkQueueEndDebugUtilsLabelEXT fp_vkQueueEndDebugUtilsLabelEXT = nullptr; +#else + void * fp_vkQueueEndDebugUtilsLabelEXT{}; +#endif +#if (defined(VK_EXT_debug_utils)) + PFN_vkQueueInsertDebugUtilsLabelEXT fp_vkQueueInsertDebugUtilsLabelEXT = nullptr; +#else + void * fp_vkQueueInsertDebugUtilsLabelEXT{}; +#endif +#if (defined(VK_EXT_debug_utils)) + PFN_vkCmdBeginDebugUtilsLabelEXT fp_vkCmdBeginDebugUtilsLabelEXT = nullptr; +#else + void * fp_vkCmdBeginDebugUtilsLabelEXT{}; +#endif +#if (defined(VK_EXT_debug_utils)) + PFN_vkCmdEndDebugUtilsLabelEXT fp_vkCmdEndDebugUtilsLabelEXT = nullptr; +#else + void * fp_vkCmdEndDebugUtilsLabelEXT{}; +#endif +#if (defined(VK_EXT_debug_utils)) + PFN_vkCmdInsertDebugUtilsLabelEXT fp_vkCmdInsertDebugUtilsLabelEXT = nullptr; +#else + void * fp_vkCmdInsertDebugUtilsLabelEXT{}; +#endif +#if (defined(VK_EXT_external_memory_host)) + PFN_vkGetMemoryHostPointerPropertiesEXT fp_vkGetMemoryHostPointerPropertiesEXT = nullptr; +#else + void * fp_vkGetMemoryHostPointerPropertiesEXT{}; +#endif +#if (defined(VK_AMD_buffer_marker)) + PFN_vkCmdWriteBufferMarkerAMD fp_vkCmdWriteBufferMarkerAMD = nullptr; +#else + void * fp_vkCmdWriteBufferMarkerAMD{}; +#endif +#if (defined(VK_VERSION_1_2)) + PFN_vkCreateRenderPass2 fp_vkCreateRenderPass2 = nullptr; +#else + void * fp_vkCreateRenderPass2{}; +#endif +#if (defined(VK_VERSION_1_2)) + PFN_vkCmdBeginRenderPass2 fp_vkCmdBeginRenderPass2 = nullptr; +#else + void * fp_vkCmdBeginRenderPass2{}; +#endif +#if (defined(VK_VERSION_1_2)) + PFN_vkCmdNextSubpass2 fp_vkCmdNextSubpass2 = nullptr; +#else + void * fp_vkCmdNextSubpass2{}; +#endif +#if (defined(VK_VERSION_1_2)) + PFN_vkCmdEndRenderPass2 fp_vkCmdEndRenderPass2 = nullptr; +#else + void * fp_vkCmdEndRenderPass2{}; +#endif +#if (defined(VK_VERSION_1_2)) + PFN_vkGetSemaphoreCounterValue fp_vkGetSemaphoreCounterValue = nullptr; +#else + void * fp_vkGetSemaphoreCounterValue{}; +#endif +#if (defined(VK_VERSION_1_2)) + PFN_vkWaitSemaphores fp_vkWaitSemaphores = nullptr; +#else + void * fp_vkWaitSemaphores{}; +#endif +#if (defined(VK_VERSION_1_2)) + PFN_vkSignalSemaphore fp_vkSignalSemaphore = nullptr; +#else + void * fp_vkSignalSemaphore{}; +#endif +#if (defined(VK_ANDROID_external_memory_android_hardware_buffer)) + PFN_vkGetAndroidHardwareBufferPropertiesANDROID fp_vkGetAndroidHardwareBufferPropertiesANDROID = nullptr; +#else + void * fp_vkGetAndroidHardwareBufferPropertiesANDROID{}; +#endif +#if (defined(VK_ANDROID_external_memory_android_hardware_buffer)) + PFN_vkGetMemoryAndroidHardwareBufferANDROID fp_vkGetMemoryAndroidHardwareBufferANDROID = nullptr; +#else + void * fp_vkGetMemoryAndroidHardwareBufferANDROID{}; +#endif +#if (defined(VK_VERSION_1_2)) + PFN_vkCmdDrawIndirectCount fp_vkCmdDrawIndirectCount = nullptr; +#else + void * fp_vkCmdDrawIndirectCount{}; +#endif +#if (defined(VK_VERSION_1_2)) + PFN_vkCmdDrawIndexedIndirectCount fp_vkCmdDrawIndexedIndirectCount = nullptr; +#else + void * fp_vkCmdDrawIndexedIndirectCount{}; +#endif +#if (defined(VK_NV_device_diagnostic_checkpoints)) + PFN_vkCmdSetCheckpointNV fp_vkCmdSetCheckpointNV = nullptr; +#else + void * fp_vkCmdSetCheckpointNV{}; +#endif +#if (defined(VK_NV_device_diagnostic_checkpoints)) + PFN_vkGetQueueCheckpointDataNV fp_vkGetQueueCheckpointDataNV = nullptr; +#else + void * fp_vkGetQueueCheckpointDataNV{}; +#endif +#if (defined(VK_EXT_transform_feedback)) + PFN_vkCmdBindTransformFeedbackBuffersEXT fp_vkCmdBindTransformFeedbackBuffersEXT = nullptr; +#else + void * fp_vkCmdBindTransformFeedbackBuffersEXT{}; +#endif +#if (defined(VK_EXT_transform_feedback)) + PFN_vkCmdBeginTransformFeedbackEXT fp_vkCmdBeginTransformFeedbackEXT = nullptr; +#else + void * fp_vkCmdBeginTransformFeedbackEXT{}; +#endif +#if (defined(VK_EXT_transform_feedback)) + PFN_vkCmdEndTransformFeedbackEXT fp_vkCmdEndTransformFeedbackEXT = nullptr; +#else + void * fp_vkCmdEndTransformFeedbackEXT{}; +#endif +#if (defined(VK_EXT_transform_feedback)) + PFN_vkCmdBeginQueryIndexedEXT fp_vkCmdBeginQueryIndexedEXT = nullptr; +#else + void * fp_vkCmdBeginQueryIndexedEXT{}; +#endif +#if (defined(VK_EXT_transform_feedback)) + PFN_vkCmdEndQueryIndexedEXT fp_vkCmdEndQueryIndexedEXT = nullptr; +#else + void * fp_vkCmdEndQueryIndexedEXT{}; +#endif +#if (defined(VK_EXT_transform_feedback)) + PFN_vkCmdDrawIndirectByteCountEXT fp_vkCmdDrawIndirectByteCountEXT = nullptr; +#else + void * fp_vkCmdDrawIndirectByteCountEXT{}; +#endif +#if (defined(VK_NV_scissor_exclusive)) + PFN_vkCmdSetExclusiveScissorNV fp_vkCmdSetExclusiveScissorNV = nullptr; +#else + void * fp_vkCmdSetExclusiveScissorNV{}; +#endif +#if ((defined(VK_NV_scissor_exclusive))) && VK_HEADER_VERSION >= 241 + PFN_vkCmdSetExclusiveScissorEnableNV fp_vkCmdSetExclusiveScissorEnableNV = nullptr; +#else + void * fp_vkCmdSetExclusiveScissorEnableNV{}; +#endif +#if (defined(VK_NV_shading_rate_image)) + PFN_vkCmdBindShadingRateImageNV fp_vkCmdBindShadingRateImageNV = nullptr; +#else + void * fp_vkCmdBindShadingRateImageNV{}; +#endif +#if (defined(VK_NV_shading_rate_image)) + PFN_vkCmdSetViewportShadingRatePaletteNV fp_vkCmdSetViewportShadingRatePaletteNV = nullptr; +#else + void * fp_vkCmdSetViewportShadingRatePaletteNV{}; +#endif +#if (defined(VK_NV_shading_rate_image)) + PFN_vkCmdSetCoarseSampleOrderNV fp_vkCmdSetCoarseSampleOrderNV = nullptr; +#else + void * fp_vkCmdSetCoarseSampleOrderNV{}; +#endif +#if (defined(VK_NV_mesh_shader)) + PFN_vkCmdDrawMeshTasksNV fp_vkCmdDrawMeshTasksNV = nullptr; +#else + void * fp_vkCmdDrawMeshTasksNV{}; +#endif +#if (defined(VK_NV_mesh_shader)) + PFN_vkCmdDrawMeshTasksIndirectNV fp_vkCmdDrawMeshTasksIndirectNV = nullptr; +#else + void * fp_vkCmdDrawMeshTasksIndirectNV{}; +#endif +#if (defined(VK_NV_mesh_shader)) + PFN_vkCmdDrawMeshTasksIndirectCountNV fp_vkCmdDrawMeshTasksIndirectCountNV = nullptr; +#else + void * fp_vkCmdDrawMeshTasksIndirectCountNV{}; +#endif +#if (defined(VK_EXT_mesh_shader)) + PFN_vkCmdDrawMeshTasksEXT fp_vkCmdDrawMeshTasksEXT = nullptr; +#else + void * fp_vkCmdDrawMeshTasksEXT{}; +#endif +#if (defined(VK_EXT_mesh_shader)) + PFN_vkCmdDrawMeshTasksIndirectEXT fp_vkCmdDrawMeshTasksIndirectEXT = nullptr; +#else + void * fp_vkCmdDrawMeshTasksIndirectEXT{}; +#endif +#if (defined(VK_EXT_mesh_shader)) + PFN_vkCmdDrawMeshTasksIndirectCountEXT fp_vkCmdDrawMeshTasksIndirectCountEXT = nullptr; +#else + void * fp_vkCmdDrawMeshTasksIndirectCountEXT{}; +#endif +#if (defined(VK_NV_ray_tracing)) + PFN_vkCompileDeferredNV fp_vkCompileDeferredNV = nullptr; +#else + void * fp_vkCompileDeferredNV{}; +#endif +#if (defined(VK_NV_ray_tracing)) + PFN_vkCreateAccelerationStructureNV fp_vkCreateAccelerationStructureNV = nullptr; +#else + void * fp_vkCreateAccelerationStructureNV{}; +#endif +#if (defined(VK_HUAWEI_invocation_mask)) + PFN_vkCmdBindInvocationMaskHUAWEI fp_vkCmdBindInvocationMaskHUAWEI = nullptr; +#else + void * fp_vkCmdBindInvocationMaskHUAWEI{}; +#endif +#if (defined(VK_KHR_acceleration_structure)) + PFN_vkDestroyAccelerationStructureKHR fp_vkDestroyAccelerationStructureKHR = nullptr; +#else + void * fp_vkDestroyAccelerationStructureKHR{}; +#endif +#if (defined(VK_NV_ray_tracing)) + PFN_vkDestroyAccelerationStructureNV fp_vkDestroyAccelerationStructureNV = nullptr; +#else + void * fp_vkDestroyAccelerationStructureNV{}; +#endif +#if (defined(VK_NV_ray_tracing)) + PFN_vkGetAccelerationStructureMemoryRequirementsNV fp_vkGetAccelerationStructureMemoryRequirementsNV = nullptr; +#else + void * fp_vkGetAccelerationStructureMemoryRequirementsNV{}; +#endif +#if (defined(VK_NV_ray_tracing)) + PFN_vkBindAccelerationStructureMemoryNV fp_vkBindAccelerationStructureMemoryNV = nullptr; +#else + void * fp_vkBindAccelerationStructureMemoryNV{}; +#endif +#if (defined(VK_NV_ray_tracing)) + PFN_vkCmdCopyAccelerationStructureNV fp_vkCmdCopyAccelerationStructureNV = nullptr; +#else + void * fp_vkCmdCopyAccelerationStructureNV{}; +#endif +#if (defined(VK_KHR_acceleration_structure)) + PFN_vkCmdCopyAccelerationStructureKHR fp_vkCmdCopyAccelerationStructureKHR = nullptr; +#else + void * fp_vkCmdCopyAccelerationStructureKHR{}; +#endif +#if (defined(VK_KHR_acceleration_structure)) + PFN_vkCopyAccelerationStructureKHR fp_vkCopyAccelerationStructureKHR = nullptr; +#else + void * fp_vkCopyAccelerationStructureKHR{}; +#endif +#if (defined(VK_KHR_acceleration_structure)) + PFN_vkCmdCopyAccelerationStructureToMemoryKHR fp_vkCmdCopyAccelerationStructureToMemoryKHR = nullptr; +#else + void * fp_vkCmdCopyAccelerationStructureToMemoryKHR{}; +#endif +#if (defined(VK_KHR_acceleration_structure)) + PFN_vkCopyAccelerationStructureToMemoryKHR fp_vkCopyAccelerationStructureToMemoryKHR = nullptr; +#else + void * fp_vkCopyAccelerationStructureToMemoryKHR{}; +#endif +#if (defined(VK_KHR_acceleration_structure)) + PFN_vkCmdCopyMemoryToAccelerationStructureKHR fp_vkCmdCopyMemoryToAccelerationStructureKHR = nullptr; +#else + void * fp_vkCmdCopyMemoryToAccelerationStructureKHR{}; +#endif +#if (defined(VK_KHR_acceleration_structure)) + PFN_vkCopyMemoryToAccelerationStructureKHR fp_vkCopyMemoryToAccelerationStructureKHR = nullptr; +#else + void * fp_vkCopyMemoryToAccelerationStructureKHR{}; +#endif +#if (defined(VK_KHR_acceleration_structure)) + PFN_vkCmdWriteAccelerationStructuresPropertiesKHR fp_vkCmdWriteAccelerationStructuresPropertiesKHR = nullptr; +#else + void * fp_vkCmdWriteAccelerationStructuresPropertiesKHR{}; +#endif +#if (defined(VK_NV_ray_tracing)) + PFN_vkCmdWriteAccelerationStructuresPropertiesNV fp_vkCmdWriteAccelerationStructuresPropertiesNV = nullptr; +#else + void * fp_vkCmdWriteAccelerationStructuresPropertiesNV{}; +#endif +#if (defined(VK_NV_ray_tracing)) + PFN_vkCmdBuildAccelerationStructureNV fp_vkCmdBuildAccelerationStructureNV = nullptr; +#else + void * fp_vkCmdBuildAccelerationStructureNV{}; +#endif +#if (defined(VK_KHR_acceleration_structure)) + PFN_vkWriteAccelerationStructuresPropertiesKHR fp_vkWriteAccelerationStructuresPropertiesKHR = nullptr; +#else + void * fp_vkWriteAccelerationStructuresPropertiesKHR{}; +#endif +#if (defined(VK_KHR_ray_tracing_pipeline)) + PFN_vkCmdTraceRaysKHR fp_vkCmdTraceRaysKHR = nullptr; +#else + void * fp_vkCmdTraceRaysKHR{}; +#endif +#if (defined(VK_NV_ray_tracing)) + PFN_vkCmdTraceRaysNV fp_vkCmdTraceRaysNV = nullptr; +#else + void * fp_vkCmdTraceRaysNV{}; +#endif +#if (defined(VK_KHR_ray_tracing_pipeline)) + PFN_vkGetRayTracingShaderGroupHandlesKHR fp_vkGetRayTracingShaderGroupHandlesKHR = nullptr; +#else + void * fp_vkGetRayTracingShaderGroupHandlesKHR{}; +#endif +#if (defined(VK_KHR_ray_tracing_pipeline)) + PFN_vkGetRayTracingCaptureReplayShaderGroupHandlesKHR fp_vkGetRayTracingCaptureReplayShaderGroupHandlesKHR = nullptr; +#else + void * fp_vkGetRayTracingCaptureReplayShaderGroupHandlesKHR{}; +#endif +#if (defined(VK_NV_ray_tracing)) + PFN_vkGetAccelerationStructureHandleNV fp_vkGetAccelerationStructureHandleNV = nullptr; +#else + void * fp_vkGetAccelerationStructureHandleNV{}; +#endif +#if (defined(VK_NV_ray_tracing)) + PFN_vkCreateRayTracingPipelinesNV fp_vkCreateRayTracingPipelinesNV = nullptr; +#else + void * fp_vkCreateRayTracingPipelinesNV{}; +#endif +#if (defined(VK_KHR_ray_tracing_pipeline)) + PFN_vkCreateRayTracingPipelinesKHR fp_vkCreateRayTracingPipelinesKHR = nullptr; +#else + void * fp_vkCreateRayTracingPipelinesKHR{}; +#endif +#if (defined(VK_KHR_ray_tracing_pipeline)) + PFN_vkCmdTraceRaysIndirectKHR fp_vkCmdTraceRaysIndirectKHR = nullptr; +#else + void * fp_vkCmdTraceRaysIndirectKHR{}; +#endif +#if (defined(VK_KHR_ray_tracing_maintenance1)) + PFN_vkCmdTraceRaysIndirect2KHR fp_vkCmdTraceRaysIndirect2KHR = nullptr; +#else + void * fp_vkCmdTraceRaysIndirect2KHR{}; +#endif +#if (defined(VK_KHR_acceleration_structure)) + PFN_vkGetDeviceAccelerationStructureCompatibilityKHR fp_vkGetDeviceAccelerationStructureCompatibilityKHR = nullptr; +#else + void * fp_vkGetDeviceAccelerationStructureCompatibilityKHR{}; +#endif +#if (defined(VK_KHR_ray_tracing_pipeline)) + PFN_vkGetRayTracingShaderGroupStackSizeKHR fp_vkGetRayTracingShaderGroupStackSizeKHR = nullptr; +#else + void * fp_vkGetRayTracingShaderGroupStackSizeKHR{}; +#endif +#if (defined(VK_KHR_ray_tracing_pipeline)) + PFN_vkCmdSetRayTracingPipelineStackSizeKHR fp_vkCmdSetRayTracingPipelineStackSizeKHR = nullptr; +#else + void * fp_vkCmdSetRayTracingPipelineStackSizeKHR{}; +#endif +#if (defined(VK_EXT_full_screen_exclusive)) + PFN_vkGetDeviceGroupSurfacePresentModes2EXT fp_vkGetDeviceGroupSurfacePresentModes2EXT = nullptr; +#else + void * fp_vkGetDeviceGroupSurfacePresentModes2EXT{}; +#endif +#if (defined(VK_EXT_full_screen_exclusive)) + PFN_vkAcquireFullScreenExclusiveModeEXT fp_vkAcquireFullScreenExclusiveModeEXT = nullptr; +#else + void * fp_vkAcquireFullScreenExclusiveModeEXT{}; +#endif +#if (defined(VK_EXT_full_screen_exclusive)) + PFN_vkReleaseFullScreenExclusiveModeEXT fp_vkReleaseFullScreenExclusiveModeEXT = nullptr; +#else + void * fp_vkReleaseFullScreenExclusiveModeEXT{}; +#endif +#if (defined(VK_KHR_performance_query)) + PFN_vkAcquireProfilingLockKHR fp_vkAcquireProfilingLockKHR = nullptr; +#else + void * fp_vkAcquireProfilingLockKHR{}; +#endif +#if (defined(VK_KHR_performance_query)) + PFN_vkReleaseProfilingLockKHR fp_vkReleaseProfilingLockKHR = nullptr; +#else + void * fp_vkReleaseProfilingLockKHR{}; +#endif +#if (defined(VK_EXT_image_drm_format_modifier)) + PFN_vkGetImageDrmFormatModifierPropertiesEXT fp_vkGetImageDrmFormatModifierPropertiesEXT = nullptr; +#else + void * fp_vkGetImageDrmFormatModifierPropertiesEXT{}; +#endif +#if (defined(VK_VERSION_1_2)) + PFN_vkGetBufferOpaqueCaptureAddress fp_vkGetBufferOpaqueCaptureAddress = nullptr; +#else + void * fp_vkGetBufferOpaqueCaptureAddress{}; +#endif +#if (defined(VK_VERSION_1_2)) + PFN_vkGetBufferDeviceAddress fp_vkGetBufferDeviceAddress = nullptr; +#else + void * fp_vkGetBufferDeviceAddress{}; +#endif +#if (defined(VK_INTEL_performance_query)) + PFN_vkInitializePerformanceApiINTEL fp_vkInitializePerformanceApiINTEL = nullptr; +#else + void * fp_vkInitializePerformanceApiINTEL{}; +#endif +#if (defined(VK_INTEL_performance_query)) + PFN_vkUninitializePerformanceApiINTEL fp_vkUninitializePerformanceApiINTEL = nullptr; +#else + void * fp_vkUninitializePerformanceApiINTEL{}; +#endif +#if (defined(VK_INTEL_performance_query)) + PFN_vkCmdSetPerformanceMarkerINTEL fp_vkCmdSetPerformanceMarkerINTEL = nullptr; +#else + void * fp_vkCmdSetPerformanceMarkerINTEL{}; +#endif +#if (defined(VK_INTEL_performance_query)) + PFN_vkCmdSetPerformanceStreamMarkerINTEL fp_vkCmdSetPerformanceStreamMarkerINTEL = nullptr; +#else + void * fp_vkCmdSetPerformanceStreamMarkerINTEL{}; +#endif +#if (defined(VK_INTEL_performance_query)) + PFN_vkCmdSetPerformanceOverrideINTEL fp_vkCmdSetPerformanceOverrideINTEL = nullptr; +#else + void * fp_vkCmdSetPerformanceOverrideINTEL{}; +#endif +#if (defined(VK_INTEL_performance_query)) + PFN_vkAcquirePerformanceConfigurationINTEL fp_vkAcquirePerformanceConfigurationINTEL = nullptr; +#else + void * fp_vkAcquirePerformanceConfigurationINTEL{}; +#endif +#if (defined(VK_INTEL_performance_query)) + PFN_vkReleasePerformanceConfigurationINTEL fp_vkReleasePerformanceConfigurationINTEL = nullptr; +#else + void * fp_vkReleasePerformanceConfigurationINTEL{}; +#endif +#if (defined(VK_INTEL_performance_query)) + PFN_vkQueueSetPerformanceConfigurationINTEL fp_vkQueueSetPerformanceConfigurationINTEL = nullptr; +#else + void * fp_vkQueueSetPerformanceConfigurationINTEL{}; +#endif +#if (defined(VK_INTEL_performance_query)) + PFN_vkGetPerformanceParameterINTEL fp_vkGetPerformanceParameterINTEL = nullptr; +#else + void * fp_vkGetPerformanceParameterINTEL{}; +#endif +#if (defined(VK_VERSION_1_2)) + PFN_vkGetDeviceMemoryOpaqueCaptureAddress fp_vkGetDeviceMemoryOpaqueCaptureAddress = nullptr; +#else + void * fp_vkGetDeviceMemoryOpaqueCaptureAddress{}; +#endif +#if (defined(VK_KHR_pipeline_executable_properties)) + PFN_vkGetPipelineExecutablePropertiesKHR fp_vkGetPipelineExecutablePropertiesKHR = nullptr; +#else + void * fp_vkGetPipelineExecutablePropertiesKHR{}; +#endif +#if (defined(VK_KHR_pipeline_executable_properties)) + PFN_vkGetPipelineExecutableStatisticsKHR fp_vkGetPipelineExecutableStatisticsKHR = nullptr; +#else + void * fp_vkGetPipelineExecutableStatisticsKHR{}; +#endif +#if (defined(VK_KHR_pipeline_executable_properties)) + PFN_vkGetPipelineExecutableInternalRepresentationsKHR fp_vkGetPipelineExecutableInternalRepresentationsKHR = nullptr; +#else + void * fp_vkGetPipelineExecutableInternalRepresentationsKHR{}; +#endif +#if (defined(VK_KHR_line_rasterization)) + PFN_vkCmdSetLineStippleKHR fp_vkCmdSetLineStippleKHR = nullptr; +#else + void * fp_vkCmdSetLineStippleKHR{}; +#endif +#if (defined(VKSC_VERSION_1_0)) + PFN_vkGetFaultData fp_vkGetFaultData = nullptr; +#else + void * fp_vkGetFaultData{}; +#endif +#if (defined(VK_KHR_acceleration_structure)) + PFN_vkCreateAccelerationStructureKHR fp_vkCreateAccelerationStructureKHR = nullptr; +#else + void * fp_vkCreateAccelerationStructureKHR{}; +#endif +#if (defined(VK_KHR_acceleration_structure)) + PFN_vkCmdBuildAccelerationStructuresKHR fp_vkCmdBuildAccelerationStructuresKHR = nullptr; +#else + void * fp_vkCmdBuildAccelerationStructuresKHR{}; +#endif +#if (defined(VK_KHR_acceleration_structure)) + PFN_vkCmdBuildAccelerationStructuresIndirectKHR fp_vkCmdBuildAccelerationStructuresIndirectKHR = nullptr; +#else + void * fp_vkCmdBuildAccelerationStructuresIndirectKHR{}; +#endif +#if (defined(VK_KHR_acceleration_structure)) + PFN_vkBuildAccelerationStructuresKHR fp_vkBuildAccelerationStructuresKHR = nullptr; +#else + void * fp_vkBuildAccelerationStructuresKHR{}; +#endif +#if (defined(VK_KHR_acceleration_structure)) + PFN_vkGetAccelerationStructureDeviceAddressKHR fp_vkGetAccelerationStructureDeviceAddressKHR = nullptr; +#else + void * fp_vkGetAccelerationStructureDeviceAddressKHR{}; +#endif +#if (defined(VK_KHR_deferred_host_operations)) + PFN_vkCreateDeferredOperationKHR fp_vkCreateDeferredOperationKHR = nullptr; +#else + void * fp_vkCreateDeferredOperationKHR{}; +#endif +#if (defined(VK_KHR_deferred_host_operations)) + PFN_vkDestroyDeferredOperationKHR fp_vkDestroyDeferredOperationKHR = nullptr; +#else + void * fp_vkDestroyDeferredOperationKHR{}; +#endif +#if (defined(VK_KHR_deferred_host_operations)) + PFN_vkGetDeferredOperationMaxConcurrencyKHR fp_vkGetDeferredOperationMaxConcurrencyKHR = nullptr; +#else + void * fp_vkGetDeferredOperationMaxConcurrencyKHR{}; +#endif +#if (defined(VK_KHR_deferred_host_operations)) + PFN_vkGetDeferredOperationResultKHR fp_vkGetDeferredOperationResultKHR = nullptr; +#else + void * fp_vkGetDeferredOperationResultKHR{}; +#endif +#if (defined(VK_KHR_deferred_host_operations)) + PFN_vkDeferredOperationJoinKHR fp_vkDeferredOperationJoinKHR = nullptr; +#else + void * fp_vkDeferredOperationJoinKHR{}; +#endif +#if (defined(VK_NV_device_generated_commands_compute)) + PFN_vkGetPipelineIndirectMemoryRequirementsNV fp_vkGetPipelineIndirectMemoryRequirementsNV = nullptr; +#else + void * fp_vkGetPipelineIndirectMemoryRequirementsNV{}; +#endif +#if (defined(VK_NV_device_generated_commands_compute)) + PFN_vkGetPipelineIndirectDeviceAddressNV fp_vkGetPipelineIndirectDeviceAddressNV = nullptr; +#else + void * fp_vkGetPipelineIndirectDeviceAddressNV{}; +#endif +#if (defined(VK_AMD_anti_lag)) + PFN_vkAntiLagUpdateAMD fp_vkAntiLagUpdateAMD = nullptr; +#else + void * fp_vkAntiLagUpdateAMD{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdSetCullMode fp_vkCmdSetCullMode = nullptr; +#else + void * fp_vkCmdSetCullMode{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdSetFrontFace fp_vkCmdSetFrontFace = nullptr; +#else + void * fp_vkCmdSetFrontFace{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdSetPrimitiveTopology fp_vkCmdSetPrimitiveTopology = nullptr; +#else + void * fp_vkCmdSetPrimitiveTopology{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdSetViewportWithCount fp_vkCmdSetViewportWithCount = nullptr; +#else + void * fp_vkCmdSetViewportWithCount{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdSetScissorWithCount fp_vkCmdSetScissorWithCount = nullptr; +#else + void * fp_vkCmdSetScissorWithCount{}; +#endif +#if (defined(VK_KHR_maintenance5)) + PFN_vkCmdBindIndexBuffer2KHR fp_vkCmdBindIndexBuffer2KHR = nullptr; +#else + void * fp_vkCmdBindIndexBuffer2KHR{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdBindVertexBuffers2 fp_vkCmdBindVertexBuffers2 = nullptr; +#else + void * fp_vkCmdBindVertexBuffers2{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdSetDepthTestEnable fp_vkCmdSetDepthTestEnable = nullptr; +#else + void * fp_vkCmdSetDepthTestEnable{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdSetDepthWriteEnable fp_vkCmdSetDepthWriteEnable = nullptr; +#else + void * fp_vkCmdSetDepthWriteEnable{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdSetDepthCompareOp fp_vkCmdSetDepthCompareOp = nullptr; +#else + void * fp_vkCmdSetDepthCompareOp{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdSetDepthBoundsTestEnable fp_vkCmdSetDepthBoundsTestEnable = nullptr; +#else + void * fp_vkCmdSetDepthBoundsTestEnable{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdSetStencilTestEnable fp_vkCmdSetStencilTestEnable = nullptr; +#else + void * fp_vkCmdSetStencilTestEnable{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdSetStencilOp fp_vkCmdSetStencilOp = nullptr; +#else + void * fp_vkCmdSetStencilOp{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state2)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetPatchControlPointsEXT fp_vkCmdSetPatchControlPointsEXT = nullptr; +#else + void * fp_vkCmdSetPatchControlPointsEXT{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdSetRasterizerDiscardEnable fp_vkCmdSetRasterizerDiscardEnable = nullptr; +#else + void * fp_vkCmdSetRasterizerDiscardEnable{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdSetDepthBiasEnable fp_vkCmdSetDepthBiasEnable = nullptr; +#else + void * fp_vkCmdSetDepthBiasEnable{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state2)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetLogicOpEXT fp_vkCmdSetLogicOpEXT = nullptr; +#else + void * fp_vkCmdSetLogicOpEXT{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdSetPrimitiveRestartEnable fp_vkCmdSetPrimitiveRestartEnable = nullptr; +#else + void * fp_vkCmdSetPrimitiveRestartEnable{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetTessellationDomainOriginEXT fp_vkCmdSetTessellationDomainOriginEXT = nullptr; +#else + void * fp_vkCmdSetTessellationDomainOriginEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetDepthClampEnableEXT fp_vkCmdSetDepthClampEnableEXT = nullptr; +#else + void * fp_vkCmdSetDepthClampEnableEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetPolygonModeEXT fp_vkCmdSetPolygonModeEXT = nullptr; +#else + void * fp_vkCmdSetPolygonModeEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetRasterizationSamplesEXT fp_vkCmdSetRasterizationSamplesEXT = nullptr; +#else + void * fp_vkCmdSetRasterizationSamplesEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetSampleMaskEXT fp_vkCmdSetSampleMaskEXT = nullptr; +#else + void * fp_vkCmdSetSampleMaskEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetAlphaToCoverageEnableEXT fp_vkCmdSetAlphaToCoverageEnableEXT = nullptr; +#else + void * fp_vkCmdSetAlphaToCoverageEnableEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetAlphaToOneEnableEXT fp_vkCmdSetAlphaToOneEnableEXT = nullptr; +#else + void * fp_vkCmdSetAlphaToOneEnableEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetLogicOpEnableEXT fp_vkCmdSetLogicOpEnableEXT = nullptr; +#else + void * fp_vkCmdSetLogicOpEnableEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetColorBlendEnableEXT fp_vkCmdSetColorBlendEnableEXT = nullptr; +#else + void * fp_vkCmdSetColorBlendEnableEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetColorBlendEquationEXT fp_vkCmdSetColorBlendEquationEXT = nullptr; +#else + void * fp_vkCmdSetColorBlendEquationEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetColorWriteMaskEXT fp_vkCmdSetColorWriteMaskEXT = nullptr; +#else + void * fp_vkCmdSetColorWriteMaskEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetRasterizationStreamEXT fp_vkCmdSetRasterizationStreamEXT = nullptr; +#else + void * fp_vkCmdSetRasterizationStreamEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetConservativeRasterizationModeEXT fp_vkCmdSetConservativeRasterizationModeEXT = nullptr; +#else + void * fp_vkCmdSetConservativeRasterizationModeEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetExtraPrimitiveOverestimationSizeEXT fp_vkCmdSetExtraPrimitiveOverestimationSizeEXT = nullptr; +#else + void * fp_vkCmdSetExtraPrimitiveOverestimationSizeEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetDepthClipEnableEXT fp_vkCmdSetDepthClipEnableEXT = nullptr; +#else + void * fp_vkCmdSetDepthClipEnableEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetSampleLocationsEnableEXT fp_vkCmdSetSampleLocationsEnableEXT = nullptr; +#else + void * fp_vkCmdSetSampleLocationsEnableEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetColorBlendAdvancedEXT fp_vkCmdSetColorBlendAdvancedEXT = nullptr; +#else + void * fp_vkCmdSetColorBlendAdvancedEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetProvokingVertexModeEXT fp_vkCmdSetProvokingVertexModeEXT = nullptr; +#else + void * fp_vkCmdSetProvokingVertexModeEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetLineRasterizationModeEXT fp_vkCmdSetLineRasterizationModeEXT = nullptr; +#else + void * fp_vkCmdSetLineRasterizationModeEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetLineStippleEnableEXT fp_vkCmdSetLineStippleEnableEXT = nullptr; +#else + void * fp_vkCmdSetLineStippleEnableEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetDepthClipNegativeOneToOneEXT fp_vkCmdSetDepthClipNegativeOneToOneEXT = nullptr; +#else + void * fp_vkCmdSetDepthClipNegativeOneToOneEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetViewportWScalingEnableNV fp_vkCmdSetViewportWScalingEnableNV = nullptr; +#else + void * fp_vkCmdSetViewportWScalingEnableNV{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetViewportSwizzleNV fp_vkCmdSetViewportSwizzleNV = nullptr; +#else + void * fp_vkCmdSetViewportSwizzleNV{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetCoverageToColorEnableNV fp_vkCmdSetCoverageToColorEnableNV = nullptr; +#else + void * fp_vkCmdSetCoverageToColorEnableNV{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetCoverageToColorLocationNV fp_vkCmdSetCoverageToColorLocationNV = nullptr; +#else + void * fp_vkCmdSetCoverageToColorLocationNV{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetCoverageModulationModeNV fp_vkCmdSetCoverageModulationModeNV = nullptr; +#else + void * fp_vkCmdSetCoverageModulationModeNV{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetCoverageModulationTableEnableNV fp_vkCmdSetCoverageModulationTableEnableNV = nullptr; +#else + void * fp_vkCmdSetCoverageModulationTableEnableNV{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetCoverageModulationTableNV fp_vkCmdSetCoverageModulationTableNV = nullptr; +#else + void * fp_vkCmdSetCoverageModulationTableNV{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetShadingRateImageEnableNV fp_vkCmdSetShadingRateImageEnableNV = nullptr; +#else + void * fp_vkCmdSetShadingRateImageEnableNV{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetCoverageReductionModeNV fp_vkCmdSetCoverageReductionModeNV = nullptr; +#else + void * fp_vkCmdSetCoverageReductionModeNV{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state3)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetRepresentativeFragmentTestEnableNV fp_vkCmdSetRepresentativeFragmentTestEnableNV = nullptr; +#else + void * fp_vkCmdSetRepresentativeFragmentTestEnableNV{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCreatePrivateDataSlot fp_vkCreatePrivateDataSlot = nullptr; +#else + void * fp_vkCreatePrivateDataSlot{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkDestroyPrivateDataSlot fp_vkDestroyPrivateDataSlot = nullptr; +#else + void * fp_vkDestroyPrivateDataSlot{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkSetPrivateData fp_vkSetPrivateData = nullptr; +#else + void * fp_vkSetPrivateData{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkGetPrivateData fp_vkGetPrivateData = nullptr; +#else + void * fp_vkGetPrivateData{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdCopyBuffer2 fp_vkCmdCopyBuffer2 = nullptr; +#else + void * fp_vkCmdCopyBuffer2{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdCopyImage2 fp_vkCmdCopyImage2 = nullptr; +#else + void * fp_vkCmdCopyImage2{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdBlitImage2 fp_vkCmdBlitImage2 = nullptr; +#else + void * fp_vkCmdBlitImage2{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdCopyBufferToImage2 fp_vkCmdCopyBufferToImage2 = nullptr; +#else + void * fp_vkCmdCopyBufferToImage2{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdCopyImageToBuffer2 fp_vkCmdCopyImageToBuffer2 = nullptr; +#else + void * fp_vkCmdCopyImageToBuffer2{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdResolveImage2 fp_vkCmdResolveImage2 = nullptr; +#else + void * fp_vkCmdResolveImage2{}; +#endif +#if (defined(VK_KHR_object_refresh)) + PFN_vkCmdRefreshObjectsKHR fp_vkCmdRefreshObjectsKHR = nullptr; +#else + void * fp_vkCmdRefreshObjectsKHR{}; +#endif +#if (defined(VK_KHR_fragment_shading_rate)) + PFN_vkCmdSetFragmentShadingRateKHR fp_vkCmdSetFragmentShadingRateKHR = nullptr; +#else + void * fp_vkCmdSetFragmentShadingRateKHR{}; +#endif +#if (defined(VK_NV_fragment_shading_rate_enums)) + PFN_vkCmdSetFragmentShadingRateEnumNV fp_vkCmdSetFragmentShadingRateEnumNV = nullptr; +#else + void * fp_vkCmdSetFragmentShadingRateEnumNV{}; +#endif +#if (defined(VK_KHR_acceleration_structure)) + PFN_vkGetAccelerationStructureBuildSizesKHR fp_vkGetAccelerationStructureBuildSizesKHR = nullptr; +#else + void * fp_vkGetAccelerationStructureBuildSizesKHR{}; +#endif +#if (defined(VK_EXT_vertex_input_dynamic_state)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetVertexInputEXT fp_vkCmdSetVertexInputEXT = nullptr; +#else + void * fp_vkCmdSetVertexInputEXT{}; +#endif +#if (defined(VK_EXT_color_write_enable)) + PFN_vkCmdSetColorWriteEnableEXT fp_vkCmdSetColorWriteEnableEXT = nullptr; +#else + void * fp_vkCmdSetColorWriteEnableEXT{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdSetEvent2 fp_vkCmdSetEvent2 = nullptr; +#else + void * fp_vkCmdSetEvent2{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdResetEvent2 fp_vkCmdResetEvent2 = nullptr; +#else + void * fp_vkCmdResetEvent2{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdWaitEvents2 fp_vkCmdWaitEvents2 = nullptr; +#else + void * fp_vkCmdWaitEvents2{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdPipelineBarrier2 fp_vkCmdPipelineBarrier2 = nullptr; +#else + void * fp_vkCmdPipelineBarrier2{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkQueueSubmit2 fp_vkQueueSubmit2 = nullptr; +#else + void * fp_vkQueueSubmit2{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdWriteTimestamp2 fp_vkCmdWriteTimestamp2 = nullptr; +#else + void * fp_vkCmdWriteTimestamp2{}; +#endif +#if (defined(VK_KHR_synchronization2)) + PFN_vkCmdWriteBufferMarker2AMD fp_vkCmdWriteBufferMarker2AMD = nullptr; +#else + void * fp_vkCmdWriteBufferMarker2AMD{}; +#endif +#if (defined(VK_KHR_synchronization2)) + PFN_vkGetQueueCheckpointData2NV fp_vkGetQueueCheckpointData2NV = nullptr; +#else + void * fp_vkGetQueueCheckpointData2NV{}; +#endif +#if (defined(VK_EXT_host_image_copy)) + PFN_vkCopyMemoryToImageEXT fp_vkCopyMemoryToImageEXT = nullptr; +#else + void * fp_vkCopyMemoryToImageEXT{}; +#endif +#if (defined(VK_EXT_host_image_copy)) + PFN_vkCopyImageToMemoryEXT fp_vkCopyImageToMemoryEXT = nullptr; +#else + void * fp_vkCopyImageToMemoryEXT{}; +#endif +#if (defined(VK_EXT_host_image_copy)) + PFN_vkCopyImageToImageEXT fp_vkCopyImageToImageEXT = nullptr; +#else + void * fp_vkCopyImageToImageEXT{}; +#endif +#if (defined(VK_EXT_host_image_copy)) + PFN_vkTransitionImageLayoutEXT fp_vkTransitionImageLayoutEXT = nullptr; +#else + void * fp_vkTransitionImageLayoutEXT{}; +#endif +#if (defined(VKSC_VERSION_1_0)) + PFN_vkGetCommandPoolMemoryConsumption fp_vkGetCommandPoolMemoryConsumption = nullptr; +#else + void * fp_vkGetCommandPoolMemoryConsumption{}; +#endif +#if (defined(VK_KHR_video_queue)) + PFN_vkCreateVideoSessionKHR fp_vkCreateVideoSessionKHR = nullptr; +#else + void * fp_vkCreateVideoSessionKHR{}; +#endif +#if (defined(VK_KHR_video_queue)) + PFN_vkDestroyVideoSessionKHR fp_vkDestroyVideoSessionKHR = nullptr; +#else + void * fp_vkDestroyVideoSessionKHR{}; +#endif +#if (defined(VK_KHR_video_queue)) + PFN_vkCreateVideoSessionParametersKHR fp_vkCreateVideoSessionParametersKHR = nullptr; +#else + void * fp_vkCreateVideoSessionParametersKHR{}; +#endif +#if (defined(VK_KHR_video_queue)) + PFN_vkUpdateVideoSessionParametersKHR fp_vkUpdateVideoSessionParametersKHR = nullptr; +#else + void * fp_vkUpdateVideoSessionParametersKHR{}; +#endif +#if (defined(VK_KHR_video_encode_queue)) + PFN_vkGetEncodedVideoSessionParametersKHR fp_vkGetEncodedVideoSessionParametersKHR = nullptr; +#else + void * fp_vkGetEncodedVideoSessionParametersKHR{}; +#endif +#if (defined(VK_KHR_video_queue)) + PFN_vkDestroyVideoSessionParametersKHR fp_vkDestroyVideoSessionParametersKHR = nullptr; +#else + void * fp_vkDestroyVideoSessionParametersKHR{}; +#endif +#if (defined(VK_KHR_video_queue)) + PFN_vkGetVideoSessionMemoryRequirementsKHR fp_vkGetVideoSessionMemoryRequirementsKHR = nullptr; +#else + void * fp_vkGetVideoSessionMemoryRequirementsKHR{}; +#endif +#if (defined(VK_KHR_video_queue)) + PFN_vkBindVideoSessionMemoryKHR fp_vkBindVideoSessionMemoryKHR = nullptr; +#else + void * fp_vkBindVideoSessionMemoryKHR{}; +#endif +#if (defined(VK_KHR_video_decode_queue)) + PFN_vkCmdDecodeVideoKHR fp_vkCmdDecodeVideoKHR = nullptr; +#else + void * fp_vkCmdDecodeVideoKHR{}; +#endif +#if (defined(VK_KHR_video_queue)) + PFN_vkCmdBeginVideoCodingKHR fp_vkCmdBeginVideoCodingKHR = nullptr; +#else + void * fp_vkCmdBeginVideoCodingKHR{}; +#endif +#if (defined(VK_KHR_video_queue)) + PFN_vkCmdControlVideoCodingKHR fp_vkCmdControlVideoCodingKHR = nullptr; +#else + void * fp_vkCmdControlVideoCodingKHR{}; +#endif +#if (defined(VK_KHR_video_queue)) + PFN_vkCmdEndVideoCodingKHR fp_vkCmdEndVideoCodingKHR = nullptr; +#else + void * fp_vkCmdEndVideoCodingKHR{}; +#endif +#if (defined(VK_KHR_video_encode_queue)) + PFN_vkCmdEncodeVideoKHR fp_vkCmdEncodeVideoKHR = nullptr; +#else + void * fp_vkCmdEncodeVideoKHR{}; +#endif +#if (defined(VK_NV_memory_decompression)) + PFN_vkCmdDecompressMemoryNV fp_vkCmdDecompressMemoryNV = nullptr; +#else + void * fp_vkCmdDecompressMemoryNV{}; +#endif +#if (defined(VK_NV_memory_decompression)) + PFN_vkCmdDecompressMemoryIndirectCountNV fp_vkCmdDecompressMemoryIndirectCountNV = nullptr; +#else + void * fp_vkCmdDecompressMemoryIndirectCountNV{}; +#endif +#if (defined(VK_EXT_descriptor_buffer)) + PFN_vkGetDescriptorSetLayoutSizeEXT fp_vkGetDescriptorSetLayoutSizeEXT = nullptr; +#else + void * fp_vkGetDescriptorSetLayoutSizeEXT{}; +#endif +#if (defined(VK_EXT_descriptor_buffer)) + PFN_vkGetDescriptorSetLayoutBindingOffsetEXT fp_vkGetDescriptorSetLayoutBindingOffsetEXT = nullptr; +#else + void * fp_vkGetDescriptorSetLayoutBindingOffsetEXT{}; +#endif +#if (defined(VK_EXT_descriptor_buffer)) + PFN_vkGetDescriptorEXT fp_vkGetDescriptorEXT = nullptr; +#else + void * fp_vkGetDescriptorEXT{}; +#endif +#if (defined(VK_EXT_descriptor_buffer)) + PFN_vkCmdBindDescriptorBuffersEXT fp_vkCmdBindDescriptorBuffersEXT = nullptr; +#else + void * fp_vkCmdBindDescriptorBuffersEXT{}; +#endif +#if (defined(VK_EXT_descriptor_buffer)) + PFN_vkCmdSetDescriptorBufferOffsetsEXT fp_vkCmdSetDescriptorBufferOffsetsEXT = nullptr; +#else + void * fp_vkCmdSetDescriptorBufferOffsetsEXT{}; +#endif +#if (defined(VK_EXT_descriptor_buffer)) + PFN_vkCmdBindDescriptorBufferEmbeddedSamplersEXT fp_vkCmdBindDescriptorBufferEmbeddedSamplersEXT = nullptr; +#else + void * fp_vkCmdBindDescriptorBufferEmbeddedSamplersEXT{}; +#endif +#if (defined(VK_EXT_descriptor_buffer)) + PFN_vkGetBufferOpaqueCaptureDescriptorDataEXT fp_vkGetBufferOpaqueCaptureDescriptorDataEXT = nullptr; +#else + void * fp_vkGetBufferOpaqueCaptureDescriptorDataEXT{}; +#endif +#if (defined(VK_EXT_descriptor_buffer)) + PFN_vkGetImageOpaqueCaptureDescriptorDataEXT fp_vkGetImageOpaqueCaptureDescriptorDataEXT = nullptr; +#else + void * fp_vkGetImageOpaqueCaptureDescriptorDataEXT{}; +#endif +#if (defined(VK_EXT_descriptor_buffer)) + PFN_vkGetImageViewOpaqueCaptureDescriptorDataEXT fp_vkGetImageViewOpaqueCaptureDescriptorDataEXT = nullptr; +#else + void * fp_vkGetImageViewOpaqueCaptureDescriptorDataEXT{}; +#endif +#if (defined(VK_EXT_descriptor_buffer)) + PFN_vkGetSamplerOpaqueCaptureDescriptorDataEXT fp_vkGetSamplerOpaqueCaptureDescriptorDataEXT = nullptr; +#else + void * fp_vkGetSamplerOpaqueCaptureDescriptorDataEXT{}; +#endif +#if (defined(VK_EXT_descriptor_buffer)) + PFN_vkGetAccelerationStructureOpaqueCaptureDescriptorDataEXT fp_vkGetAccelerationStructureOpaqueCaptureDescriptorDataEXT = nullptr; +#else + void * fp_vkGetAccelerationStructureOpaqueCaptureDescriptorDataEXT{}; +#endif +#if (defined(VK_EXT_pageable_device_local_memory)) + PFN_vkSetDeviceMemoryPriorityEXT fp_vkSetDeviceMemoryPriorityEXT = nullptr; +#else + void * fp_vkSetDeviceMemoryPriorityEXT{}; +#endif +#if (defined(VK_KHR_present_wait)) + PFN_vkWaitForPresentKHR fp_vkWaitForPresentKHR = nullptr; +#else + void * fp_vkWaitForPresentKHR{}; +#endif +#if (defined(VK_FUCHSIA_buffer_collection)) + PFN_vkCreateBufferCollectionFUCHSIA fp_vkCreateBufferCollectionFUCHSIA = nullptr; +#else + void * fp_vkCreateBufferCollectionFUCHSIA{}; +#endif +#if (defined(VK_FUCHSIA_buffer_collection)) + PFN_vkSetBufferCollectionBufferConstraintsFUCHSIA fp_vkSetBufferCollectionBufferConstraintsFUCHSIA = nullptr; +#else + void * fp_vkSetBufferCollectionBufferConstraintsFUCHSIA{}; +#endif +#if (defined(VK_FUCHSIA_buffer_collection)) + PFN_vkSetBufferCollectionImageConstraintsFUCHSIA fp_vkSetBufferCollectionImageConstraintsFUCHSIA = nullptr; +#else + void * fp_vkSetBufferCollectionImageConstraintsFUCHSIA{}; +#endif +#if (defined(VK_FUCHSIA_buffer_collection)) + PFN_vkDestroyBufferCollectionFUCHSIA fp_vkDestroyBufferCollectionFUCHSIA = nullptr; +#else + void * fp_vkDestroyBufferCollectionFUCHSIA{}; +#endif +#if (defined(VK_FUCHSIA_buffer_collection)) + PFN_vkGetBufferCollectionPropertiesFUCHSIA fp_vkGetBufferCollectionPropertiesFUCHSIA = nullptr; +#else + void * fp_vkGetBufferCollectionPropertiesFUCHSIA{}; +#endif +#if (defined(VK_NV_cuda_kernel_launch)) + PFN_vkCreateCudaModuleNV fp_vkCreateCudaModuleNV = nullptr; +#else + void * fp_vkCreateCudaModuleNV{}; +#endif +#if (defined(VK_NV_cuda_kernel_launch)) + PFN_vkGetCudaModuleCacheNV fp_vkGetCudaModuleCacheNV = nullptr; +#else + void * fp_vkGetCudaModuleCacheNV{}; +#endif +#if (defined(VK_NV_cuda_kernel_launch)) + PFN_vkCreateCudaFunctionNV fp_vkCreateCudaFunctionNV = nullptr; +#else + void * fp_vkCreateCudaFunctionNV{}; +#endif +#if (defined(VK_NV_cuda_kernel_launch)) + PFN_vkDestroyCudaModuleNV fp_vkDestroyCudaModuleNV = nullptr; +#else + void * fp_vkDestroyCudaModuleNV{}; +#endif +#if (defined(VK_NV_cuda_kernel_launch)) + PFN_vkDestroyCudaFunctionNV fp_vkDestroyCudaFunctionNV = nullptr; +#else + void * fp_vkDestroyCudaFunctionNV{}; +#endif +#if (defined(VK_NV_cuda_kernel_launch)) + PFN_vkCmdCudaLaunchKernelNV fp_vkCmdCudaLaunchKernelNV = nullptr; +#else + void * fp_vkCmdCudaLaunchKernelNV{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdBeginRendering fp_vkCmdBeginRendering = nullptr; +#else + void * fp_vkCmdBeginRendering{}; +#endif +#if (defined(VK_VERSION_1_3)) + PFN_vkCmdEndRendering fp_vkCmdEndRendering = nullptr; +#else + void * fp_vkCmdEndRendering{}; +#endif +#if (defined(VK_VALVE_descriptor_set_host_mapping)) + PFN_vkGetDescriptorSetLayoutHostMappingInfoVALVE fp_vkGetDescriptorSetLayoutHostMappingInfoVALVE = nullptr; +#else + void * fp_vkGetDescriptorSetLayoutHostMappingInfoVALVE{}; +#endif +#if (defined(VK_VALVE_descriptor_set_host_mapping)) + PFN_vkGetDescriptorSetHostMappingVALVE fp_vkGetDescriptorSetHostMappingVALVE = nullptr; +#else + void * fp_vkGetDescriptorSetHostMappingVALVE{}; +#endif +#if (defined(VK_EXT_opacity_micromap)) + PFN_vkCreateMicromapEXT fp_vkCreateMicromapEXT = nullptr; +#else + void * fp_vkCreateMicromapEXT{}; +#endif +#if (defined(VK_EXT_opacity_micromap)) + PFN_vkCmdBuildMicromapsEXT fp_vkCmdBuildMicromapsEXT = nullptr; +#else + void * fp_vkCmdBuildMicromapsEXT{}; +#endif +#if (defined(VK_EXT_opacity_micromap)) + PFN_vkBuildMicromapsEXT fp_vkBuildMicromapsEXT = nullptr; +#else + void * fp_vkBuildMicromapsEXT{}; +#endif +#if (defined(VK_EXT_opacity_micromap)) + PFN_vkDestroyMicromapEXT fp_vkDestroyMicromapEXT = nullptr; +#else + void * fp_vkDestroyMicromapEXT{}; +#endif +#if (defined(VK_EXT_opacity_micromap)) + PFN_vkCmdCopyMicromapEXT fp_vkCmdCopyMicromapEXT = nullptr; +#else + void * fp_vkCmdCopyMicromapEXT{}; +#endif +#if (defined(VK_EXT_opacity_micromap)) + PFN_vkCopyMicromapEXT fp_vkCopyMicromapEXT = nullptr; +#else + void * fp_vkCopyMicromapEXT{}; +#endif +#if (defined(VK_EXT_opacity_micromap)) + PFN_vkCmdCopyMicromapToMemoryEXT fp_vkCmdCopyMicromapToMemoryEXT = nullptr; +#else + void * fp_vkCmdCopyMicromapToMemoryEXT{}; +#endif +#if (defined(VK_EXT_opacity_micromap)) + PFN_vkCopyMicromapToMemoryEXT fp_vkCopyMicromapToMemoryEXT = nullptr; +#else + void * fp_vkCopyMicromapToMemoryEXT{}; +#endif +#if (defined(VK_EXT_opacity_micromap)) + PFN_vkCmdCopyMemoryToMicromapEXT fp_vkCmdCopyMemoryToMicromapEXT = nullptr; +#else + void * fp_vkCmdCopyMemoryToMicromapEXT{}; +#endif +#if (defined(VK_EXT_opacity_micromap)) + PFN_vkCopyMemoryToMicromapEXT fp_vkCopyMemoryToMicromapEXT = nullptr; +#else + void * fp_vkCopyMemoryToMicromapEXT{}; +#endif +#if (defined(VK_EXT_opacity_micromap)) + PFN_vkCmdWriteMicromapsPropertiesEXT fp_vkCmdWriteMicromapsPropertiesEXT = nullptr; +#else + void * fp_vkCmdWriteMicromapsPropertiesEXT{}; +#endif +#if (defined(VK_EXT_opacity_micromap)) + PFN_vkWriteMicromapsPropertiesEXT fp_vkWriteMicromapsPropertiesEXT = nullptr; +#else + void * fp_vkWriteMicromapsPropertiesEXT{}; +#endif +#if (defined(VK_EXT_opacity_micromap)) + PFN_vkGetDeviceMicromapCompatibilityEXT fp_vkGetDeviceMicromapCompatibilityEXT = nullptr; +#else + void * fp_vkGetDeviceMicromapCompatibilityEXT{}; +#endif +#if (defined(VK_EXT_opacity_micromap)) + PFN_vkGetMicromapBuildSizesEXT fp_vkGetMicromapBuildSizesEXT = nullptr; +#else + void * fp_vkGetMicromapBuildSizesEXT{}; +#endif +#if (defined(VK_EXT_shader_module_identifier)) + PFN_vkGetShaderModuleIdentifierEXT fp_vkGetShaderModuleIdentifierEXT = nullptr; +#else + void * fp_vkGetShaderModuleIdentifierEXT{}; +#endif +#if (defined(VK_EXT_shader_module_identifier)) + PFN_vkGetShaderModuleCreateInfoIdentifierEXT fp_vkGetShaderModuleCreateInfoIdentifierEXT = nullptr; +#else + void * fp_vkGetShaderModuleCreateInfoIdentifierEXT{}; +#endif +#if (defined(VK_KHR_maintenance5)) + PFN_vkGetImageSubresourceLayout2KHR fp_vkGetImageSubresourceLayout2KHR = nullptr; +#else + void * fp_vkGetImageSubresourceLayout2KHR{}; +#endif +#if (defined(VK_EXT_pipeline_properties)) + PFN_vkGetPipelinePropertiesEXT fp_vkGetPipelinePropertiesEXT = nullptr; +#else + void * fp_vkGetPipelinePropertiesEXT{}; +#endif +#if (defined(VK_EXT_metal_objects)) + PFN_vkExportMetalObjectsEXT fp_vkExportMetalObjectsEXT = nullptr; +#else + void * fp_vkExportMetalObjectsEXT{}; +#endif +#if (defined(VK_QCOM_tile_properties)) + PFN_vkGetFramebufferTilePropertiesQCOM fp_vkGetFramebufferTilePropertiesQCOM = nullptr; +#else + void * fp_vkGetFramebufferTilePropertiesQCOM{}; +#endif +#if (defined(VK_QCOM_tile_properties)) + PFN_vkGetDynamicRenderingTilePropertiesQCOM fp_vkGetDynamicRenderingTilePropertiesQCOM = nullptr; +#else + void * fp_vkGetDynamicRenderingTilePropertiesQCOM{}; +#endif +#if (defined(VK_NV_optical_flow)) + PFN_vkCreateOpticalFlowSessionNV fp_vkCreateOpticalFlowSessionNV = nullptr; +#else + void * fp_vkCreateOpticalFlowSessionNV{}; +#endif +#if (defined(VK_NV_optical_flow)) + PFN_vkDestroyOpticalFlowSessionNV fp_vkDestroyOpticalFlowSessionNV = nullptr; +#else + void * fp_vkDestroyOpticalFlowSessionNV{}; +#endif +#if (defined(VK_NV_optical_flow)) + PFN_vkBindOpticalFlowSessionImageNV fp_vkBindOpticalFlowSessionImageNV = nullptr; +#else + void * fp_vkBindOpticalFlowSessionImageNV{}; +#endif +#if (defined(VK_NV_optical_flow)) + PFN_vkCmdOpticalFlowExecuteNV fp_vkCmdOpticalFlowExecuteNV = nullptr; +#else + void * fp_vkCmdOpticalFlowExecuteNV{}; +#endif +#if (defined(VK_EXT_device_fault)) + PFN_vkGetDeviceFaultInfoEXT fp_vkGetDeviceFaultInfoEXT = nullptr; +#else + void * fp_vkGetDeviceFaultInfoEXT{}; +#endif +#if (defined(VK_EXT_depth_bias_control)) + PFN_vkCmdSetDepthBias2EXT fp_vkCmdSetDepthBias2EXT = nullptr; +#else + void * fp_vkCmdSetDepthBias2EXT{}; +#endif +#if (defined(VK_EXT_swapchain_maintenance1)) + PFN_vkReleaseSwapchainImagesEXT fp_vkReleaseSwapchainImagesEXT = nullptr; +#else + void * fp_vkReleaseSwapchainImagesEXT{}; +#endif +#if (defined(VK_KHR_maintenance5)) + PFN_vkGetDeviceImageSubresourceLayoutKHR fp_vkGetDeviceImageSubresourceLayoutKHR = nullptr; +#else + void * fp_vkGetDeviceImageSubresourceLayoutKHR{}; +#endif +#if (defined(VK_KHR_map_memory2)) + PFN_vkMapMemory2KHR fp_vkMapMemory2KHR = nullptr; +#else + void * fp_vkMapMemory2KHR{}; +#endif +#if (defined(VK_KHR_map_memory2)) + PFN_vkUnmapMemory2KHR fp_vkUnmapMemory2KHR = nullptr; +#else + void * fp_vkUnmapMemory2KHR{}; +#endif +#if (defined(VK_EXT_shader_object)) + PFN_vkCreateShadersEXT fp_vkCreateShadersEXT = nullptr; +#else + void * fp_vkCreateShadersEXT{}; +#endif +#if (defined(VK_EXT_shader_object)) + PFN_vkDestroyShaderEXT fp_vkDestroyShaderEXT = nullptr; +#else + void * fp_vkDestroyShaderEXT{}; +#endif +#if (defined(VK_EXT_shader_object)) + PFN_vkGetShaderBinaryDataEXT fp_vkGetShaderBinaryDataEXT = nullptr; +#else + void * fp_vkGetShaderBinaryDataEXT{}; +#endif +#if (defined(VK_EXT_shader_object)) + PFN_vkCmdBindShadersEXT fp_vkCmdBindShadersEXT = nullptr; +#else + void * fp_vkCmdBindShadersEXT{}; +#endif +#if (defined(VK_QNX_external_memory_screen_buffer)) + PFN_vkGetScreenBufferPropertiesQNX fp_vkGetScreenBufferPropertiesQNX = nullptr; +#else + void * fp_vkGetScreenBufferPropertiesQNX{}; +#endif +#if (defined(VK_AMDX_shader_enqueue)) + PFN_vkGetExecutionGraphPipelineScratchSizeAMDX fp_vkGetExecutionGraphPipelineScratchSizeAMDX = nullptr; +#else + void * fp_vkGetExecutionGraphPipelineScratchSizeAMDX{}; +#endif +#if (defined(VK_AMDX_shader_enqueue)) + PFN_vkGetExecutionGraphPipelineNodeIndexAMDX fp_vkGetExecutionGraphPipelineNodeIndexAMDX = nullptr; +#else + void * fp_vkGetExecutionGraphPipelineNodeIndexAMDX{}; +#endif +#if (defined(VK_AMDX_shader_enqueue)) + PFN_vkCreateExecutionGraphPipelinesAMDX fp_vkCreateExecutionGraphPipelinesAMDX = nullptr; +#else + void * fp_vkCreateExecutionGraphPipelinesAMDX{}; +#endif +#if (defined(VK_AMDX_shader_enqueue)) + PFN_vkCmdInitializeGraphScratchMemoryAMDX fp_vkCmdInitializeGraphScratchMemoryAMDX = nullptr; +#else + void * fp_vkCmdInitializeGraphScratchMemoryAMDX{}; +#endif +#if (defined(VK_AMDX_shader_enqueue)) + PFN_vkCmdDispatchGraphAMDX fp_vkCmdDispatchGraphAMDX = nullptr; +#else + void * fp_vkCmdDispatchGraphAMDX{}; +#endif +#if (defined(VK_AMDX_shader_enqueue)) + PFN_vkCmdDispatchGraphIndirectAMDX fp_vkCmdDispatchGraphIndirectAMDX = nullptr; +#else + void * fp_vkCmdDispatchGraphIndirectAMDX{}; +#endif +#if (defined(VK_AMDX_shader_enqueue)) + PFN_vkCmdDispatchGraphIndirectCountAMDX fp_vkCmdDispatchGraphIndirectCountAMDX = nullptr; +#else + void * fp_vkCmdDispatchGraphIndirectCountAMDX{}; +#endif +#if (defined(VK_KHR_maintenance6)) + PFN_vkCmdBindDescriptorSets2KHR fp_vkCmdBindDescriptorSets2KHR = nullptr; +#else + void * fp_vkCmdBindDescriptorSets2KHR{}; +#endif +#if (defined(VK_KHR_maintenance6)) + PFN_vkCmdPushConstants2KHR fp_vkCmdPushConstants2KHR = nullptr; +#else + void * fp_vkCmdPushConstants2KHR{}; +#endif +#if (defined(VK_KHR_maintenance6)) + PFN_vkCmdPushDescriptorSet2KHR fp_vkCmdPushDescriptorSet2KHR = nullptr; +#else + void * fp_vkCmdPushDescriptorSet2KHR{}; +#endif +#if (defined(VK_KHR_maintenance6)) + PFN_vkCmdPushDescriptorSetWithTemplate2KHR fp_vkCmdPushDescriptorSetWithTemplate2KHR = nullptr; +#else + void * fp_vkCmdPushDescriptorSetWithTemplate2KHR{}; +#endif +#if (defined(VK_KHR_maintenance6)) + PFN_vkCmdSetDescriptorBufferOffsets2EXT fp_vkCmdSetDescriptorBufferOffsets2EXT = nullptr; +#else + void * fp_vkCmdSetDescriptorBufferOffsets2EXT{}; +#endif +#if (defined(VK_KHR_maintenance6)) + PFN_vkCmdBindDescriptorBufferEmbeddedSamplers2EXT fp_vkCmdBindDescriptorBufferEmbeddedSamplers2EXT = nullptr; +#else + void * fp_vkCmdBindDescriptorBufferEmbeddedSamplers2EXT{}; +#endif +#if (defined(VK_NV_low_latency2)) + PFN_vkSetLatencySleepModeNV fp_vkSetLatencySleepModeNV = nullptr; +#else + void * fp_vkSetLatencySleepModeNV{}; +#endif +#if (defined(VK_NV_low_latency2)) + PFN_vkLatencySleepNV fp_vkLatencySleepNV = nullptr; +#else + void * fp_vkLatencySleepNV{}; +#endif +#if (defined(VK_NV_low_latency2)) + PFN_vkSetLatencyMarkerNV fp_vkSetLatencyMarkerNV = nullptr; +#else + void * fp_vkSetLatencyMarkerNV{}; +#endif +#if ((defined(VK_NV_low_latency2))) && VK_HEADER_VERSION >= 271 + PFN_vkGetLatencyTimingsNV fp_vkGetLatencyTimingsNV = nullptr; +#else + void * fp_vkGetLatencyTimingsNV{}; +#endif +#if (defined(VK_NV_low_latency2)) + PFN_vkQueueNotifyOutOfBandNV fp_vkQueueNotifyOutOfBandNV = nullptr; +#else + void * fp_vkQueueNotifyOutOfBandNV{}; +#endif +#if (defined(VK_KHR_dynamic_rendering_local_read)) + PFN_vkCmdSetRenderingAttachmentLocationsKHR fp_vkCmdSetRenderingAttachmentLocationsKHR = nullptr; +#else + void * fp_vkCmdSetRenderingAttachmentLocationsKHR{}; +#endif +#if (defined(VK_KHR_dynamic_rendering_local_read)) + PFN_vkCmdSetRenderingInputAttachmentIndicesKHR fp_vkCmdSetRenderingInputAttachmentIndicesKHR = nullptr; +#else + void * fp_vkCmdSetRenderingInputAttachmentIndicesKHR{}; +#endif +#if (defined(VK_EXT_host_query_reset)) + PFN_vkResetQueryPoolEXT fp_vkResetQueryPoolEXT = nullptr; +#else + void * fp_vkResetQueryPoolEXT{}; +#endif +#if (defined(VK_KHR_maintenance1)) + PFN_vkTrimCommandPoolKHR fp_vkTrimCommandPoolKHR = nullptr; +#else + void * fp_vkTrimCommandPoolKHR{}; +#endif +#if (defined(VK_KHR_device_group)) + PFN_vkGetDeviceGroupPeerMemoryFeaturesKHR fp_vkGetDeviceGroupPeerMemoryFeaturesKHR = nullptr; +#else + void * fp_vkGetDeviceGroupPeerMemoryFeaturesKHR{}; +#endif +#if (defined(VK_KHR_bind_memory2)) + PFN_vkBindBufferMemory2KHR fp_vkBindBufferMemory2KHR = nullptr; +#else + void * fp_vkBindBufferMemory2KHR{}; +#endif +#if (defined(VK_KHR_bind_memory2)) + PFN_vkBindImageMemory2KHR fp_vkBindImageMemory2KHR = nullptr; +#else + void * fp_vkBindImageMemory2KHR{}; +#endif +#if (defined(VK_KHR_device_group)) + PFN_vkCmdSetDeviceMaskKHR fp_vkCmdSetDeviceMaskKHR = nullptr; +#else + void * fp_vkCmdSetDeviceMaskKHR{}; +#endif +#if (defined(VK_KHR_device_group)) + PFN_vkCmdDispatchBaseKHR fp_vkCmdDispatchBaseKHR = nullptr; +#else + void * fp_vkCmdDispatchBaseKHR{}; +#endif +#if (defined(VK_KHR_descriptor_update_template)) + PFN_vkCreateDescriptorUpdateTemplateKHR fp_vkCreateDescriptorUpdateTemplateKHR = nullptr; +#else + void * fp_vkCreateDescriptorUpdateTemplateKHR{}; +#endif +#if (defined(VK_KHR_descriptor_update_template)) + PFN_vkDestroyDescriptorUpdateTemplateKHR fp_vkDestroyDescriptorUpdateTemplateKHR = nullptr; +#else + void * fp_vkDestroyDescriptorUpdateTemplateKHR{}; +#endif +#if (defined(VK_KHR_descriptor_update_template)) + PFN_vkUpdateDescriptorSetWithTemplateKHR fp_vkUpdateDescriptorSetWithTemplateKHR = nullptr; +#else + void * fp_vkUpdateDescriptorSetWithTemplateKHR{}; +#endif +#if (defined(VK_KHR_get_memory_requirements2)) + PFN_vkGetBufferMemoryRequirements2KHR fp_vkGetBufferMemoryRequirements2KHR = nullptr; +#else + void * fp_vkGetBufferMemoryRequirements2KHR{}; +#endif +#if (defined(VK_KHR_get_memory_requirements2)) + PFN_vkGetImageMemoryRequirements2KHR fp_vkGetImageMemoryRequirements2KHR = nullptr; +#else + void * fp_vkGetImageMemoryRequirements2KHR{}; +#endif +#if (defined(VK_KHR_get_memory_requirements2)) + PFN_vkGetImageSparseMemoryRequirements2KHR fp_vkGetImageSparseMemoryRequirements2KHR = nullptr; +#else + void * fp_vkGetImageSparseMemoryRequirements2KHR{}; +#endif +#if (defined(VK_KHR_maintenance4)) + PFN_vkGetDeviceBufferMemoryRequirementsKHR fp_vkGetDeviceBufferMemoryRequirementsKHR = nullptr; +#else + void * fp_vkGetDeviceBufferMemoryRequirementsKHR{}; +#endif +#if (defined(VK_KHR_maintenance4)) + PFN_vkGetDeviceImageMemoryRequirementsKHR fp_vkGetDeviceImageMemoryRequirementsKHR = nullptr; +#else + void * fp_vkGetDeviceImageMemoryRequirementsKHR{}; +#endif +#if (defined(VK_KHR_maintenance4)) + PFN_vkGetDeviceImageSparseMemoryRequirementsKHR fp_vkGetDeviceImageSparseMemoryRequirementsKHR = nullptr; +#else + void * fp_vkGetDeviceImageSparseMemoryRequirementsKHR{}; +#endif +#if (defined(VK_KHR_sampler_ycbcr_conversion)) + PFN_vkCreateSamplerYcbcrConversionKHR fp_vkCreateSamplerYcbcrConversionKHR = nullptr; +#else + void * fp_vkCreateSamplerYcbcrConversionKHR{}; +#endif +#if (defined(VK_KHR_sampler_ycbcr_conversion)) + PFN_vkDestroySamplerYcbcrConversionKHR fp_vkDestroySamplerYcbcrConversionKHR = nullptr; +#else + void * fp_vkDestroySamplerYcbcrConversionKHR{}; +#endif +#if (defined(VK_KHR_maintenance3)) + PFN_vkGetDescriptorSetLayoutSupportKHR fp_vkGetDescriptorSetLayoutSupportKHR = nullptr; +#else + void * fp_vkGetDescriptorSetLayoutSupportKHR{}; +#endif +#if (defined(VK_EXT_calibrated_timestamps)) + PFN_vkGetCalibratedTimestampsEXT fp_vkGetCalibratedTimestampsEXT = nullptr; +#else + void * fp_vkGetCalibratedTimestampsEXT{}; +#endif +#if (defined(VK_KHR_create_renderpass2)) + PFN_vkCreateRenderPass2KHR fp_vkCreateRenderPass2KHR = nullptr; +#else + void * fp_vkCreateRenderPass2KHR{}; +#endif +#if (defined(VK_KHR_create_renderpass2)) + PFN_vkCmdBeginRenderPass2KHR fp_vkCmdBeginRenderPass2KHR = nullptr; +#else + void * fp_vkCmdBeginRenderPass2KHR{}; +#endif +#if (defined(VK_KHR_create_renderpass2)) + PFN_vkCmdNextSubpass2KHR fp_vkCmdNextSubpass2KHR = nullptr; +#else + void * fp_vkCmdNextSubpass2KHR{}; +#endif +#if (defined(VK_KHR_create_renderpass2)) + PFN_vkCmdEndRenderPass2KHR fp_vkCmdEndRenderPass2KHR = nullptr; +#else + void * fp_vkCmdEndRenderPass2KHR{}; +#endif +#if (defined(VK_KHR_timeline_semaphore)) + PFN_vkGetSemaphoreCounterValueKHR fp_vkGetSemaphoreCounterValueKHR = nullptr; +#else + void * fp_vkGetSemaphoreCounterValueKHR{}; +#endif +#if (defined(VK_KHR_timeline_semaphore)) + PFN_vkWaitSemaphoresKHR fp_vkWaitSemaphoresKHR = nullptr; +#else + void * fp_vkWaitSemaphoresKHR{}; +#endif +#if (defined(VK_KHR_timeline_semaphore)) + PFN_vkSignalSemaphoreKHR fp_vkSignalSemaphoreKHR = nullptr; +#else + void * fp_vkSignalSemaphoreKHR{}; +#endif +#if (defined(VK_AMD_draw_indirect_count)) + PFN_vkCmdDrawIndirectCountAMD fp_vkCmdDrawIndirectCountAMD = nullptr; +#else + void * fp_vkCmdDrawIndirectCountAMD{}; +#endif +#if (defined(VK_AMD_draw_indirect_count)) + PFN_vkCmdDrawIndexedIndirectCountAMD fp_vkCmdDrawIndexedIndirectCountAMD = nullptr; +#else + void * fp_vkCmdDrawIndexedIndirectCountAMD{}; +#endif +#if (defined(VK_NV_ray_tracing)) + PFN_vkGetRayTracingShaderGroupHandlesNV fp_vkGetRayTracingShaderGroupHandlesNV = nullptr; +#else + void * fp_vkGetRayTracingShaderGroupHandlesNV{}; +#endif +#if (defined(VK_KHR_buffer_device_address)) + PFN_vkGetBufferOpaqueCaptureAddressKHR fp_vkGetBufferOpaqueCaptureAddressKHR = nullptr; +#else + void * fp_vkGetBufferOpaqueCaptureAddressKHR{}; +#endif +#if (defined(VK_EXT_buffer_device_address)) + PFN_vkGetBufferDeviceAddressEXT fp_vkGetBufferDeviceAddressEXT = nullptr; +#else + void * fp_vkGetBufferDeviceAddressEXT{}; +#endif +#if (defined(VK_KHR_buffer_device_address)) + PFN_vkGetDeviceMemoryOpaqueCaptureAddressKHR fp_vkGetDeviceMemoryOpaqueCaptureAddressKHR = nullptr; +#else + void * fp_vkGetDeviceMemoryOpaqueCaptureAddressKHR{}; +#endif +#if (defined(VK_EXT_line_rasterization)) + PFN_vkCmdSetLineStippleEXT fp_vkCmdSetLineStippleEXT = nullptr; +#else + void * fp_vkCmdSetLineStippleEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetCullModeEXT fp_vkCmdSetCullModeEXT = nullptr; +#else + void * fp_vkCmdSetCullModeEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetFrontFaceEXT fp_vkCmdSetFrontFaceEXT = nullptr; +#else + void * fp_vkCmdSetFrontFaceEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetPrimitiveTopologyEXT fp_vkCmdSetPrimitiveTopologyEXT = nullptr; +#else + void * fp_vkCmdSetPrimitiveTopologyEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetViewportWithCountEXT fp_vkCmdSetViewportWithCountEXT = nullptr; +#else + void * fp_vkCmdSetViewportWithCountEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetScissorWithCountEXT fp_vkCmdSetScissorWithCountEXT = nullptr; +#else + void * fp_vkCmdSetScissorWithCountEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdBindVertexBuffers2EXT fp_vkCmdBindVertexBuffers2EXT = nullptr; +#else + void * fp_vkCmdBindVertexBuffers2EXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetDepthTestEnableEXT fp_vkCmdSetDepthTestEnableEXT = nullptr; +#else + void * fp_vkCmdSetDepthTestEnableEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetDepthWriteEnableEXT fp_vkCmdSetDepthWriteEnableEXT = nullptr; +#else + void * fp_vkCmdSetDepthWriteEnableEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetDepthCompareOpEXT fp_vkCmdSetDepthCompareOpEXT = nullptr; +#else + void * fp_vkCmdSetDepthCompareOpEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetDepthBoundsTestEnableEXT fp_vkCmdSetDepthBoundsTestEnableEXT = nullptr; +#else + void * fp_vkCmdSetDepthBoundsTestEnableEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetStencilTestEnableEXT fp_vkCmdSetStencilTestEnableEXT = nullptr; +#else + void * fp_vkCmdSetStencilTestEnableEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetStencilOpEXT fp_vkCmdSetStencilOpEXT = nullptr; +#else + void * fp_vkCmdSetStencilOpEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state2)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetRasterizerDiscardEnableEXT fp_vkCmdSetRasterizerDiscardEnableEXT = nullptr; +#else + void * fp_vkCmdSetRasterizerDiscardEnableEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state2)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetDepthBiasEnableEXT fp_vkCmdSetDepthBiasEnableEXT = nullptr; +#else + void * fp_vkCmdSetDepthBiasEnableEXT{}; +#endif +#if (defined(VK_EXT_extended_dynamic_state2)) || (defined(VK_EXT_shader_object)) + PFN_vkCmdSetPrimitiveRestartEnableEXT fp_vkCmdSetPrimitiveRestartEnableEXT = nullptr; +#else + void * fp_vkCmdSetPrimitiveRestartEnableEXT{}; +#endif +#if (defined(VK_EXT_private_data)) + PFN_vkCreatePrivateDataSlotEXT fp_vkCreatePrivateDataSlotEXT = nullptr; +#else + void * fp_vkCreatePrivateDataSlotEXT{}; +#endif +#if (defined(VK_EXT_private_data)) + PFN_vkDestroyPrivateDataSlotEXT fp_vkDestroyPrivateDataSlotEXT = nullptr; +#else + void * fp_vkDestroyPrivateDataSlotEXT{}; +#endif +#if (defined(VK_EXT_private_data)) + PFN_vkSetPrivateDataEXT fp_vkSetPrivateDataEXT = nullptr; +#else + void * fp_vkSetPrivateDataEXT{}; +#endif +#if (defined(VK_EXT_private_data)) + PFN_vkGetPrivateDataEXT fp_vkGetPrivateDataEXT = nullptr; +#else + void * fp_vkGetPrivateDataEXT{}; +#endif +#if (defined(VK_KHR_copy_commands2)) + PFN_vkCmdCopyBuffer2KHR fp_vkCmdCopyBuffer2KHR = nullptr; +#else + void * fp_vkCmdCopyBuffer2KHR{}; +#endif +#if (defined(VK_KHR_copy_commands2)) + PFN_vkCmdCopyImage2KHR fp_vkCmdCopyImage2KHR = nullptr; +#else + void * fp_vkCmdCopyImage2KHR{}; +#endif +#if (defined(VK_KHR_copy_commands2)) + PFN_vkCmdBlitImage2KHR fp_vkCmdBlitImage2KHR = nullptr; +#else + void * fp_vkCmdBlitImage2KHR{}; +#endif +#if (defined(VK_KHR_copy_commands2)) + PFN_vkCmdCopyBufferToImage2KHR fp_vkCmdCopyBufferToImage2KHR = nullptr; +#else + void * fp_vkCmdCopyBufferToImage2KHR{}; +#endif +#if (defined(VK_KHR_copy_commands2)) + PFN_vkCmdCopyImageToBuffer2KHR fp_vkCmdCopyImageToBuffer2KHR = nullptr; +#else + void * fp_vkCmdCopyImageToBuffer2KHR{}; +#endif +#if (defined(VK_KHR_copy_commands2)) + PFN_vkCmdResolveImage2KHR fp_vkCmdResolveImage2KHR = nullptr; +#else + void * fp_vkCmdResolveImage2KHR{}; +#endif +#if (defined(VK_KHR_synchronization2)) + PFN_vkCmdSetEvent2KHR fp_vkCmdSetEvent2KHR = nullptr; +#else + void * fp_vkCmdSetEvent2KHR{}; +#endif +#if (defined(VK_KHR_synchronization2)) + PFN_vkCmdResetEvent2KHR fp_vkCmdResetEvent2KHR = nullptr; +#else + void * fp_vkCmdResetEvent2KHR{}; +#endif +#if (defined(VK_KHR_synchronization2)) + PFN_vkCmdWaitEvents2KHR fp_vkCmdWaitEvents2KHR = nullptr; +#else + void * fp_vkCmdWaitEvents2KHR{}; +#endif +#if (defined(VK_KHR_synchronization2)) + PFN_vkCmdPipelineBarrier2KHR fp_vkCmdPipelineBarrier2KHR = nullptr; +#else + void * fp_vkCmdPipelineBarrier2KHR{}; +#endif +#if (defined(VK_KHR_synchronization2)) + PFN_vkQueueSubmit2KHR fp_vkQueueSubmit2KHR = nullptr; +#else + void * fp_vkQueueSubmit2KHR{}; +#endif +#if (defined(VK_KHR_synchronization2)) + PFN_vkCmdWriteTimestamp2KHR fp_vkCmdWriteTimestamp2KHR = nullptr; +#else + void * fp_vkCmdWriteTimestamp2KHR{}; +#endif +#if (defined(VK_KHR_dynamic_rendering)) + PFN_vkCmdBeginRenderingKHR fp_vkCmdBeginRenderingKHR = nullptr; +#else + void * fp_vkCmdBeginRenderingKHR{}; +#endif +#if (defined(VK_KHR_dynamic_rendering)) + PFN_vkCmdEndRenderingKHR fp_vkCmdEndRenderingKHR = nullptr; +#else + void * fp_vkCmdEndRenderingKHR{}; +#endif +#if (defined(VK_EXT_host_image_copy)) || (defined(VK_EXT_image_compression_control)) + PFN_vkGetImageSubresourceLayout2EXT fp_vkGetImageSubresourceLayout2EXT = nullptr; +#else + void * fp_vkGetImageSubresourceLayout2EXT{}; +#endif + bool is_populated() const { return populated; } + VkDevice device = VK_NULL_HANDLE; +private: + bool populated = false; +}; + +} // namespace vkb \ No newline at end of file diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/tests/CMakeLists.txt b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/CMakeLists.txt new file mode 100644 index 0000000..3f734c4 --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/CMakeLists.txt @@ -0,0 +1,130 @@ +if (WIN32) + add_library(VulkanMock SHARED vulkan_mock.hpp vulkan_mock.cpp) + # Need to name the target "vulkan-1" so that it'll be loaded instead of the *actual* vulkan-1.dll on the system + set_target_properties(VulkanMock PROPERTIES OUTPUT_NAME "vulkan-1") +else() + add_library(VulkanMock STATIC vulkan_mock.hpp vulkan_mock.cpp) +endif() +target_link_libraries(VulkanMock + PUBLIC + Vulkan::Headers vk-bootstrap Catch2::Catch2 + PRIVATE + vk-bootstrap-compiler-warnings +) +target_compile_features(VulkanMock PUBLIC cxx_std_17) +target_compile_definitions(VulkanMock PUBLIC VK_NO_PROTOTYPES COMPILING_DLL) +if(WIN32) + if (CMAKE_CXX_COMPILER_ID MATCHES "MSVC" OR CMAKE_CXX_COMPILER_FRONTEND_VARIANT MATCHES "MSVC") + target_link_options(VulkanMock PRIVATE /DEF:${CMAKE_CURRENT_SOURCE_DIR}/vulkan_mock.def) + elseif (CMAKE_CXX_COMPILER_FRONTEND_VARIANT MATCHES "GNU") + target_link_options(VulkanMock PRIVATE -Wl,/DEF:${CMAKE_CURRENT_SOURCE_DIR}/vulkan_mock.def) + endif() +endif() + +add_executable(vk-bootstrap-test + vulkan_library_loader.hpp + vulkan_mock_setup.hpp + vulkan_mock_setup.cpp + bootstrap_tests.cpp + error_code_tests.cpp + unit_tests.cpp + include_checks.cpp + vulkan_hpp_tests.cpp +) + +target_link_libraries(vk-bootstrap-test + PRIVATE + vk-bootstrap + Vulkan::Headers + vk-bootstrap-compiler-warnings + VulkanMock + Catch2::Catch2WithMain +) + +if (CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") + target_compile_options(vk-bootstrap-test PRIVATE -Wno-error=deprecated-declarations) +elseif(CMAKE_CXX_COMPILER_ID MATCHES "MSVC") + target_compile_options(vk-bootstrap-test PRIVATE /wd4996) +endif() + +if (WIN32 AND CMAKE_CXX_COMPILER_ID MATCHES "Clang") + target_compile_options(vk-bootstrap-compiler-warnings INTERFACE -Wno-microsoft-cast) +endif() + +list(APPEND CMAKE_MODULE_PATH ${Catch2_SOURCE_DIR}/extras) +include(Catch) +catch_discover_tests(vk-bootstrap-test) + +# Test add_subdirectory suppport using fetch content vulkan headers +add_test(NAME integration.add_subdirectory.fetch_content_vulkan_headers + COMMAND ${CMAKE_CTEST_COMMAND} + --build-and-test ${CMAKE_CURRENT_LIST_DIR}/integration + ${CMAKE_CURRENT_BINARY_DIR}/add_subdirectory/fetch_content_vulkan_headers + --build-generator ${CMAKE_GENERATOR} + --build-options -DADD_SUBDIRECTORY_TESTING=ON -DVULKAN_HEADER_VERSION_GIT_TAG=${VK_BOOTSTRAP_SOURCE_HEADER_VERSION_GIT_TAG} +) + +get_target_property(vulkan_headers_include_dir Vulkan::Headers INTERFACE_INCLUDE_DIRECTORIES) + +# Test add_subdirectory suppport by setting VK_BOOTSTRAP_VULKAN_HEADER_DIR to the include directory of the Vulkan::Headers +add_test(NAME integration.add_subdirectory.vulkan_header_dir + COMMAND ${CMAKE_CTEST_COMMAND} + --build-and-test ${CMAKE_CURRENT_LIST_DIR}/integration + ${CMAKE_CURRENT_BINARY_DIR}/add_subdirectory/vulkan_header_dir + --build-generator ${CMAKE_GENERATOR} + --build-options -DADD_SUBDIRECTORY_TESTING=ON -DVK_BOOTSTRAP_VULKAN_HEADER_DIR=${vulkan_headers_include_dir} +) + +set(test_install_dir "${CMAKE_CURRENT_BINARY_DIR}/install") +add_test(NAME integration.install + COMMAND ${CMAKE_COMMAND} --install ${CMAKE_BINARY_DIR} --prefix ${test_install_dir} --config $ +) + +find_package(VulkanHeaders CONFIG) +if (VulkanHeaders_FOUND) + set(vulkan_headers_package_location ${VulkanHeaders_DIR}) + + # Test add_subdirectory suppport using find_package(VulkanHeaders) + add_test(NAME integration.add_subdirectory.find_package_vulkan_headers + COMMAND ${CMAKE_CTEST_COMMAND} + --build-and-test ${CMAKE_CURRENT_LIST_DIR}/integration + ${CMAKE_CURRENT_BINARY_DIR}/add_subdirectory/find_package_vulkan_headers + --build-generator ${CMAKE_GENERATOR} + --build-options -DADD_SUBDIRECTORY_TESTING=ON -DCMAKE_PREFIX_PATH=${vulkan_headers_install_dir} + ) + + # Test find_package suppport using find_package(VulkanHeaders) + add_test(NAME integration.find_package.find_package_vulkan_headers + COMMAND ${CMAKE_CTEST_COMMAND} + --build-and-test ${CMAKE_CURRENT_LIST_DIR}/integration + ${CMAKE_CURRENT_BINARY_DIR}/find_package/find_package_vulkan_headers + --build-generator ${CMAKE_GENERATOR} + --build-options -DFIND_PACKAGE_TESTING=ON "-DCMAKE_PREFIX_PATH=${vulkan_headers_install_dir};${test_install_dir}" + ) + + set_tests_properties(integration.find_package.find_package_vulkan_headers PROPERTIES DEPENDS integration.install) +endif() + + +find_package(Vulkan) +if (Vulkan_FOUND) + # Test add_subdirectory suppport using find_package(Vulkan) + add_test(NAME integration.add_subdirectory.find_package_vulkan + COMMAND ${CMAKE_CTEST_COMMAND} + --build-and-test ${CMAKE_CURRENT_LIST_DIR}/integration + ${CMAKE_CURRENT_BINARY_DIR}/add_subdirectory/find_package_vulkan + --build-generator ${CMAKE_GENERATOR} + --build-options -DADD_SUBDIRECTORY_TESTING=ON -DFIND_PACKAGE_VULKAN=ON + ) + + # Test find_package suppport using find_package(Vulkan) + add_test(NAME integration.find_package.find_package_vulkan + COMMAND ${CMAKE_CTEST_COMMAND} + --build-and-test ${CMAKE_CURRENT_LIST_DIR}/integration + ${CMAKE_CURRENT_BINARY_DIR}/find_package/find_package_vulkan + --build-generator ${CMAKE_GENERATOR} + --build-options -DFIND_PACKAGE_TESTING=ON -DCMAKE_PREFIX_PATH=${test_install_dir} -DFIND_PACKAGE_VULKAN=ON + ) + + set_tests_properties(integration.find_package.find_package_vulkan PROPERTIES DEPENDS integration.install) +endif() diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/tests/bootstrap_tests.cpp b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/bootstrap_tests.cpp new file mode 100644 index 0000000..4c2b2fd --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/bootstrap_tests.cpp @@ -0,0 +1,926 @@ +#include "vulkan_library_loader.hpp" + +#include "vulkan_mock.hpp" +#include "vulkan_mock_setup.hpp" + +// TODO +// changing present modes and/or image formats + +TEST_CASE("Instance with surface", "[VkBootstrap.bootstrap]") { + VulkanMock& mock = get_and_setup_default(); + mock.api_version = VK_API_VERSION_1_1; + mock.physical_devices_details[0].properties.apiVersion = VK_API_VERSION_1_1; + mock.physical_devices_details[0].extensions.push_back(get_extension_properties("VK_KHR_multiview")); + mock.physical_devices_details[0].extensions.push_back(get_extension_properties("VK_KHR_driver_properties")); + mock.physical_devices_details[0].extensions.push_back(get_extension_properties("VK_EXT_robustness2")); + auto surface = mock.get_new_surface(get_basic_surface_details()); + GIVEN("A window and a vulkan instance") { + + auto sys_info_ret = vkb::SystemInfo::get_system_info(); + REQUIRE(sys_info_ret); + + vkb::InstanceBuilder instance_builder; + auto instance_ret = instance_builder.require_api_version(1, 1, 0) + .set_minimum_instance_version(1, 0, 0) + .use_default_debug_messenger() + .build(); + REQUIRE(instance_ret); + vkb::Instance instance = instance_ret.value(); + + GIVEN("A default selected physical device") { + vkb::PhysicalDeviceSelector phys_device_selector(instance); + auto phys_device_ret = phys_device_selector.set_surface(surface).select(); + REQUIRE(phys_device_ret); + vkb::PhysicalDevice physical_device = phys_device_ret.value(); + + GIVEN("A device created with default parameters") { + vkb::DeviceBuilder device_builder(physical_device); + auto device_ret = device_builder.build(); + REQUIRE(device_ret); + vkb::Device device = device_ret.value(); + + // possible swapchain creation... + + vkb::destroy_device(device); + } + } + + THEN("Can select physical device with customized requirements") { + vkb::PhysicalDeviceSelector selector(instance); + auto phys_dev_ret = selector.set_surface(surface) + .add_desired_extension(VK_KHR_MULTIVIEW_EXTENSION_NAME) + .add_required_extension(VK_KHR_DRIVER_PROPERTIES_EXTENSION_NAME) + .set_minimum_version(1, 0) + .select(); + REQUIRE(phys_dev_ret.has_value()); + + REQUIRE(phys_dev_ret->is_extension_present(VK_KHR_DRIVER_PROPERTIES_EXTENSION_NAME)); + REQUIRE(!phys_dev_ret->is_extension_present(VK_KHR_16BIT_STORAGE_EXTENSION_NAME)); + + REQUIRE(phys_dev_ret->enable_extension_if_present(VK_EXT_ROBUSTNESS_2_EXTENSION_NAME)); + REQUIRE(!phys_dev_ret->enable_extension_if_present(VK_KHR_16BIT_STORAGE_EXTENSION_NAME)); + + const std::vector extension_set_1 = { VK_KHR_DRIVER_PROPERTIES_EXTENSION_NAME, + VK_EXT_ROBUSTNESS_2_EXTENSION_NAME }; + const std::vector extension_set_2 = { VK_KHR_16BIT_STORAGE_EXTENSION_NAME, + VK_KHR_DRIVER_PROPERTIES_EXTENSION_NAME }; + + REQUIRE(phys_dev_ret->enable_extensions_if_present(extension_set_1)); + REQUIRE(!phys_dev_ret->enable_extensions_if_present(extension_set_2)); + + auto device_ret = vkb::DeviceBuilder(phys_dev_ret.value()).build(); + REQUIRE(device_ret.has_value()); + vkb::destroy_device(device_ret.value()); + } + + vkb::destroy_surface(instance, surface); + vkb::destroy_instance(instance); + } + GIVEN("Two Instances") { + vkb::InstanceBuilder instance_builder1; + auto instance_ret1 = instance_builder1.use_default_debug_messenger().build(); + REQUIRE(instance_ret1); + vkb::InstanceBuilder instance_builder2; + auto instance_ret2 = instance_builder2.use_default_debug_messenger().build(); + REQUIRE(instance_ret2); + + vkb::destroy_instance(instance_ret1.value()); + vkb::destroy_instance(instance_ret2.value()); + } +} + +TEST_CASE("instance configuration", "[VkBootstrap.bootstrap]") { + [[maybe_unused]] VulkanMock& mock = get_and_setup_default(); + SECTION("custom debug callback") { + vkb::InstanceBuilder builder; + + auto instance_ret = builder.request_validation_layers() + .set_app_name("test app") + .set_app_version(1, 0, 0) + .set_engine_name("engine_name") + .set_engine_version(9, 9, 9) + .set_debug_callback([](VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, + VkDebugUtilsMessageTypeFlagsEXT messageType, + const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, + void* + /*pUserData*/) -> VkBool32 { + auto ms = vkb::to_string_message_severity(messageSeverity); + auto mt = vkb::to_string_message_type(messageType); + printf("[%s: %s](user defined)\n%s\n", ms, mt, pCallbackData->pMessage); + return VK_FALSE; + }) + .build(); + + REQUIRE(instance_ret.has_value()); + + vkb::destroy_instance(instance_ret.value()); + } + SECTION("Validation configuration") { + vkb::InstanceBuilder builder; + + auto instance_ret = + builder.request_validation_layers() + .require_api_version(1, 0, 34) + .use_default_debug_messenger() + .add_validation_feature_enable(VkValidationFeatureEnableEXT::VK_VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_EXT) + .add_validation_feature_disable(VkValidationFeatureDisableEXT::VK_VALIDATION_FEATURE_DISABLE_OBJECT_LIFETIMES_EXT) + .add_validation_disable(VkValidationCheckEXT::VK_VALIDATION_CHECK_SHADERS_EXT) + .build(); + REQUIRE(instance_ret.has_value()); + vkb::destroy_instance(instance_ret.value()); + } +} + +TEST_CASE("Headless Vulkan", "[VkBootstrap.bootstrap]") { + [[maybe_unused]] VulkanMock& mock = get_and_setup_default(); + auto instance = get_headless_instance(); + + vkb::PhysicalDeviceSelector phys_device_selector(instance); + auto phys_device_ret = phys_device_selector.select(); + REQUIRE(phys_device_ret.has_value()); + auto phys_device = phys_device_ret.value(); + + vkb::DeviceBuilder device_builder(phys_device); + auto device_ret = device_builder.build(); + REQUIRE(device_ret.has_value()); + vkb::destroy_device(device_ret.value()); + + vkb::destroy_instance(instance); +} + +TEST_CASE("Device Configuration", "[VkBootstrap.bootstrap]") { + VulkanMock& mock = get_and_setup_default(); + mock.api_version = VK_API_VERSION_1_1; + mock.physical_devices_details[0].properties.apiVersion = VK_API_VERSION_1_1; + auto instance = get_instance(1); + auto surface = mock.get_new_surface(get_basic_surface_details()); + + vkb::PhysicalDeviceSelector phys_device_selector(instance); + + auto phys_device_ret = phys_device_selector.set_minimum_version(1, 1).set_surface(surface).select(); + REQUIRE(phys_device_ret.has_value()); + auto phys_device = phys_device_ret.value(); + + + SECTION("Custom queue setup") { + std::vector queue_descriptions; + auto queue_families = phys_device.get_queue_families(); + for (uint32_t i = 0; i < (uint32_t)queue_families.size(); i++) { + if (queue_families[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) { + queue_descriptions.push_back( + vkb::CustomQueueDescription(i, std::vector(queue_families[i].queueCount, 1.0f))); + } + } + if (phys_device.has_dedicated_compute_queue()) { + for (uint32_t i = 0; i < (uint32_t)queue_families.size(); i++) { + if ((queue_families[i].queueFlags & VK_QUEUE_COMPUTE_BIT) && + (queue_families[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) == 0 && + (queue_families[i].queueFlags & VK_QUEUE_TRANSFER_BIT) == 0) + queue_descriptions.push_back( + vkb::CustomQueueDescription(i, std::vector(queue_families[i].queueCount, 1.0f))); + } + } else if (phys_device.has_separate_compute_queue()) { + for (uint32_t i = 0; i < (uint32_t)queue_families.size(); i++) { + if ((queue_families[i].queueFlags & VK_QUEUE_COMPUTE_BIT) && + ((queue_families[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) == 0)) { + queue_descriptions.push_back( + vkb::CustomQueueDescription(i, std::vector(queue_families[i].queueCount, 1.0f))); + } + } + } + + vkb::DeviceBuilder device_builder(phys_device); + auto device_ret = device_builder.custom_queue_setup(queue_descriptions).build(); + REQUIRE(device_ret.has_value()); + vkb::destroy_device(device_ret.value()); + } + + SECTION("VkPhysicalDeviceFeatures2 in pNext Chain") { + VkPhysicalDeviceShaderDrawParameterFeatures shader_draw_features{}; + shader_draw_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETER_FEATURES; + + vkb::DeviceBuilder device_builder(phys_device_ret.value()); + auto device_ret = device_builder.add_pNext(&shader_draw_features).build(); + REQUIRE(device_ret.has_value()); + vkb::destroy_device(device_ret.value()); + } + + vkb::destroy_surface(instance, surface); + vkb::destroy_instance(instance); +} + + +TEST_CASE("Select all Physical Devices", "[VkBootstrap.bootstrap]") { + VulkanMock& mock = get_and_setup_default(); + mock.api_version = VK_API_VERSION_1_1; + mock.physical_devices_details[0].properties.apiVersion = VK_API_VERSION_1_1; + std::copy_n("mocking_gpus_for_fun_and_profit", VK_MAX_DRIVER_NAME_SIZE, mock.physical_devices_details[0].properties.deviceName); + + auto instance = get_instance(1); + auto surface = mock.get_new_surface(get_basic_surface_details()); + + auto instance_dispatch_table = instance.make_table(); + // needs to successfully create an instance dispatch table + REQUIRE(instance_dispatch_table.fp_vkEnumeratePhysicalDevices); + + + vkb::PhysicalDeviceSelector phys_device_selector(instance, surface); + + auto phys_device_ret = phys_device_selector.select_devices(); + REQUIRE(phys_device_ret.has_value()); + auto phys_devices = phys_device_ret.value(); + + REQUIRE(phys_devices.at(0).name.size() > 0); + + auto phys_device_names_ret = phys_device_selector.select_device_names(); + REQUIRE(phys_device_names_ret.has_value()); + REQUIRE(phys_device_names_ret.value().at(0).size() > 0); + + vkb::DeviceBuilder device_builder(phys_devices.at(0)); + auto device_ret = device_builder.build(); + REQUIRE(device_ret.has_value()); + auto dispatch_table = device_ret.value().make_table(); + // needs to successfully create a dispatch table + REQUIRE(dispatch_table.fp_vkCreateCommandPool); +} + +TEST_CASE("Loading Dispatch Table", "[VkBootstrap.bootstrap]") { + [[maybe_unused]] VulkanMock& mock = get_and_setup_default(); + auto instance = get_headless_instance(0); + { + vkb::PhysicalDeviceSelector selector(instance); + auto phys_dev_ret = selector.select_first_device_unconditionally().select(); + REQUIRE(phys_dev_ret.has_value()); + + vkb::DeviceBuilder device_builder(phys_dev_ret.value()); + auto device_ret = device_builder.build(); + REQUIRE(device_ret.has_value()); + auto dispatch_table = device_ret.value().make_table(); + + // Create a basic Device specific type to test with + VkFenceCreateInfo info{}; + info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; + + VkFence fence = VK_NULL_HANDLE; + dispatch_table.createFence(&info, nullptr, &fence); + REQUIRE(fence != VK_NULL_HANDLE); + + dispatch_table.destroyFence(fence, nullptr); + vkb::destroy_device(device_ret.value()); + } + vkb::destroy_instance(instance); +} + +TEST_CASE("Swapchain", "[VkBootstrap.bootstrap]") { + VulkanMock& mock = get_and_setup_default(); + mock.api_version = VK_API_VERSION_1_1; + mock.physical_devices_details[0].properties.apiVersion = VK_API_VERSION_1_1; + auto surface = mock.get_new_surface(get_basic_surface_details()); + GIVEN("A working instance, window, surface, and device") { + auto instance = get_instance(1); + + vkb::PhysicalDeviceSelector phys_device_selector(instance); + auto phys_device_ret = phys_device_selector.set_surface(surface).select(); + REQUIRE(phys_device_ret.has_value()); + auto phys_device = phys_device_ret.value(); + + vkb::DeviceBuilder device_builder(phys_device); + auto device_ret = device_builder.build(); + REQUIRE(device_ret.has_value()); + vkb::Device device = device_ret.value(); + + auto graphics_queue_index = device.get_queue_index(vkb::QueueType::graphics).value(); + auto present_queue_index = device.get_queue_index(vkb::QueueType::present).value(); + + THEN("Swapchain can be made") { + vkb::SwapchainBuilder swapchain_builder(device); + auto swapchain_ret = swapchain_builder.build(); + REQUIRE(swapchain_ret.has_value()); + auto swapchain = swapchain_ret.value(); + + THEN("Acquire swapchain images and views") { + auto images = swapchain.get_images(); + REQUIRE(images.has_value()); + REQUIRE(images.value().size() > 0); + + auto image_views = swapchain.get_image_views(); + REQUIRE(image_views.has_value()); + REQUIRE(image_views.value().size() > 0); + swapchain.destroy_image_views(image_views.value()); + } + AND_THEN("Acquire swapchain images views with nullptr pNext chain") { + auto image_views = swapchain.get_image_views(nullptr); + REQUIRE(image_views.has_value()); + REQUIRE(image_views.value().size() > 0); + swapchain.destroy_image_views(image_views.value()); + } + AND_THEN("Acquire swapchain image views with valid pNext chain") { + VkImageViewUsageCreateInfo usage = { VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO, nullptr, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT }; + auto image_views = swapchain.get_image_views(&usage); + REQUIRE(image_views.has_value()); + REQUIRE(image_views.value().size() > 0); + swapchain.destroy_image_views(image_views.value()); + } + + vkb::destroy_swapchain(swapchain_ret.value()); + } + + AND_THEN("Swapchain configuration") { + vkb::SwapchainBuilder swapchain_builder(device); + auto swapchain_ret = swapchain_builder.set_desired_extent(256, 256) + .set_desired_format({ VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR }) + .set_desired_present_mode(VK_PRESENT_MODE_IMMEDIATE_KHR) + .set_pre_transform_flags(VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) + .set_composite_alpha_flags(VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR) + .set_clipped(false) + .set_image_array_layer_count(1) + .build(); + REQUIRE(swapchain_ret.has_value()); + + vkb::destroy_swapchain(swapchain_ret.value()); + } + AND_THEN("Swapchain defaults can be used") { + vkb::SwapchainBuilder swapchain_builder(device); + auto swapchain_ret = swapchain_builder.use_default_format_selection() + .use_default_present_mode_selection() + .use_default_image_usage_flags() + .build(); + REQUIRE(swapchain_ret.has_value()); + + vkb::destroy_swapchain(swapchain_ret.value()); + } + AND_THEN("Swapchain can be recreated") { + vkb::SwapchainBuilder swapchain_builder(device); + auto swapchain_ret = swapchain_builder.build(); + REQUIRE(swapchain_ret.has_value()); + + auto swapchain = swapchain_ret.value(); + + auto recreated_swapchain_ret = swapchain_builder.set_old_swapchain(swapchain).build(); + REQUIRE(recreated_swapchain_ret.has_value()); + + vkb::destroy_swapchain(swapchain_ret.value()); + vkb::destroy_swapchain(recreated_swapchain_ret.value()); + } + AND_THEN("Swapchain can be created from individual handles") { + vkb::SwapchainBuilder swapchain_builder( + device.physical_device.physical_device, device.device, surface, graphics_queue_index, present_queue_index); + auto swapchain_ret = swapchain_builder.build(); + REQUIRE(swapchain_ret.has_value()); + + auto swapchain = swapchain_ret.value(); + + auto recreated_swapchain_ret = swapchain_builder.set_old_swapchain(swapchain).build(); + REQUIRE(recreated_swapchain_ret.has_value()); + + vkb::destroy_swapchain(swapchain_ret.value()); + vkb::destroy_swapchain(recreated_swapchain_ret.value()); + } + AND_THEN("Swapchain can be create with default gotten handles") { + vkb::SwapchainBuilder swapchain_builder(device.physical_device.physical_device, device.device, surface); + auto swapchain_ret = swapchain_builder.build(); + REQUIRE(swapchain_ret.has_value()); + + auto swapchain = swapchain_ret.value(); + + auto recreated_swapchain_ret = swapchain_builder.set_old_swapchain(swapchain).build(); + REQUIRE(recreated_swapchain_ret.has_value()); + + vkb::destroy_swapchain(swapchain_ret.value()); + vkb::destroy_swapchain(recreated_swapchain_ret.value()); + } + + vkb::destroy_device(device_ret.value()); + vkb::destroy_surface(instance, surface); + vkb::destroy_instance(instance); + } +} + +void* VKAPI_PTR shim_vkAllocationFunction( + void* /*pUserData*/, size_t size, size_t /*alignment*/, VkSystemAllocationScope /*allocationScope*/) { + return malloc(size); +} +void* VKAPI_PTR shim_vkReallocationFunction( + void* /*pUserData*/, void* pOriginal, size_t size, size_t /*alignment*/, VkSystemAllocationScope /*allocationScope*/) { + return realloc(pOriginal, size); +} +void VKAPI_PTR shim_vkFreeFunction(void* /*pUserData*/, void* pMemory) { return free(pMemory); } + + +TEST_CASE("Allocation Callbacks", "[VkBootstrap.bootstrap]") { + VulkanMock& mock = get_and_setup_default(); + auto surface = mock.get_new_surface(get_basic_surface_details()); + + VkAllocationCallbacks allocation_callbacks{}; + allocation_callbacks.pfnAllocation = &shim_vkAllocationFunction; + allocation_callbacks.pfnReallocation = &shim_vkReallocationFunction; + allocation_callbacks.pfnFree = &shim_vkFreeFunction; + + vkb::InstanceBuilder builder; + + auto instance_ret = builder.request_validation_layers() + .set_allocation_callbacks(&allocation_callbacks) + .use_default_debug_messenger() + .build(); + REQUIRE(instance_ret.has_value()); + + vkb::PhysicalDeviceSelector phys_device_selector(instance_ret.value()); + + auto phys_device_ret = phys_device_selector.set_surface(surface).select(); + REQUIRE(phys_device_ret.has_value()); + auto phys_device = phys_device_ret.value(); + + vkb::DeviceBuilder device_builder(phys_device); + auto device_ret = device_builder.set_allocation_callbacks(&allocation_callbacks).build(); + REQUIRE(device_ret.has_value()); + vkb::Device device = device_ret.value(); + + vkb::SwapchainBuilder swapchain_builder(device); + auto swapchain_ret = swapchain_builder.set_allocation_callbacks(&allocation_callbacks).build(); + REQUIRE(swapchain_ret.has_value()); + // auto swapchain = swapchain_ret.value (); + + vkb::destroy_swapchain(swapchain_ret.value()); + vkb::destroy_device(device_ret.value()); + + vkb::destroy_surface(instance_ret.value(), surface); + vkb::destroy_instance(instance_ret.value()); +} + +TEST_CASE("SystemInfo Loading Vulkan Automatically", "[VkBootstrap.loading]") { + [[maybe_unused]] VulkanMock& mock = get_and_setup_default(); + auto info_ret = vkb::SystemInfo::get_system_info(); + REQUIRE(info_ret); + vkb::InstanceBuilder builder; + auto ret = builder.build(); + REQUIRE(ret); +} + +TEST_CASE("SystemInfo Loading Vulkan Manually", "[VkBootstrap.loading]") { + [[maybe_unused]] VulkanMock& mock = get_and_setup_default(); + VulkanLibrary vk_lib; + REQUIRE(vk_lib.vkGetInstanceProcAddr); + auto info_ret = vkb::SystemInfo::get_system_info(vk_lib.vkGetInstanceProcAddr); + REQUIRE(info_ret); + vkb::InstanceBuilder builder; + auto ret = builder.build(); + REQUIRE(ret); + vk_lib.close(); +} + +TEST_CASE("InstanceBuilder Loading Vulkan Automatically", "[VkBootstrap.loading]") { + [[maybe_unused]] VulkanMock& mock = get_and_setup_default(); + vkb::InstanceBuilder builder; + auto ret = builder.build(); + REQUIRE(ret); +} + +TEST_CASE("InstanceBuilder Loading Vulkan Manually", "[VkBootstrap.loading]") { + [[maybe_unused]] VulkanMock& mock = get_and_setup_default(); + VulkanLibrary vk_lib; + REQUIRE(vk_lib.vkGetInstanceProcAddr); + vkb::InstanceBuilder builder{ vk_lib.vkGetInstanceProcAddr }; + auto ret = builder.build(); + vk_lib.close(); +} +TEST_CASE("ReLoading Vulkan Automatically", "[VkBootstrap.loading]") { + [[maybe_unused]] VulkanMock& mock = get_and_setup_default(); + { + vkb::InstanceBuilder builder; + auto ret = builder.build(); + REQUIRE(ret); + } + { + vkb::InstanceBuilder builder; + auto ret = builder.build(); + REQUIRE(ret); + } +} + +TEST_CASE("ReLoading Vulkan Manually", "[VkBootstrap.loading]") { + [[maybe_unused]] VulkanMock& mock = get_and_setup_default(); + { + VulkanLibrary vk_lib; + REQUIRE(vk_lib.vkGetInstanceProcAddr); + vkb::InstanceBuilder builder{ vk_lib.vkGetInstanceProcAddr }; + auto ret = builder.build(); + REQUIRE(ret); + vk_lib.close(); + } + { + VulkanLibrary vk_lib; + REQUIRE(vk_lib.vkGetInstanceProcAddr); + vkb::InstanceBuilder builder{ vk_lib.vkGetInstanceProcAddr }; + auto ret = builder.build(); + REQUIRE(ret); + vk_lib.close(); + } +} + +TEST_CASE("Querying Required Extension Features but with 1.0", "[VkBootstrap.select_features]") { + VulkanMock& mock = get_and_setup_default(); + mock.instance_extensions.push_back(get_extension_properties("VK_KHR_get_physical_device_properties2")); + mock.physical_devices_details[0].extensions.push_back(get_extension_properties("VK_EXT_descriptor_indexing")); + mock.physical_devices_details[0].extensions.push_back(get_extension_properties("VK_KHR_maintenance3")); + auto mock_descriptor_indexing_features = VkPhysicalDeviceDescriptorIndexingFeaturesEXT{}; + mock_descriptor_indexing_features.runtimeDescriptorArray = true; + mock.physical_devices_details[0].add_features_pNext_struct(mock_descriptor_indexing_features); + GIVEN("A working instance") { + auto instance = get_headless_instance(); + // Requires a device that supports runtime descriptor arrays via descriptor indexing extension. + { + VkPhysicalDeviceDescriptorIndexingFeaturesEXT descriptor_indexing_features{}; + descriptor_indexing_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES_EXT; + descriptor_indexing_features.runtimeDescriptorArray = true; + + vkb::PhysicalDeviceSelector selector(instance); + auto phys_dev_ret = selector.add_required_extension(VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME) + .add_required_extension(VK_KHR_MAINTENANCE3_EXTENSION_NAME) + .add_required_extension_features(descriptor_indexing_features) + .select(); + REQUIRE(phys_dev_ret.has_value()); + + vkb::DeviceBuilder device_builder(phys_dev_ret.value()); + auto device_ret = device_builder.build(); + REQUIRE(device_ret.has_value()); + vkb::destroy_device(device_ret.value()); + } + vkb::destroy_instance(instance); + } +} +TEST_CASE("Querying Required Extension Features", "[VkBootstrap.select_features]") { + VulkanMock& mock = get_and_setup_default(); + mock.instance_extensions.push_back(get_extension_properties("VK_KHR_get_physical_device_properties2")); + mock.physical_devices_details[0].extensions.push_back(get_extension_properties("VK_EXT_descriptor_indexing")); + mock.physical_devices_details[0].extensions.push_back(get_extension_properties("VK_KHR_maintenance3")); + auto mock_descriptor_indexing_features = VkPhysicalDeviceDescriptorIndexingFeaturesEXT{}; + mock_descriptor_indexing_features.runtimeDescriptorArray = true; + mock.physical_devices_details[0].add_features_pNext_struct(mock_descriptor_indexing_features); + GIVEN("A working instance") { + auto instance = get_headless_instance(); + // Requires a device that supports runtime descriptor arrays via descriptor indexing extension. + { + VkPhysicalDeviceDescriptorIndexingFeaturesEXT descriptor_indexing_features{}; + descriptor_indexing_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES_EXT; + descriptor_indexing_features.runtimeDescriptorArray = true; + + vkb::PhysicalDeviceSelector selector(instance); + auto phys_dev_ret = selector.add_required_extension(VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME) + .add_required_extension(VK_KHR_MAINTENANCE3_EXTENSION_NAME) + .add_required_extension_features(descriptor_indexing_features) + .select(); + REQUIRE(phys_dev_ret.has_value()); + + REQUIRE(phys_dev_ret.value().are_extension_features_present(descriptor_indexing_features)); + + vkb::DeviceBuilder device_builder(phys_dev_ret.value()); + auto device_ret = device_builder.build(); + REQUIRE(device_ret.has_value()); + vkb::destroy_device(device_ret.value()); + } + vkb::destroy_instance(instance); + } +} + +TEST_CASE("Adding Optional Extension Features", "[VkBootstrap.enable_features_if_present]") { + VulkanMock& mock = get_and_setup_default(); + mock.api_version = VK_API_VERSION_1_1; + mock.physical_devices_details[0].properties.apiVersion = VK_API_VERSION_1_1; + mock.instance_extensions.push_back(get_extension_properties("VK_KHR_get_physical_device_properties2")); + auto vulkan_10_features = VkPhysicalDeviceFeatures{}; + vulkan_10_features.multiViewport = true; + mock.physical_devices_details[0].features = vulkan_10_features; + + auto vulkan_11_features = VkPhysicalDeviceVulkan11Features{}; + vulkan_11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES; + vulkan_11_features.shaderDrawParameters = true; + mock.physical_devices_details[0].add_features_pNext_struct(vulkan_11_features); + + auto vulkan_12_features = VkPhysicalDeviceVulkan12Features{}; + // Forget to set this sType - let vk-bootstrap deal with it + vulkan_12_features.bufferDeviceAddress = true; + mock.physical_devices_details[0].add_features_pNext_struct(vulkan_12_features); + + + GIVEN("A working instance and physical device which has a VkPhysicalDeviceVulkan12Features in its features pNext " + "chain") { + auto instance = get_headless_instance(); + + VkPhysicalDeviceVulkan12Features physical_device_features_12{}; + physical_device_features_12.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES; + physical_device_features_12.bufferDeviceAddress = true; + + vkb::PhysicalDeviceSelector selector(instance); + selector.add_required_extension_features(physical_device_features_12); + { + + SECTION("Require enable_features_if_present to work with an empty feature struct") { + auto phys_dev = selector.select().value(); + VkPhysicalDeviceFeatures phys_dev_features_empty{}; + REQUIRE(phys_dev.enable_features_if_present(phys_dev_features_empty)); + auto device = vkb::DeviceBuilder(phys_dev).build().value(); + vkb::destroy_device(device); + } + SECTION("Require enable_features_if_present to fail with an unsupported feature struct") { + auto phys_dev = selector.select().value(); + VkPhysicalDeviceFeatures phys_dev_features_bad{}; + phys_dev_features_bad.depthClamp = true; + REQUIRE(!phys_dev.enable_features_if_present(phys_dev_features_bad)); + auto device = vkb::DeviceBuilder(phys_dev).build().value(); + REQUIRE(!mock.physical_devices_details.at(0).created_device_details.at(0).features.depthClamp); + vkb::destroy_device(device); + } + SECTION("Require enable_features_if_present to work with a supported feature struct") { + auto phys_dev = selector.select().value(); + VkPhysicalDeviceFeatures phys_dev_features_good{}; + phys_dev_features_good.multiViewport = true; + REQUIRE(phys_dev.enable_features_if_present(phys_dev_features_good)); + auto device = vkb::DeviceBuilder(phys_dev).build().value(); + REQUIRE(mock.physical_devices_details.at(0).created_device_details.at(0).features.multiViewport); + vkb::destroy_device(device); + } + + SECTION("Require enable_extension_features_if_present to work with an empty 1.1 feature struct") { + auto phys_dev = selector.select().value(); + VkPhysicalDeviceVulkan11Features phys_dev_vulkan_11_features{}; + phys_dev_vulkan_11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES; + REQUIRE(phys_dev.enable_extension_features_if_present(phys_dev_vulkan_11_features)); + auto device = vkb::DeviceBuilder(phys_dev).build().value(); + vkb::destroy_device(device); + } + SECTION("Require enable_extension_features_if_present to fail with an unsupported 1.1 feature struct") { + auto phys_dev = selector.select().value(); + VkPhysicalDeviceVulkan11Features phys_dev_vulkan_11_features{}; + phys_dev_vulkan_11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES; + phys_dev_vulkan_11_features.multiview = true; + REQUIRE(!phys_dev.enable_extension_features_if_present(phys_dev_vulkan_11_features)); + auto device = vkb::DeviceBuilder(phys_dev).build().value(); + auto* s = reinterpret_cast( + &mock.physical_devices_details.at(0).created_device_details.at(0).features_pNextChain.at(0)); + REQUIRE(s->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES); + vkb::destroy_device(device); + } + SECTION("Require enable_extension_features_if_present to work with a supported 1.1 feature struct") { + auto phys_dev = selector.select().value(); + VkPhysicalDeviceVulkan11Features phys_dev_vulkan_11_features{}; + phys_dev_vulkan_11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES; + phys_dev_vulkan_11_features.shaderDrawParameters = true; + REQUIRE(phys_dev.enable_extension_features_if_present(phys_dev_vulkan_11_features)); + auto device = vkb::DeviceBuilder(phys_dev).build().value(); + auto* s = reinterpret_cast( + &mock.physical_devices_details.at(0).created_device_details.at(0).features_pNextChain.at(1)); + REQUIRE(s->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES); + REQUIRE(s->shaderDrawParameters); + vkb::destroy_device(device); + } + } + vkb::destroy_instance(instance); + } +} + +TEST_CASE("Passing vkb classes to Vulkan handles", "[VkBootstrap.pass_class_to_handle]") { + VulkanMock& mock = get_and_setup_default(); + auto surface = mock.get_new_surface(get_basic_surface_details()); + GIVEN("A working instance") { + auto instance = get_instance(); + + // Check if we can get instance functions. + PFN_vkVoidFunction instanceFunction = instance.fp_vkGetInstanceProcAddr(instance, "vkEnumeratePhysicalDevices"); // validation layers should be provided. + REQUIRE(instanceFunction); + + vkb::PhysicalDeviceSelector physicalDeviceSelector(instance); + auto physicalDevice = + physicalDeviceSelector.add_required_extension(VK_KHR_SWAPCHAIN_EXTENSION_NAME).set_surface(surface).select(); + REQUIRE(physicalDevice.has_value()); + vkb::DeviceBuilder deviceBuilder(physicalDevice.value()); + auto device = deviceBuilder.build(); + REQUIRE(device.has_value()); + + // Check if we can get a device function address, passing vkb::Device to the function. + PFN_vkVoidFunction deviceFunction = instance.fp_vkGetDeviceProcAddr(device.value(), "vkAcquireNextImageKHR"); + REQUIRE(deviceFunction); + } +} + +TEST_CASE("Querying Required Extension Features in 1.1", "[VkBootstrap.version]") { + VulkanMock& mock = get_and_setup_default(); + mock.instance_extensions.push_back(get_extension_properties("VK_KHR_get_physical_device_properties2")); + mock.physical_devices_details[0].extensions.push_back(get_extension_properties("VK_EXT_descriptor_indexing")); + mock.physical_devices_details[0].extensions.push_back(get_extension_properties("VK_KHR_maintenance3")); + auto mock_descriptor_indexing_features = VkPhysicalDeviceDescriptorIndexingFeaturesEXT{}; + mock_descriptor_indexing_features.runtimeDescriptorArray = true; + mock.physical_devices_details[0].add_features_pNext_struct(mock_descriptor_indexing_features); + GIVEN("A working instance") { + auto instance = get_headless_instance(); + SECTION("Requires a device that supports runtime descriptor arrays via descriptor indexing extension.") { + VkPhysicalDeviceDescriptorIndexingFeaturesEXT descriptor_indexing_features{}; + descriptor_indexing_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES_EXT; + descriptor_indexing_features.runtimeDescriptorArray = true; + + vkb::PhysicalDeviceSelector selector(instance); + auto phys_dev_ret = selector.add_required_extension(VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME) + .add_required_extension(VK_KHR_MAINTENANCE3_EXTENSION_NAME) + .add_required_extension_features(descriptor_indexing_features) + .select(); + REQUIRE(phys_dev_ret.has_value()); + + REQUIRE(phys_dev_ret.value().are_extension_features_present(descriptor_indexing_features)); + + VkPhysicalDeviceASTCDecodeFeaturesEXT astc_features{}; + astc_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ASTC_DECODE_FEATURES_EXT; + astc_features.decodeModeSharedExponent = true; + REQUIRE(!phys_dev_ret.value().are_extension_features_present(astc_features)); + + VkPhysicalDeviceDescriptorIndexingFeaturesEXT unsupported_descriptor_indexing_features{}; + unsupported_descriptor_indexing_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES_EXT; + unsupported_descriptor_indexing_features.runtimeDescriptorArray = true; + unsupported_descriptor_indexing_features.descriptorBindingUniformTexelBufferUpdateAfterBind = true; + REQUIRE(!phys_dev_ret.value().are_extension_features_present(unsupported_descriptor_indexing_features)); + + vkb::DeviceBuilder device_builder(phys_dev_ret.value()); + auto device_ret = device_builder.build(); + REQUIRE(device_ret.has_value()); + vkb::destroy_device(device_ret.value()); + } + SECTION("Add a custom VkPhysicalDeviceFeatures2 pNext chain to the DeviceBuilder, without using " + "add_required_extension_features()") { + VkPhysicalDeviceDescriptorIndexingFeaturesEXT descriptor_indexing_features{}; + descriptor_indexing_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES_EXT; + descriptor_indexing_features.runtimeDescriptorArray = true; + + vkb::PhysicalDeviceSelector selector(instance); + auto phys_dev_ret = selector.add_required_extension(VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME) + .add_required_extension(VK_KHR_MAINTENANCE3_EXTENSION_NAME) + .select(); + REQUIRE(phys_dev_ret.has_value()); + + REQUIRE(!phys_dev_ret.value().are_extension_features_present(descriptor_indexing_features)); + + VkPhysicalDeviceASTCDecodeFeaturesEXT astc_features{}; + astc_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ASTC_DECODE_FEATURES_EXT; + astc_features.decodeModeSharedExponent = true; + REQUIRE(!phys_dev_ret.value().are_extension_features_present(astc_features)); + + VkPhysicalDeviceFeatures2 phys_dev_feats2{}; + phys_dev_feats2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2; + phys_dev_feats2.pNext = reinterpret_cast(&descriptor_indexing_features); + + vkb::DeviceBuilder device_builder(phys_dev_ret.value()); + auto device_ret = device_builder.add_pNext(&phys_dev_feats2).build(); + REQUIRE(device_ret.has_value()); + vkb::destroy_device(device_ret.value()); + } + SECTION( + "Try to add a custom VkPhysicalDeviceFeatures2 pNext chain to the DeviceBuilder, resulting in an error") { + VkPhysicalDeviceDescriptorIndexingFeaturesEXT descriptor_indexing_features{}; + descriptor_indexing_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES_EXT; + descriptor_indexing_features.runtimeDescriptorArray = true; + + vkb::PhysicalDeviceSelector selector(instance); + auto phys_dev_ret = selector.add_required_extension(VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME) + .add_required_extension(VK_KHR_MAINTENANCE3_EXTENSION_NAME) + .add_required_extension_features(descriptor_indexing_features) + .select(); + REQUIRE(phys_dev_ret.has_value()); + + REQUIRE(phys_dev_ret.value().are_extension_features_present(descriptor_indexing_features)); + + VkPhysicalDeviceFeatures2 phys_dev_feats2{}; + phys_dev_feats2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2; + phys_dev_feats2.pNext = reinterpret_cast(&descriptor_indexing_features); + + vkb::DeviceBuilder device_builder(phys_dev_ret.value()); + auto device_ret = device_builder.add_pNext(&phys_dev_feats2).build(); + REQUIRE(device_ret.error() == + vkb::DeviceError::VkPhysicalDeviceFeatures2_in_pNext_chain_while_using_add_required_extension_features); + } + + vkb::destroy_instance(instance); + } +} + +TEST_CASE("Querying Vulkan 1.1 and 1.2 features", "[VkBootstrap.version]") { + VulkanMock& mock = get_and_setup_default(); + mock.api_version = VK_API_VERSION_1_2; + mock.physical_devices_details[0].properties.apiVersion = VK_API_VERSION_1_2; + + auto mock_vulkan_11_features = VkPhysicalDeviceVulkan11Features{}; + mock_vulkan_11_features.multiview = true; + mock.physical_devices_details[0].add_features_pNext_struct(mock_vulkan_11_features); + + auto mock_vulkan_12_features = VkPhysicalDeviceVulkan12Features{}; + mock_vulkan_12_features.bufferDeviceAddress = true; + mock.physical_devices_details[0].add_features_pNext_struct(mock_vulkan_12_features); + + GIVEN("A working instance") { + auto instance = get_headless_instance(2); // make sure we use 1.2 + SECTION("Requires a device that supports multiview and bufferDeviceAddress") { + VkPhysicalDeviceVulkan11Features features_11{}; + features_11.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES; + features_11.multiview = true; + VkPhysicalDeviceVulkan12Features features_12{}; + features_12.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES; + features_12.bufferDeviceAddress = true; + + vkb::PhysicalDeviceSelector selector(instance); + auto phys_dev_ret = selector.set_required_features_11(features_11).set_required_features_12(features_12).select(); + REQUIRE(phys_dev_ret.has_value()); + + vkb::DeviceBuilder device_builder(phys_dev_ret.value()); + auto device_ret = device_builder.build(); + REQUIRE(device_ret.has_value()); + auto* s1 = reinterpret_cast( + &mock.physical_devices_details.at(0).created_device_details.at(0).features_pNextChain.at(0)); + REQUIRE(s1->multiview); + auto* s2 = reinterpret_cast( + &mock.physical_devices_details.at(0).created_device_details.at(0).features_pNextChain.at(1)); + REQUIRE(s2->bufferDeviceAddress); + + vkb::destroy_device(device_ret.value()); + } + mock.api_version = VK_API_VERSION_1_1; + mock.physical_devices_details[0].properties.apiVersion = VK_API_VERSION_1_1; + SECTION("protectedMemory should NOT be supported") { + VkPhysicalDeviceVulkan11Features features_11{}; + features_11.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES; + features_11.protectedMemory = true; + + vkb::PhysicalDeviceSelector selector(instance); + auto phys_dev_ret = selector.set_required_features_11(features_11).select(); + REQUIRE(!phys_dev_ret.has_value()); + } + vkb::destroy_instance(instance); + } +} + +TEST_CASE("Add required features in multiple calls", "[VkBootstrap.required_features]") { + VulkanMock& mock = get_and_setup_default(); + mock.api_version = VK_API_VERSION_1_2; + mock.physical_devices_details[0].properties.apiVersion = VK_API_VERSION_1_2; + mock.physical_devices_details[0].features.independentBlend = true; + mock.physical_devices_details[0].features.shaderInt64 = true; + + GIVEN("A working instance") { + auto instance = get_headless_instance(1); // make sure we use 1.1 + SECTION("Requires a device that supports independentBlend and shaderInt64") { + VkPhysicalDeviceFeatures features1{}; + features1.independentBlend = true; + VkPhysicalDeviceFeatures features2{}; + features2.shaderInt64 = true; + + vkb::PhysicalDeviceSelector selector(instance); + auto phys_dev_ret = selector.set_required_features(features1).set_required_features(features2).select(); + REQUIRE(phys_dev_ret.has_value()); + + vkb::DeviceBuilder device_builder(phys_dev_ret.value()); + auto device_ret = device_builder.build(); + REQUIRE(device_ret.has_value()); + + REQUIRE(mock.physical_devices_details.at(0).created_device_details.at(0).features.independentBlend); + REQUIRE(mock.physical_devices_details.at(0).created_device_details.at(0).features.shaderInt64); + + vkb::destroy_device(device_ret.value()); + } + vkb::destroy_instance(instance); + } +} + +TEST_CASE("Add required extension features in multiple calls", "[VkBootstrap.required_features]") { + VulkanMock& mock = get_and_setup_default(); + mock.api_version = VK_API_VERSION_1_2; + mock.physical_devices_details[0].properties.apiVersion = VK_API_VERSION_1_2; + + auto mock_vulkan_11_features = VkPhysicalDeviceVulkan11Features{}; + mock_vulkan_11_features.multiview = true; + mock_vulkan_11_features.samplerYcbcrConversion = true; + mock.physical_devices_details[0].add_features_pNext_struct(mock_vulkan_11_features); + + GIVEN("A working instance") { + auto instance = get_headless_instance(1); // make sure we use 1.1 + SECTION("Requires a device that supports multiview and samplerYcbcrConversion") { + VkPhysicalDeviceVulkan11Features features1{}; + features1.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES; + features1.multiview = true; + + VkPhysicalDeviceVulkan11Features features2{}; + features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES; + features2.samplerYcbcrConversion = true; + + + vkb::PhysicalDeviceSelector selector(instance); + auto phys_dev_ret = selector.set_required_features_11(features1).set_required_features_11(features2).select(); + REQUIRE(phys_dev_ret.has_value()); + + vkb::DeviceBuilder device_builder(phys_dev_ret.value()); + auto device_ret = device_builder.build(); + REQUIRE(device_ret.has_value()); + auto* s1 = reinterpret_cast( + &mock.physical_devices_details.at(0).created_device_details.at(0).features_pNextChain.at(0)); + REQUIRE(s1->multiview); + REQUIRE(s1->samplerYcbcrConversion); + + vkb::destroy_device(device_ret.value()); + } + vkb::destroy_instance(instance); + } +} diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/tests/error_code_tests.cpp b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/error_code_tests.cpp new file mode 100644 index 0000000..619f7e2 --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/error_code_tests.cpp @@ -0,0 +1,88 @@ +#include + +#include "VkBootstrap.h" + +TEST_CASE("is_error_code_enum", "[VkBootstrap.error_code]") { + STATIC_REQUIRE(std::is_error_code_enum::value); + STATIC_REQUIRE(std::is_error_code_enum::value); + STATIC_REQUIRE(std::is_error_code_enum::value); + STATIC_REQUIRE(std::is_error_code_enum::value); + STATIC_REQUIRE(std::is_error_code_enum::value); +} + +TEST_CASE("make_error_code", "[VkBootstrap.error_code]") { + GIVEN("An InstanceError") { + const auto error = vkb::InstanceError::vulkan_unavailable; + + WHEN("Creating an error code from it") { + std::error_code ec = make_error_code(error); + THEN("The error code is equal to the original error") { REQUIRE(ec == error); } + + THEN("The error code is not equal to an unrelated error") { + REQUIRE(ec != vkb::InstanceError::failed_create_instance); + } + + THEN("We can get the error message") { REQUIRE(ec.message() == "vulkan_unavailable"); } + } + } + + GIVEN("A PhysicalDeviceError") { + const auto error = vkb::PhysicalDeviceError::no_physical_devices_found; + + WHEN("Creating an error code from it") { + std::error_code ec = make_error_code(error); + THEN("The error code is equal to the original error") { REQUIRE(ec == error); } + + THEN("The error code is not equal to an unrelated error") { + REQUIRE(ec != vkb::InstanceError::failed_create_instance); + } + + THEN("We can get the error message") { REQUIRE(ec.message() == "no_physical_devices_found"); } + } + } + + GIVEN("A QueueError") { + const auto error = vkb::QueueError::invalid_queue_family_index; + + WHEN("Creating an error code from it") { + std::error_code ec = make_error_code(error); + THEN("The error code is equal to the original error") { REQUIRE(ec == error); } + + THEN("The error code is not equal to an unrelated error") { + REQUIRE(ec != vkb::InstanceError::failed_create_instance); + } + + THEN("We can get the error message") { REQUIRE(ec.message() == "invalid_queue_family_index"); } + } + } + + GIVEN("A DeviceError") { + const auto error = vkb::DeviceError::failed_create_device; + + WHEN("Creating an error code from it") { + std::error_code ec = make_error_code(error); + THEN("The error code is equal to the original error") { REQUIRE(ec == error); } + + THEN("The error code is not equal to an unrelated error") { + REQUIRE(ec != vkb::InstanceError::failed_create_instance); + } + + THEN("We can get the error message") { REQUIRE(ec.message() == "failed_create_device"); } + } + } + + GIVEN("A SwapchainError") { + const auto error = vkb::SwapchainError::failed_create_swapchain; + + WHEN("Creating an error code from it") { + std::error_code ec = make_error_code(error); + THEN("The error code is equal to the original error") { REQUIRE(ec == error); } + + THEN("The error code is not equal to an unrelated error") { + REQUIRE(ec != vkb::InstanceError::failed_create_instance); + } + + THEN("We can get the error message") { REQUIRE(ec.message() == "failed_create_swapchain"); } + } + } +} diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/tests/include_checks.cpp b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/include_checks.cpp new file mode 100644 index 0000000..a19f535 --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/include_checks.cpp @@ -0,0 +1,26 @@ + +// Enable the platform specific parts of the API +#if defined(__ANDROID__) +#define VK_USE_PLATFORM_ANDROID_KHR +#endif + +#if defined(__APPLE__) +#define VK_USE_PLATFORM_IOS_MVK +#define VK_USE_PLATFORM_MACOS_MVK +#define VK_USE_PLATFORM_METAL_EXT +#endif + +#if defined(WIN32) +#define VK_USE_PLATFORM_WIN32_KHR +#endif + +#if defined(__linux__) +#define VK_USE_PLATFORM_WAYLAND_KHR +#define VK_USE_PLATFORM_XCB_KHR +#define VK_USE_PLATFORM_XLIB_KHR +#define VK_USE_PLATFORM_XLIB_XRANDR_EXT +#endif + +#define VK_ENABLE_BETA_EXTENSIONS + +#include "VkBootstrap.h" diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/tests/integration/CMakeLists.txt b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/integration/CMakeLists.txt new file mode 100644 index 0000000..5d16d6d --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/integration/CMakeLists.txt @@ -0,0 +1,41 @@ +cmake_minimum_required(VERSION 3.14.2) + +project(IntegrationTests LANGUAGES CXX) + +if (VULKAN_HEADER_VERSION_GIT_TAG) + include(FetchContent) + FetchContent_Declare( + VulkanHeadersIntegrationTest + GIT_REPOSITORY https://github.com/KhronosGroup/Vulkan-Headers + GIT_TAG ${VULKAN_HEADER_VERSION_GIT_TAG} + ) + FetchContent_MakeAvailable(VulkanHeadersIntegrationTest) + + if (NOT TARGET Vulkan::Headers) + message(FATAL_ERROR "Vulkan::Headers target not defined") + endif() +endif() + +if (FIND_PACKAGE_VULKAN_HEADERS) + find_package(VulkanHeaders REQUIRED) +endif() + +if (FIND_PACKAGE_VULKAN) + find_package(Vulkan REQUIRED) +endif() + +if (ADD_SUBDIRECTORY_TESTING) + add_subdirectory(../.. ${CMAKE_CURRENT_BINARY_DIR}/vk-bootstrap) +endif() + +if (FIND_PACKAGE_TESTING) + find_package(vk-bootstrap CONFIG REQUIRED) +endif() + +if (NOT TARGET vk-bootstrap::vk-bootstrap) + message(FATAL_ERROR "vk-bootstrap::vk-bootstrap target not defined") +endif() + +add_executable(integration_test integration_test.cpp) +target_link_libraries(integration_test vk-bootstrap::vk-bootstrap) + diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/tests/integration/integration_test.cpp b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/integration/integration_test.cpp new file mode 100644 index 0000000..1028b1b --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/integration/integration_test.cpp @@ -0,0 +1,6 @@ +#include "VkBootstrap.h" + +int main() { + [[maybe_unused]] vkb::InstanceBuilder builder{}; + return 0; +} diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/tests/unit_tests.cpp b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/unit_tests.cpp new file mode 100644 index 0000000..1e4aa0d --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/unit_tests.cpp @@ -0,0 +1,85 @@ +#include + +#include "VkBootstrap.cpp" + + +TEST_CASE("Single Queue Device", "[UnitTests.queue_selection_logic]") { + std::vector families = { VkQueueFamilyProperties{ + VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT, 1, 0, VkExtent3D{ 1, 1, 1 } } }; + + REQUIRE(0 == vkb::detail::get_first_queue_index(families, VK_QUEUE_GRAPHICS_BIT)); + REQUIRE(vkb::detail::QUEUE_INDEX_MAX_VALUE == + vkb::detail::get_separate_queue_index(families, VK_QUEUE_COMPUTE_BIT, VK_QUEUE_TRANSFER_BIT)); + REQUIRE(vkb::detail::QUEUE_INDEX_MAX_VALUE == + vkb::detail::get_separate_queue_index(families, VK_QUEUE_TRANSFER_BIT, VK_QUEUE_COMPUTE_BIT)); + REQUIRE(vkb::detail::QUEUE_INDEX_MAX_VALUE == + vkb::detail::get_dedicated_queue_index(families, VK_QUEUE_COMPUTE_BIT, VK_QUEUE_TRANSFER_BIT)); + REQUIRE(vkb::detail::QUEUE_INDEX_MAX_VALUE == + vkb::detail::get_dedicated_queue_index(families, VK_QUEUE_TRANSFER_BIT, VK_QUEUE_COMPUTE_BIT)); +} + +TEST_CASE("Dedicated Compute Queue, Separate Transfer", "[UnitTests.queue_selection_logic]") { + SECTION("Dedicated Queue First") { + std::vector families = { + VkQueueFamilyProperties{ + VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT, 1, 0, VkExtent3D{ 1, 1, 1 } }, + VkQueueFamilyProperties{ VK_QUEUE_COMPUTE_BIT, 1, 0, VkExtent3D{ 1, 1, 1 } }, + VkQueueFamilyProperties{ VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT, 1, 0, VkExtent3D{ 1, 1, 1 } } + }; + + REQUIRE(0 == vkb::detail::get_first_queue_index(families, VK_QUEUE_GRAPHICS_BIT)); + REQUIRE(1 == vkb::detail::get_separate_queue_index(families, VK_QUEUE_COMPUTE_BIT, VK_QUEUE_TRANSFER_BIT)); + REQUIRE(2 == vkb::detail::get_separate_queue_index(families, VK_QUEUE_TRANSFER_BIT, VK_QUEUE_COMPUTE_BIT)); + REQUIRE(1 == vkb::detail::get_dedicated_queue_index(families, VK_QUEUE_COMPUTE_BIT, VK_QUEUE_TRANSFER_BIT)); + REQUIRE(vkb::detail::QUEUE_INDEX_MAX_VALUE == + vkb::detail::get_dedicated_queue_index(families, VK_QUEUE_TRANSFER_BIT, VK_QUEUE_COMPUTE_BIT)); + } + SECTION("Dedicated Queue Last") { + std::vector families = { + VkQueueFamilyProperties{ + VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT, 1, 0, VkExtent3D{ 1, 1, 1 } }, + VkQueueFamilyProperties{ VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT, 1, 0, VkExtent3D{ 1, 1, 1 } }, + VkQueueFamilyProperties{ VK_QUEUE_COMPUTE_BIT, 1, 0, VkExtent3D{ 1, 1, 1 } } + }; + + REQUIRE(0 == vkb::detail::get_first_queue_index(families, VK_QUEUE_GRAPHICS_BIT)); + REQUIRE(2 == vkb::detail::get_separate_queue_index(families, VK_QUEUE_COMPUTE_BIT, VK_QUEUE_TRANSFER_BIT)); + REQUIRE(1 == vkb::detail::get_separate_queue_index(families, VK_QUEUE_TRANSFER_BIT, VK_QUEUE_COMPUTE_BIT)); + REQUIRE(2 == vkb::detail::get_dedicated_queue_index(families, VK_QUEUE_COMPUTE_BIT, VK_QUEUE_TRANSFER_BIT)); + REQUIRE(vkb::detail::QUEUE_INDEX_MAX_VALUE == + vkb::detail::get_dedicated_queue_index(families, VK_QUEUE_TRANSFER_BIT, VK_QUEUE_COMPUTE_BIT)); + } +} + +TEST_CASE("Dedicated Transfer Queue, Separate Compute", "[UnitTests.queue_selection_logic]") { + SECTION("Dedicated Queue First") { + std::vector families = { + VkQueueFamilyProperties{ + VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT, 1, 0, VkExtent3D{ 1, 1, 1 } }, + VkQueueFamilyProperties{ VK_QUEUE_TRANSFER_BIT, 1, 0, VkExtent3D{ 1, 1, 1 } }, + VkQueueFamilyProperties{ VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT, 1, 0, VkExtent3D{ 1, 1, 1 } } + }; + + REQUIRE(0 == vkb::detail::get_first_queue_index(families, VK_QUEUE_GRAPHICS_BIT)); + REQUIRE(2 == vkb::detail::get_separate_queue_index(families, VK_QUEUE_COMPUTE_BIT, VK_QUEUE_TRANSFER_BIT)); + REQUIRE(1 == vkb::detail::get_separate_queue_index(families, VK_QUEUE_TRANSFER_BIT, VK_QUEUE_COMPUTE_BIT)); + REQUIRE(vkb::detail::QUEUE_INDEX_MAX_VALUE == + vkb::detail::get_dedicated_queue_index(families, VK_QUEUE_COMPUTE_BIT, VK_QUEUE_TRANSFER_BIT)); + REQUIRE(1 == vkb::detail::get_dedicated_queue_index(families, VK_QUEUE_TRANSFER_BIT, VK_QUEUE_COMPUTE_BIT)); + } + SECTION("Dedicated Queue Last") { + std::vector families = { + VkQueueFamilyProperties{ + VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT, 1, 0, VkExtent3D{ 1, 1, 1 } }, + VkQueueFamilyProperties{ VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT, 1, 0, VkExtent3D{ 1, 1, 1 } }, + VkQueueFamilyProperties{ VK_QUEUE_TRANSFER_BIT, 1, 0, VkExtent3D{ 1, 1, 1 } } + }; + + REQUIRE(0 == vkb::detail::get_first_queue_index(families, VK_QUEUE_GRAPHICS_BIT)); + REQUIRE(1 == vkb::detail::get_separate_queue_index(families, VK_QUEUE_COMPUTE_BIT, VK_QUEUE_TRANSFER_BIT)); + REQUIRE(2 == vkb::detail::get_separate_queue_index(families, VK_QUEUE_TRANSFER_BIT, VK_QUEUE_COMPUTE_BIT)); + REQUIRE(vkb::detail::QUEUE_INDEX_MAX_VALUE == + vkb::detail::get_dedicated_queue_index(families, VK_QUEUE_COMPUTE_BIT, VK_QUEUE_TRANSFER_BIT)); + REQUIRE(2 == vkb::detail::get_dedicated_queue_index(families, VK_QUEUE_TRANSFER_BIT, VK_QUEUE_COMPUTE_BIT)); + } +} diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/tests/vulkan_hpp_tests.cpp b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/vulkan_hpp_tests.cpp new file mode 100644 index 0000000..738f316 --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/vulkan_hpp_tests.cpp @@ -0,0 +1,109 @@ +#include "vulkan_library_loader.hpp" + +#include "vulkan_mock.hpp" +#include "vulkan_mock_setup.hpp" + +#include + + +TEST_CASE("VulkanHpp Instance with surface", "[VkBootstrap.vulkan_hpp]") { + VulkanMock& mock = get_and_setup_default(); + mock.api_version = VK_API_VERSION_1_1; + mock.physical_devices_details[0].properties.apiVersion = VK_API_VERSION_1_1; + mock.physical_devices_details[0].extensions.push_back(get_extension_properties("VK_KHR_multiview")); + mock.physical_devices_details[0].extensions.push_back(get_extension_properties("VK_KHR_driver_properties")); + mock.physical_devices_details[0].extensions.push_back(get_extension_properties("VK_EXT_robustness2")); + mock.physical_devices_details[0].extensions.push_back(get_extension_properties("VK_EXT_descriptor_indexing")); + VkPhysicalDeviceDescriptorIndexingFeatures physical_device_descriptor_indexing_features{}; + physical_device_descriptor_indexing_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES; + physical_device_descriptor_indexing_features.runtimeDescriptorArray = true; + physical_device_descriptor_indexing_features.descriptorBindingPartiallyBound = true; + mock.physical_devices_details[0].add_features_pNext_struct(physical_device_descriptor_indexing_features); + mock.physical_devices_details[0].extensions.push_back(get_extension_properties("VK_EXT_subgroup_size_control")); + VkPhysicalDeviceSubgroupSizeControlFeatures physical_device_subgroup_size_control_features{}; + physical_device_subgroup_size_control_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES; + physical_device_subgroup_size_control_features.subgroupSizeControl = true; + physical_device_subgroup_size_control_features.computeFullSubgroups = true; + mock.physical_devices_details[0].add_features_pNext_struct(physical_device_subgroup_size_control_features); + + auto surface = mock.get_new_surface(get_basic_surface_details()); + vk::SurfaceKHR hpp_surface{ surface }; + GIVEN("A window and a vulkan instance") { + + auto sys_info_ret = vkb::SystemInfo::get_system_info(); + REQUIRE(sys_info_ret); + + vkb::InstanceBuilder instance_builder; + auto instance_ret = instance_builder.require_api_version(1, 1, 0) + .set_minimum_instance_version(1, 0, 0) + .use_default_debug_messenger() + .build(); + REQUIRE(instance_ret); + vkb::Instance instance = instance_ret.value(); + vk::Instance hpp_instance{ instance }; + + GIVEN("A default selected physical device") { + vkb::PhysicalDeviceSelector phys_device_selector(instance); +#if VK_USE_64_BIT_PTR_DEFINES == 1 + auto phys_device_ret = phys_device_selector.set_surface(hpp_surface).select(); +#else + auto phys_device_ret = phys_device_selector.set_surface(static_cast(hpp_surface)).select(); +#endif + REQUIRE(phys_device_ret); + vkb::PhysicalDevice physical_device = phys_device_ret.value(); + + GIVEN("A device created with default parameters") { + vkb::DeviceBuilder device_builder(physical_device); + auto device_ret = device_builder.build(); + REQUIRE(device_ret); + vkb::Device device = device_ret.value(); + + // possible swapchain creation... + + vkb::destroy_device(device); + } + } + + THEN("Can select physical device with customized requirements") { + vkb::PhysicalDeviceSelector selector(instance); + auto phys_dev_ret = +#if VK_USE_64_BIT_PTR_DEFINES == 1 + selector + .set_surface(hpp_surface) +#else + selector + .set_surface(static_cast(hpp_surface)) +#endif + .add_required_extension_features( + vk::PhysicalDeviceSubgroupSizeControlFeatures{}.setSubgroupSizeControl(true).setComputeFullSubgroups(true)) + .set_minimum_version(1, 0) + .select(); + + REQUIRE(phys_dev_ret.has_value()); + + REQUIRE(phys_dev_ret->is_extension_present(VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME)); + + const std::vector extension_set_1 = { VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME }; + + REQUIRE(phys_dev_ret->enable_extensions_if_present(extension_set_1)); + + vk::PhysicalDeviceDescriptorIndexingFeatures physical_device_descriptor_indexing_features_hpp; + physical_device_descriptor_indexing_features_hpp.setRuntimeDescriptorArray(vk::True); + physical_device_descriptor_indexing_features_hpp.setDescriptorBindingPartiallyBound(vk::True); + + phys_dev_ret->enable_extension_features_if_present(physical_device_descriptor_indexing_features_hpp); + + auto device_ret = vkb::DeviceBuilder(phys_dev_ret.value()).build(); + REQUIRE(device_ret.has_value()); + vk::Device hpp_device{ device_ret.value().device }; + vkb::destroy_device(device_ret.value()); + } +#if VK_USE_64_BIT_PTR_DEFINES == 1 + vkb::destroy_surface(hpp_instance, hpp_surface); +#else + vkb::destroy_surface(hpp_instance, static_cast(hpp_surface)); +#endif + + vkb::destroy_instance(instance); + } +} diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/tests/vulkan_library_loader.hpp b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/vulkan_library_loader.hpp new file mode 100644 index 0000000..480b3c5 --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/vulkan_library_loader.hpp @@ -0,0 +1,63 @@ +#pragma once + +#include + +#include +#include + +#if defined(_WIN32) +#include +#define NOMINMAX +#include +#endif // _WIN32 + +#include "../src/VkBootstrap.h" + +#if defined(__linux__) || defined(__APPLE__) +#include +#endif + +struct VulkanLibrary { +#if defined(__linux__) || defined(__APPLE__) + void* library; +#elif defined(_WIN32) + + HMODULE library; +#endif + + VulkanLibrary() { +#if defined(__linux__) + library = dlopen("libvulkan.so.1", RTLD_NOW | RTLD_LOCAL); + if (!library) library = dlopen("libvulkan.so", RTLD_NOW | RTLD_LOCAL); +#elif defined(__APPLE__) + library = dlopen("libvulkan.dylib", RTLD_NOW | RTLD_LOCAL); + if (!library) library = dlopen("libvulkan.1.dylib", RTLD_NOW | RTLD_LOCAL); +#elif defined(_WIN32) + library = LoadLibrary(TEXT("vulkan-1.dll")); +#else + assert(false && "Unsupported platform"); +#endif + if (!library) return; +#if defined(__linux__) || defined(__APPLE__) + vkGetInstanceProcAddr = reinterpret_cast(dlsym(library, "vkGetInstanceProcAddr")); +#elif defined(_WIN32) + vkGetInstanceProcAddr = reinterpret_cast(GetProcAddress(library, "vkGetInstanceProcAddr")); +#endif + } + + void close() { +#if defined(__linux__) || defined(__APPLE__) + dlclose(library); +#elif defined(_WIN32) + FreeLibrary(library); +#endif + library = 0; + } + + void init(VkInstance instance) { + vkGetDeviceProcAddr = (PFN_vkGetDeviceProcAddr)vkGetInstanceProcAddr(instance, "vkGetDeviceProcAddr"); + } + + PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = VK_NULL_HANDLE; + PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr = VK_NULL_HANDLE; +}; diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/tests/vulkan_mock.cpp b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/vulkan_mock.cpp new file mode 100644 index 0000000..5afdc86 --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/vulkan_mock.cpp @@ -0,0 +1,450 @@ + + +#include "vulkan_mock.hpp" + +#include + +#include + +#if defined(__linux__) || defined(__APPLE__) +#include +#endif + +#define GPA_IMPL(x) \ + if (strcmp(pName, #x) == 0) { \ + return reinterpret_cast(shim_##x); \ + } + +VulkanMock mock; + +extern "C" { +VulkanMock* get_vulkan_mock() { + mock = VulkanMock{}; + return &mock; +} +} + +template VkResult fill_out_count_pointer_pair(std::vector const& data_vec, uint32_t* pCount, T* pData) { + if (pCount == nullptr) { + return VK_ERROR_OUT_OF_HOST_MEMORY; + } + if (pData == nullptr) { + if (pCount) *pCount = static_cast(data_vec.size()); + return VK_SUCCESS; + } else { + uint32_t amount_written = 0; + uint32_t amount_to_write = static_cast(data_vec.size()); + if (*pCount < data_vec.size()) { + amount_to_write = *pCount; + } + for (size_t i = 0; i < amount_to_write; i++) { + pData[i] = data_vec[i]; + amount_written++; + } + if (*pCount < data_vec.size()) { + *pCount = amount_written; + return VK_INCOMPLETE; + } + *pCount = amount_written; + return VK_SUCCESS; + } +} + +VKAPI_ATTR VkResult VKAPI_CALL shim_vkEnumerateInstanceVersion(uint32_t* pApiVersion) { + if (pApiVersion == nullptr) { + return VK_ERROR_DEVICE_LOST; + } + *pApiVersion = mock.api_version; + return VK_SUCCESS; +} + +VKAPI_ATTR VkResult VKAPI_CALL shim_vkEnumerateInstanceExtensionProperties( + const char* pLayerName, uint32_t* pPropertyCount, VkExtensionProperties* pProperties) { + if (pLayerName) { + for (size_t i = 0; i < mock.instance_layers.size(); i++) { + if (strcmp(mock.instance_layers[i].layerName, pLayerName) == 0) { + return fill_out_count_pointer_pair(mock.per_layer_instance_extension_properties[i], pPropertyCount, pProperties); + } + } + // Layer not found, fill out with empty list + return fill_out_count_pointer_pair({}, pPropertyCount, pProperties); + } + return fill_out_count_pointer_pair(mock.instance_extensions, pPropertyCount, pProperties); +} + +VKAPI_ATTR VkResult VKAPI_CALL shim_vkEnumerateInstanceLayerProperties(uint32_t* pPropertyCount, VkLayerProperties* pProperties) { + return fill_out_count_pointer_pair(mock.instance_layers, pPropertyCount, pProperties); +} + +VKAPI_ATTR VkResult VKAPI_CALL shim_vkCreateInstance([[maybe_unused]] const VkInstanceCreateInfo* pCreateInfo, + [[maybe_unused]] const VkAllocationCallbacks* pAllocator, + VkInstance* pInstance) { + if (pInstance == nullptr) { + return VK_ERROR_INITIALIZATION_FAILED; + } + *pInstance = get_handle(0x0000ABCDU); + return VK_SUCCESS; +} +VKAPI_ATTR void VKAPI_CALL shim_vkDestroyInstance( + [[maybe_unused]] VkInstance instance, [[maybe_unused]] const VkAllocationCallbacks* pAllocator) {} + +VKAPI_ATTR VkResult VKAPI_CALL shim_vkCreateDebugUtilsMessengerEXT([[maybe_unused]] VkInstance instance, + [[maybe_unused]] const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, + [[maybe_unused]] const VkAllocationCallbacks* pAllocator, + VkDebugUtilsMessengerEXT* pMessenger) { + if (instance == nullptr) { + return VK_ERROR_INITIALIZATION_FAILED; + } + *pMessenger = get_uint64_handle(0xDEBE0000DEBE0000U); + return VK_SUCCESS; +} + +VKAPI_ATTR void VKAPI_CALL shim_vkDestroyDebugUtilsMessengerEXT([[maybe_unused]] VkInstance instance, + [[maybe_unused]] VkDebugUtilsMessengerEXT messenger, + [[maybe_unused]] const VkAllocationCallbacks* pAllocator) {} + +VKAPI_ATTR VkResult VKAPI_CALL shim_vkEnumeratePhysicalDevices( + VkInstance instance, uint32_t* pPhysicalDeviceCount, VkPhysicalDevice* pPhysicalDevices) { + if (instance == nullptr) { + return VK_ERROR_INITIALIZATION_FAILED; + } + return fill_out_count_pointer_pair(mock.physical_device_handles, pPhysicalDeviceCount, pPhysicalDevices); +} + +VulkanMock::PhysicalDeviceDetails& get_physical_device_details(VkPhysicalDevice physicalDevice) { + for (size_t i = 0; i < mock.physical_device_handles.size(); i++) { + if (mock.physical_device_handles[i] == physicalDevice) return mock.physical_devices_details[i]; + } + assert(false && "should never reach here!"); + return mock.physical_devices_details.front(); +} + +VKAPI_ATTR void VKAPI_CALL shim_vkGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) { + *pFeatures = get_physical_device_details(physicalDevice).features; +} +VKAPI_ATTR void VKAPI_CALL shim_vkGetPhysicalDeviceProperties(VkPhysicalDevice physicalDevice, VkPhysicalDeviceProperties* pProperties) { + *pProperties = get_physical_device_details(physicalDevice).properties; +} + +VKAPI_ATTR void VKAPI_CALL shim_vkGetPhysicalDeviceQueueFamilyProperties( + VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties* pQueueFamilyProperties) { + fill_out_count_pointer_pair( + get_physical_device_details(physicalDevice).queue_family_properties, pQueueFamilyPropertyCount, pQueueFamilyProperties); +} + +VKAPI_ATTR void VKAPI_CALL shim_vkGetPhysicalDeviceMemoryProperties( + VkPhysicalDevice physicalDevice, VkPhysicalDeviceMemoryProperties* pMemoryProperties) { + *pMemoryProperties = get_physical_device_details(physicalDevice).memory_properties; +} + +VKAPI_ATTR void VKAPI_CALL shim_vkGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures2* pFeatures) { + pFeatures->features = get_physical_device_details(physicalDevice).features; + const auto& phys_dev = get_physical_device_details(physicalDevice); + VkBaseOutStructure* current = static_cast(pFeatures->pNext); + while (current) { + for (const auto& features_pNext : phys_dev.features_pNextChain) { + if (features_pNext.sType == current->sType) { + VkBaseOutStructure* next = static_cast(current->pNext); + std::memcpy(static_cast(current), + static_cast(&features_pNext), + get_pnext_chain_struct_size(features_pNext.sType)); + // Repair pNext void* since we clobbered it in the memcpy + current->pNext = next; + break; + } + } + current = static_cast(current->pNext); + } +} +VKAPI_ATTR void VKAPI_CALL shim_vkGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures2* pFeatures) { + shim_vkGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures); +} + +VKAPI_ATTR VkResult VKAPI_CALL shim_vkEnumerateDeviceExtensionProperties( + VkPhysicalDevice physicalDevice, const char* pLayerName, uint32_t* pPropertyCount, VkExtensionProperties* pProperties) { + if (pLayerName) { + for (size_t i = 0; i < mock.instance_layers.size(); i++) { + if (strcmp(mock.instance_layers[i].layerName, pLayerName) == 0) { + return fill_out_count_pointer_pair(mock.per_layer_device_extension_properties[i], pPropertyCount, pProperties); + } + } + // Layer not found, fill out with empty list + return fill_out_count_pointer_pair({}, pPropertyCount, pProperties); + } + return fill_out_count_pointer_pair(get_physical_device_details(physicalDevice).extensions, pPropertyCount, pProperties); +} + + +VKAPI_ATTR VkResult VKAPI_CALL shim_vkCreateDevice(VkPhysicalDevice physicalDevice, + [[maybe_unused]] const VkDeviceCreateInfo* pCreateInfo, + [[maybe_unused]] const VkAllocationCallbacks* pAllocator, + VkDevice* pDevice) { + if (physicalDevice == nullptr) { + return VK_ERROR_INITIALIZATION_FAILED; + } + *pDevice = get_handle(0x0000ABCDU); + auto& physical_device_details = get_physical_device_details(physicalDevice); + physical_device_details.created_device_handles.push_back(*pDevice); + VkPhysicalDeviceFeatures new_feats{}; + if (pCreateInfo->pEnabledFeatures) { + new_feats = *pCreateInfo->pEnabledFeatures; + } + std::vector new_chain; + std::vector created_extensions; + for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) { + created_extensions.push_back(pCreateInfo->ppEnabledExtensionNames[i]); + } + const void* pNext_chain = pCreateInfo->pNext; + while (pNext_chain) { + const auto* chain = static_cast(pNext_chain); + const void* next = chain->pNext; + if (check_if_features2_struct(chain->sType) > 0) { + vkb::detail::GenericFeaturesPNextNode node; + std::memcpy(static_cast(&node), pNext_chain, get_pnext_chain_struct_size(chain->sType)); + new_chain.push_back(node); + } + if (chain->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2) { + new_feats = static_cast(pNext_chain)->features; + } + pNext_chain = next; + } + physical_device_details.created_device_details.push_back({ new_feats, created_extensions, new_chain }); + return VK_SUCCESS; +} + +VKAPI_ATTR void VKAPI_CALL shim_vkDestroyDevice( + [[maybe_unused]] VkDevice device, [[maybe_unused]] const VkAllocationCallbacks* pAllocator) { + for (auto& physical_devices : mock.physical_devices_details) { + auto it = std::find( + std::begin(physical_devices.created_device_handles), std::end(physical_devices.created_device_handles), device); + if (it != std::end(physical_devices.created_device_handles)) { + auto index = it - physical_devices.created_device_handles.begin(); + physical_devices.created_device_handles.erase(it); + physical_devices.created_device_details.erase(physical_devices.created_device_details.begin() + index); + } + } +} + +VKAPI_ATTR void VKAPI_CALL shim_vkGetDeviceQueue(VkDevice device, uint32_t queueFamilyIndex, uint32_t queueIndex, VkQueue* pQueue) { + for (auto& physical_devices : mock.physical_devices_details) { + auto it = std::find( + std::begin(physical_devices.created_device_handles), std::end(physical_devices.created_device_handles), device); + if (it != std::end(physical_devices.created_device_handles)) { + if (queueFamilyIndex < physical_devices.queue_family_properties.size() && + queueIndex < physical_devices.queue_family_properties[queueFamilyIndex].queueCount) { + *pQueue = get_handle(0x0000CCEEU + queueIndex); + return; + } + } + } +} + +VKAPI_ATTR VkResult VKAPI_CALL shim_vkCreateCommandPool([[maybe_unused]] VkDevice device, + [[maybe_unused]] const VkCommandPoolCreateInfo* pCreateInfo, + [[maybe_unused]] const VkAllocationCallbacks* pAllocator, + VkCommandPool* pCommandPool) { + *pCommandPool = get_uint64_handle(0x0000ABBBU); + return VK_SUCCESS; +} + +VKAPI_ATTR VkResult VKAPI_CALL shim_vkCreateFence([[maybe_unused]] VkDevice device, + [[maybe_unused]] const VkFenceCreateInfo* pCreateInfo, + [[maybe_unused]] const VkAllocationCallbacks* pAllocator, + VkFence* pFence) { + *pFence = get_uint64_handle(0x0000AAACU); + return VK_SUCCESS; +} +VKAPI_ATTR void VKAPI_CALL shim_vkDestroyFence( + [[maybe_unused]] VkDevice device, [[maybe_unused]] VkFence fence, [[maybe_unused]] const VkAllocationCallbacks* pAllocator) {} + +VKAPI_ATTR VkResult VKAPI_CALL shim_vkCreateSwapchainKHR([[maybe_unused]] VkDevice device, + [[maybe_unused]] const VkSwapchainCreateInfoKHR* pCreateInfo, + [[maybe_unused]] const VkAllocationCallbacks* pAllocator, + VkSwapchainKHR* pSwapchain) { + *pSwapchain = get_uint64_handle(0x0000FFFEU); + return VK_SUCCESS; +} +VKAPI_ATTR VkResult VKAPI_CALL shim_vkGetSwapchainImagesKHR( + [[maybe_unused]] VkDevice device, [[maybe_unused]] VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages) { + + std::vector images{ get_uint64_handle(0x0000EDD0U), + get_uint64_handle(0x0000EDD1U), + get_uint64_handle(0x0000EDD1U) }; + return fill_out_count_pointer_pair(images, pSwapchainImageCount, pSwapchainImages); +} + +VKAPI_ATTR VkResult VKAPI_CALL shim_vkCreateImageView([[maybe_unused]] VkDevice device, + [[maybe_unused]] const VkImageViewCreateInfo* pCreateInfo, + [[maybe_unused]] const VkAllocationCallbacks* pAllocator, + VkImageView* pView) { + if (pView) *pView = get_uint64_handle(0x0000CCCEU); + return VK_SUCCESS; +} + +VKAPI_ATTR void VKAPI_CALL shim_vkDestroyImageView([[maybe_unused]] VkDevice device, + [[maybe_unused]] VkImageView imageView, + [[maybe_unused]] const VkAllocationCallbacks* pAllocator) {} + +VKAPI_ATTR void VKAPI_CALL shim_vkDestroySwapchainKHR([[maybe_unused]] VkDevice device, + [[maybe_unused]] VkSwapchainKHR swapchain, + [[maybe_unused]] const VkAllocationCallbacks* pAllocator) {} + +VKAPI_ATTR VkResult VKAPI_CALL shim_vkAcquireNextImageKHR([[maybe_unused]] VkDevice device, + [[maybe_unused]] VkSwapchainKHR swapchain, + [[maybe_unused]] uint64_t timeout, + [[maybe_unused]] VkSemaphore semaphore, + [[maybe_unused]] VkFence fence, + [[maybe_unused]] uint32_t* pImageIndex) { + return VK_SUCCESS; +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL shim_vkGetDeviceProcAddr(VkDevice device, const char* pName) { + if (device == VK_NULL_HANDLE) { + return nullptr; + } + GPA_IMPL(vkDestroyDevice) + GPA_IMPL(vkGetDeviceQueue) + GPA_IMPL(vkCreateCommandPool) + GPA_IMPL(vkCreateFence) + GPA_IMPL(vkDestroyFence) + GPA_IMPL(vkCreateSwapchainKHR) + GPA_IMPL(vkGetSwapchainImagesKHR) + GPA_IMPL(vkCreateImageView) + GPA_IMPL(vkDestroyImageView) + GPA_IMPL(vkDestroySwapchainKHR) + GPA_IMPL(vkAcquireNextImageKHR) + + return nullptr; +} + +VKAPI_ATTR void VKAPI_CALL shim_vkDestroySurfaceKHR([[maybe_unused]] VkInstance instance, + [[maybe_unused]] VkSurfaceKHR surface, + [[maybe_unused]] const VkAllocationCallbacks* pAllocator) {} + +VKAPI_ATTR VkResult VKAPI_CALL shim_vkGetPhysicalDeviceSurfaceSupportKHR( + VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex, VkSurfaceKHR surface, VkBool32* pSupported) { + + for (size_t i = 0; i < mock.physical_device_handles.size(); i++) { + if (physicalDevice == mock.physical_device_handles[i]) { + if (queueFamilyIndex >= mock.physical_devices_details[i].queue_family_properties.size()) { + return VK_ERROR_FORMAT_NOT_SUPPORTED; + } + } + } + if (surface && pSupported) { + *pSupported = true; + } + return VK_SUCCESS; +} +VKAPI_ATTR VkResult VKAPI_CALL shim_vkGetPhysicalDeviceSurfaceFormatsKHR( + [[maybe_unused]] VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, uint32_t* pSurfaceFormatCount, VkSurfaceFormatKHR* pSurfaceFormats) { + for (size_t i = 0; i < mock.surface_handles.size(); i++) { + if (mock.surface_handles[i] == surface) { + return fill_out_count_pointer_pair(mock.surface_details[i].surface_formats, pSurfaceFormatCount, pSurfaceFormats); + } + } + return VK_ERROR_SURFACE_LOST_KHR; +} + +VKAPI_ATTR VkResult VKAPI_CALL shim_vkGetPhysicalDeviceSurfacePresentModesKHR( + [[maybe_unused]] VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, uint32_t* pPresentModeCount, VkPresentModeKHR* pPresentModes) { + for (size_t i = 0; i < mock.surface_handles.size(); i++) { + if (mock.surface_handles[i] == surface) { + return fill_out_count_pointer_pair(mock.surface_details[i].present_modes, pPresentModeCount, pPresentModes); + } + } + return VK_ERROR_SURFACE_LOST_KHR; +} + +VKAPI_ATTR VkResult VKAPI_CALL shim_vkGetPhysicalDeviceSurfaceCapabilitiesKHR( + [[maybe_unused]] VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, VkSurfaceCapabilitiesKHR* pSurfaceCapabilities) { + for (size_t i = 0; i < mock.surface_handles.size(); i++) { + if (mock.surface_handles[i] == surface) { + *pSurfaceCapabilities = mock.surface_details[i].capabilities; + return VK_SUCCESS; + } + } + return VK_ERROR_SURFACE_LOST_KHR; +} + +PFN_vkVoidFunction shim_vkGetInstanceProcAddr([[maybe_unused]] VkInstance instance, [[maybe_unused]] const char* pName) { + GPA_IMPL(vkEnumerateInstanceVersion) + GPA_IMPL(vkEnumerateInstanceExtensionProperties) + GPA_IMPL(vkEnumerateInstanceLayerProperties) + GPA_IMPL(vkCreateInstance) + + GPA_IMPL(vkDestroyInstance) + GPA_IMPL(vkCreateDebugUtilsMessengerEXT) + GPA_IMPL(vkDestroyDebugUtilsMessengerEXT) + GPA_IMPL(vkEnumeratePhysicalDevices) + GPA_IMPL(vkGetPhysicalDeviceFeatures) + GPA_IMPL(vkGetPhysicalDeviceFeatures2) + GPA_IMPL(vkGetPhysicalDeviceFeatures2KHR) + GPA_IMPL(vkGetPhysicalDeviceProperties) + GPA_IMPL(vkGetPhysicalDeviceQueueFamilyProperties) + GPA_IMPL(vkGetPhysicalDeviceMemoryProperties) + GPA_IMPL(vkEnumerateDeviceExtensionProperties) + + GPA_IMPL(vkCreateDevice) + GPA_IMPL(vkGetDeviceProcAddr) + GPA_IMPL(vkGetDeviceQueue) + GPA_IMPL(vkDestroyDevice) + + GPA_IMPL(vkDestroySurfaceKHR) + GPA_IMPL(vkGetPhysicalDeviceSurfaceSupportKHR) + GPA_IMPL(vkGetPhysicalDeviceSurfaceFormatsKHR) + GPA_IMPL(vkGetPhysicalDeviceSurfacePresentModesKHR) + GPA_IMPL(vkGetPhysicalDeviceSurfaceCapabilitiesKHR) + + // Only used by the tests, not by vk-bootstrap + GPA_IMPL(vkCreateCommandPool) + + return nullptr; +} + +extern "C" { +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetInstanceProcAddr(VkInstance instance, const char* pName) { + return shim_vkGetInstanceProcAddr(instance, pName); +} + +#if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__GNU__) +#define DLSYM_FUNC_NAME dlsym + +#elif defined(__APPLE__) +#define DLSYM_FUNC_NAME my_dlsym +#endif + +using PFN_DLSYM = void* (*)(void* handle, const char* symbol); + + +#if defined(__APPLE__) +#define real_dlsym dlsym +#else +PFN_DLSYM real_dlsym = nullptr; +#endif + +void* DLSYM_FUNC_NAME([[maybe_unused]] void* handle, const char* symbol) { + if (strcmp(symbol, "vkGetInstanceProcAddr") == 0) { + return reinterpret_cast(shim_vkGetInstanceProcAddr); + } + + return nullptr; +} + +/* Shiming functions on apple is limited by the linker prefering to not use functions in the + * executable in loaded dylibs. By adding an interposer, we redirect the linker to use our + * version of the function over the real one, thus shimming the system function. + */ +#if defined(__APPLE__) +#define MACOS_ATTRIB __attribute__((section("__DATA,__interpose"))) +#define VOIDCP_CAST(_func) reinterpret_cast(&_func) + +struct Interposer { + const void* shim_function; + const void* underlying_function; +}; + +__attribute__((used)) static Interposer _interpose_dlsym MACOS_ATTRIB = { VOIDCP_CAST(my_dlsym), VOIDCP_CAST(dlsym) }; + +#endif +} diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/tests/vulkan_mock.def b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/vulkan_mock.def new file mode 100644 index 0000000..237dd50 --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/vulkan_mock.def @@ -0,0 +1,4 @@ +LIBRARY vulkan-1 +EXPORTS +get_vulkan_mock +vkGetInstanceProcAddr diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/tests/vulkan_mock.hpp b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/vulkan_mock.hpp new file mode 100644 index 0000000..53590fd --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/vulkan_mock.hpp @@ -0,0 +1,108 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include + +#include + +#include + +// Helper function to return the size of the sType if it is a known features struct, otherwise return 0 +// Hand written, must be updated to include any used struct. +inline size_t check_if_features2_struct(VkStructureType type) { + switch (type) { + case (VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES): + return sizeof(VkPhysicalDeviceDescriptorIndexingFeatures); + case (VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES): + return sizeof(VkPhysicalDeviceVulkan11Features); + case (VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES): + return sizeof(VkPhysicalDeviceVulkan12Features); + case (VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES): + return sizeof(VkPhysicalDeviceSubgroupSizeControlFeatures); + default: + return 0; + } +} + +inline size_t get_pnext_chain_struct_size(VkStructureType type) { + auto size = check_if_features2_struct(type); + assert(size > 0 && "Must update get_pnext_chain_struct_size(VkStructureType type) to add type!"); + return size; +} + +template T get_handle(size_t value) { return reinterpret_cast(value); } + +#if INTPTR_MAX == INT32_MAX +template uint64_t get_uint64_handle(uint64_t value) { return static_cast(value); } +#elif INTPTR_MAX == INT64_MAX +template T get_uint64_handle(uint64_t value) { return reinterpret_cast(value); } +#endif + +struct VulkanMock { + uint32_t api_version = VK_API_VERSION_1_3; + std::vector instance_extensions; + std::vector instance_layers; + std::vector> per_layer_instance_extension_properties; + std::vector> per_layer_device_extension_properties; + + void add_layer(VkLayerProperties layer_properties, + std::vector layer_instance_extensions, + std::vector layer_device_extensions) { + instance_layers.push_back(layer_properties); + per_layer_instance_extension_properties.push_back(layer_instance_extensions); + per_layer_instance_extension_properties.push_back(layer_device_extensions); + } + + struct SurfaceDetails { + VkSurfaceCapabilitiesKHR capabilities{}; + std::vector surface_formats; + std::vector present_modes; + }; + + std::vector surface_handles; + std::vector surface_details; + + VkSurfaceKHR get_new_surface(SurfaceDetails details) { + surface_handles.push_back( + get_uint64_handle(static_cast(0x123456789ABU + surface_handles.size()))); + surface_details.push_back(details); + return surface_handles.back(); + } + + struct CreatedDeviceDetails { + VkPhysicalDeviceFeatures features{}; + std::vector extensions; + std::vector features_pNextChain; + }; + + struct PhysicalDeviceDetails { + VkPhysicalDeviceProperties properties{}; + VkPhysicalDeviceFeatures features{}; + VkPhysicalDeviceMemoryProperties memory_properties{}; + std::vector extensions; + std::vector queue_family_properties; + std::vector features_pNextChain; + + std::vector created_device_handles; + std::vector created_device_details; + + template void add_features_pNext_struct(T features) { features_pNextChain.push_back(features); } + }; + + std::vector physical_device_handles; + std::vector physical_devices_details; + + void add_physical_device(PhysicalDeviceDetails details) { + physical_device_handles.push_back(get_handle(0x22334455U + physical_device_handles.size())); + physical_devices_details.emplace_back(std::move(details)); + } +}; + +extern "C" { +VulkanMock* get_vulkan_mock(); +} diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/tests/vulkan_mock_setup.cpp b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/vulkan_mock_setup.cpp new file mode 100644 index 0000000..d39369a --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/vulkan_mock_setup.cpp @@ -0,0 +1,60 @@ + +#include "vulkan_mock_setup.hpp" + +vkb::Instance get_instance(uint32_t minor_version) { + auto instance_ret = vkb::InstanceBuilder().request_validation_layers().require_api_version(1, minor_version).build(); + REQUIRE(instance_ret.has_value()); + return instance_ret.value(); +} +vkb::Instance get_headless_instance(uint32_t minor_version) { + auto instance_ret = + vkb::InstanceBuilder().request_validation_layers().require_api_version(1, minor_version).set_headless().build(); + REQUIRE(instance_ret.has_value()); + return instance_ret.value(); +} + +VkExtensionProperties get_extension_properties(const char* extName) { + VkExtensionProperties ext_props{}; + std::copy_n(extName, VK_MAX_EXTENSION_NAME_SIZE, ext_props.extensionName); + return ext_props; +} + +VulkanMock& get_and_setup_default() { + VulkanMock& mock = *get_vulkan_mock(); + mock.instance_extensions.push_back(get_extension_properties(VK_KHR_SURFACE_EXTENSION_NAME)); +#if defined(_WIN32) + mock.instance_extensions.push_back(get_extension_properties("VK_KHR_win32_surface")); +#elif defined(__ANDROID__) + mock.instance_extensions.push_back(get_extension_properties("VK_KHR_android_surface")); +#elif defined(_DIRECT2DISPLAY) + mock.instance_extensions.push_back(get_extension_properties("VK_KHR_android_surface")); +#elif defined(__linux__) + mock.instance_extensions.push_back(get_extension_properties("VK_KHR_xcb_surface")); + mock.instance_extensions.push_back(get_extension_properties("VK_KHR_xlib_surface")); + mock.instance_extensions.push_back(get_extension_properties("VK_KHR_wayland_surface")); +#elif defined(__APPLE__) + mock.instance_extensions.push_back(get_extension_properties("VK_EXT_metal_surface")); +#endif + mock.instance_extensions.push_back(get_extension_properties(VK_EXT_DEBUG_UTILS_EXTENSION_NAME)); + VulkanMock::PhysicalDeviceDetails physical_device_details{}; + physical_device_details.extensions.push_back(get_extension_properties(VK_KHR_SWAPCHAIN_EXTENSION_NAME)); + physical_device_details.properties.apiVersion = VK_API_VERSION_1_0; + VkQueueFamilyProperties queue_family_properties{}; + queue_family_properties.queueCount = 1; + queue_family_properties.queueFlags = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT; + queue_family_properties.minImageTransferGranularity = { 1, 1, 1 }; + physical_device_details.queue_family_properties.push_back(queue_family_properties); + mock.add_physical_device(std::move(physical_device_details)); + return mock; +} + +VulkanMock::SurfaceDetails get_basic_surface_details() { + VulkanMock::SurfaceDetails details; + details.present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR); + details.surface_formats.push_back(VkSurfaceFormatKHR{ VK_FORMAT_R8G8B8_SRGB, VK_COLORSPACE_SRGB_NONLINEAR_KHR }); + details.capabilities.minImageCount = 2; + details.capabilities.minImageExtent = { 600, 800 }; + details.capabilities.currentExtent = { 600, 800 }; + details.capabilities.supportedUsageFlags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + return details; +} diff --git a/Ifnity/Ifnity/vendor/vk-bootstrap/tests/vulkan_mock_setup.hpp b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/vulkan_mock_setup.hpp new file mode 100644 index 0000000..cc99e69 --- /dev/null +++ b/Ifnity/Ifnity/vendor/vk-bootstrap/tests/vulkan_mock_setup.hpp @@ -0,0 +1,18 @@ +#pragma once + +#include + +#include "vulkan_mock.hpp" + +#include + + +vkb::Instance get_instance(uint32_t minor_version = 0); + +vkb::Instance get_headless_instance(uint32_t minor_version = 0); + +VkExtensionProperties get_extension_properties(const char* extName); + +VulkanMock& get_and_setup_default(); + +VulkanMock::SurfaceDetails get_basic_surface_details(); diff --git a/Ifnity/Sandbox/CMakeLists.txt b/Ifnity/Sandbox/CMakeLists.txt index 14bc663..83c0349 100644 --- a/Ifnity/Sandbox/CMakeLists.txt +++ b/Ifnity/Sandbox/CMakeLists.txt @@ -26,7 +26,10 @@ add_executable(${PROJECT_NAME} ${SOURCES} ${HEADERS}) #Add Ifnity dependencies add_dependencies(${PROJECT_NAME} Ifnity) - +if(BUILD_SHARED_IFNITY) + target_compile_definitions(Sandbox PRIVATE IFNITY_USE_SHARED) + message("IFNITY_USE_SHARED CREATE = ON ") +endif() # Link Ifnity library dll target_link_libraries(${PROJECT_NAME} PUBLIC Ifnity) @@ -40,3 +43,9 @@ add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD $ $ ) + +add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_directory + ${CMAKE_SOURCE_DIR}/../Shaders + $/Shaders +) diff --git a/Ifnity/Sandbox/src/Source.cpp b/Ifnity/Sandbox/src/Source.cpp index 4c1a23f..3b9a4d2 100644 --- a/Ifnity/Sandbox/src/Source.cpp +++ b/Ifnity/Sandbox/src/Source.cpp @@ -1,10 +1,11 @@ // IFNITY.cp -#include "pch.h" + #include + using namespace IFNITY::rhi; class ExampleLayer: public IFNITY::GLFWEventListener, public IFNITY::Layer @@ -133,26 +134,33 @@ class ImGuiTestLayer : public IFNITY::Layer IFNITY::App::GetApp() .SetGraphicsAPI(GraphicsAPI::D3D12, api != GraphicsAPI::D3D12); break; + + case 3: + // Accin para la opcin 3 + IFNITY_LOG(LogApp, INFO, "VULKAN"); + IFNITY::App::GetApp() + .SetGraphicsAPI(GraphicsAPI::VULKAN, api != GraphicsAPI::VULKAN); + break; default: - IFNITY_LOG(LogApp, INFO, "No option "); + break; } } void ChooseApi() { - static int opcionSeleccionada = 0; - const char* opciones[] = { "OPENGL", "D3D11","D3D12"}; + static int selectOption = 0; + const char* options[] = { "OPENGL", "D3D11","D3D12","VULKAN"}; ImGui::Begin("API WINDOW"); // Comienza la creacin de la ventana // Combo box con las opciones - if (ImGui::Combo("Choose Option ", &opcionSeleccionada, opciones, IM_ARRAYSIZE(opciones))) { + if (ImGui::Combo("Choose Option ", &selectOption, options, IM_ARRAYSIZE(options))) { // Este bloque se ejecuta cada vez que se selecciona una opcin diferente } // Botn que ejecuta la funcin cuando se hace clic if (ImGui::Button("OK")) { - AccionPorOpcion(opcionSeleccionada); + AccionPorOpcion(selectOption); } ImGui::End(); // Termina la creacin de la ventana @@ -196,7 +204,7 @@ class Source_TestD3D12 : public IFNITY::App public: Source_TestD3D12(IFNITY::rhi::GraphicsAPI api) : IFNITY::App(api) { - + PushLayer(new ExampleLayer()); } ~Source_TestD3D12() override { @@ -206,7 +214,11 @@ class Source_TestD3D12 : public IFNITY::App IFNITY::App* IFNITY::CreateApp() { - auto api = IFNITY::rhi::GraphicsAPI::D3D12; + + + auto api = IFNITY::rhi::GraphicsAPI::VULKAN; + + //return new Source_TestD3D12(api); return new Source(api); }