Window.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. using Ryujinx.Graphics.GAL;
  2. using Silk.NET.Vulkan;
  3. using Silk.NET.Vulkan.Extensions.KHR;
  4. using System;
  5. using System.Linq;
  6. using VkFormat = Silk.NET.Vulkan.Format;
  7. namespace Ryujinx.Graphics.Vulkan
  8. {
  9. class Window : WindowBase, IDisposable
  10. {
  11. private const int SurfaceWidth = 1280;
  12. private const int SurfaceHeight = 720;
  13. private readonly VulkanRenderer _gd;
  14. private readonly SurfaceKHR _surface;
  15. private readonly PhysicalDevice _physicalDevice;
  16. private readonly Device _device;
  17. private SwapchainKHR _swapchain;
  18. private Image[] _swapchainImages;
  19. private Auto<DisposableImageView>[] _swapchainImageViews;
  20. private Semaphore _imageAvailableSemaphore;
  21. private Semaphore _renderFinishedSemaphore;
  22. private int _width;
  23. private int _height;
  24. private bool _vsyncEnabled;
  25. private bool _vsyncModeChanged;
  26. private VkFormat _format;
  27. public unsafe Window(VulkanRenderer gd, SurfaceKHR surface, PhysicalDevice physicalDevice, Device device)
  28. {
  29. _gd = gd;
  30. _physicalDevice = physicalDevice;
  31. _device = device;
  32. _surface = surface;
  33. CreateSwapchain();
  34. var semaphoreCreateInfo = new SemaphoreCreateInfo()
  35. {
  36. SType = StructureType.SemaphoreCreateInfo
  37. };
  38. gd.Api.CreateSemaphore(device, semaphoreCreateInfo, null, out _imageAvailableSemaphore).ThrowOnError();
  39. gd.Api.CreateSemaphore(device, semaphoreCreateInfo, null, out _renderFinishedSemaphore).ThrowOnError();
  40. }
  41. private void RecreateSwapchain()
  42. {
  43. var oldSwapchain = _swapchain;
  44. int imageCount = _swapchainImageViews.Length;
  45. _vsyncModeChanged = false;
  46. for (int i = 0; i < imageCount; i++)
  47. {
  48. _swapchainImageViews[i].Dispose();
  49. }
  50. // Destroy old Swapchain.
  51. _gd.Api.DeviceWaitIdle(_device);
  52. _gd.SwapchainApi.DestroySwapchain(_device, oldSwapchain, Span<AllocationCallbacks>.Empty);
  53. CreateSwapchain();
  54. }
  55. private unsafe void CreateSwapchain()
  56. {
  57. _gd.SurfaceApi.GetPhysicalDeviceSurfaceCapabilities(_physicalDevice, _surface, out var capabilities);
  58. uint surfaceFormatsCount;
  59. _gd.SurfaceApi.GetPhysicalDeviceSurfaceFormats(_physicalDevice, _surface, &surfaceFormatsCount, null);
  60. var surfaceFormats = new SurfaceFormatKHR[surfaceFormatsCount];
  61. fixed (SurfaceFormatKHR* pSurfaceFormats = surfaceFormats)
  62. {
  63. _gd.SurfaceApi.GetPhysicalDeviceSurfaceFormats(_physicalDevice, _surface, &surfaceFormatsCount, pSurfaceFormats);
  64. }
  65. uint presentModesCount;
  66. _gd.SurfaceApi.GetPhysicalDeviceSurfacePresentModes(_physicalDevice, _surface, &presentModesCount, null);
  67. var presentModes = new PresentModeKHR[presentModesCount];
  68. fixed (PresentModeKHR* pPresentModes = presentModes)
  69. {
  70. _gd.SurfaceApi.GetPhysicalDeviceSurfacePresentModes(_physicalDevice, _surface, &presentModesCount, pPresentModes);
  71. }
  72. uint imageCount = capabilities.MinImageCount + 1;
  73. if (capabilities.MaxImageCount > 0 && imageCount > capabilities.MaxImageCount)
  74. {
  75. imageCount = capabilities.MaxImageCount;
  76. }
  77. var surfaceFormat = ChooseSwapSurfaceFormat(surfaceFormats);
  78. var extent = ChooseSwapExtent(capabilities);
  79. _width = (int)extent.Width;
  80. _height = (int)extent.Height;
  81. _format = surfaceFormat.Format;
  82. var oldSwapchain = _swapchain;
  83. var swapchainCreateInfo = new SwapchainCreateInfoKHR()
  84. {
  85. SType = StructureType.SwapchainCreateInfoKhr,
  86. Surface = _surface,
  87. MinImageCount = imageCount,
  88. ImageFormat = surfaceFormat.Format,
  89. ImageColorSpace = surfaceFormat.ColorSpace,
  90. ImageExtent = extent,
  91. ImageUsage = ImageUsageFlags.ColorAttachmentBit | ImageUsageFlags.TransferDstBit,
  92. ImageSharingMode = SharingMode.Exclusive,
  93. ImageArrayLayers = 1,
  94. PreTransform = capabilities.CurrentTransform,
  95. CompositeAlpha = CompositeAlphaFlagsKHR.OpaqueBitKhr,
  96. PresentMode = ChooseSwapPresentMode(presentModes, _vsyncEnabled),
  97. Clipped = true
  98. };
  99. _gd.SwapchainApi.CreateSwapchain(_device, swapchainCreateInfo, null, out _swapchain).ThrowOnError();
  100. _gd.SwapchainApi.GetSwapchainImages(_device, _swapchain, &imageCount, null);
  101. _swapchainImages = new Image[imageCount];
  102. fixed (Image* pSwapchainImages = _swapchainImages)
  103. {
  104. _gd.SwapchainApi.GetSwapchainImages(_device, _swapchain, &imageCount, pSwapchainImages);
  105. }
  106. _swapchainImageViews = new Auto<DisposableImageView>[imageCount];
  107. for (int i = 0; i < imageCount; i++)
  108. {
  109. _swapchainImageViews[i] = CreateSwapchainImageView(_swapchainImages[i], surfaceFormat.Format);
  110. }
  111. }
  112. private unsafe Auto<DisposableImageView> CreateSwapchainImageView(Image swapchainImage, VkFormat format)
  113. {
  114. var componentMapping = new ComponentMapping(
  115. ComponentSwizzle.R,
  116. ComponentSwizzle.G,
  117. ComponentSwizzle.B,
  118. ComponentSwizzle.A);
  119. var aspectFlags = ImageAspectFlags.ColorBit;
  120. var subresourceRange = new ImageSubresourceRange(aspectFlags, 0, 1, 0, 1);
  121. var imageCreateInfo = new ImageViewCreateInfo()
  122. {
  123. SType = StructureType.ImageViewCreateInfo,
  124. Image = swapchainImage,
  125. ViewType = ImageViewType.Type2D,
  126. Format = format,
  127. Components = componentMapping,
  128. SubresourceRange = subresourceRange
  129. };
  130. _gd.Api.CreateImageView(_device, imageCreateInfo, null, out var imageView).ThrowOnError();
  131. return new Auto<DisposableImageView>(new DisposableImageView(_gd.Api, _device, imageView));
  132. }
  133. private static SurfaceFormatKHR ChooseSwapSurfaceFormat(SurfaceFormatKHR[] availableFormats)
  134. {
  135. if (availableFormats.Length == 1 && availableFormats[0].Format == VkFormat.Undefined)
  136. {
  137. return new SurfaceFormatKHR(VkFormat.B8G8R8A8Unorm, ColorSpaceKHR.PaceSrgbNonlinearKhr);
  138. }
  139. foreach (var format in availableFormats)
  140. {
  141. if (format.Format == VkFormat.B8G8R8A8Unorm && format.ColorSpace == ColorSpaceKHR.PaceSrgbNonlinearKhr)
  142. {
  143. return format;
  144. }
  145. }
  146. return availableFormats[0];
  147. }
  148. private static PresentModeKHR ChooseSwapPresentMode(PresentModeKHR[] availablePresentModes, bool vsyncEnabled)
  149. {
  150. if (!vsyncEnabled && availablePresentModes.Contains(PresentModeKHR.ImmediateKhr))
  151. {
  152. return PresentModeKHR.ImmediateKhr;
  153. }
  154. else if (availablePresentModes.Contains(PresentModeKHR.MailboxKhr))
  155. {
  156. return PresentModeKHR.MailboxKhr;
  157. }
  158. else if (availablePresentModes.Contains(PresentModeKHR.FifoKhr))
  159. {
  160. return PresentModeKHR.FifoKhr;
  161. }
  162. else
  163. {
  164. return PresentModeKHR.FifoKhr;
  165. }
  166. }
  167. public static Extent2D ChooseSwapExtent(SurfaceCapabilitiesKHR capabilities)
  168. {
  169. if (capabilities.CurrentExtent.Width != uint.MaxValue)
  170. {
  171. return capabilities.CurrentExtent;
  172. }
  173. else
  174. {
  175. uint width = Math.Max(capabilities.MinImageExtent.Width, Math.Min(capabilities.MaxImageExtent.Width, SurfaceWidth));
  176. uint height = Math.Max(capabilities.MinImageExtent.Height, Math.Min(capabilities.MaxImageExtent.Height, SurfaceHeight));
  177. return new Extent2D(width, height);
  178. }
  179. }
  180. public unsafe override void Present(ITexture texture, ImageCrop crop, Action swapBuffersCallback)
  181. {
  182. uint nextImage = 0;
  183. while (true)
  184. {
  185. var acquireResult = _gd.SwapchainApi.AcquireNextImage(
  186. _device,
  187. _swapchain,
  188. ulong.MaxValue,
  189. _imageAvailableSemaphore,
  190. new Fence(),
  191. ref nextImage);
  192. if (acquireResult == Result.ErrorOutOfDateKhr ||
  193. acquireResult == Result.SuboptimalKhr ||
  194. _vsyncModeChanged)
  195. {
  196. RecreateSwapchain();
  197. }
  198. else
  199. {
  200. acquireResult.ThrowOnError();
  201. break;
  202. }
  203. }
  204. var swapchainImage = _swapchainImages[nextImage];
  205. _gd.FlushAllCommands();
  206. var cbs = _gd.CommandBufferPool.Rent();
  207. Transition(
  208. cbs.CommandBuffer,
  209. swapchainImage,
  210. 0,
  211. AccessFlags.TransferWriteBit,
  212. ImageLayout.Undefined,
  213. ImageLayout.General);
  214. var view = (TextureView)texture;
  215. int srcX0, srcX1, srcY0, srcY1;
  216. float scale = view.ScaleFactor;
  217. if (crop.Left == 0 && crop.Right == 0)
  218. {
  219. srcX0 = 0;
  220. srcX1 = (int)(view.Width / scale);
  221. }
  222. else
  223. {
  224. srcX0 = crop.Left;
  225. srcX1 = crop.Right;
  226. }
  227. if (crop.Top == 0 && crop.Bottom == 0)
  228. {
  229. srcY0 = 0;
  230. srcY1 = (int)(view.Height / scale);
  231. }
  232. else
  233. {
  234. srcY0 = crop.Top;
  235. srcY1 = crop.Bottom;
  236. }
  237. if (scale != 1f)
  238. {
  239. srcX0 = (int)(srcX0 * scale);
  240. srcY0 = (int)(srcY0 * scale);
  241. srcX1 = (int)Math.Ceiling(srcX1 * scale);
  242. srcY1 = (int)Math.Ceiling(srcY1 * scale);
  243. }
  244. if (ScreenCaptureRequested)
  245. {
  246. CaptureFrame(view, srcX0, srcY0, srcX1 - srcX0, srcY1 - srcY0, view.Info.Format.IsBgr(), crop.FlipX, crop.FlipY);
  247. ScreenCaptureRequested = false;
  248. }
  249. float ratioX = crop.IsStretched ? 1.0f : MathF.Min(1.0f, _height * crop.AspectRatioX / (_width * crop.AspectRatioY));
  250. float ratioY = crop.IsStretched ? 1.0f : MathF.Min(1.0f, _width * crop.AspectRatioY / (_height * crop.AspectRatioX));
  251. int dstWidth = (int)(_width * ratioX);
  252. int dstHeight = (int)(_height * ratioY);
  253. int dstPaddingX = (_width - dstWidth) / 2;
  254. int dstPaddingY = (_height - dstHeight) / 2;
  255. int dstX0 = crop.FlipX ? _width - dstPaddingX : dstPaddingX;
  256. int dstX1 = crop.FlipX ? dstPaddingX : _width - dstPaddingX;
  257. int dstY0 = crop.FlipY ? dstPaddingY : _height - dstPaddingY;
  258. int dstY1 = crop.FlipY ? _height - dstPaddingY : dstPaddingY;
  259. _gd.HelperShader.Blit(
  260. _gd,
  261. cbs,
  262. view,
  263. _swapchainImageViews[nextImage],
  264. _width,
  265. _height,
  266. _format,
  267. new Extents2D(srcX0, srcY0, srcX1, srcY1),
  268. new Extents2D(dstX0, dstY1, dstX1, dstY0),
  269. true,
  270. true);
  271. Transition(
  272. cbs.CommandBuffer,
  273. swapchainImage,
  274. 0,
  275. 0,
  276. ImageLayout.General,
  277. ImageLayout.PresentSrcKhr);
  278. _gd.CommandBufferPool.Return(
  279. cbs,
  280. stackalloc[] { _imageAvailableSemaphore },
  281. stackalloc[] { PipelineStageFlags.ColorAttachmentOutputBit },
  282. stackalloc[] { _renderFinishedSemaphore });
  283. // TODO: Present queue.
  284. var semaphore = _renderFinishedSemaphore;
  285. var swapchain = _swapchain;
  286. Result result;
  287. var presentInfo = new PresentInfoKHR()
  288. {
  289. SType = StructureType.PresentInfoKhr,
  290. WaitSemaphoreCount = 1,
  291. PWaitSemaphores = &semaphore,
  292. SwapchainCount = 1,
  293. PSwapchains = &swapchain,
  294. PImageIndices = &nextImage,
  295. PResults = &result
  296. };
  297. lock (_gd.QueueLock)
  298. {
  299. _gd.SwapchainApi.QueuePresent(_gd.Queue, presentInfo);
  300. }
  301. }
  302. private unsafe void Transition(
  303. CommandBuffer commandBuffer,
  304. Image image,
  305. AccessFlags srcAccess,
  306. AccessFlags dstAccess,
  307. ImageLayout srcLayout,
  308. ImageLayout dstLayout)
  309. {
  310. var subresourceRange = new ImageSubresourceRange(ImageAspectFlags.ColorBit, 0, 1, 0, 1);
  311. var barrier = new ImageMemoryBarrier()
  312. {
  313. SType = StructureType.ImageMemoryBarrier,
  314. SrcAccessMask = srcAccess,
  315. DstAccessMask = dstAccess,
  316. OldLayout = srcLayout,
  317. NewLayout = dstLayout,
  318. SrcQueueFamilyIndex = Vk.QueueFamilyIgnored,
  319. DstQueueFamilyIndex = Vk.QueueFamilyIgnored,
  320. Image = image,
  321. SubresourceRange = subresourceRange
  322. };
  323. _gd.Api.CmdPipelineBarrier(
  324. commandBuffer,
  325. PipelineStageFlags.TopOfPipeBit,
  326. PipelineStageFlags.AllCommandsBit,
  327. 0,
  328. 0,
  329. null,
  330. 0,
  331. null,
  332. 1,
  333. barrier);
  334. }
  335. private void CaptureFrame(TextureView texture, int x, int y, int width, int height, bool isBgra, bool flipX, bool flipY)
  336. {
  337. byte[] bitmap = texture.GetData(x, y, width, height);
  338. _gd.OnScreenCaptured(new ScreenCaptureImageInfo(width, height, isBgra, bitmap, flipX, flipY));
  339. }
  340. public override void SetSize(int width, int height)
  341. {
  342. // Not needed as we can get the size from the surface.
  343. }
  344. public override void ChangeVSyncMode(bool vsyncEnabled)
  345. {
  346. _vsyncEnabled = vsyncEnabled;
  347. _vsyncModeChanged = true;
  348. }
  349. protected virtual void Dispose(bool disposing)
  350. {
  351. if (disposing)
  352. {
  353. unsafe
  354. {
  355. _gd.Api.DestroySemaphore(_device, _renderFinishedSemaphore, null);
  356. _gd.Api.DestroySemaphore(_device, _imageAvailableSemaphore, null);
  357. for (int i = 0; i < _swapchainImageViews.Length; i++)
  358. {
  359. _swapchainImageViews[i].Dispose();
  360. }
  361. _gd.SwapchainApi.DestroySwapchain(_device, _swapchain, null);
  362. }
  363. }
  364. }
  365. public override void Dispose()
  366. {
  367. Dispose(true);
  368. }
  369. }
  370. }