From 1753e731da3f7f2c6b0dc0cdeee45f29fd8704af Mon Sep 17 00:00:00 2001 From: libretroadmin Date: Fri, 24 Jun 2022 17:41:20 +0200 Subject: [PATCH] - Get rid of unused Vulkan SwapChain code - Get rid of unused GetRefreshRate OS-specific code - Get rid of unused GetHostRefreshRate code - Get rid of unused Vulkan-context CreateVulkanInstance/SelectInstanceExtensions/ContextCreate - Get rid of unused Vulkan-context threading code - Get rid of unused Vulkan-context Present code (unused for libretro core) --- src/common/CMakeLists.txt | 3 - src/common/vulkan/context.cpp | 331 +--------- src/common/vulkan/context.h | 44 -- src/common/vulkan/staging_texture.cpp | 2 +- src/common/vulkan/swap_chain.cpp | 851 -------------------------- src/common/vulkan/swap_chain.h | 106 ---- src/common/window_info.cpp | 160 ----- src/common/window_info.h | 2 - src/core/host_display.cpp | 11 - src/core/host_display.h | 2 - 10 files changed, 2 insertions(+), 1510 deletions(-) delete mode 100644 src/common/vulkan/swap_chain.cpp delete mode 100644 src/common/vulkan/swap_chain.h delete mode 100644 src/common/window_info.cpp diff --git a/src/common/CMakeLists.txt b/src/common/CMakeLists.txt index 04f5dfee..c0e34d8a 100644 --- a/src/common/CMakeLists.txt +++ b/src/common/CMakeLists.txt @@ -104,13 +104,10 @@ add_library(common vulkan/staging_texture.h vulkan/stream_buffer.cpp vulkan/stream_buffer.h - vulkan/swap_chain.cpp - vulkan/swap_chain.h vulkan/texture.cpp vulkan/texture.h vulkan/util.cpp vulkan/util.h - window_info.cpp window_info.h ) diff --git a/src/common/vulkan/context.cpp b/src/common/vulkan/context.cpp index 84fcd6b4..d7098d20 100644 --- a/src/common/vulkan/context.cpp +++ b/src/common/vulkan/context.cpp @@ -8,7 +8,6 @@ #include "../log.h" #include "../string_util.h" #include "../window_info.h" -#include "swap_chain.h" #include "util.h" #include #include @@ -39,8 +38,6 @@ Context::Context(VkInstance instance, VkPhysicalDevice physical_device, bool own Context::~Context() { - StopPresentThread(); - if (m_device != VK_NULL_HANDLE) WaitForGPUIdle(); @@ -97,125 +94,6 @@ bool Context::CheckValidationLayerAvailablility() }) != layer_list.end()); } -VkInstance Context::CreateVulkanInstance(const WindowInfo* wi, bool enable_debug_utils, bool enable_validation_layer) -{ - ExtensionList enabled_extensions; - if (!SelectInstanceExtensions(&enabled_extensions, wi, enable_debug_utils)) - return VK_NULL_HANDLE; - - VkApplicationInfo app_info = {}; - app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; - app_info.pNext = nullptr; - app_info.pApplicationName = "DuckStation"; - app_info.applicationVersion = VK_MAKE_VERSION(0, 1, 0); - app_info.pEngineName = "DuckStation"; - app_info.engineVersion = VK_MAKE_VERSION(0, 1, 0); - app_info.apiVersion = VK_MAKE_VERSION(1, 0, 0); - - VkInstanceCreateInfo instance_create_info = {}; - instance_create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; - instance_create_info.pNext = nullptr; - instance_create_info.flags = 0; - instance_create_info.pApplicationInfo = &app_info; - instance_create_info.enabledExtensionCount = static_cast(enabled_extensions.size()); - instance_create_info.ppEnabledExtensionNames = enabled_extensions.data(); - instance_create_info.enabledLayerCount = 0; - instance_create_info.ppEnabledLayerNames = nullptr; - - // Enable debug layer on debug builds - if (enable_validation_layer) - { - static const char* layer_names[] = {"VK_LAYER_KHRONOS_validation"}; - instance_create_info.enabledLayerCount = 1; - instance_create_info.ppEnabledLayerNames = layer_names; - } - - VkInstance instance; - VkResult res = vkCreateInstance(&instance_create_info, nullptr, &instance); - if (res != VK_SUCCESS) - { - LOG_VULKAN_ERROR(res, "vkCreateInstance failed: "); - return nullptr; - } - - return instance; -} - -bool Context::SelectInstanceExtensions(ExtensionList* extension_list, const WindowInfo* wi, bool enable_debug_utils) -{ - u32 extension_count = 0; - VkResult res = vkEnumerateInstanceExtensionProperties(nullptr, &extension_count, nullptr); - if (res != VK_SUCCESS) - { - LOG_VULKAN_ERROR(res, "vkEnumerateInstanceExtensionProperties failed: "); - return false; - } - - if (extension_count == 0) - { - Log_ErrorPrintf("Vulkan: No extensions supported by instance."); - return false; - } - - std::vector available_extension_list(extension_count); - res = vkEnumerateInstanceExtensionProperties(nullptr, &extension_count, available_extension_list.data()); - Assert(res == VK_SUCCESS); - - for (const auto& extension_properties : available_extension_list) - Log_InfoPrintf("Available extension: %s", extension_properties.extensionName); - - auto SupportsExtension = [&](const char* name, bool required) { - if (std::find_if(available_extension_list.begin(), available_extension_list.end(), - [&](const VkExtensionProperties& properties) { - return !strcmp(name, properties.extensionName); - }) != available_extension_list.end()) - { - Log_InfoPrintf("Enabling extension: %s", name); - extension_list->push_back(name); - return true; - } - - if (required) - Log_ErrorPrintf("Vulkan: Missing required extension %s.", name); - - return false; - }; - - // Common extensions - if (wi && wi->type != WindowInfo::Type::Surfaceless && !SupportsExtension(VK_KHR_SURFACE_EXTENSION_NAME, true)) - return false; - -#if defined(VK_USE_PLATFORM_WIN32_KHR) - if (wi && wi->type == WindowInfo::Type::Win32 && !SupportsExtension(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, true)) - return false; -#endif -#if defined(VK_USE_PLATFORM_XLIB_KHR) - if (wi && wi->type == WindowInfo::Type::X11 && !SupportsExtension(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, true)) - return false; -#endif -#if defined(VK_USE_PLATFORM_WAYLAND_KHR) - if (wi && wi->type == WindowInfo::Type::Wayland && !SupportsExtension(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, true)) - return false; -#endif -#if defined(VK_USE_PLATFORM_ANDROID_KHR) - if (wi && wi->type == WindowInfo::Type::Android && !SupportsExtension(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME, true)) - return false; -#endif -#if defined(VK_USE_PLATFORM_METAL_EXT) - if (wi && wi->type == WindowInfo::Type::MacOS && !SupportsExtension(VK_EXT_METAL_SURFACE_EXTENSION_NAME, true)) - return false; -#endif - - if (wi && wi->type == WindowInfo::Type::Display && !SupportsExtension(VK_KHR_DISPLAY_EXTENSION_NAME, true)) - return false; - - // VK_EXT_debug_utils - if (enable_debug_utils && !SupportsExtension(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, false)) - Log_WarningPrintf("Vulkan: Debug report requested, but extension is not available."); - - return true; -} - Context::GPUList Context::EnumerateGPUs(VkInstance instance) { u32 gpu_count = 0; @@ -289,102 +167,6 @@ Context::GPUNameList Context::EnumerateGPUNames(VkInstance instance) return gpu_names; } -bool Context::Create(std::string_view gpu_name, const WindowInfo* wi, std::unique_ptr* out_swap_chain, - bool threaded_presentation, bool enable_debug_utils, bool enable_validation_layer) -{ - AssertMsg(!g_vulkan_context, "Has no current context"); - - if (!Vulkan::LoadVulkanLibrary()) - { - Log_ErrorPrintf("Failed to load Vulkan library"); - return false; - } - - const bool enable_surface = (wi && wi->type != WindowInfo::Type::Surfaceless); - VkInstance instance = CreateVulkanInstance(wi, enable_debug_utils, enable_validation_layer); - if (instance == VK_NULL_HANDLE) - { - Vulkan::UnloadVulkanLibrary(); - return false; - } - - if (!Vulkan::LoadVulkanInstanceFunctions(instance)) - { - Log_ErrorPrintf("Failed to load Vulkan instance functions"); - vkDestroyInstance(instance, nullptr); - Vulkan::UnloadVulkanLibrary(); - return false; - } - - GPUList gpus = EnumerateGPUs(instance); - if (gpus.empty()) - { - vkDestroyInstance(instance, nullptr); - Vulkan::UnloadVulkanLibrary(); - return false; - } - - u32 gpu_index = 0; - GPUNameList gpu_names = EnumerateGPUNames(instance); - if (!gpu_name.empty()) - { - for (; gpu_index < static_cast(gpu_names.size()); gpu_index++) - { - Log_InfoPrintf("GPU %u: %s", static_cast(gpu_index), gpu_names[gpu_index].c_str()); - if (gpu_names[gpu_index] == gpu_name) - break; - } - - if (gpu_index == static_cast(gpu_names.size())) - { - Log_WarningPrintf("Requested GPU '%s' not found, using first (%s)", std::string(gpu_name).c_str(), - gpu_names[0].c_str()); - gpu_index = 0; - } - } - else - { - Log_InfoPrintf("No GPU requested, using first (%s)", gpu_names[0].c_str()); - } - - VkSurfaceKHR surface = VK_NULL_HANDLE; - WindowInfo wi_copy; - if (wi) - wi_copy = *wi; - - if (enable_surface && - (surface = SwapChain::CreateVulkanSurface(instance, gpus[gpu_index], &wi_copy)) == VK_NULL_HANDLE) - { - vkDestroyInstance(instance, nullptr); - Vulkan::UnloadVulkanLibrary(); - return false; - } - - g_vulkan_context.reset(new Context(instance, gpus[gpu_index], true)); - - // Enable debug reports if the "Host GPU" log category is enabled. - if (enable_debug_utils) - g_vulkan_context->EnableDebugUtils(); - - // Attempt to create the device. - if (!g_vulkan_context->CreateDevice(surface, enable_validation_layer, nullptr, 0, nullptr, 0, nullptr) || - !g_vulkan_context->CreateGlobalDescriptorPool() || !g_vulkan_context->CreateCommandBuffers() || - (enable_surface && (*out_swap_chain = SwapChain::Create(wi_copy, surface, true)) == nullptr)) - { - // Since we are destroying the instance, we're also responsible for destroying the surface. - if (surface != VK_NULL_HANDLE) - vkDestroySurfaceKHR(instance, surface, nullptr); - - g_vulkan_context.reset(); - return false; - } - - if (threaded_presentation) - g_vulkan_context->StartPresentThread(); - - return true; -} - bool Context::CreateFromExistingInstance(VkInstance instance, VkPhysicalDevice gpu, VkSurfaceKHR surface, bool take_ownership, bool enable_validation_layer, bool enable_debug_utils, const char** required_device_extensions /* = nullptr */, @@ -827,7 +609,6 @@ void Context::WaitForFenceCounter(u64 fence_counter) void Context::WaitForGPUIdle() { - WaitForPresentComplete(); vkDeviceWaitIdle(m_device); } @@ -879,24 +660,7 @@ void Context::SubmitCommandBuffer(VkSemaphore wait_semaphore /* = VK_NULL_HANDLE // This command buffer now has commands, so can't be re-used without waiting. resources.needs_fence_wait = true; - std::unique_lock lock(m_present_mutex); - WaitForPresentComplete(lock); - - if (!submit_on_thread || !m_present_thread.joinable()) - { - DoSubmitCommandBuffer(m_current_frame, wait_semaphore, signal_semaphore); - if (present_swap_chain != VK_NULL_HANDLE) - DoPresent(signal_semaphore, present_swap_chain, present_image_index); - return; - } - - m_queued_present.command_buffer_index = m_current_frame; - m_queued_present.present_swap_chain = present_swap_chain; - m_queued_present.present_image_index = present_image_index; - m_queued_present.wait_semaphore = wait_semaphore; - m_queued_present.signal_semaphore = signal_semaphore; - m_present_done.store(false); - m_present_queued_cv.notify_one(); + DoSubmitCommandBuffer(m_current_frame, wait_semaphore, signal_semaphore); } void Context::DoSubmitCommandBuffer(u32 index, VkSemaphore wait_semaphore, VkSemaphore signal_semaphore) @@ -928,88 +692,6 @@ void Context::DoSubmitCommandBuffer(u32 index, VkSemaphore wait_semaphore, VkSem } } -void Context::DoPresent(VkSemaphore wait_semaphore, VkSwapchainKHR present_swap_chain, uint32_t present_image_index) -{ - // Should have a signal semaphore. - Assert(wait_semaphore != VK_NULL_HANDLE); - VkPresentInfoKHR present_info = {VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, - nullptr, - 1, - &wait_semaphore, - 1, - &present_swap_chain, - &present_image_index, - nullptr}; - const Vulkan::Util::DebugScope debugScope(m_present_queue, "Context::DoPresent: %u", present_image_index); - VkResult res = vkQueuePresentKHR(m_present_queue, &present_info); - if (res != VK_SUCCESS) - { - // VK_ERROR_OUT_OF_DATE_KHR is not fatal, just means we need to recreate our swap chain. - if (res != VK_ERROR_OUT_OF_DATE_KHR && res != VK_SUBOPTIMAL_KHR) - LOG_VULKAN_ERROR(res, "vkQueuePresentKHR failed: "); - - m_last_present_failed.store(true); - } -} - -void Context::WaitForPresentComplete() -{ - if (m_present_done.load()) - return; - - std::unique_lock lock(m_present_mutex); - WaitForPresentComplete(lock); -} - -void Context::WaitForPresentComplete(std::unique_lock& lock) -{ - if (m_present_done.load()) - return; - - m_present_done_cv.wait(lock, [this]() { return m_present_done.load(); }); -} - -void Context::PresentThread() -{ - std::unique_lock lock(m_present_mutex); - while (!m_present_thread_done.load()) - { - m_present_queued_cv.wait(lock, [this]() { return !m_present_done.load() || m_present_thread_done.load(); }); - - if (m_present_done.load()) - continue; - - DoSubmitCommandBuffer(m_queued_present.command_buffer_index, m_queued_present.wait_semaphore, - m_queued_present.signal_semaphore); - DoPresent(m_queued_present.signal_semaphore, m_queued_present.present_swap_chain, - m_queued_present.present_image_index); - m_present_done.store(true); - m_present_done_cv.notify_one(); - } -} - -void Context::StartPresentThread() -{ - Assert(!m_present_thread.joinable()); - m_present_thread_done.store(false); - m_present_thread = std::thread(&Context::PresentThread, this); -} - -void Context::StopPresentThread() -{ - if (!m_present_thread.joinable()) - return; - - { - std::unique_lock lock(m_present_mutex); - WaitForPresentComplete(lock); - m_present_thread_done.store(true); - m_present_queued_cv.notify_one(); - } - - m_present_thread.join(); -} - void Context::MoveToNextCommandBuffer() { ActivateCommandBuffer((m_current_frame + 1) % NUM_COMMAND_BUFFERS); @@ -1019,9 +701,6 @@ void Context::ActivateCommandBuffer(u32 index) { FrameResources& resources = m_frame_resources[index]; - if (!m_present_done.load() && m_queued_present.command_buffer_index == index) - WaitForPresentComplete(); - // Wait for the GPU to finish with all resources for this command buffer. if (resources.fence_counter > m_completed_fence_counter) WaitForCommandBufferCompletion(index); @@ -1059,18 +738,10 @@ void Context::ExecuteCommandBuffer(bool wait_for_completion) const u32 current_frame = m_current_frame; SubmitCommandBuffer(); MoveToNextCommandBuffer(); - if (wait_for_completion) WaitForCommandBufferCompletion(current_frame); } -bool Context::CheckLastPresentFail() -{ - bool res = m_last_present_failed; - m_last_present_failed = false; - return res; -} - void Context::DeferBufferDestruction(VkBuffer object) { FrameResources& resources = m_frame_resources[m_current_frame]; diff --git a/src/common/vulkan/context.h b/src/common/vulkan/context.h index 4b3f28b1..1a06f41c 100644 --- a/src/common/vulkan/context.h +++ b/src/common/vulkan/context.h @@ -8,22 +8,14 @@ #include "../types.h" #include "vulkan_loader.h" #include -#include -#include #include #include #include -#include #include -#include #include -struct WindowInfo; - namespace Vulkan { -class SwapChain; - class Context { public: @@ -37,19 +29,12 @@ public: // Determines if the Vulkan validation layer is available on the system. static bool CheckValidationLayerAvailablility(); - // Helper method to create a Vulkan instance. - static VkInstance CreateVulkanInstance(const WindowInfo* wi, bool enable_debug_utils, bool enable_validation_layer); - // Returns a list of Vulkan-compatible GPUs. using GPUList = std::vector; using GPUNameList = std::vector; static GPUList EnumerateGPUs(VkInstance instance); static GPUNameList EnumerateGPUNames(VkInstance instance); - // Creates a new context and sets it up as global. - static bool Create(std::string_view gpu_name, const WindowInfo* wi, std::unique_ptr* out_swap_chain, - bool threaded_presentation, bool enable_debug_utils, bool enable_validation_layer); - // Creates a new context from a pre-existing instance. static bool CreateFromExistingInstance(VkInstance instance, VkPhysicalDevice gpu, VkSurfaceKHR surface, bool take_ownership, bool enable_validation_layer, bool enable_debug_utils, @@ -159,10 +144,6 @@ public: void MoveToNextCommandBuffer(); void ExecuteCommandBuffer(bool wait_for_completion); - void WaitForPresentComplete(); - - // Was the last present submitted to the queue a failure? If so, we must recreate our swapchain. - bool CheckLastPresentFail(); // Schedule a vulkan resource for destruction later on. This will occur when the command buffer // is next re-used, and the GPU has finished working with the specified resource. @@ -184,7 +165,6 @@ private: Context(VkInstance instance, VkPhysicalDevice physical_device, bool owns_device); using ExtensionList = std::vector; - static bool SelectInstanceExtensions(ExtensionList* extension_list, const WindowInfo* wi, bool enable_debug_utils); bool SelectDeviceExtensions(ExtensionList* extension_list, bool enable_surface); bool SelectDeviceFeatures(const VkPhysicalDeviceFeatures* required_features); bool CreateDevice(VkSurfaceKHR surface, bool enable_validation_layer, const char** required_device_extensions, @@ -201,11 +181,6 @@ private: void WaitForCommandBufferCompletion(u32 index); void DoSubmitCommandBuffer(u32 index, VkSemaphore wait_semaphore, VkSemaphore signal_semaphore); - void DoPresent(VkSemaphore wait_semaphore, VkSwapchainKHR present_swap_chain, uint32_t present_image_index); - void WaitForPresentComplete(std::unique_lock& lock); - void PresentThread(); - void StartPresentThread(); - void StopPresentThread(); struct FrameResources { @@ -240,25 +215,6 @@ private: bool m_owns_device = false; - std::atomic_bool m_last_present_failed{false}; - std::atomic_bool m_present_done{true}; - std::mutex m_present_mutex; - std::condition_variable m_present_queued_cv; - std::condition_variable m_present_done_cv; - std::thread m_present_thread; - std::atomic_bool m_present_thread_done{false}; - - struct QueuedPresent - { - VkSemaphore wait_semaphore; - VkSemaphore signal_semaphore; - VkSwapchainKHR present_swap_chain; - u32 command_buffer_index; - u32 present_image_index; - }; - - QueuedPresent m_queued_present = {}; - // Render pass cache using RenderPassCacheKey = std::tuple; std::map m_render_pass_cache; diff --git a/src/common/vulkan/staging_texture.cpp b/src/common/vulkan/staging_texture.cpp index 559f640b..93642feb 100644 --- a/src/common/vulkan/staging_texture.cpp +++ b/src/common/vulkan/staging_texture.cpp @@ -288,4 +288,4 @@ void StagingTexture::PrepareForAccess() Flush(); } -} // namespace Vulkan \ No newline at end of file +} // namespace Vulkan diff --git a/src/common/vulkan/swap_chain.cpp b/src/common/vulkan/swap_chain.cpp deleted file mode 100644 index c392bcc4..00000000 --- a/src/common/vulkan/swap_chain.cpp +++ /dev/null @@ -1,851 +0,0 @@ -// Copyright 2016 Dolphin Emulator Project -// Copyright 2020 DuckStation Emulator Project -// Licensed under GPLv2+ -// Refer to the LICENSE file included. - -#include "swap_chain.h" -#include "../assert.h" -#include "../log.h" -#include "context.h" -#include "util.h" -#include -#include -#include -Log_SetChannel(Vulkan::SwapChain); - -#if defined(VK_USE_PLATFORM_XLIB_KHR) -#include -#endif - -#if defined(__APPLE__) -#include - -static bool CreateMetalLayer(WindowInfo* wi) -{ - id view = reinterpret_cast(wi->window_handle); - - Class clsCAMetalLayer = objc_getClass("CAMetalLayer"); - if (!clsCAMetalLayer) - { - Log_ErrorPrint("Failed to get CAMetalLayer class."); - return false; - } - - // [CAMetalLayer layer] - id layer = reinterpret_cast(objc_msgSend)(objc_getClass("CAMetalLayer"), sel_getUid("layer")); - if (!layer) - { - Log_ErrorPrint("Failed to create Metal layer."); - return false; - } - - // [view setWantsLayer:YES] - reinterpret_cast(objc_msgSend)(view, sel_getUid("setWantsLayer:"), YES); - - // [view setLayer:layer] - reinterpret_cast(objc_msgSend)(view, sel_getUid("setLayer:"), layer); - - // NSScreen* screen = [NSScreen mainScreen] - id screen = reinterpret_cast(objc_msgSend)(objc_getClass("NSScreen"), sel_getUid("mainScreen")); - - // CGFloat factor = [screen backingScaleFactor] - double factor = reinterpret_cast(objc_msgSend)(screen, sel_getUid("backingScaleFactor")); - - // layer.contentsScale = factor - reinterpret_cast(objc_msgSend)(layer, sel_getUid("setContentsScale:"), factor); - - // Store the layer pointer, that way MoltenVK doesn't call [NSView layer] outside the main thread. - wi->surface_handle = layer; - return true; -} - -static void DestroyMetalLayer(WindowInfo* wi) -{ - id view = reinterpret_cast(wi->window_handle); - id layer = reinterpret_cast(wi->surface_handle); - if (layer == nil) - return; - - reinterpret_cast(objc_msgSend)(view, sel_getUid("setLayer:"), nil); - reinterpret_cast(objc_msgSend)(view, sel_getUid("setWantsLayer:"), NO); - reinterpret_cast(objc_msgSend)(layer, sel_getUid("release")); - wi->surface_handle = nullptr; -} - -#endif - -namespace Vulkan { -SwapChain::SwapChain(const WindowInfo& wi, VkSurfaceKHR surface, bool vsync) - : m_window_info(wi), m_surface(surface), m_vsync_enabled(vsync) -{ -} - -SwapChain::~SwapChain() -{ - DestroySemaphores(); - DestroySwapChainImages(); - DestroySwapChain(); - DestroySurface(); -} - -static VkSurfaceKHR CreateDisplaySurface(VkInstance instance, VkPhysicalDevice physical_device, WindowInfo* wi) -{ - Log_InfoPrintf("Trying to create a VK_KHR_display surface of %ux%u", wi->surface_width, wi->surface_height); - - u32 num_displays; - VkResult res = vkGetPhysicalDeviceDisplayPropertiesKHR(physical_device, &num_displays, nullptr); - if (res != VK_SUCCESS || num_displays == 0) - { - LOG_VULKAN_ERROR(res, "vkGetPhysicalDeviceDisplayPropertiesKHR() failed:"); - return {}; - } - - std::vector displays(num_displays); - res = vkGetPhysicalDeviceDisplayPropertiesKHR(physical_device, &num_displays, displays.data()); - if (res != VK_SUCCESS || num_displays != displays.size()) - { - LOG_VULKAN_ERROR(res, "vkGetPhysicalDeviceDisplayPropertiesKHR() failed:"); - return {}; - } - - for (u32 display_index = 0; display_index < num_displays; display_index++) - { - const VkDisplayPropertiesKHR& props = displays[display_index]; - Log_DevPrintf("Testing display '%s'", props.displayName); - - u32 num_modes; - res = vkGetDisplayModePropertiesKHR(physical_device, props.display, &num_modes, nullptr); - if (res != VK_SUCCESS || num_modes == 0) - { - LOG_VULKAN_ERROR(res, "vkGetDisplayModePropertiesKHR() failed:"); - continue; - } - - std::vector modes(num_modes); - res = vkGetDisplayModePropertiesKHR(physical_device, props.display, &num_modes, modes.data()); - if (res != VK_SUCCESS || num_modes != modes.size()) - { - LOG_VULKAN_ERROR(res, "vkGetDisplayModePropertiesKHR() failed:"); - continue; - } - - const VkDisplayModePropertiesKHR* matched_mode = nullptr; - for (const VkDisplayModePropertiesKHR& mode : modes) - { - const float refresh_rate = static_cast(mode.parameters.refreshRate) / 1000.0f; - Log_DevPrintf(" Mode %ux%u @ %f", mode.parameters.visibleRegion.width, mode.parameters.visibleRegion.height, - refresh_rate); - - if (!matched_mode && - ((wi->surface_width == 0 && wi->surface_height == 0) || - (mode.parameters.visibleRegion.width == wi->surface_width && - mode.parameters.visibleRegion.height == wi->surface_height && - (wi->surface_refresh_rate == 0.0f || std::abs(refresh_rate - wi->surface_refresh_rate) < 0.1f)))) - { - matched_mode = &mode; - } - } - - if (!matched_mode) - { - Log_DevPrintf("No modes matched on '%s'", props.displayName); - continue; - } - - u32 num_planes; - res = vkGetPhysicalDeviceDisplayPlanePropertiesKHR(physical_device, &num_planes, nullptr); - if (res != VK_SUCCESS) - { - LOG_VULKAN_ERROR(res, "vkGetPhysicalDeviceDisplayPlanePropertiesKHR() failed:"); - continue; - } - if (num_planes == 0) - continue; - - std::vector planes(num_planes); - res = vkGetPhysicalDeviceDisplayPlanePropertiesKHR(physical_device, &num_planes, planes.data()); - if (res != VK_SUCCESS || num_planes != planes.size()) - { - LOG_VULKAN_ERROR(res, "vkGetPhysicalDeviceDisplayPlanePropertiesKHR() failed:"); - continue; - } - - u32 plane_index = 0; - for (; plane_index < num_planes; plane_index++) - { - u32 supported_display_count; - res = vkGetDisplayPlaneSupportedDisplaysKHR(physical_device, plane_index, &supported_display_count, nullptr); - if (res != VK_SUCCESS) - { - LOG_VULKAN_ERROR(res, "vkGetDisplayPlaneSupportedDisplaysKHR() failed:"); - continue; - } - if (supported_display_count == 0) - continue; - - std::vector supported_displays(supported_display_count); - res = vkGetDisplayPlaneSupportedDisplaysKHR(physical_device, plane_index, &supported_display_count, - supported_displays.data()); - if (res != VK_SUCCESS) - { - LOG_VULKAN_ERROR(res, "vkGetDisplayPlaneSupportedDisplaysKHR() failed:"); - continue; - } - - const bool is_supported = - std::find(supported_displays.begin(), supported_displays.end(), props.display) != supported_displays.end(); - if (!is_supported) - continue; - - break; - } - - if (plane_index == num_planes) - { - Log_DevPrintf("No planes matched on '%s'", props.displayName); - continue; - } - - VkDisplaySurfaceCreateInfoKHR info = {}; - info.sType = VK_STRUCTURE_TYPE_DISPLAY_SURFACE_CREATE_INFO_KHR; - info.displayMode = matched_mode->displayMode; - info.planeIndex = plane_index; - info.planeStackIndex = planes[plane_index].currentStackIndex; - info.transform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; - info.globalAlpha = 1.0f; - info.alphaMode = VK_DISPLAY_PLANE_ALPHA_OPAQUE_BIT_KHR; - info.imageExtent = matched_mode->parameters.visibleRegion; - - VkSurfaceKHR surface; - res = vkCreateDisplayPlaneSurfaceKHR(instance, &info, nullptr, &surface); - if (res != VK_SUCCESS) - { - LOG_VULKAN_ERROR(res, "vkCreateDisplayPlaneSurfaceKHR() failed: "); - continue; - } - - wi->surface_refresh_rate = static_cast(matched_mode->parameters.refreshRate) / 1000.0f; - return surface; - } - - return VK_NULL_HANDLE; -} - -static std::vector GetDisplayModes(VkInstance instance, VkPhysicalDevice physical_device, - const WindowInfo& wi) -{ - - u32 num_displays; - VkResult res = vkGetPhysicalDeviceDisplayPropertiesKHR(physical_device, &num_displays, nullptr); - if (res != VK_SUCCESS) - { - LOG_VULKAN_ERROR(res, "vkGetPhysicalDeviceDisplayPropertiesKHR() failed:"); - return {}; - } - if (num_displays == 0) - { - Log_ErrorPrint("No displays were returned"); - return {}; - } - - std::vector displays(num_displays); - res = vkGetPhysicalDeviceDisplayPropertiesKHR(physical_device, &num_displays, displays.data()); - if (res != VK_SUCCESS || num_displays != displays.size()) - { - LOG_VULKAN_ERROR(res, "vkGetPhysicalDeviceDisplayPropertiesKHR() failed:"); - return {}; - } - - std::vector result; - for (u32 display_index = 0; display_index < num_displays; display_index++) - { - const VkDisplayPropertiesKHR& props = displays[display_index]; - - u32 num_modes; - res = vkGetDisplayModePropertiesKHR(physical_device, props.display, &num_modes, nullptr); - if (res != VK_SUCCESS || num_modes == 0) - { - LOG_VULKAN_ERROR(res, "vkGetDisplayModePropertiesKHR() failed:"); - continue; - } - - std::vector modes(num_modes); - res = vkGetDisplayModePropertiesKHR(physical_device, props.display, &num_modes, modes.data()); - if (res != VK_SUCCESS || num_modes != modes.size()) - { - LOG_VULKAN_ERROR(res, "vkGetDisplayModePropertiesKHR() failed:"); - continue; - } - - for (const VkDisplayModePropertiesKHR& mode : modes) - { - const float refresh_rate = static_cast(mode.parameters.refreshRate) / 1000.0f; - if (std::find_if(result.begin(), result.end(), [&mode, refresh_rate](const SwapChain::FullscreenModeInfo& mi) { - return (mi.width == mode.parameters.visibleRegion.width && - mi.height == mode.parameters.visibleRegion.height && mode.parameters.refreshRate == refresh_rate); - }) != result.end()) - { - continue; - } - - result.push_back(SwapChain::FullscreenModeInfo{static_cast(mode.parameters.visibleRegion.width), - static_cast(mode.parameters.visibleRegion.height), - refresh_rate}); - } - } - - return result; -} - -VkSurfaceKHR SwapChain::CreateVulkanSurface(VkInstance instance, VkPhysicalDevice physical_device, WindowInfo* wi) -{ -#if defined(VK_USE_PLATFORM_WIN32_KHR) - if (wi->type == WindowInfo::Type::Win32) - { - VkWin32SurfaceCreateInfoKHR surface_create_info = { - VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR, // VkStructureType sType - nullptr, // const void* pNext - 0, // VkWin32SurfaceCreateFlagsKHR flags - nullptr, // HINSTANCE hinstance - reinterpret_cast(wi->window_handle) // HWND hwnd - }; - - VkSurfaceKHR surface; - VkResult res = vkCreateWin32SurfaceKHR(instance, &surface_create_info, nullptr, &surface); - if (res != VK_SUCCESS) - { - LOG_VULKAN_ERROR(res, "vkCreateWin32SurfaceKHR failed: "); - return VK_NULL_HANDLE; - } - - return surface; - } -#endif - -#if defined(VK_USE_PLATFORM_XLIB_KHR) - if (wi->type == WindowInfo::Type::X11) - { - VkXlibSurfaceCreateInfoKHR surface_create_info = { - VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR, // VkStructureType sType - nullptr, // const void* pNext - 0, // VkXlibSurfaceCreateFlagsKHR flags - static_cast(wi->display_connection), // Display* dpy - reinterpret_cast(wi->window_handle) // Window window - }; - - VkSurfaceKHR surface; - VkResult res = vkCreateXlibSurfaceKHR(instance, &surface_create_info, nullptr, &surface); - if (res != VK_SUCCESS) - { - LOG_VULKAN_ERROR(res, "vkCreateXlibSurfaceKHR failed: "); - return VK_NULL_HANDLE; - } - - return surface; - } -#endif - -#if defined(VK_USE_PLATFORM_WAYLAND_KHR) - if (wi->type == WindowInfo::Type::Wayland) - { - VkWaylandSurfaceCreateInfoKHR surface_create_info = {VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR, nullptr, 0, - static_cast(wi->display_connection), - static_cast(wi->window_handle)}; - - VkSurfaceKHR surface; - VkResult res = vkCreateWaylandSurfaceKHR(instance, &surface_create_info, nullptr, &surface); - if (res != VK_SUCCESS) - { - LOG_VULKAN_ERROR(res, "vkCreateWaylandSurfaceEXT failed: "); - return VK_NULL_HANDLE; - } - - return surface; - } -#endif - -#if defined(VK_USE_PLATFORM_ANDROID_KHR) - if (wi->type == WindowInfo::Type::Android) - { - VkAndroidSurfaceCreateInfoKHR surface_create_info = { - VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR, // VkStructureType sType - nullptr, // const void* pNext - 0, // VkAndroidSurfaceCreateFlagsKHR flags - reinterpret_cast(wi->window_handle) // ANativeWindow* window - }; - - VkSurfaceKHR surface; - VkResult res = vkCreateAndroidSurfaceKHR(instance, &surface_create_info, nullptr, &surface); - if (res != VK_SUCCESS) - { - LOG_VULKAN_ERROR(res, "vkCreateAndroidSurfaceKHR failed: "); - return VK_NULL_HANDLE; - } - - return surface; - } -#endif - -#if defined(VK_USE_PLATFORM_METAL_EXT) - if (wi->type == WindowInfo::Type::MacOS) - { - if (!wi->surface_handle && !CreateMetalLayer(wi)) - return VK_NULL_HANDLE; - - VkMetalSurfaceCreateInfoEXT surface_create_info = {VK_STRUCTURE_TYPE_METAL_SURFACE_CREATE_INFO_EXT, nullptr, 0, - static_cast(wi->surface_handle)}; - - VkSurfaceKHR surface; - VkResult res = vkCreateMetalSurfaceEXT(instance, &surface_create_info, nullptr, &surface); - if (res != VK_SUCCESS) - { - LOG_VULKAN_ERROR(res, "vkCreateMetalSurfaceEXT failed: "); - return VK_NULL_HANDLE; - } - - return surface; - } -#elif defined(VK_USE_PLATFORM_MACOS_MVK) - if (wi->type == WindowInfo::Type::MacOS) - { - VkMacOSSurfaceCreateInfoMVK surface_create_info = {VK_STRUCTURE_TYPE_MACOS_SURFACE_CREATE_INFO_MVK, nullptr, 0, - wi->window_handle}; - - VkSurfaceKHR surface; - VkResult res = vkCreateMacOSSurfaceMVK(instance, &surface_create_info, nullptr, &surface); - if (res != VK_SUCCESS) - { - LOG_VULKAN_ERROR(res, "vkCreateMacOSSurfaceMVK failed: "); - return VK_NULL_HANDLE; - } - - return surface; - } -#endif - - if (wi->type == WindowInfo::Type::Display) - return CreateDisplaySurface(instance, physical_device, wi); - - return VK_NULL_HANDLE; -} - -void SwapChain::DestroyVulkanSurface(VkInstance instance, WindowInfo* wi, VkSurfaceKHR surface) -{ - vkDestroySurfaceKHR(g_vulkan_context->GetVulkanInstance(), surface, nullptr); - -#if defined(__APPLE__) - if (wi->type == WindowInfo::Type::MacOS && wi->surface_handle) - DestroyMetalLayer(wi); -#endif -} - -std::vector -SwapChain::GetSurfaceFullscreenModes(VkInstance instance, VkPhysicalDevice physical_device, const WindowInfo& wi) -{ - if (wi.type == WindowInfo::Type::Display) - return GetDisplayModes(instance, physical_device, wi); - - return {}; -} - -std::unique_ptr SwapChain::Create(const WindowInfo& wi, VkSurfaceKHR surface, bool vsync) -{ - std::unique_ptr swap_chain = std::make_unique(wi, surface, vsync); - if (!swap_chain->CreateSwapChain() || !swap_chain->SetupSwapChainImages() || !swap_chain->CreateSemaphores()) - return nullptr; - - return swap_chain; -} - -bool SwapChain::SelectSurfaceFormat() -{ - u32 format_count; - VkResult res = - vkGetPhysicalDeviceSurfaceFormatsKHR(g_vulkan_context->GetPhysicalDevice(), m_surface, &format_count, nullptr); - if (res != VK_SUCCESS || format_count == 0) - { - LOG_VULKAN_ERROR(res, "vkGetPhysicalDeviceSurfaceFormatsKHR failed: "); - return false; - } - - std::vector surface_formats(format_count); - res = vkGetPhysicalDeviceSurfaceFormatsKHR(g_vulkan_context->GetPhysicalDevice(), m_surface, &format_count, - surface_formats.data()); - Assert(res == VK_SUCCESS); - - // If there is a single undefined surface format, the device doesn't care, so we'll just use RGBA - if (surface_formats[0].format == VK_FORMAT_UNDEFINED) - { - m_surface_format.format = VK_FORMAT_R8G8B8A8_UNORM; - m_surface_format.colorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR; - return true; - } - - // Try to find a suitable format. - for (const VkSurfaceFormatKHR& surface_format : surface_formats) - { - // Some drivers seem to return a SRGB format here (Intel Mesa). - // This results in gamma correction when presenting to the screen, which we don't want. - // Use a linear format instead, if this is the case. - m_surface_format.format = Util::GetLinearFormat(surface_format.format); - m_surface_format.colorSpace = surface_format.colorSpace; - return true; - } - - Panic("Failed to find a suitable format for swap chain buffers."); - return false; -} - -bool SwapChain::SelectPresentMode() -{ - VkResult res; - u32 mode_count; - res = - vkGetPhysicalDeviceSurfacePresentModesKHR(g_vulkan_context->GetPhysicalDevice(), m_surface, &mode_count, nullptr); - if (res != VK_SUCCESS || mode_count == 0) - { - LOG_VULKAN_ERROR(res, "vkGetPhysicalDeviceSurfaceFormatsKHR failed: "); - return false; - } - - std::vector present_modes(mode_count); - res = vkGetPhysicalDeviceSurfacePresentModesKHR(g_vulkan_context->GetPhysicalDevice(), m_surface, &mode_count, - present_modes.data()); - Assert(res == VK_SUCCESS); - - // Checks if a particular mode is supported, if it is, returns that mode. - auto CheckForMode = [&present_modes](VkPresentModeKHR check_mode) { - auto it = std::find_if(present_modes.begin(), present_modes.end(), - [check_mode](VkPresentModeKHR mode) { return check_mode == mode; }); - return it != present_modes.end(); - }; - - // If vsync is enabled, use VK_PRESENT_MODE_FIFO_KHR. - // This check should not fail with conforming drivers, as the FIFO present mode is mandated by - // the specification (VK_KHR_swapchain). In case it isn't though, fall through to any other mode. - if (m_vsync_enabled && CheckForMode(VK_PRESENT_MODE_FIFO_KHR)) - { - m_present_mode = VK_PRESENT_MODE_FIFO_KHR; - return true; - } - - // Prefer screen-tearing, if possible, for lowest latency. - if (CheckForMode(VK_PRESENT_MODE_IMMEDIATE_KHR)) - { - m_present_mode = VK_PRESENT_MODE_IMMEDIATE_KHR; - return true; - } - - // Use optimized-vsync above vsync. - if (CheckForMode(VK_PRESENT_MODE_MAILBOX_KHR)) - { - m_present_mode = VK_PRESENT_MODE_MAILBOX_KHR; - return true; - } - - // Fall back to whatever is available. - m_present_mode = present_modes[0]; - return true; -} - -bool SwapChain::CreateSwapChain() -{ - // Look up surface properties to determine image count and dimensions - VkSurfaceCapabilitiesKHR surface_capabilities; - VkResult res = - vkGetPhysicalDeviceSurfaceCapabilitiesKHR(g_vulkan_context->GetPhysicalDevice(), m_surface, &surface_capabilities); - if (res != VK_SUCCESS) - { - LOG_VULKAN_ERROR(res, "vkGetPhysicalDeviceSurfaceCapabilitiesKHR failed: "); - return false; - } - - // Select swap chain format and present mode - if (!SelectSurfaceFormat() || !SelectPresentMode()) - return false; - - // Select number of images in swap chain, we prefer one buffer in the background to work on - u32 image_count = std::max(surface_capabilities.minImageCount + 1u, 2u); - - // maxImageCount can be zero, in which case there isn't an upper limit on the number of buffers. - if (surface_capabilities.maxImageCount > 0) - image_count = std::min(image_count, surface_capabilities.maxImageCount); - - // Determine the dimensions of the swap chain. Values of -1 indicate the size we specify here - // determines window size? - VkExtent2D size = surface_capabilities.currentExtent; -#ifndef ANDROID - if (size.width == UINT32_MAX) -#endif - { - size.width = m_window_info.surface_width; - size.height = m_window_info.surface_height; - } - size.width = - std::clamp(size.width, surface_capabilities.minImageExtent.width, surface_capabilities.maxImageExtent.width); - size.height = - std::clamp(size.height, surface_capabilities.minImageExtent.height, surface_capabilities.maxImageExtent.height); - - // Prefer identity transform if possible - VkSurfaceTransformFlagBitsKHR transform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; - if (!(surface_capabilities.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR)) - transform = surface_capabilities.currentTransform; - - // Select swap chain flags, we only need a colour attachment - VkImageUsageFlags image_usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; - if (!(surface_capabilities.supportedUsageFlags & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT)) - { - Log_ErrorPrintf("Vulkan: Swap chain does not support usage as color attachment"); - return false; - } - - // Store the old/current swap chain when recreating for resize - VkSwapchainKHR old_swap_chain = m_swap_chain; - m_swap_chain = VK_NULL_HANDLE; - - // Now we can actually create the swap chain - VkSwapchainCreateInfoKHR swap_chain_info = {VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR, - nullptr, - 0, - m_surface, - image_count, - m_surface_format.format, - m_surface_format.colorSpace, - size, - 1u, - image_usage, - VK_SHARING_MODE_EXCLUSIVE, - 0, - nullptr, - transform, - VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, - m_present_mode, - VK_TRUE, - old_swap_chain}; - std::array indices = {{ - g_vulkan_context->GetGraphicsQueueFamilyIndex(), - g_vulkan_context->GetPresentQueueFamilyIndex(), - }}; - if (g_vulkan_context->GetGraphicsQueueFamilyIndex() != g_vulkan_context->GetPresentQueueFamilyIndex()) - { - swap_chain_info.imageSharingMode = VK_SHARING_MODE_CONCURRENT; - swap_chain_info.queueFamilyIndexCount = 2; - swap_chain_info.pQueueFamilyIndices = indices.data(); - } - - if (m_swap_chain == VK_NULL_HANDLE) - { - res = vkCreateSwapchainKHR(g_vulkan_context->GetDevice(), &swap_chain_info, nullptr, &m_swap_chain); - } - if (res != VK_SUCCESS) - { - LOG_VULKAN_ERROR(res, "vkCreateSwapchainKHR failed: "); - return false; - } - - // Now destroy the old swap chain, since it's been recreated. - // We can do this immediately since all work should have been completed before calling resize. - if (old_swap_chain != VK_NULL_HANDLE) - vkDestroySwapchainKHR(g_vulkan_context->GetDevice(), old_swap_chain, nullptr); - - m_window_info.surface_width = std::max(1u, size.width); - m_window_info.surface_height = std::max(1u, size.height); - return true; -} - -bool SwapChain::SetupSwapChainImages() -{ - Assert(m_images.empty()); - - u32 image_count; - VkResult res = vkGetSwapchainImagesKHR(g_vulkan_context->GetDevice(), m_swap_chain, &image_count, nullptr); - if (res != VK_SUCCESS) - { - LOG_VULKAN_ERROR(res, "vkGetSwapchainImagesKHR failed: "); - return false; - } - - std::vector images(image_count); - res = vkGetSwapchainImagesKHR(g_vulkan_context->GetDevice(), m_swap_chain, &image_count, images.data()); - Assert(res == VK_SUCCESS); - - m_load_render_pass = g_vulkan_context->GetRenderPass(m_surface_format.format, VK_FORMAT_UNDEFINED, - VK_SAMPLE_COUNT_1_BIT, VK_ATTACHMENT_LOAD_OP_LOAD); - m_clear_render_pass = g_vulkan_context->GetRenderPass(m_surface_format.format, VK_FORMAT_UNDEFINED, - VK_SAMPLE_COUNT_1_BIT, VK_ATTACHMENT_LOAD_OP_CLEAR); - if (m_load_render_pass == VK_NULL_HANDLE || m_clear_render_pass == VK_NULL_HANDLE) - { - Panic("Failed to get swap chain render passes."); - return false; - } - - m_images.reserve(image_count); - for (u32 i = 0; i < image_count; i++) - { - SwapChainImage image; - image.image = images[i]; - - // Create texture object, which creates a view of the backbuffer - if (!image.texture.Adopt(image.image, VK_IMAGE_VIEW_TYPE_2D, m_window_info.surface_width, - m_window_info.surface_height, 1, 1, m_surface_format.format, VK_SAMPLE_COUNT_1_BIT)) - { - return false; - } - - image.framebuffer = image.texture.CreateFramebuffer(m_load_render_pass); - if (image.framebuffer == VK_NULL_HANDLE) - return false; - - m_images.emplace_back(std::move(image)); - } - - return true; -} - -void SwapChain::DestroySwapChainImages() -{ - for (auto& it : m_images) - { - // Images themselves are cleaned up by the swap chain object - vkDestroyFramebuffer(g_vulkan_context->GetDevice(), it.framebuffer, nullptr); - } - m_images.clear(); -} - -void SwapChain::DestroySwapChain() -{ - if (m_swap_chain == VK_NULL_HANDLE) - return; - - vkDestroySwapchainKHR(g_vulkan_context->GetDevice(), m_swap_chain, nullptr); - m_swap_chain = VK_NULL_HANDLE; -} - -VkResult SwapChain::AcquireNextImage() -{ - if (!m_swap_chain) - return VK_ERROR_SURFACE_LOST_KHR; - - return vkAcquireNextImageKHR(g_vulkan_context->GetDevice(), m_swap_chain, UINT64_MAX, m_image_available_semaphore, - VK_NULL_HANDLE, &m_current_image); -} - -bool SwapChain::ResizeSwapChain(u32 new_width /* = 0 */, u32 new_height /* = 0 */) -{ - DestroySwapChainImages(); - - if (new_width != 0 && new_height != 0) - { - m_window_info.surface_width = new_width; - m_window_info.surface_height = new_height; - } - - if (!CreateSwapChain() || !SetupSwapChainImages()) - { - DestroySwapChainImages(); - DestroySwapChain(); - return false; - } - - return true; -} - -bool SwapChain::RecreateSwapChain() -{ - DestroySwapChainImages(); - - if (!CreateSwapChain() || !SetupSwapChainImages()) - { - DestroySwapChainImages(); - DestroySwapChain(); - return false; - } - - return true; -} - -bool SwapChain::RecreateSurface(const WindowInfo& new_wi) -{ - // Destroy the old swap chain, images, and surface. - DestroySwapChainImages(); - DestroySwapChain(); - DestroySurface(); - - // Re-create the surface with the new native handle - m_window_info = new_wi; - m_surface = - CreateVulkanSurface(g_vulkan_context->GetVulkanInstance(), g_vulkan_context->GetPhysicalDevice(), &m_window_info); - if (m_surface == VK_NULL_HANDLE) - return false; - - // The validation layers get angry at us if we don't call this before creating the swapchain. - VkBool32 present_supported = VK_TRUE; - VkResult res = - vkGetPhysicalDeviceSurfaceSupportKHR(g_vulkan_context->GetPhysicalDevice(), - g_vulkan_context->GetPresentQueueFamilyIndex(), m_surface, &present_supported); - if (res != VK_SUCCESS) - { - LOG_VULKAN_ERROR(res, "vkGetPhysicalDeviceSurfaceSupportKHR failed: "); - return false; - } - if (!present_supported) - { - Panic("Recreated surface does not support presenting."); - return false; - } - - // Finally re-create the swap chain - if (!CreateSwapChain() || !SetupSwapChainImages()) - return false; - - return true; -} - -void SwapChain::DestroySurface() -{ - if (m_surface == VK_NULL_HANDLE) - return; - - DestroyVulkanSurface(g_vulkan_context->GetVulkanInstance(), &m_window_info, m_surface); - m_surface = VK_NULL_HANDLE; -} - -bool SwapChain::CreateSemaphores() -{ - // Create two semaphores, one that is triggered when the swapchain buffer is ready, another after - // submit and before present - VkSemaphoreCreateInfo semaphore_info = { - VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, // VkStructureType sType - nullptr, // const void* pNext - 0 // VkSemaphoreCreateFlags flags - }; - - VkResult res; - if ((res = vkCreateSemaphore(g_vulkan_context->GetDevice(), &semaphore_info, nullptr, - &m_image_available_semaphore)) != VK_SUCCESS || - (res = vkCreateSemaphore(g_vulkan_context->GetDevice(), &semaphore_info, nullptr, - &m_rendering_finished_semaphore)) != VK_SUCCESS) - { - LOG_VULKAN_ERROR(res, "vkCreateSemaphore failed: "); - return false; - } - - return true; -} - -void SwapChain::DestroySemaphores() -{ - if (m_image_available_semaphore != VK_NULL_HANDLE) - { - vkDestroySemaphore(g_vulkan_context->GetDevice(), m_image_available_semaphore, nullptr); - m_image_available_semaphore = VK_NULL_HANDLE; - } - - if (m_rendering_finished_semaphore != VK_NULL_HANDLE) - { - vkDestroySemaphore(g_vulkan_context->GetDevice(), m_rendering_finished_semaphore, nullptr); - m_rendering_finished_semaphore = VK_NULL_HANDLE; - } -} - -} // namespace Vulkan diff --git a/src/common/vulkan/swap_chain.h b/src/common/vulkan/swap_chain.h deleted file mode 100644 index b1501f74..00000000 --- a/src/common/vulkan/swap_chain.h +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright 2016 Dolphin Emulator Project -// Copyright 2020 DuckStation Emulator Project -// Licensed under GPLv2+ -// Refer to the LICENSE file included. - -#pragma once - -#include "../types.h" -#include "../window_info.h" -#include "texture.h" -#include "vulkan_loader.h" -#include -#include - -namespace Vulkan { - -class SwapChain -{ -public: - SwapChain(const WindowInfo& wi, VkSurfaceKHR surface, bool vsync); - ~SwapChain(); - - // Creates a vulkan-renderable surface for the specified window handle. - static VkSurfaceKHR CreateVulkanSurface(VkInstance instance, VkPhysicalDevice physical_device, WindowInfo* wi); - - // Destroys a previously-created surface. - static void DestroyVulkanSurface(VkInstance instance, WindowInfo* wi, VkSurfaceKHR surface); - - // Enumerates fullscreen modes for window info. - struct FullscreenModeInfo - { - u32 width; - u32 height; - float refresh_rate; - }; - static std::vector - GetSurfaceFullscreenModes(VkInstance instance, VkPhysicalDevice physical_device, const WindowInfo& wi); - - // Create a new swap chain from a pre-existing surface. - static std::unique_ptr Create(const WindowInfo& wi, VkSurfaceKHR surface, bool vsync); - - ALWAYS_INLINE VkSurfaceKHR GetSurface() const { return m_surface; } - ALWAYS_INLINE VkSurfaceFormatKHR GetSurfaceFormat() const { return m_surface_format; } - ALWAYS_INLINE VkFormat GetTextureFormat() const { return m_surface_format.format; } - ALWAYS_INLINE bool IsVSyncEnabled() const { return m_vsync_enabled; } - ALWAYS_INLINE VkSwapchainKHR GetSwapChain() const { return m_swap_chain; } - ALWAYS_INLINE const WindowInfo& GetWindowInfo() const { return m_window_info; } - ALWAYS_INLINE u32 GetWidth() const { return m_window_info.surface_width; } - ALWAYS_INLINE u32 GetHeight() const { return m_window_info.surface_height; } - ALWAYS_INLINE u32 GetCurrentImageIndex() const { return m_current_image; } - ALWAYS_INLINE u32 GetImageCount() const { return static_cast(m_images.size()); } - ALWAYS_INLINE VkImage GetCurrentImage() const { return m_images[m_current_image].image; } - ALWAYS_INLINE const Texture& GetCurrentTexture() const { return m_images[m_current_image].texture; } - ALWAYS_INLINE Texture& GetCurrentTexture() { return m_images[m_current_image].texture; } - ALWAYS_INLINE VkFramebuffer GetCurrentFramebuffer() const { return m_images[m_current_image].framebuffer; } - ALWAYS_INLINE VkRenderPass GetLoadRenderPass() const { return m_load_render_pass; } - ALWAYS_INLINE VkRenderPass GetClearRenderPass() const { return m_clear_render_pass; } - ALWAYS_INLINE VkSemaphore GetImageAvailableSemaphore() const { return m_image_available_semaphore; } - ALWAYS_INLINE VkSemaphore GetRenderingFinishedSemaphore() const { return m_rendering_finished_semaphore; } - VkResult AcquireNextImage(); - - bool RecreateSurface(const WindowInfo& new_wi); - bool ResizeSwapChain(u32 new_width = 0, u32 new_height = 0); - bool RecreateSwapChain(); - -private: - bool SelectSurfaceFormat(); - bool SelectPresentMode(); - - bool CreateSwapChain(); - void DestroySwapChain(); - - bool SetupSwapChainImages(); - void DestroySwapChainImages(); - - void DestroySurface(); - - bool CreateSemaphores(); - void DestroySemaphores(); - - struct SwapChainImage - { - VkImage image; - Texture texture; - VkFramebuffer framebuffer; - }; - - WindowInfo m_window_info; - - VkSurfaceKHR m_surface = VK_NULL_HANDLE; - VkSurfaceFormatKHR m_surface_format = {}; - VkPresentModeKHR m_present_mode = VK_PRESENT_MODE_IMMEDIATE_KHR; - - VkRenderPass m_load_render_pass = VK_NULL_HANDLE; - VkRenderPass m_clear_render_pass = VK_NULL_HANDLE; - - VkSemaphore m_image_available_semaphore = VK_NULL_HANDLE; - VkSemaphore m_rendering_finished_semaphore = VK_NULL_HANDLE; - - VkSwapchainKHR m_swap_chain = VK_NULL_HANDLE; - std::vector m_images; - u32 m_current_image = 0; - bool m_vsync_enabled = false; -}; - -} // namespace Vulkan diff --git a/src/common/window_info.cpp b/src/common/window_info.cpp deleted file mode 100644 index bda4d613..00000000 --- a/src/common/window_info.cpp +++ /dev/null @@ -1,160 +0,0 @@ -#include "window_info.h" - -#if defined(_WIN32) && !defined(_UWP) - -#include "common/windows_headers.h" -#include - -static bool GetRefreshRateFromDWM(HWND hwnd, float* refresh_rate) -{ - static HMODULE dwm_module = nullptr; - static HRESULT(STDAPICALLTYPE * is_composition_enabled)(BOOL * pfEnabled) = nullptr; - static HRESULT(STDAPICALLTYPE * get_timing_info)(HWND hwnd, DWM_TIMING_INFO * pTimingInfo) = nullptr; - static bool load_tried = false; - if (!load_tried) - { - load_tried = true; - dwm_module = LoadLibrary("dwmapi.dll"); - if (dwm_module) - { - std::atexit([]() { - FreeLibrary(dwm_module); - dwm_module = nullptr; - }); - is_composition_enabled = - reinterpret_cast(GetProcAddress(dwm_module, "DwmIsCompositionEnabled")); - get_timing_info = - reinterpret_cast(GetProcAddress(dwm_module, "DwmGetCompositionTimingInfo")); - } - } - - BOOL composition_enabled; - if (!is_composition_enabled || FAILED(is_composition_enabled(&composition_enabled) || !get_timing_info)) - return false; - - DWM_TIMING_INFO ti = {}; - ti.cbSize = sizeof(ti); - HRESULT hr = get_timing_info(nullptr, &ti); - if (SUCCEEDED(hr)) - { - if (ti.rateRefresh.uiNumerator == 0 || ti.rateRefresh.uiDenominator == 0) - return false; - - *refresh_rate = static_cast(ti.rateRefresh.uiNumerator) / static_cast(ti.rateRefresh.uiDenominator); - return true; - } - - return false; -} - -static bool GetRefreshRateFromMonitor(HWND hwnd, float* refresh_rate) -{ - HMONITOR mon = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST); - if (!mon) - return false; - - MONITORINFOEXW mi = {}; - mi.cbSize = sizeof(mi); - if (GetMonitorInfoW(mon, &mi)) - { - DEVMODEW dm = {}; - dm.dmSize = sizeof(dm); - - // 0/1 are reserved for "defaults". - if (EnumDisplaySettingsW(mi.szDevice, ENUM_CURRENT_SETTINGS, &dm) && dm.dmDisplayFrequency > 1) - { - *refresh_rate = static_cast(dm.dmDisplayFrequency); - return true; - } - } - - return false; -} - -bool WindowInfo::QueryRefreshRateForWindow(const WindowInfo& wi, float* refresh_rate) -{ - if (wi.type != Type::Win32 || !wi.window_handle) - return false; - - // Try DWM first, then fall back to integer values. - const HWND hwnd = static_cast(wi.window_handle); - return GetRefreshRateFromDWM(hwnd, refresh_rate) || GetRefreshRateFromMonitor(hwnd, refresh_rate); -} - -#else - -#ifdef USE_X11 - -#include "common/scope_guard.h" -#include "gl/x11_window.h" -#include - -static bool GetRefreshRateFromXRandR(const WindowInfo& wi, float* refresh_rate) -{ - Display* display = static_cast(wi.display_connection); - Window window = static_cast(reinterpret_cast(wi.window_handle)); - if (!display || !window) - return false; - - GL::X11InhibitErrors inhibiter; - - XRRScreenResources* res = XRRGetScreenResources(display, window); - if (!res) - return false; - - Common::ScopeGuard res_guard([res]() { XRRFreeScreenResources(res); }); - - int num_monitors; - XRRMonitorInfo* mi = XRRGetMonitors(display, window, True, &num_monitors); - if (num_monitors < 0) - return false; - - Common::ScopeGuard mi_guard([mi]() { XRRFreeMonitors(mi); }); - if (mi->noutput <= 0) - return false; - - XRROutputInfo* oi = XRRGetOutputInfo(display, res, mi->outputs[0]); - if (!oi) - return false; - - Common::ScopeGuard oi_guard([oi]() { XRRFreeOutputInfo(oi); }); - - XRRCrtcInfo* ci = XRRGetCrtcInfo(display, res, oi->crtc); - if (!ci) - return false; - - Common::ScopeGuard ci_guard([ci]() { XRRFreeCrtcInfo(ci); }); - - XRRModeInfo* mode = nullptr; - for (int i = 0; i < res->nmode; i++) - { - if (res->modes[i].id == ci->mode) - { - mode = &res->modes[i]; - break; - } - } - if (!mode) - return false; - - if (mode->dotClock == 0 || mode->hTotal == 0 || mode->vTotal == 0) - return false; - - *refresh_rate = - static_cast(mode->dotClock) / (static_cast(mode->hTotal) * static_cast(mode->vTotal)); - return true; -} - -#endif // USE_X11 - -bool WindowInfo::QueryRefreshRateForWindow(const WindowInfo& wi, float* refresh_rate) -{ -#if defined(USE_X11) - if (wi.type == WindowInfo::Type::X11) - return GetRefreshRateFromXRandR(wi, refresh_rate); -#endif - - return false; -} - -#endif diff --git a/src/common/window_info.h b/src/common/window_info.h index be1cc15b..f909aeb3 100644 --- a/src/common/window_info.h +++ b/src/common/window_info.h @@ -40,6 +40,4 @@ struct WindowInfo #ifdef __APPLE__ void* surface_handle = nullptr; #endif - - static bool QueryRefreshRateForWindow(const WindowInfo& wi, float* refresh_rate); }; diff --git a/src/core/host_display.cpp b/src/core/host_display.cpp index 50a1d340..5a557b2c 100644 --- a/src/core/host_display.cpp +++ b/src/core/host_display.cpp @@ -90,17 +90,6 @@ bool HostDisplay::SetDisplayPixels(HostDisplayPixelFormat format, u32 width, u32 return true; } -bool HostDisplay::GetHostRefreshRate(float* refresh_rate) -{ - if (m_window_info.surface_refresh_rate > 0.0f) - { - *refresh_rate = m_window_info.surface_refresh_rate; - return true; - } - - return WindowInfo::QueryRefreshRateForWindow(m_window_info, refresh_rate); -} - void HostDisplay::SetSoftwareCursor(std::unique_ptr texture, float scale /*= 1.0f*/) { m_cursor_texture = std::move(texture); diff --git a/src/core/host_display.h b/src/core/host_display.h index 7b3c2483..dfc84ec8 100644 --- a/src/core/host_display.h +++ b/src/core/host_display.h @@ -180,8 +180,6 @@ public: virtual void EndSetDisplayPixels() = 0; virtual bool SetDisplayPixels(HostDisplayPixelFormat format, u32 width, u32 height, const void* buffer, u32 pitch); - virtual bool GetHostRefreshRate(float* refresh_rate); - void SetDisplayLinearFiltering(bool enabled) { m_display_linear_filtering = enabled; } void SetDisplayTopMargin(s32 height) { m_display_top_margin = height; } void SetDisplayIntegerScaling(bool enabled) { m_display_integer_scaling = enabled; }