LCOV - code coverage report
Current view: top level - source/renderer/backend/vulkan - Device.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 0 617 0.0 %
Date: 2026-12-03 01:19:39 Functions: 0 47 0.0 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "precompiled.h"
      19             : 
      20             : #include "Device.h"
      21             : 
      22             : #include "lib/alignment.h"
      23             : #include "lib/build_version.h"
      24             : #include "lib/debug.h"
      25             : #include "lib/sysdep/os.h"
      26             : #include "ps/CLogger.h"
      27             : #include "ps/ConfigDB.h"
      28             : #include "ps/Profile.h"
      29             : #include "ps/containers/StaticVector.h"
      30             : #include "renderer/backend/Format.h"
      31             : #include "renderer/backend/vulkan/Buffer.h"
      32             : #include "renderer/backend/vulkan/DescriptorManager.h"
      33             : #include "renderer/backend/vulkan/DeviceCommandContext.h"
      34             : #include "renderer/backend/vulkan/DeviceSelection.h"
      35             : #include "renderer/backend/vulkan/Framebuffer.h"
      36             : #include "renderer/backend/vulkan/Mapping.h"
      37             : #include "renderer/backend/vulkan/PipelineState.h"
      38             : #include "renderer/backend/vulkan/RenderPassManager.h"
      39             : #include "renderer/backend/vulkan/RingCommandContext.h"
      40             : #include "renderer/backend/vulkan/SamplerManager.h"
      41             : #include "renderer/backend/vulkan/ShaderProgram.h"
      42             : #include "renderer/backend/vulkan/SubmitScheduler.h"
      43             : #include "renderer/backend/vulkan/SwapChain.h"
      44             : #include "renderer/backend/vulkan/Texture.h"
      45             : #include "renderer/backend/vulkan/Utilities.h"
      46             : #include "scriptinterface/Object.h"
      47             : #include "scriptinterface/Request.h"
      48             : 
      49             : #include <SDL_version.h>
      50             : #include <SDL_video.h>
      51             : #include <algorithm>
      52             : #include <array>
      53             : #include <iterator>
      54             : #include <js/RootingAPI.h>
      55             : #include <js/Value.h>
      56             : #include <limits>
      57             : #include <string>
      58             : #include <string_view>
      59             : #include <vector>
      60             : #include <vk_platform.h>
      61             : 
      62             : // According to https://wiki.libsdl.org/SDL_Vulkan_LoadLibrary the following
      63             : // functionality is supported since SDL 2.0.6.
      64             : #if SDL_VERSION_ATLEAST(2, 0, 6)
      65             : #include <SDL_vulkan.h>
      66             : #endif
      67             : 
      68             : namespace Renderer
      69             : {
      70             : 
      71             : namespace Backend
      72             : {
      73             : 
      74             : namespace Vulkan
      75             : {
      76             : 
      77             : namespace
      78             : {
      79             : 
      80             : constexpr size_t QUERY_POOL_SIZE{NUMBER_OF_FRAMES_IN_FLIGHT * 1024};
      81             : 
      82           0 : std::vector<const char*> GetRequiredSDLExtensions(SDL_Window* window)
      83             : {
      84           0 :     if (!window)
      85           0 :         return {};
      86             : 
      87           0 :     const size_t MAX_EXTENSION_COUNT = 16;
      88           0 :     unsigned int SDLExtensionCount = MAX_EXTENSION_COUNT;
      89           0 :     const char* SDLExtensions[MAX_EXTENSION_COUNT];
      90           0 :     ENSURE(SDL_Vulkan_GetInstanceExtensions(window, &SDLExtensionCount, SDLExtensions));
      91           0 :     std::vector<const char*> requiredExtensions;
      92           0 :     requiredExtensions.reserve(SDLExtensionCount);
      93           0 :     std::copy_n(SDLExtensions, SDLExtensionCount, std::back_inserter(requiredExtensions));
      94           0 :     return requiredExtensions;
      95             : }
      96             : 
      97           0 : std::vector<std::string> GetAvailableValidationLayers()
      98             : {
      99           0 :     uint32_t layerCount = 0;
     100           0 :     ENSURE_VK_SUCCESS(vkEnumerateInstanceLayerProperties(&layerCount, nullptr));
     101             : 
     102           0 :     std::vector<VkLayerProperties> availableLayers(layerCount);
     103           0 :     ENSURE_VK_SUCCESS(vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data()));
     104             : 
     105           0 :     for (const VkLayerProperties& layer : availableLayers)
     106             :     {
     107           0 :         LOGMESSAGE("Vulkan validation layer: '{}' ({}) v{}.{}.{}.{}",
     108             :             layer.layerName, layer.description,
     109             :             VK_API_VERSION_VARIANT(layer.specVersion),
     110             :             VK_API_VERSION_MAJOR(layer.specVersion),
     111             :             VK_API_VERSION_MINOR(layer.specVersion),
     112             :             VK_API_VERSION_PATCH(layer.specVersion));
     113             :     }
     114             : 
     115           0 :     std::vector<std::string> availableValidationLayers;
     116           0 :     availableValidationLayers.reserve(layerCount);
     117           0 :     for (const VkLayerProperties& layer : availableLayers)
     118           0 :         availableValidationLayers.emplace_back(layer.layerName);
     119           0 :     return availableValidationLayers;
     120             : }
     121             : 
     122           0 : std::vector<std::string> GetAvailableInstanceExtensions(const char* layerName = nullptr)
     123             : {
     124           0 :     uint32_t extensionCount = 0;
     125           0 :     ENSURE_VK_SUCCESS(vkEnumerateInstanceExtensionProperties(layerName, &extensionCount, nullptr));
     126           0 :     std::vector<VkExtensionProperties> extensions(extensionCount);
     127           0 :     ENSURE_VK_SUCCESS(vkEnumerateInstanceExtensionProperties(layerName, &extensionCount, extensions.data()));
     128             : 
     129           0 :     std::vector<std::string> availableExtensions;
     130           0 :     for (const VkExtensionProperties& extension : extensions)
     131           0 :         availableExtensions.emplace_back(extension.extensionName);
     132           0 :     return availableExtensions;
     133             : }
     134             : 
     135           0 : VKAPI_ATTR VkBool32 VKAPI_CALL DebugCallback(
     136             :     VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
     137             :     VkDebugUtilsMessageTypeFlagsEXT messageType,
     138             :     const VkDebugUtilsMessengerCallbackDataEXT* callbackData,
     139             :     void* /*userData*/)
     140             : {
     141           0 :     if ((messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) || (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT))
     142           0 :         LOGMESSAGE("Vulkan: {}", callbackData->pMessage);
     143           0 :     else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT)
     144             :     {
     145           0 :         struct HideRule
     146             :         {
     147             :             VkDebugUtilsMessageTypeFlagsEXT flags;
     148             :             std::string_view pattern;
     149             :             bool skip;
     150             :         };
     151           0 :         constexpr HideRule hideRules[] =
     152             :         {
     153             :             // Not consumed shader output is a known problem which produces too
     154             :             // many warning.
     155             :             {VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT, "OutputNotConsumed", false},
     156             :             // TODO: check vkGetImageMemoryRequirements2 for prefersDedicatedAllocation.
     157             :             {VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT, "vkBindMemory-small-dedicated-allocation", false},
     158             :             {VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT, "vkAllocateMemory-small-allocation", false},
     159             :             // We have some unnecessary clears which were needed for GL.
     160             :             // Ignore message for now, because they're spawned each frame.
     161             :             {VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT, "ClearCmdBeforeDraw", true},
     162             :             {VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT, "vkCmdClearAttachments-clear-after-load", true},
     163             :             // TODO: investigate probably false-positive report.
     164             :             {VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT, "vkCmdBeginRenderPass-StoreOpDontCareThenLoadOpLoad", true},
     165             :         };
     166           0 :         const auto it = std::find_if(std::begin(hideRules), std::end(hideRules),
     167           0 :             [messageType, message = std::string_view{callbackData->pMessage}](const HideRule& hideRule) -> bool
     168             :             {
     169           0 :                 return (hideRule.flags & messageType) && message.find(hideRule.pattern) != std::string_view::npos;
     170             :             });
     171           0 :         if (it == std::end(hideRules))
     172           0 :             LOGWARNING("Vulkan: {}", callbackData->pMessage);
     173           0 :         else if (!it->skip)
     174           0 :             LOGMESSAGE("Vulkan: {}", callbackData->pMessage);
     175             :     }
     176           0 :     else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT)
     177           0 :         LOGERROR("Vulkan: {}", callbackData->pMessage);
     178             : 
     179           0 :     return VK_FALSE;
     180             : }
     181             : 
     182             : // A workaround function to meet calling conventions of Vulkan, SDL and GLAD.
     183           0 : GLADapiproc GetInstanceProcAddr(VkInstance instance, const char* name)
     184             : {
     185             : #if SDL_VERSION_ATLEAST(2, 0, 6)
     186           0 :     PFN_vkGetInstanceProcAddr function = reinterpret_cast<PFN_vkGetInstanceProcAddr>(SDL_Vulkan_GetVkGetInstanceProcAddr());
     187           0 :     return reinterpret_cast<GLADapiproc>(function(instance, name));
     188             : #else
     189             :     return nullptr;
     190             : #endif
     191             : }
     192             : 
     193             : } // anonymous namespace
     194             : 
     195             : // static
     196           0 : std::unique_ptr<CDevice> CDevice::Create(SDL_Window* window)
     197             : {
     198           0 :     if (!window)
     199             :     {
     200           0 :         LOGERROR("Can't create Vulkan device without window.");
     201           0 :         return nullptr;
     202             :     }
     203             : 
     204           0 :     GLADuserptrloadfunc gladLoadFunction = reinterpret_cast<GLADuserptrloadfunc>(GetInstanceProcAddr);
     205             : 
     206           0 :     std::unique_ptr<CDevice> device(new CDevice());
     207           0 :     device->m_Window = window;
     208             : 
     209             : #ifdef NDEBUG
     210           0 :     bool enableDebugMessages{g_ConfigDB.Get("renderer.backend.debugmessages", false)};
     211           0 :     bool enableDebugLabels{g_ConfigDB.Get("renderer.backend.debuglabels", false)};
     212           0 :     bool enableDebugScopedLabels{g_ConfigDB.Get("renderer.backend.debugscopedlabels", false)};
     213             : #else
     214             :     bool enableDebugMessages = true;
     215             :     bool enableDebugLabels = true;
     216             :     bool enableDebugScopedLabels = true;
     217             : #endif
     218             : 
     219           0 :     int gladVulkanVersion = gladLoadVulkanUserPtr(nullptr, gladLoadFunction, nullptr);
     220           0 :     if (!gladVulkanVersion)
     221             :     {
     222           0 :         LOGERROR("GLAD unable to load vulkan.");
     223           0 :         return nullptr;
     224             :     }
     225             : 
     226           0 :     VkApplicationInfo applicationInfo{};
     227           0 :     applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
     228           0 :     applicationInfo.pApplicationName = "0 A.D.";
     229           0 :     applicationInfo.applicationVersion = VK_MAKE_VERSION(PS_VERSION_MAJOR, PS_VERSION_MINOR, PS_VERSION_PATCH);
     230           0 :     applicationInfo.pEngineName = "Pyrogenesis";
     231           0 :     applicationInfo.engineVersion = applicationInfo.applicationVersion;
     232           0 :     applicationInfo.apiVersion = VK_API_VERSION_1_1;
     233             : 
     234           0 :     std::vector<const char*> requiredInstanceExtensions = GetRequiredSDLExtensions(window);
     235             : 
     236           0 :     device->m_ValidationLayers = GetAvailableValidationLayers();
     237           0 :     auto hasValidationLayer = [&layers = device->m_ValidationLayers](const char* name) -> bool
     238             :     {
     239           0 :         return std::find(layers.begin(), layers.end(), name) != layers.end();
     240           0 :     };
     241           0 :     device->m_InstanceExtensions = GetAvailableInstanceExtensions();
     242           0 :     auto hasInstanceExtension = [&extensions = device->m_InstanceExtensions](const char* name) -> bool
     243             :     {
     244           0 :         return std::find(extensions.begin(), extensions.end(), name) != extensions.end();
     245           0 :     };
     246             : 
     247             : #ifdef NDEBUG
     248           0 :     bool enableDebugContext{g_ConfigDB.Get("renderer.backend.debugcontext", false)};
     249             : #else
     250             :     bool enableDebugContext = true;
     251             : #endif
     252             : 
     253           0 :     if (!hasInstanceExtension(VK_EXT_DEBUG_UTILS_EXTENSION_NAME))
     254           0 :         enableDebugMessages = enableDebugLabels = enableDebugScopedLabels = false;
     255           0 :     const bool enableDebugLayers = enableDebugContext || enableDebugMessages || enableDebugLabels || enableDebugScopedLabels;
     256             :     if (enableDebugLayers)
     257           0 :         requiredInstanceExtensions.emplace_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
     258             : 
     259           0 :     std::vector<const char*> requestedValidationLayers;
     260           0 :     const bool enableValidationFeatures = enableDebugMessages && hasValidationLayer("VK_LAYER_KHRONOS_validation");
     261           0 :     if (enableValidationFeatures)
     262           0 :         requestedValidationLayers.emplace_back("VK_LAYER_KHRONOS_validation");
     263             : 
     264             :     // https://github.com/KhronosGroup/Vulkan-ValidationLayers/blob/master/docs/synchronization_usage.md
     265           0 :     VkValidationFeatureEnableEXT validationFeatureEnables[] =
     266             :     {
     267             :         VK_VALIDATION_FEATURE_ENABLE_BEST_PRACTICES_EXT,
     268             :         VK_VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT
     269             :     };
     270           0 :     VkValidationFeaturesEXT validationFeatures{};
     271           0 :     validationFeatures.sType = VK_STRUCTURE_TYPE_VALIDATION_FEATURES_EXT;
     272           0 :     validationFeatures.enabledValidationFeatureCount = std::size(validationFeatureEnables);
     273           0 :     validationFeatures.pEnabledValidationFeatures = validationFeatureEnables;
     274             : 
     275           0 :     VkInstanceCreateInfo instanceCreateInfo{};
     276           0 :     instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
     277           0 :     instanceCreateInfo.pApplicationInfo = &applicationInfo;
     278           0 :     instanceCreateInfo.enabledExtensionCount = requiredInstanceExtensions.size();
     279           0 :     instanceCreateInfo.ppEnabledExtensionNames = requiredInstanceExtensions.data();
     280           0 :     if (requestedValidationLayers.empty())
     281             :     {
     282             :         instanceCreateInfo.enabledLayerCount = 0;
     283             :         instanceCreateInfo.ppEnabledLayerNames = nullptr;
     284             :     }
     285             :     else
     286             :     {
     287           0 :         instanceCreateInfo.enabledLayerCount = requestedValidationLayers.size();
     288           0 :         instanceCreateInfo.ppEnabledLayerNames = requestedValidationLayers.data();
     289             :     }
     290             : 
     291             :     // Enabling validation features might significantly reduce performance,
     292             :     // even more than the standard validation layer.
     293           0 :     if (enableValidationFeatures && enableDebugContext)
     294             :     {
     295           0 :         instanceCreateInfo.pNext = &validationFeatures;
     296             :     }
     297             : 
     298           0 :     const VkResult createInstanceResult = vkCreateInstance(&instanceCreateInfo, nullptr, &device->m_Instance);
     299           0 :     if (createInstanceResult != VK_SUCCESS)
     300             :     {
     301           0 :         if (createInstanceResult == VK_ERROR_INCOMPATIBLE_DRIVER)
     302           0 :             LOGERROR("Can't create Vulkan instance: incompatible driver.");
     303           0 :         else if (createInstanceResult == VK_ERROR_EXTENSION_NOT_PRESENT)
     304           0 :             LOGERROR("Can't create Vulkan instance: extension not present.");
     305           0 :         else if (createInstanceResult == VK_ERROR_LAYER_NOT_PRESENT)
     306           0 :             LOGERROR("Can't create Vulkan instance: layer not present.");
     307             :         else
     308           0 :             LOGERROR("Unknown error during Vulkan instance creation: {} ({})",
     309             :                 static_cast<int>(createInstanceResult), Utilities::GetVkResultName(createInstanceResult));
     310           0 :         return nullptr;
     311             :     }
     312             : 
     313           0 :     gladVulkanVersion = gladLoadVulkanUserPtr(nullptr, gladLoadFunction, device->m_Instance);
     314           0 :     if (!gladVulkanVersion)
     315             :     {
     316           0 :         LOGERROR("GLAD unable to re-load vulkan after its instance creation.");
     317           0 :         return nullptr;
     318             :     }
     319             : 
     320           0 :     if (GLAD_VK_EXT_debug_utils && enableDebugMessages)
     321             :     {
     322           0 :         VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo{};
     323           0 :         debugCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
     324           0 :         debugCreateInfo.messageSeverity =
     325             :             VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT |
     326             :             VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT |
     327             :             VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
     328           0 :         debugCreateInfo.messageType =
     329             :             VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
     330             :             VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
     331             :             VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
     332           0 :         debugCreateInfo.pfnUserCallback = DebugCallback;
     333           0 :         debugCreateInfo.pUserData = nullptr;
     334             : 
     335           0 :         ENSURE_VK_SUCCESS(vkCreateDebugUtilsMessengerEXT(
     336             :             device->m_Instance, &debugCreateInfo, nullptr, &device->m_DebugMessenger));
     337             :     }
     338             : 
     339           0 :     if (window)
     340           0 :         ENSURE(SDL_Vulkan_CreateSurface(window, device->m_Instance, &device->m_Surface));
     341             : 
     342           0 :     const std::vector<const char*> requiredDeviceExtensions =
     343             :     {
     344             :         VK_KHR_SWAPCHAIN_EXTENSION_NAME
     345           0 :     };
     346           0 :     std::vector<SAvailablePhysicalDevice> availablePhyscialDevices =
     347           0 :         GetAvailablePhysicalDevices(device->m_Instance, device->m_Surface, requiredDeviceExtensions);
     348           0 :     for (const SAvailablePhysicalDevice& device : availablePhyscialDevices)
     349             :     {
     350           0 :         LOGMESSAGE("Vulkan available device: '{}' Type: {} Supported: {}",
     351             :             device.properties.deviceName, static_cast<uint32_t>(device.properties.deviceType),
     352             :             IsPhysicalDeviceUnsupported(device) ? 'N' : 'Y');
     353           0 :         LOGMESSAGE("  ID: {} VendorID: {} API Version: {} Driver Version: {}",
     354             :             device.properties.deviceID, device.properties.vendorID,
     355             :             device.properties.apiVersion, device.properties.driverVersion);
     356           0 :         LOGMESSAGE("  hasRequiredExtensions: {} hasOutputToSurfaceSupport: {}",
     357             :             device.hasRequiredExtensions ? 'Y' : 'N', device.hasOutputToSurfaceSupport ? 'Y' : 'N');
     358           0 :         LOGMESSAGE("  graphicsQueueFamilyIndex: {} presentQueueFamilyIndex: {} families: {}",
     359             :             device.graphicsQueueFamilyIndex, device.presentQueueFamilyIndex,
     360             :             device.queueFamilies.size());
     361           0 :         LOGMESSAGE("  maxBoundDescriptorSets: {}", device.properties.limits.maxBoundDescriptorSets);
     362           0 :         for (const VkSurfaceFormatKHR& surfaceFormat : device.surfaceFormats)
     363             :         {
     364           0 :             LOGMESSAGE("  Surface format: {} colorSpace: {} Supported: {}",
     365             :                 static_cast<uint32_t>(surfaceFormat.format),
     366             :                 static_cast<uint32_t>(surfaceFormat.colorSpace),
     367             :                 IsSurfaceFormatSupported(surfaceFormat) ? 'Y' : 'N');
     368             :         }
     369           0 :         for (uint32_t memoryTypeIndex = 0; memoryTypeIndex < device.memoryProperties.memoryTypeCount; ++memoryTypeIndex)
     370             :         {
     371           0 :             const VkMemoryType& type = device.memoryProperties.memoryTypes[memoryTypeIndex];
     372           0 :             LOGMESSAGE("  Memory Type Index: {} Flags: {} Heap Index: {}",
     373             :                 memoryTypeIndex, type.propertyFlags, type.heapIndex);
     374             :         }
     375           0 :         for (uint32_t memoryHeapIndex = 0; memoryHeapIndex < device.memoryProperties.memoryHeapCount; ++memoryHeapIndex)
     376             :         {
     377           0 :             const VkMemoryHeap& heap = device.memoryProperties.memoryHeaps[memoryHeapIndex];
     378           0 :             LOGMESSAGE("  Memory Heap Index: {} Size: {} Flags: {}",
     379             :                 memoryHeapIndex, heap.size / 1024, heap.flags);
     380             :         }
     381             :     }
     382           0 :     device->m_AvailablePhysicalDevices = availablePhyscialDevices;
     383             :     // We need to remove unsupported devices first.
     384           0 :     availablePhyscialDevices.erase(
     385           0 :         std::remove_if(
     386             :             availablePhyscialDevices.begin(), availablePhyscialDevices.end(),
     387             :             IsPhysicalDeviceUnsupported),
     388           0 :         availablePhyscialDevices.end());
     389           0 :     if (availablePhyscialDevices.empty())
     390             :     {
     391           0 :         LOGERROR("Vulkan can not find any supported and suitable device.");
     392           0 :         return nullptr;
     393             :     }
     394             : 
     395           0 :     const int deviceIndexOverride{g_ConfigDB.Get("renderer.backend.vulkan.deviceindexoverride", -1)};
     396           0 :     auto chosenDeviceIt = device->m_AvailablePhysicalDevices.end();
     397           0 :     if (deviceIndexOverride >= 0)
     398             :     {
     399           0 :         chosenDeviceIt = std::find_if(
     400           0 :             device->m_AvailablePhysicalDevices.begin(), device->m_AvailablePhysicalDevices.end(),
     401           0 :             [deviceIndexOverride](const SAvailablePhysicalDevice& availableDevice)
     402             :             {
     403           0 :                 return availableDevice.index == static_cast<uint32_t>(deviceIndexOverride);
     404             :             });
     405           0 :         if (chosenDeviceIt == device->m_AvailablePhysicalDevices.end())
     406           0 :             LOGWARNING("Device with override index {} not found.", deviceIndexOverride);
     407             :     }
     408           0 :     if (chosenDeviceIt == device->m_AvailablePhysicalDevices.end())
     409             :     {
     410           0 :         const bool chooseBestDevice{g_ConfigDB.Get("renderer.backend.vulkan.choosebestdevice", false)};
     411           0 :         if (chooseBestDevice)
     412             :         {
     413             :             // We need to choose the best available device fits our needs.
     414           0 :             chosenDeviceIt = min_element(
     415             :                 availablePhyscialDevices.begin(), availablePhyscialDevices.end(),
     416             :                 ComparePhysicalDevices);
     417             :         }
     418             :         else
     419             :         {
     420             :             // By default we assume that the Vulkan driver provides a decent default.
     421           0 :             chosenDeviceIt = availablePhyscialDevices.begin();
     422             :         }
     423             :     }
     424           0 :     device->m_ChoosenDevice = *chosenDeviceIt;
     425           0 :     const SAvailablePhysicalDevice& choosenDevice = device->m_ChoosenDevice;
     426           0 :     device->m_AvailablePhysicalDevices.erase(std::remove_if(
     427           0 :         device->m_AvailablePhysicalDevices.begin(), device->m_AvailablePhysicalDevices.end(),
     428           0 :         [physicalDevice = choosenDevice.device](const SAvailablePhysicalDevice& device)
     429             :         {
     430           0 :             return physicalDevice == device.device;
     431           0 :         }), device->m_AvailablePhysicalDevices.end());
     432             : 
     433           0 :     gladVulkanVersion = gladLoadVulkanUserPtr(choosenDevice.device, gladLoadFunction, device->m_Instance);
     434           0 :     if (!gladVulkanVersion)
     435             :     {
     436           0 :         LOGERROR("GLAD unable to re-load vulkan after choosing its physical device.");
     437           0 :         return nullptr;
     438             :     }
     439             : 
     440             : #if !OS_MACOSX
     441           0 :     auto hasDeviceExtension = [&extensions = choosenDevice.extensions](const char* name) -> bool
     442             :     {
     443           0 :         return std::find(extensions.begin(), extensions.end(), name) != extensions.end();
     444           0 :     };
     445           0 :     const bool hasDescriptorIndexing = hasDeviceExtension(VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME);
     446             : #else
     447             :     // Metal on macOS doesn't support combined samplers natively. Currently
     448             :     // they break compiling SPIR-V shaders with descriptor indexing into MTL
     449             :     // shaders when using MoltenVK.
     450             :     const bool hasDescriptorIndexing = false;
     451             : #endif
     452           0 :     const bool hasNeededDescriptorIndexingFeatures =
     453           0 :         hasDescriptorIndexing &&
     454           0 :         choosenDevice.descriptorIndexingProperties.maxUpdateAfterBindDescriptorsInAllPools >= 65536 &&
     455           0 :         choosenDevice.descriptorIndexingFeatures.shaderSampledImageArrayNonUniformIndexing &&
     456           0 :         choosenDevice.descriptorIndexingFeatures.runtimeDescriptorArray &&
     457           0 :         choosenDevice.descriptorIndexingFeatures.descriptorBindingVariableDescriptorCount &&
     458           0 :         choosenDevice.descriptorIndexingFeatures.descriptorBindingPartiallyBound &&
     459           0 :         choosenDevice.descriptorIndexingFeatures.descriptorBindingUpdateUnusedWhilePending &&
     460           0 :         choosenDevice.descriptorIndexingFeatures.descriptorBindingSampledImageUpdateAfterBind;
     461             : 
     462           0 :     std::vector<const char*> deviceExtensions = requiredDeviceExtensions;
     463           0 :     if (hasDescriptorIndexing)
     464           0 :         deviceExtensions.emplace_back(VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME);
     465             : 
     466           0 :     device->m_GraphicsQueueFamilyIndex = choosenDevice.graphicsQueueFamilyIndex;
     467           0 :     const std::array<size_t, 1> queueFamilyIndices{{
     468             :         choosenDevice.graphicsQueueFamilyIndex
     469           0 :     }};
     470             : 
     471           0 :     PS::StaticVector<VkDeviceQueueCreateInfo, 1> queueCreateInfos;
     472           0 :     const float queuePriority = 1.0f;
     473           0 :     std::transform(queueFamilyIndices.begin(), queueFamilyIndices.end(),
     474             :         std::back_inserter(queueCreateInfos),
     475           0 :         [&queuePriority](const size_t queueFamilyIndex)
     476             :         {
     477           0 :             VkDeviceQueueCreateInfo queueCreateInfo{};
     478           0 :             queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
     479           0 :             queueCreateInfo.pQueuePriorities = &queuePriority;
     480           0 :             queueCreateInfo.queueCount = 1;
     481           0 :             queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
     482           0 :             return queueCreateInfo;
     483             :         });
     484             : 
     485             :     // https://github.com/KhronosGroup/Vulkan-Guide/blob/master/chapters/enabling_features.adoc
     486           0 :     VkPhysicalDeviceFeatures deviceFeatures{};
     487           0 :     VkPhysicalDeviceFeatures2 deviceFeatures2{};
     488           0 :     VkPhysicalDeviceDescriptorIndexingFeaturesEXT descriptorIndexingFeatures{};
     489             : 
     490           0 :     deviceFeatures.textureCompressionBC = choosenDevice.features.textureCompressionBC;
     491           0 :     deviceFeatures.samplerAnisotropy = choosenDevice.features.samplerAnisotropy;
     492           0 :     deviceFeatures.fillModeNonSolid = choosenDevice.features.fillModeNonSolid;
     493             : 
     494           0 :     descriptorIndexingFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES_EXT;
     495           0 :     descriptorIndexingFeatures.shaderSampledImageArrayNonUniformIndexing =
     496           0 :         choosenDevice.descriptorIndexingFeatures.shaderSampledImageArrayNonUniformIndexing;
     497           0 :     descriptorIndexingFeatures.runtimeDescriptorArray =
     498           0 :         choosenDevice.descriptorIndexingFeatures.runtimeDescriptorArray;
     499           0 :     descriptorIndexingFeatures.descriptorBindingVariableDescriptorCount =
     500           0 :         choosenDevice.descriptorIndexingFeatures.descriptorBindingVariableDescriptorCount;
     501           0 :     descriptorIndexingFeatures.descriptorBindingPartiallyBound =
     502           0 :         choosenDevice.descriptorIndexingFeatures.descriptorBindingPartiallyBound;
     503           0 :     descriptorIndexingFeatures.descriptorBindingUpdateUnusedWhilePending =
     504           0 :         choosenDevice.descriptorIndexingFeatures.descriptorBindingUpdateUnusedWhilePending;
     505           0 :     descriptorIndexingFeatures.descriptorBindingSampledImageUpdateAfterBind =
     506           0 :         choosenDevice.descriptorIndexingFeatures.descriptorBindingSampledImageUpdateAfterBind;
     507             : 
     508           0 :     deviceFeatures2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
     509           0 :     deviceFeatures2.features = deviceFeatures;
     510           0 :     if (hasNeededDescriptorIndexingFeatures)
     511           0 :         deviceFeatures2.pNext = &descriptorIndexingFeatures;
     512             : 
     513           0 :     VkDeviceCreateInfo deviceCreateInfo{};
     514           0 :     deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
     515           0 :     deviceCreateInfo.queueCreateInfoCount = queueCreateInfos.size();
     516           0 :     deviceCreateInfo.pQueueCreateInfos = queueCreateInfos.data();
     517           0 :     deviceCreateInfo.enabledExtensionCount = deviceExtensions.size();
     518           0 :     deviceCreateInfo.ppEnabledExtensionNames = deviceExtensions.data();
     519           0 :     deviceCreateInfo.pEnabledFeatures = nullptr;
     520           0 :     deviceCreateInfo.pNext = &deviceFeatures2;
     521           0 :     deviceCreateInfo.enabledLayerCount = 0;
     522           0 :     deviceCreateInfo.ppEnabledLayerNames = nullptr;
     523             : 
     524           0 :     const VkResult createDeviceResult = vkCreateDevice(
     525           0 :         choosenDevice.device, &deviceCreateInfo, nullptr, &device->m_Device);
     526           0 :     if (createDeviceResult != VK_SUCCESS)
     527             :     {
     528           0 :         if (createDeviceResult == VK_ERROR_FEATURE_NOT_PRESENT)
     529           0 :             LOGERROR("Can't create Vulkan device: feature not present.");
     530           0 :         else if (createDeviceResult == VK_ERROR_EXTENSION_NOT_PRESENT)
     531           0 :             LOGERROR("Can't create Vulkan device: extension not present.");
     532             :         else
     533           0 :             LOGERROR("Unknown error during Vulkan device creation: {} ({})",
     534             :                 static_cast<int>(createDeviceResult), Utilities::GetVkResultName(createDeviceResult));
     535           0 :         return nullptr;
     536             :     }
     537             : 
     538           0 :     VmaVulkanFunctions vulkanFunctions{};
     539           0 :     vulkanFunctions.vkGetInstanceProcAddr = vkGetInstanceProcAddr;
     540           0 :     vulkanFunctions.vkGetDeviceProcAddr = vkGetDeviceProcAddr;
     541           0 :     vulkanFunctions.vkGetPhysicalDeviceProperties = vkGetPhysicalDeviceProperties;
     542           0 :     vulkanFunctions.vkGetPhysicalDeviceMemoryProperties = vkGetPhysicalDeviceMemoryProperties;
     543           0 :     vulkanFunctions.vkAllocateMemory = vkAllocateMemory;
     544           0 :     vulkanFunctions.vkFreeMemory = vkFreeMemory;
     545           0 :     vulkanFunctions.vkMapMemory = vkMapMemory;
     546           0 :     vulkanFunctions.vkUnmapMemory = vkUnmapMemory;
     547           0 :     vulkanFunctions.vkFlushMappedMemoryRanges = vkFlushMappedMemoryRanges;
     548           0 :     vulkanFunctions.vkInvalidateMappedMemoryRanges = vkInvalidateMappedMemoryRanges;
     549           0 :     vulkanFunctions.vkBindBufferMemory = vkBindBufferMemory;
     550           0 :     vulkanFunctions.vkBindImageMemory = vkBindImageMemory;
     551           0 :     vulkanFunctions.vkGetBufferMemoryRequirements = vkGetBufferMemoryRequirements;
     552           0 :     vulkanFunctions.vkGetImageMemoryRequirements = vkGetImageMemoryRequirements;
     553           0 :     vulkanFunctions.vkCreateBuffer = vkCreateBuffer;
     554           0 :     vulkanFunctions.vkDestroyBuffer = vkDestroyBuffer;
     555           0 :     vulkanFunctions.vkCreateImage = vkCreateImage;
     556           0 :     vulkanFunctions.vkDestroyImage = vkDestroyImage;
     557           0 :     vulkanFunctions.vkCmdCopyBuffer = vkCmdCopyBuffer;
     558             :     // Functions promoted to Vulkan 1.1.
     559           0 :     vulkanFunctions.vkGetBufferMemoryRequirements2KHR = vkGetBufferMemoryRequirements2;
     560           0 :     vulkanFunctions.vkGetImageMemoryRequirements2KHR = vkGetImageMemoryRequirements2;
     561           0 :     vulkanFunctions.vkBindBufferMemory2KHR = vkBindBufferMemory2;
     562           0 :     vulkanFunctions.vkBindImageMemory2KHR = vkBindImageMemory2;
     563           0 :     vulkanFunctions.vkGetPhysicalDeviceMemoryProperties2KHR = vkGetPhysicalDeviceMemoryProperties2;
     564             : 
     565           0 :     VmaAllocatorCreateInfo allocatorCreateInfo{};
     566           0 :     allocatorCreateInfo.instance = device->m_Instance;
     567           0 :     allocatorCreateInfo.physicalDevice = choosenDevice.device;
     568           0 :     allocatorCreateInfo.device = device->m_Device;
     569           0 :     allocatorCreateInfo.vulkanApiVersion = applicationInfo.apiVersion;
     570           0 :     allocatorCreateInfo.pVulkanFunctions = &vulkanFunctions;
     571           0 :     const VkResult createVMAAllocatorResult =
     572           0 :         vmaCreateAllocator(&allocatorCreateInfo, &device->m_VMAAllocator);
     573           0 :     if (createVMAAllocatorResult != VK_SUCCESS)
     574             :     {
     575           0 :         LOGERROR("Failed to create VMA allocator: {} ({})", static_cast<int>(createVMAAllocatorResult),
     576             :             Utilities::GetVkResultName(createVMAAllocatorResult));
     577           0 :         return nullptr;
     578             :     }
     579             : 
     580             :     // We need to use VK_SHARING_MODE_CONCURRENT if we have graphics and present
     581             :     // in different queues.
     582           0 :     vkGetDeviceQueue(device->m_Device, choosenDevice.graphicsQueueFamilyIndex,
     583           0 :         0, &device->m_GraphicsQueue);
     584           0 :     ENSURE(device->m_GraphicsQueue != VK_NULL_HANDLE);
     585             : 
     586           0 :     Capabilities& capabilities = device->m_Capabilities;
     587             : 
     588           0 :     capabilities.debugLabels = enableDebugLabels;
     589           0 :     capabilities.debugScopedLabels = enableDebugScopedLabels;
     590           0 :     capabilities.S3TC = choosenDevice.features.textureCompressionBC;
     591           0 :     capabilities.computeShaders = true;
     592           0 :     capabilities.storage = choosenDevice.properties.limits.maxStorageBufferRange >= GiB;
     593           0 :     capabilities.instancing = true;
     594           0 :     capabilities.maxSampleCount = 1;
     595           0 :     const VkSampleCountFlags sampleCountFlags =
     596           0 :         choosenDevice.properties.limits.framebufferColorSampleCounts
     597           0 :         & choosenDevice.properties.limits.framebufferDepthSampleCounts
     598           0 :         & choosenDevice.properties.limits.framebufferStencilSampleCounts;
     599           0 :     const std::array<VkSampleCountFlagBits, 5> allowedSampleCountBits =
     600             :     {
     601             :         VK_SAMPLE_COUNT_1_BIT,
     602             :         VK_SAMPLE_COUNT_2_BIT,
     603             :         VK_SAMPLE_COUNT_4_BIT,
     604             :         VK_SAMPLE_COUNT_8_BIT,
     605             :         VK_SAMPLE_COUNT_16_BIT,
     606             :     };
     607           0 :     for (size_t index = 0; index < allowedSampleCountBits.size(); ++index)
     608           0 :         if (sampleCountFlags & allowedSampleCountBits[index])
     609           0 :             device->m_Capabilities.maxSampleCount = 1u << index;
     610           0 :     capabilities.multisampling = device->m_Capabilities.maxSampleCount > 1;
     611           0 :     capabilities.anisotropicFiltering = choosenDevice.features.samplerAnisotropy;
     612           0 :     capabilities.maxAnisotropy = choosenDevice.properties.limits.maxSamplerAnisotropy;
     613           0 :     capabilities.maxTextureSize =
     614           0 :         choosenDevice.properties.limits.maxImageDimension2D;
     615           0 :     capabilities.timestamps =
     616           0 :         choosenDevice.properties.limits.timestampComputeAndGraphics
     617           0 :         && choosenDevice.properties.limits.timestampPeriod > 0;
     618           0 :     if (capabilities.timestamps)
     619             :     {
     620           0 :         capabilities.timestampMultiplier =
     621           0 :             device->m_ChoosenDevice.properties.limits.timestampPeriod / 1e9;
     622             :     }
     623             : 
     624           0 :     device->m_RenderPassManager =
     625           0 :         std::make_unique<CRenderPassManager>(device.get());
     626           0 :     device->m_SamplerManager = std::make_unique<CSamplerManager>(device.get());
     627             : 
     628           0 :     device->m_SubmitScheduler = CSubmitScheduler::Create(
     629           0 :         device.get(), device->m_GraphicsQueue);
     630           0 :     if (!device->m_SubmitScheduler)
     631           0 :         return nullptr;
     632             : 
     633           0 :     const bool useDescriptorIndexing{hasNeededDescriptorIndexingFeatures &&
     634           0 :         !g_ConfigDB.Get("renderer.backend.vulkan.disabledescriptorindexing", false)};
     635           0 :     device->m_DescriptorManager =
     636           0 :         std::make_unique<CDescriptorManager>(device.get(), useDescriptorIndexing);
     637             : 
     638           0 :     device->m_Name = choosenDevice.properties.deviceName;
     639           0 :     device->m_Version =
     640           0 :         std::to_string(VK_API_VERSION_VARIANT(choosenDevice.properties.apiVersion)) +
     641           0 :         "." + std::to_string(VK_API_VERSION_MAJOR(choosenDevice.properties.apiVersion)) +
     642           0 :         "." + std::to_string(VK_API_VERSION_MINOR(choosenDevice.properties.apiVersion)) +
     643           0 :         "." + std::to_string(VK_API_VERSION_PATCH(choosenDevice.properties.apiVersion));
     644             : 
     645           0 :     device->m_DriverInformation = std::to_string(choosenDevice.properties.driverVersion);
     646             : 
     647             :     // Refs:
     648             :     // * https://www.khronos.org/registry/vulkan/specs/1.3-extensions/man/html/VkPhysicalDeviceProperties.html
     649             :     // * https://pcisig.com/membership/member-companies
     650           0 :     device->m_VendorID = std::to_string(choosenDevice.properties.vendorID);
     651             : 
     652           0 :     device->m_Extensions = choosenDevice.extensions;
     653             : 
     654           0 :     if (device->m_Capabilities.timestamps)
     655             :     {
     656           0 :         VkQueryPoolCreateInfo queryPoolInfo{};
     657           0 :         queryPoolInfo.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
     658           0 :         queryPoolInfo.queryType = VK_QUERY_TYPE_TIMESTAMP;
     659           0 :         queryPoolInfo.queryCount = QUERY_POOL_SIZE;
     660             : 
     661           0 :         ENSURE_VK_SUCCESS(vkCreateQueryPool(
     662             :             device->GetVkDevice(), &queryPoolInfo, nullptr, &device->m_QueryPool));
     663             : 
     664           0 :         device->m_Queries.resize(QUERY_POOL_SIZE);
     665             :     }
     666             : 
     667           0 :     return device;
     668           0 : }
     669             : 
     670           0 : CDevice::CDevice() = default;
     671             : 
     672           0 : CDevice::~CDevice()
     673             : {
     674             :     // The order of destroying does matter to avoid use-after-free and validation
     675             :     // layers complaints.
     676             : 
     677           0 :     m_SubmitScheduler.reset();
     678             : 
     679           0 :     if (m_QueryPool)
     680           0 :         vkDestroyQueryPool(GetVkDevice(), m_QueryPool, nullptr);
     681             : 
     682           0 :     ProcessDeviceObjectToDestroyQueue(true);
     683             : 
     684           0 :     m_RenderPassManager.reset();
     685           0 :     m_SamplerManager.reset();
     686           0 :     m_DescriptorManager.reset();
     687             : 
     688           0 :     ProcessObjectToDestroyQueue(true);
     689             : 
     690           0 :     if (m_VMAAllocator != VK_NULL_HANDLE)
     691           0 :         vmaDestroyAllocator(m_VMAAllocator);
     692             : 
     693           0 :     if (m_Device != VK_NULL_HANDLE)
     694           0 :         vkDestroyDevice(m_Device, nullptr);
     695             : 
     696           0 :     if (m_Surface != VK_NULL_HANDLE)
     697           0 :         vkDestroySurfaceKHR(m_Instance, m_Surface, nullptr);
     698             : 
     699           0 :     if (GLAD_VK_EXT_debug_utils && m_DebugMessenger)
     700           0 :         vkDestroyDebugUtilsMessengerEXT(m_Instance, m_DebugMessenger, nullptr);
     701             : 
     702           0 :     if (m_Instance != VK_NULL_HANDLE)
     703           0 :         vkDestroyInstance(m_Instance, nullptr);
     704           0 : }
     705             : 
     706           0 : void CDevice::Report(const Script::Request& rq, JS::HandleValue settings)
     707             : {
     708           0 :     Script::SetProperty(rq, settings, "name", "vulkan");
     709             : 
     710           0 :     Script::SetProperty(rq, settings, "extensions", m_Extensions);
     711             : 
     712           0 :     JS::RootedValue device(rq.cx);
     713           0 :     Script::CreateObject(rq, &device);
     714           0 :     ReportAvailablePhysicalDevice(m_ChoosenDevice, rq, device);
     715           0 :     Script::SetProperty(rq, settings, "choosen_device", device);
     716             : 
     717           0 :     JS::RootedValueVector availableDevices{rq.cx};
     718           0 :     if (!availableDevices.reserve(m_AvailablePhysicalDevices.size()))
     719           0 :         throw std::runtime_error{"Reserve failed"};
     720           0 :     for (const SAvailablePhysicalDevice& d : m_AvailablePhysicalDevices)
     721             :     {
     722           0 :         JS::RootedValue device(rq.cx);
     723           0 :         Script::CreateObject(rq, &device);
     724           0 :         ReportAvailablePhysicalDevice(d, rq, device);
     725           0 :         if (!availableDevices.append(device))
     726           0 :             throw std::runtime_error{"Append failed"};
     727           0 :     }
     728           0 :     Script::SetProperty(rq, settings, "available_devices",
     729           0 :         JS::RootedValue{rq.cx, JS::ObjectValue(*JS::NewArrayObject(rq.cx, availableDevices))});
     730             : 
     731           0 :     Script::SetProperty(rq, settings, "instance_extensions", m_InstanceExtensions);
     732           0 :     Script::SetProperty(rq, settings, "validation_layers", m_ValidationLayers);
     733           0 : }
     734             : 
     735           0 : std::unique_ptr<ISwapChain> CDevice::CreateSwapChain(
     736             :     const char* name, SDL_Window* window,
     737             :     int surfaceDrawableWidth, int surfaceDrawableHeight,
     738             :     const bool vsync, std::unique_ptr<ISwapChain> oldSwapChain)
     739             : {
     740           0 :     ENSURE(window == m_Window);
     741           0 :     ENSURE(m_Window);
     742           0 :     if (window)
     743           0 :         SDL_Vulkan_GetDrawableSize(window, &surfaceDrawableWidth, &surfaceDrawableHeight);
     744           0 :     return CSwapChain::Create(
     745             :         this, m_SubmitScheduler.get(),
     746             :         m_GraphicsQueueFamilyIndex, m_GraphicsQueue,
     747             :         name, m_Surface,
     748             :         surfaceDrawableWidth, surfaceDrawableHeight,
     749           0 :         vsync, std::move(oldSwapChain));
     750             : }
     751             : 
     752           0 : void CDevice::WaitUntilIdle()
     753             : {
     754           0 :     vkDeviceWaitIdle(m_Device);
     755             : 
     756             :     // Since we know there is no GPU work in progress we can free resources
     757             :     // queued for deletion.
     758           0 :     ProcessDeviceObjectToDestroyQueue(true);
     759           0 :     ProcessObjectToDestroyQueue(true);
     760           0 : }
     761             : 
     762           0 : std::unique_ptr<IGraphicsPipelineState> CDevice::CreateGraphicsPipelineState(
     763             :     const SGraphicsPipelineStateDesc& pipelineStateDesc)
     764             : {
     765           0 :     return CGraphicsPipelineState::Create(this, pipelineStateDesc);
     766             : }
     767             : 
     768           0 : std::unique_ptr<IComputePipelineState> CDevice::CreateComputePipelineState(
     769             :     const SComputePipelineStateDesc& pipelineStateDesc)
     770             : {
     771           0 :     return CComputePipelineState::Create(this, pipelineStateDesc);
     772             : }
     773             : 
     774           0 : std::unique_ptr<IVertexInputLayout> CDevice::CreateVertexInputLayout(
     775             :     const std::span<const SVertexAttributeFormat> attributes)
     776             : {
     777           0 :     return std::make_unique<CVertexInputLayout>(this, attributes);
     778             : }
     779             : 
     780           0 : std::unique_ptr<ITexture> CDevice::CreateTexture(
     781             :     const char* name, const ITexture::Type type, const uint32_t usage,
     782             :     const Format format, const uint32_t width, const uint32_t height,
     783             :     const Sampler::Desc& defaultSamplerDesc, const uint32_t MIPLevelCount, const uint32_t sampleCount)
     784             : {
     785           0 :     return CTexture::Create(
     786             :         this, name, type, usage, format, width, height,
     787           0 :         defaultSamplerDesc, MIPLevelCount, sampleCount);
     788             : }
     789             : 
     790           0 : std::unique_ptr<ITexture> CDevice::CreateTexture2D(
     791             :     const char* name, const uint32_t usage,
     792             :     const Format format, const uint32_t width, const uint32_t height,
     793             :     const Sampler::Desc& defaultSamplerDesc, const uint32_t MIPLevelCount, const uint32_t sampleCount)
     794             : {
     795           0 :     return CreateTexture(
     796             :         name, ITexture::Type::TEXTURE_2D, usage, format,
     797           0 :         width, height, defaultSamplerDesc, MIPLevelCount, sampleCount);
     798             : }
     799             : 
     800           0 : std::unique_ptr<IFramebuffer> CDevice::CreateFramebuffer(
     801             :     const char* name, SColorAttachment* colorAttachment,
     802             :     SDepthStencilAttachment* depthStencilAttachment)
     803             : {
     804           0 :     return CFramebuffer::Create(
     805           0 :         this, name, colorAttachment, depthStencilAttachment);
     806             : }
     807             : 
     808           0 : std::unique_ptr<IBuffer> CDevice::CreateBuffer(
     809             :     const char* name, const IBuffer::Type type, const uint32_t size, const uint32_t usage)
     810             : {
     811           0 :     return CreateCBuffer(name, type, size, usage);
     812             : }
     813             : 
     814           0 : std::unique_ptr<CBuffer> CDevice::CreateCBuffer(
     815             :     const char* name, const IBuffer::Type type, const uint32_t size, const uint32_t usage)
     816             : {
     817           0 :     return CBuffer::Create(this, name, type, size, usage);
     818             : }
     819             : 
     820           0 : std::unique_ptr<IShaderProgram> CDevice::CreateShaderProgram(
     821             :     const CStr& name, const CShaderDefines& defines)
     822             : {
     823           0 :     return CShaderProgram::Create(this, name, defines);
     824             : }
     825             : 
     826           0 : std::unique_ptr<IDeviceCommandContext> CDevice::CreateCommandContext()
     827             : {
     828           0 :     return CDeviceCommandContext::Create(this);
     829             : }
     830             : 
     831           0 : void CDevice::OnPresent()
     832             : {
     833           0 :     ProcessObjectToDestroyQueue();
     834           0 :     ProcessDeviceObjectToDestroyQueue();
     835             : 
     836           0 :     ++m_FrameID;
     837           0 : }
     838             : 
     839           0 : void CDevice::OnSwapChainRecreation()
     840             : {
     841             :     // We're sure that a client must call WaitUntilIdle to be able to
     842             :     // recreate a swapchain.
     843           0 :     ProcessObjectToDestroyQueue(true);
     844           0 :     ProcessDeviceObjectToDestroyQueue(true);
     845           0 : }
     846             : 
     847           0 : bool CDevice::IsTextureFormatSupported(const Format format) const
     848             : {
     849           0 :     switch (format)
     850             :     {
     851             :     case Format::UNDEFINED:
     852             :         return false;
     853             : 
     854             :     case Format::R8G8B8_UNORM:
     855             :         return false;
     856             : 
     857           0 :     case Format::BC1_RGB_UNORM:
     858           0 :     case Format::BC1_RGB_SRGB:
     859           0 :     case Format::BC1_RGBA_UNORM:
     860           0 :     case Format::BC1_RGBA_SRGB:
     861           0 :     case Format::BC2_UNORM:
     862           0 :     case Format::BC2_SRGB:
     863           0 :     case Format::BC3_UNORM:
     864           0 :     case Format::BC3_SRGB:
     865           0 :         if (m_Capabilities.S3TC)
     866             :             return true;
     867             :         else
     868             :             break;
     869             : 
     870             :     default:
     871             :         break;
     872             :     }
     873             : 
     874           0 :     VkFormatProperties formatProperties{};
     875           0 :     vkGetPhysicalDeviceFormatProperties(
     876           0 :         m_ChoosenDevice.device, Mapping::FromFormat(format), &formatProperties);
     877           0 :     return formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT;
     878             : }
     879             : 
     880           0 : bool CDevice::IsFramebufferFormatSupported(const Format format) const
     881             : {
     882           0 :     VkFormatProperties formatProperties{};
     883           0 :     vkGetPhysicalDeviceFormatProperties(
     884           0 :         m_ChoosenDevice.device, Mapping::FromFormat(format), &formatProperties);
     885           0 :     if (IsDepthFormat(format))
     886           0 :         return formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT;
     887           0 :     return formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT;
     888             : }
     889             : 
     890           0 : Format CDevice::GetPreferredDepthStencilFormat(
     891             :     const uint32_t usage, const bool depth, const bool stencil) const
     892             : {
     893           0 :     ENSURE(depth || stencil);
     894           0 :     Format format = Format::UNDEFINED;
     895           0 :     if (stencil)
     896             :     {
     897             :         // https://github.com/KhronosGroup/Vulkan-Guide/blob/main/chapters/depth.adoc#depth-formats
     898             :         // At least one of VK_FORMAT_D24_UNORM_S8_UINT or VK_FORMAT_D32_SFLOAT_S8_UINT
     899             :         // must also be supported.
     900           0 :         if (IsFormatSupportedForUsage(Format::D24_UNORM_S8_UINT, usage))
     901             :             format = Format::D24_UNORM_S8_UINT;
     902             :         else
     903           0 :             format = Format::D32_SFLOAT_S8_UINT;
     904             :     }
     905             :     else
     906             :     {
     907           0 :         std::array<Format, 3> formatRequestOrder;
     908             :         // TODO: add most known vendors to enum.
     909             :         // https://developer.nvidia.com/blog/vulkan-dos-donts/
     910           0 :         if (m_ChoosenDevice.properties.vendorID == 0x10DE)
     911           0 :             formatRequestOrder = {Format::D24_UNORM, Format::D32_SFLOAT, Format::D16_UNORM};
     912             :         else
     913           0 :             formatRequestOrder = {Format::D32_SFLOAT, Format::D24_UNORM, Format::D16_UNORM};
     914           0 :         for (const Format formatRequest : formatRequestOrder)
     915           0 :             if (IsFormatSupportedForUsage(formatRequest, usage))
     916             :             {
     917             :                 format = formatRequest;
     918             :                 break;
     919             :             }
     920             :     }
     921           0 :     return format;
     922             : }
     923             : 
     924           0 : uint32_t CDevice::AllocateQuery()
     925             : {
     926           0 :     ENSURE(m_Capabilities.timestamps);
     927           0 :     auto it = std::find_if(
     928           0 :         m_Queries.begin(), m_Queries.end(), [](const CDevice::Query& query)
     929             :         {
     930           0 :             return !query.occupied;
     931             :         });
     932           0 :     ENSURE(it != m_Queries.end());
     933           0 :     it->occupied = true;
     934           0 :     return std::distance(m_Queries.begin(), it);
     935             : }
     936             : 
     937           0 : void CDevice::FreeQuery(const uint32_t handle)
     938             : {
     939           0 :     ENSURE(handle < m_Queries.size());
     940           0 :     ENSURE(m_Queries[handle].occupied);
     941           0 :     m_Queries[handle].occupied = false;
     942           0 : }
     943             : 
     944           0 : bool CDevice::IsQueryResultAvailable(const uint32_t handle) const
     945             : {
     946           0 :     ENSURE(handle < m_Queries.size());
     947           0 :     const Query& query{m_Queries[handle]};
     948           0 :     ENSURE(query.occupied);
     949           0 :     ENSURE(query.submitted);
     950           0 :     if (query.lastUsageFrameID + NUMBER_OF_FRAMES_IN_FLIGHT > m_FrameID)
     951             :         return false;
     952           0 :     uint64_t data{};
     953           0 :     return vkGetQueryPoolResults(
     954           0 :         GetVkDevice(), m_QueryPool, handle, 1, sizeof(data), &data, 0, VK_QUERY_RESULT_64_BIT) != VK_NOT_READY;
     955             : }
     956             : 
     957           0 : uint64_t CDevice::GetQueryResult(const uint32_t handle)
     958             : {
     959           0 :     ENSURE(handle < m_Queries.size());
     960           0 :     Query& query{m_Queries[handle]};
     961           0 :     ENSURE(query.occupied);
     962           0 :     ENSURE(query.submitted);
     963           0 :     uint64_t data{};
     964           0 :     ENSURE_VK_SUCCESS(vkGetQueryPoolResults(
     965             :         GetVkDevice(), m_QueryPool, handle, 1, sizeof(data), &data, 0, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT));
     966           0 :     query.submitted = false;
     967           0 :     return data;
     968             : }
     969             : 
     970           0 : void CDevice::CollectStatistics(StatisticsVector& statistics) const
     971             : {
     972           0 :     VmaBudget heapBudgets[VK_MAX_MEMORY_HEAPS];
     973           0 :     vmaGetHeapBudgets(m_VMAAllocator, heapBudgets);
     974             : 
     975           0 :     VmaStatistics totalStatistics{};
     976           0 :     for (uint32_t index{0}; index < m_ChoosenDevice.memoryProperties.memoryHeapCount; ++index)
     977             :     {
     978           0 :         totalStatistics.blockCount += heapBudgets[index].statistics.blockCount;
     979           0 :         totalStatistics.allocationCount += heapBudgets[index].statistics.allocationCount;
     980           0 :         totalStatistics.blockBytes += heapBudgets[index].statistics.blockBytes;
     981           0 :         totalStatistics.allocationBytes += heapBudgets[index].statistics.allocationBytes;
     982             :     }
     983             : 
     984           0 :     statistics.emplace_back("VMA total blockCount", "", totalStatistics.blockCount);
     985           0 :     statistics.emplace_back("VMA total allocationCount", "", totalStatistics.allocationCount);
     986           0 :     statistics.emplace_back("VMA total blockBytes", "MiB", static_cast<uint32_t>(totalStatistics.blockBytes / MiB));
     987           0 :     statistics.emplace_back("VMA total allocationBytes", "MiB", static_cast<uint32_t>(totalStatistics.allocationBytes / MiB));
     988             : 
     989           0 :     m_DescriptorManager->CollectStatistics(statistics);
     990           0 :     m_SamplerManager->CollectStatistics(statistics);
     991           0 :     m_RenderPassManager->CollectStatistics(statistics);
     992           0 : }
     993             : 
     994           0 : bool CDevice::IsFormatSupportedForUsage(const Format format, const uint32_t usage) const
     995             : {
     996           0 :     VkFormatProperties formatProperties{};
     997           0 :     vkGetPhysicalDeviceFormatProperties(
     998           0 :         m_ChoosenDevice.device, Mapping::FromFormat(format), &formatProperties);
     999           0 :     VkFormatFeatureFlags expectedFeatures = 0;
    1000           0 :     if (usage & ITexture::Usage::COLOR_ATTACHMENT)
    1001           0 :         expectedFeatures |= VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT;
    1002           0 :     if (usage & ITexture::Usage::DEPTH_STENCIL_ATTACHMENT)
    1003           0 :         expectedFeatures |= VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT;
    1004           0 :     if (usage & ITexture::Usage::SAMPLED)
    1005           0 :         expectedFeatures |= VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT;
    1006           0 :     if (usage & ITexture::Usage::TRANSFER_SRC)
    1007           0 :         expectedFeatures |= VK_FORMAT_FEATURE_TRANSFER_SRC_BIT;
    1008           0 :     if (usage & ITexture::Usage::TRANSFER_DST)
    1009           0 :         expectedFeatures |= VK_FORMAT_FEATURE_TRANSFER_DST_BIT;
    1010           0 :     return (formatProperties.optimalTilingFeatures & expectedFeatures) == expectedFeatures;
    1011             : }
    1012             : 
    1013           0 : void CDevice::InsertTimestampQuery(VkCommandBuffer commandBuffer, const uint32_t handle, const bool isScopeBegin)
    1014             : {
    1015           0 :     ENSURE(handle < m_Queries.size());
    1016           0 :     vkCmdResetQueryPool(
    1017             :         commandBuffer, m_QueryPool, handle, 1);
    1018           0 :     vkCmdWriteTimestamp(
    1019             :         commandBuffer, isScopeBegin ? VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT : VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, m_QueryPool, handle);
    1020           0 :     m_Queries[handle].lastUsageFrameID = m_FrameID;
    1021           0 :     m_Queries[handle].submitted = true;
    1022           0 : }
    1023             : 
    1024           0 : void CDevice::ScheduleObjectToDestroy(
    1025             :     VkObjectType type, const uint64_t handle, const VmaAllocation allocation)
    1026             : {
    1027           0 :     m_ObjectToDestroyQueue.push({m_FrameID, type, handle, allocation});
    1028           0 : }
    1029             : 
    1030           0 : void CDevice::ScheduleTextureToDestroy(const DeviceObjectUID uid)
    1031             : {
    1032           0 :     m_TextureToDestroyQueue.push({m_FrameID, uid});
    1033           0 : }
    1034             : 
    1035           0 : void CDevice::ScheduleBufferToDestroy(const DeviceObjectUID uid)
    1036             : {
    1037           0 :     m_BufferToDestroyQueue.push({m_FrameID, uid});
    1038           0 : }
    1039             : 
    1040           0 : void CDevice::SetObjectName(VkObjectType type, const uint64_t handle, const char* name)
    1041             : {
    1042           0 :     if (!m_Capabilities.debugLabels)
    1043           0 :         return;
    1044           0 :     VkDebugUtilsObjectNameInfoEXT nameInfo{};
    1045           0 :     nameInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
    1046           0 :     nameInfo.objectType = type;
    1047           0 :     nameInfo.objectHandle = handle;
    1048           0 :     nameInfo.pObjectName = name;
    1049           0 :     vkSetDebugUtilsObjectNameEXT(m_Device, &nameInfo);
    1050             : }
    1051             : 
    1052           0 : std::unique_ptr<CRingCommandContext> CDevice::CreateRingCommandContext(const size_t size)
    1053             : {
    1054           0 :     return CRingCommandContext::Create(
    1055           0 :         this, size, m_GraphicsQueueFamilyIndex, *m_SubmitScheduler);
    1056             : }
    1057             : 
    1058           0 : void CDevice::ProcessObjectToDestroyQueue(const bool ignoreFrameID)
    1059             : {
    1060           0 :     while (!m_ObjectToDestroyQueue.empty() &&
    1061           0 :         (ignoreFrameID || m_ObjectToDestroyQueue.front().frameID + NUMBER_OF_FRAMES_IN_FLIGHT < m_FrameID))
    1062             :     {
    1063           0 :         ObjectToDestroy& object = m_ObjectToDestroyQueue.front();
    1064             : #if VK_USE_64_BIT_PTR_DEFINES
    1065           0 :         void* handle = reinterpret_cast<void*>(object.handle);
    1066             : #else
    1067             :         const uint64_t handle = object.handle;
    1068             : #endif
    1069           0 :         switch (object.type)
    1070             :         {
    1071           0 :         case VK_OBJECT_TYPE_IMAGE:
    1072           0 :             vmaDestroyImage(GetVMAAllocator(), static_cast<VkImage>(handle), object.allocation);
    1073           0 :             break;
    1074           0 :         case VK_OBJECT_TYPE_BUFFER:
    1075           0 :             vmaDestroyBuffer(GetVMAAllocator(), static_cast<VkBuffer>(handle), object.allocation);
    1076           0 :             break;
    1077           0 :         case VK_OBJECT_TYPE_IMAGE_VIEW:
    1078           0 :             vkDestroyImageView(m_Device, static_cast<VkImageView>(handle), nullptr);
    1079           0 :             break;
    1080           0 :         case VK_OBJECT_TYPE_BUFFER_VIEW:
    1081           0 :             vkDestroyBufferView(m_Device, static_cast<VkBufferView>(handle), nullptr);
    1082           0 :             break;
    1083           0 :         case VK_OBJECT_TYPE_FRAMEBUFFER:
    1084           0 :             vkDestroyFramebuffer(m_Device, static_cast<VkFramebuffer>(handle), nullptr);
    1085           0 :             break;
    1086           0 :         case VK_OBJECT_TYPE_RENDER_PASS:
    1087           0 :             vkDestroyRenderPass(m_Device, static_cast<VkRenderPass>(handle), nullptr);
    1088           0 :             break;
    1089           0 :         case VK_OBJECT_TYPE_SAMPLER:
    1090           0 :             vkDestroySampler(m_Device, static_cast<VkSampler>(handle), nullptr);
    1091           0 :             break;
    1092           0 :         case VK_OBJECT_TYPE_SHADER_MODULE:
    1093           0 :             vkDestroyShaderModule(m_Device, static_cast<VkShaderModule>(handle), nullptr);
    1094           0 :             break;
    1095           0 :         case VK_OBJECT_TYPE_PIPELINE_LAYOUT:
    1096           0 :             vkDestroyPipelineLayout(m_Device, static_cast<VkPipelineLayout>(handle), nullptr);
    1097           0 :             break;
    1098           0 :         case VK_OBJECT_TYPE_PIPELINE:
    1099           0 :             vkDestroyPipeline(m_Device, static_cast<VkPipeline>(handle), nullptr);
    1100           0 :             break;
    1101           0 :         case VK_OBJECT_TYPE_DESCRIPTOR_POOL:
    1102           0 :             vkDestroyDescriptorPool(m_Device, static_cast<VkDescriptorPool>(handle), nullptr);
    1103           0 :             break;
    1104           0 :         default:
    1105           0 :             debug_warn("Unsupported object to destroy type.");
    1106             :         }
    1107           0 :         m_ObjectToDestroyQueue.pop();
    1108             :     }
    1109           0 : }
    1110             : 
    1111           0 : void CDevice::ProcessDeviceObjectToDestroyQueue(const bool ignoreFrameID)
    1112             : {
    1113           0 :     while (!m_TextureToDestroyQueue.empty() &&
    1114           0 :         (ignoreFrameID || m_TextureToDestroyQueue.front().first + NUMBER_OF_FRAMES_IN_FLIGHT < m_FrameID))
    1115             :     {
    1116           0 :         GetDescriptorManager().OnTextureDestroy(m_TextureToDestroyQueue.front().second);
    1117           0 :         m_TextureToDestroyQueue.pop();
    1118             :     }
    1119             : 
    1120           0 :     while (!m_BufferToDestroyQueue.empty() &&
    1121           0 :         (ignoreFrameID || m_BufferToDestroyQueue.front().first + NUMBER_OF_FRAMES_IN_FLIGHT < m_FrameID))
    1122             :     {
    1123           0 :         GetDescriptorManager().OnBufferDestroy(m_BufferToDestroyQueue.front().second);
    1124           0 :         m_BufferToDestroyQueue.pop();
    1125             :     }
    1126           0 : }
    1127             : 
    1128           0 : DeviceObjectUID CDevice::GenerateNextDeviceObjectUID()
    1129             : {
    1130           0 :     ENSURE(m_LastAvailableUID < std::numeric_limits<DeviceObjectUID>::max());
    1131           0 :     return m_LastAvailableUID++;
    1132             : }
    1133             : 
    1134           0 : std::unique_ptr<IDevice> CreateDevice(SDL_Window* window)
    1135             : {
    1136           0 :     return Vulkan::CDevice::Create(window);
    1137             : }
    1138             : 
    1139             : } // namespace Vulkan
    1140             : 
    1141             : } // namespace Backend
    1142             : 
    1143             : } // namespace Renderer

Generated by: LCOV version 1.16