vk_swapchain.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. // SPDX-FileCopyrightText: Copyright 2019 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <algorithm>
  4. #include <array>
  5. #include <limits>
  6. #include <vector>
  7. #include "common/logging/log.h"
  8. #include "common/polyfill_ranges.h"
  9. #include "common/settings.h"
  10. #include "core/core.h"
  11. #include "video_core/renderer_vulkan/vk_scheduler.h"
  12. #include "video_core/renderer_vulkan/vk_swapchain.h"
  13. #include "video_core/vulkan_common/vulkan_device.h"
  14. #include "video_core/vulkan_common/vulkan_wrapper.h"
  15. #include "vulkan/vulkan_core.h"
  16. namespace Vulkan {
  17. namespace {
  18. VkSurfaceFormatKHR ChooseSwapSurfaceFormat(vk::Span<VkSurfaceFormatKHR> formats) {
  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(), [](const auto& format) {
  26. return format.format == VK_FORMAT_B8G8R8A8_UNORM &&
  27. format.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
  28. });
  29. return found != formats.end() ? *found : formats[0];
  30. }
  31. static VkPresentModeKHR ChooseSwapPresentMode(bool has_imm, bool has_mailbox,
  32. bool has_fifo_relaxed) {
  33. // Mailbox doesn't lock the application like FIFO (vsync)
  34. // FIFO present mode locks the framerate to the monitor's refresh rate
  35. Settings::VSyncMode setting = [has_imm, has_mailbox]() {
  36. // Choose Mailbox or Immediate if unlocked and those modes are supported
  37. const auto mode = Settings::values.vsync_mode.GetValue();
  38. if (Settings::values.use_speed_limit.GetValue()) {
  39. return mode;
  40. }
  41. switch (mode) {
  42. case Settings::VSyncMode::Fifo:
  43. case Settings::VSyncMode::FifoRelaxed:
  44. if (has_mailbox) {
  45. return Settings::VSyncMode::Mailbox;
  46. } else if (has_imm) {
  47. return Settings::VSyncMode::Immediate;
  48. }
  49. [[fallthrough]];
  50. default:
  51. return mode;
  52. }
  53. }();
  54. if ((setting == Settings::VSyncMode::Mailbox && !has_mailbox) ||
  55. (setting == Settings::VSyncMode::Immediate && !has_imm) ||
  56. (setting == Settings::VSyncMode::FifoRelaxed && !has_fifo_relaxed)) {
  57. setting = Settings::VSyncMode::Fifo;
  58. }
  59. switch (setting) {
  60. case Settings::VSyncMode::Immediate:
  61. return VK_PRESENT_MODE_IMMEDIATE_KHR;
  62. case Settings::VSyncMode::Mailbox:
  63. return VK_PRESENT_MODE_MAILBOX_KHR;
  64. case Settings::VSyncMode::Fifo:
  65. return VK_PRESENT_MODE_FIFO_KHR;
  66. case Settings::VSyncMode::FifoRelaxed:
  67. return VK_PRESENT_MODE_FIFO_RELAXED_KHR;
  68. default:
  69. return VK_PRESENT_MODE_FIFO_KHR;
  70. }
  71. }
  72. VkExtent2D ChooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, u32 width, u32 height) {
  73. constexpr auto undefined_size{std::numeric_limits<u32>::max()};
  74. if (capabilities.currentExtent.width != undefined_size) {
  75. return capabilities.currentExtent;
  76. }
  77. VkExtent2D extent;
  78. extent.width = std::max(capabilities.minImageExtent.width,
  79. std::min(capabilities.maxImageExtent.width, width));
  80. extent.height = std::max(capabilities.minImageExtent.height,
  81. std::min(capabilities.maxImageExtent.height, height));
  82. return extent;
  83. }
  84. VkCompositeAlphaFlagBitsKHR ChooseAlphaFlags(const VkSurfaceCapabilitiesKHR& capabilities) {
  85. if (capabilities.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR) {
  86. return VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
  87. } else if (capabilities.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR) {
  88. return VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
  89. } else {
  90. LOG_ERROR(Render_Vulkan, "Unknown composite alpha flags value {:#x}",
  91. capabilities.supportedCompositeAlpha);
  92. return VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
  93. }
  94. }
  95. } // Anonymous namespace
  96. Swapchain::Swapchain(VkSurfaceKHR surface_, const Device& device_, Scheduler& scheduler_,
  97. u32 width_, u32 height_, bool srgb)
  98. : surface{surface_}, device{device_}, scheduler{scheduler_} {
  99. Create(surface_, width_, height_, srgb);
  100. }
  101. Swapchain::~Swapchain() = default;
  102. void Swapchain::Create(VkSurfaceKHR surface_, u32 width_, u32 height_, bool srgb) {
  103. is_outdated = false;
  104. is_suboptimal = false;
  105. width = width_;
  106. height = height_;
  107. surface = surface_;
  108. const auto physical_device = device.GetPhysical();
  109. const auto capabilities{physical_device.GetSurfaceCapabilitiesKHR(surface)};
  110. if (capabilities.maxImageExtent.width == 0 || capabilities.maxImageExtent.height == 0) {
  111. return;
  112. }
  113. Destroy();
  114. CreateSwapchain(capabilities, srgb);
  115. CreateSemaphores();
  116. resource_ticks.clear();
  117. resource_ticks.resize(image_count);
  118. }
  119. bool Swapchain::AcquireNextImage() {
  120. const VkResult result = device.GetLogical().AcquireNextImageKHR(
  121. *swapchain, std::numeric_limits<u64>::max(), *present_semaphores[frame_index],
  122. VK_NULL_HANDLE, &image_index);
  123. switch (result) {
  124. case VK_SUCCESS:
  125. break;
  126. case VK_SUBOPTIMAL_KHR:
  127. is_suboptimal = true;
  128. break;
  129. case VK_ERROR_OUT_OF_DATE_KHR:
  130. is_outdated = true;
  131. break;
  132. default:
  133. LOG_ERROR(Render_Vulkan, "vkAcquireNextImageKHR returned {}", vk::ToString(result));
  134. break;
  135. }
  136. scheduler.Wait(resource_ticks[image_index]);
  137. resource_ticks[image_index] = scheduler.CurrentTick();
  138. return is_suboptimal || is_outdated;
  139. }
  140. void Swapchain::Present(VkSemaphore render_semaphore) {
  141. const auto present_queue{device.GetPresentQueue()};
  142. const VkPresentInfoKHR present_info{
  143. .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
  144. .pNext = nullptr,
  145. .waitSemaphoreCount = render_semaphore ? 1U : 0U,
  146. .pWaitSemaphores = &render_semaphore,
  147. .swapchainCount = 1,
  148. .pSwapchains = swapchain.address(),
  149. .pImageIndices = &image_index,
  150. .pResults = nullptr,
  151. };
  152. std::scoped_lock lock{scheduler.submit_mutex};
  153. switch (const VkResult result = present_queue.Present(present_info)) {
  154. case VK_SUCCESS:
  155. break;
  156. case VK_SUBOPTIMAL_KHR:
  157. LOG_DEBUG(Render_Vulkan, "Suboptimal swapchain");
  158. break;
  159. case VK_ERROR_OUT_OF_DATE_KHR:
  160. is_outdated = true;
  161. break;
  162. default:
  163. LOG_CRITICAL(Render_Vulkan, "Failed to present with error {}", vk::ToString(result));
  164. break;
  165. }
  166. ++frame_index;
  167. if (frame_index >= image_count) {
  168. frame_index = 0;
  169. }
  170. }
  171. void Swapchain::CreateSwapchain(const VkSurfaceCapabilitiesKHR& capabilities, bool srgb) {
  172. const auto physical_device{device.GetPhysical()};
  173. const auto formats{physical_device.GetSurfaceFormatsKHR(surface)};
  174. const auto present_modes = physical_device.GetSurfacePresentModesKHR(surface);
  175. has_mailbox = std::find(present_modes.begin(), present_modes.end(),
  176. VK_PRESENT_MODE_MAILBOX_KHR) != present_modes.end();
  177. has_imm = std::find(present_modes.begin(), present_modes.end(),
  178. VK_PRESENT_MODE_IMMEDIATE_KHR) != present_modes.end();
  179. has_fifo_relaxed = std::find(present_modes.begin(), present_modes.end(),
  180. VK_PRESENT_MODE_FIFO_RELAXED_KHR) != present_modes.end();
  181. const VkCompositeAlphaFlagBitsKHR alpha_flags{ChooseAlphaFlags(capabilities)};
  182. surface_format = ChooseSwapSurfaceFormat(formats);
  183. present_mode = ChooseSwapPresentMode(has_imm, has_mailbox, has_fifo_relaxed);
  184. u32 requested_image_count{capabilities.minImageCount + 1};
  185. // Ensure Triple buffering if possible.
  186. if (capabilities.maxImageCount > 0) {
  187. if (requested_image_count > capabilities.maxImageCount) {
  188. requested_image_count = capabilities.maxImageCount;
  189. } else {
  190. requested_image_count =
  191. std::max(requested_image_count, std::min(3U, capabilities.maxImageCount));
  192. }
  193. } else {
  194. requested_image_count = std::max(requested_image_count, 3U);
  195. }
  196. VkSwapchainCreateInfoKHR swapchain_ci{
  197. .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
  198. .pNext = nullptr,
  199. .flags = 0,
  200. .surface = surface,
  201. .minImageCount = requested_image_count,
  202. .imageFormat = surface_format.format,
  203. .imageColorSpace = surface_format.colorSpace,
  204. .imageExtent = {},
  205. .imageArrayLayers = 1,
  206. .imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT,
  207. .imageSharingMode = VK_SHARING_MODE_EXCLUSIVE,
  208. .queueFamilyIndexCount = 0,
  209. .pQueueFamilyIndices = nullptr,
  210. #ifdef ANDROID
  211. // On Android, do not allow surface rotation to deviate from the frontend.
  212. .preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR,
  213. #else
  214. .preTransform = capabilities.currentTransform,
  215. #endif
  216. .compositeAlpha = alpha_flags,
  217. .presentMode = present_mode,
  218. .clipped = VK_FALSE,
  219. .oldSwapchain = nullptr,
  220. };
  221. const u32 graphics_family{device.GetGraphicsFamily()};
  222. const u32 present_family{device.GetPresentFamily()};
  223. const std::array<u32, 2> queue_indices{graphics_family, present_family};
  224. if (graphics_family != present_family) {
  225. swapchain_ci.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
  226. swapchain_ci.queueFamilyIndexCount = static_cast<u32>(queue_indices.size());
  227. swapchain_ci.pQueueFamilyIndices = queue_indices.data();
  228. }
  229. static constexpr std::array view_formats{VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_B8G8R8A8_SRGB};
  230. VkImageFormatListCreateInfo format_list{
  231. .sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO_KHR,
  232. .pNext = nullptr,
  233. .viewFormatCount = static_cast<u32>(view_formats.size()),
  234. .pViewFormats = view_formats.data(),
  235. };
  236. if (device.IsKhrSwapchainMutableFormatEnabled()) {
  237. format_list.pNext = std::exchange(swapchain_ci.pNext, &format_list);
  238. swapchain_ci.flags |= VK_SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR;
  239. }
  240. // Request the size again to reduce the possibility of a TOCTOU race condition.
  241. const auto updated_capabilities = physical_device.GetSurfaceCapabilitiesKHR(surface);
  242. swapchain_ci.imageExtent = ChooseSwapExtent(updated_capabilities, width, height);
  243. // Don't add code within this and the swapchain creation.
  244. swapchain = device.GetLogical().CreateSwapchainKHR(swapchain_ci);
  245. extent = swapchain_ci.imageExtent;
  246. current_srgb = srgb;
  247. images = swapchain.GetImages();
  248. image_count = static_cast<u32>(images.size());
  249. #ifdef ANDROID
  250. // Android is already ordered the same as Switch.
  251. image_view_format = srgb ? VK_FORMAT_R8G8B8A8_SRGB : VK_FORMAT_R8G8B8A8_UNORM;
  252. #else
  253. image_view_format = srgb ? VK_FORMAT_B8G8R8A8_SRGB : VK_FORMAT_B8G8R8A8_UNORM;
  254. #endif
  255. }
  256. void Swapchain::CreateSemaphores() {
  257. present_semaphores.resize(image_count);
  258. std::ranges::generate(present_semaphores,
  259. [this] { return device.GetLogical().CreateSemaphore(); });
  260. render_semaphores.resize(image_count);
  261. std::ranges::generate(render_semaphores,
  262. [this] { return device.GetLogical().CreateSemaphore(); });
  263. }
  264. void Swapchain::Destroy() {
  265. frame_index = 0;
  266. present_semaphores.clear();
  267. swapchain.reset();
  268. }
  269. bool Swapchain::NeedsPresentModeUpdate() const {
  270. const auto requested_mode = ChooseSwapPresentMode(has_imm, has_mailbox, has_fifo_relaxed);
  271. return present_mode != requested_mode;
  272. }
  273. } // namespace Vulkan