vk_swapchain.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. // Copyright 2019 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <array>
  6. #include <limits>
  7. #include <vector>
  8. #include "common/assert.h"
  9. #include "common/logging/log.h"
  10. #include "core/core.h"
  11. #include "core/frontend/framebuffer_layout.h"
  12. #include "video_core/renderer_vulkan/vk_device.h"
  13. #include "video_core/renderer_vulkan/vk_scheduler.h"
  14. #include "video_core/renderer_vulkan/vk_swapchain.h"
  15. #include "video_core/vulkan_common/vulkan_wrapper.h"
  16. namespace Vulkan {
  17. namespace {
  18. VkSurfaceFormatKHR ChooseSwapSurfaceFormat(vk::Span<VkSurfaceFormatKHR> formats, bool srgb) {
  19. if (formats.size() == 1 && formats[0].format == VK_FORMAT_UNDEFINED) {
  20. VkSurfaceFormatKHR format;
  21. format.format = VK_FORMAT_B8G8R8A8_UNORM;
  22. format.colorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
  23. return format;
  24. }
  25. const auto& found = std::find_if(formats.begin(), formats.end(), [srgb](const auto& format) {
  26. const auto request_format = srgb ? VK_FORMAT_B8G8R8A8_SRGB : VK_FORMAT_B8G8R8A8_UNORM;
  27. return format.format == request_format &&
  28. format.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
  29. });
  30. return found != formats.end() ? *found : formats[0];
  31. }
  32. VkPresentModeKHR ChooseSwapPresentMode(vk::Span<VkPresentModeKHR> modes) {
  33. // Mailbox doesn't lock the application like fifo (vsync), prefer it
  34. const auto found = std::find(modes.begin(), modes.end(), VK_PRESENT_MODE_MAILBOX_KHR);
  35. return found != modes.end() ? *found : VK_PRESENT_MODE_FIFO_KHR;
  36. }
  37. VkExtent2D ChooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, u32 width, u32 height) {
  38. constexpr auto undefined_size{std::numeric_limits<u32>::max()};
  39. if (capabilities.currentExtent.width != undefined_size) {
  40. return capabilities.currentExtent;
  41. }
  42. VkExtent2D extent;
  43. extent.width = std::max(capabilities.minImageExtent.width,
  44. std::min(capabilities.maxImageExtent.width, width));
  45. extent.height = std::max(capabilities.minImageExtent.height,
  46. std::min(capabilities.maxImageExtent.height, height));
  47. return extent;
  48. }
  49. } // Anonymous namespace
  50. VKSwapchain::VKSwapchain(VkSurfaceKHR surface_, const VKDevice& device_, VKScheduler& scheduler_)
  51. : surface{surface_}, device{device_}, scheduler{scheduler_} {}
  52. VKSwapchain::~VKSwapchain() = default;
  53. void VKSwapchain::Create(u32 width, u32 height, bool srgb) {
  54. const auto physical_device = device.GetPhysical();
  55. const auto capabilities{physical_device.GetSurfaceCapabilitiesKHR(surface)};
  56. if (capabilities.maxImageExtent.width == 0 || capabilities.maxImageExtent.height == 0) {
  57. return;
  58. }
  59. device.GetLogical().WaitIdle();
  60. Destroy();
  61. CreateSwapchain(capabilities, width, height, srgb);
  62. CreateSemaphores();
  63. CreateImageViews();
  64. resource_ticks.clear();
  65. resource_ticks.resize(image_count);
  66. }
  67. void VKSwapchain::AcquireNextImage() {
  68. device.GetLogical().AcquireNextImageKHR(*swapchain, std::numeric_limits<u64>::max(),
  69. *present_semaphores[frame_index], {}, &image_index);
  70. scheduler.Wait(resource_ticks[image_index]);
  71. }
  72. bool VKSwapchain::Present(VkSemaphore render_semaphore) {
  73. const VkSemaphore present_semaphore{*present_semaphores[frame_index]};
  74. const std::array<VkSemaphore, 2> semaphores{present_semaphore, render_semaphore};
  75. const auto present_queue{device.GetPresentQueue()};
  76. bool recreated = false;
  77. const VkPresentInfoKHR present_info{
  78. .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
  79. .pNext = nullptr,
  80. .waitSemaphoreCount = render_semaphore ? 2U : 1U,
  81. .pWaitSemaphores = semaphores.data(),
  82. .swapchainCount = 1,
  83. .pSwapchains = swapchain.address(),
  84. .pImageIndices = &image_index,
  85. .pResults = nullptr,
  86. };
  87. switch (const VkResult result = present_queue.Present(present_info)) {
  88. case VK_SUCCESS:
  89. break;
  90. case VK_SUBOPTIMAL_KHR:
  91. LOG_DEBUG(Render_Vulkan, "Suboptimal swapchain");
  92. break;
  93. case VK_ERROR_OUT_OF_DATE_KHR:
  94. if (current_width > 0 && current_height > 0) {
  95. Create(current_width, current_height, current_srgb);
  96. recreated = true;
  97. }
  98. break;
  99. default:
  100. LOG_CRITICAL(Render_Vulkan, "Failed to present with error {}", vk::ToString(result));
  101. break;
  102. }
  103. resource_ticks[image_index] = scheduler.CurrentTick();
  104. frame_index = (frame_index + 1) % static_cast<u32>(image_count);
  105. return recreated;
  106. }
  107. bool VKSwapchain::HasFramebufferChanged(const Layout::FramebufferLayout& framebuffer) const {
  108. // TODO(Rodrigo): Handle framebuffer pixel format changes
  109. return framebuffer.width != current_width || framebuffer.height != current_height;
  110. }
  111. void VKSwapchain::CreateSwapchain(const VkSurfaceCapabilitiesKHR& capabilities, u32 width,
  112. u32 height, bool srgb) {
  113. const auto physical_device{device.GetPhysical()};
  114. const auto formats{physical_device.GetSurfaceFormatsKHR(surface)};
  115. const auto present_modes{physical_device.GetSurfacePresentModesKHR(surface)};
  116. const VkSurfaceFormatKHR surface_format{ChooseSwapSurfaceFormat(formats, srgb)};
  117. const VkPresentModeKHR present_mode{ChooseSwapPresentMode(present_modes)};
  118. u32 requested_image_count{capabilities.minImageCount + 1};
  119. if (capabilities.maxImageCount > 0 && requested_image_count > capabilities.maxImageCount) {
  120. requested_image_count = capabilities.maxImageCount;
  121. }
  122. VkSwapchainCreateInfoKHR swapchain_ci{
  123. .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
  124. .pNext = nullptr,
  125. .flags = 0,
  126. .surface = surface,
  127. .minImageCount = requested_image_count,
  128. .imageFormat = surface_format.format,
  129. .imageColorSpace = surface_format.colorSpace,
  130. .imageExtent = {},
  131. .imageArrayLayers = 1,
  132. .imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
  133. .imageSharingMode = VK_SHARING_MODE_EXCLUSIVE,
  134. .queueFamilyIndexCount = 0,
  135. .pQueueFamilyIndices = nullptr,
  136. .preTransform = capabilities.currentTransform,
  137. .compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
  138. .presentMode = present_mode,
  139. .clipped = VK_FALSE,
  140. .oldSwapchain = nullptr,
  141. };
  142. const u32 graphics_family{device.GetGraphicsFamily()};
  143. const u32 present_family{device.GetPresentFamily()};
  144. const std::array<u32, 2> queue_indices{graphics_family, present_family};
  145. if (graphics_family != present_family) {
  146. swapchain_ci.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
  147. swapchain_ci.queueFamilyIndexCount = static_cast<u32>(queue_indices.size());
  148. swapchain_ci.pQueueFamilyIndices = queue_indices.data();
  149. }
  150. // Request the size again to reduce the possibility of a TOCTOU race condition.
  151. const auto updated_capabilities = physical_device.GetSurfaceCapabilitiesKHR(surface);
  152. swapchain_ci.imageExtent = ChooseSwapExtent(updated_capabilities, width, height);
  153. // Don't add code within this and the swapchain creation.
  154. swapchain = device.GetLogical().CreateSwapchainKHR(swapchain_ci);
  155. extent = swapchain_ci.imageExtent;
  156. current_width = extent.width;
  157. current_height = extent.height;
  158. current_srgb = srgb;
  159. images = swapchain.GetImages();
  160. image_count = static_cast<u32>(images.size());
  161. image_format = surface_format.format;
  162. }
  163. void VKSwapchain::CreateSemaphores() {
  164. present_semaphores.resize(image_count);
  165. std::generate(present_semaphores.begin(), present_semaphores.end(),
  166. [this] { return device.GetLogical().CreateSemaphore(); });
  167. }
  168. void VKSwapchain::CreateImageViews() {
  169. VkImageViewCreateInfo ci{
  170. .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
  171. .pNext = nullptr,
  172. .flags = 0,
  173. .image = {},
  174. .viewType = VK_IMAGE_VIEW_TYPE_2D,
  175. .format = image_format,
  176. .components =
  177. {
  178. .r = VK_COMPONENT_SWIZZLE_IDENTITY,
  179. .g = VK_COMPONENT_SWIZZLE_IDENTITY,
  180. .b = VK_COMPONENT_SWIZZLE_IDENTITY,
  181. .a = VK_COMPONENT_SWIZZLE_IDENTITY,
  182. },
  183. .subresourceRange =
  184. {
  185. .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
  186. .baseMipLevel = 0,
  187. .levelCount = 1,
  188. .baseArrayLayer = 0,
  189. .layerCount = 1,
  190. },
  191. };
  192. image_views.resize(image_count);
  193. for (std::size_t i = 0; i < image_count; i++) {
  194. ci.image = images[i];
  195. image_views[i] = device.GetLogical().CreateImageView(ci);
  196. }
  197. }
  198. void VKSwapchain::Destroy() {
  199. frame_index = 0;
  200. present_semaphores.clear();
  201. framebuffers.clear();
  202. image_views.clear();
  203. swapchain.reset();
  204. }
  205. } // namespace Vulkan