VulkanRenderer.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  1. using Ryujinx.Common.Configuration;
  2. using Ryujinx.Common.Logging;
  3. using Ryujinx.Graphics.GAL;
  4. using Ryujinx.Graphics.Shader;
  5. using Ryujinx.Graphics.Shader.Translation;
  6. using Ryujinx.Graphics.Vulkan.MoltenVK;
  7. using Ryujinx.Graphics.Vulkan.Queries;
  8. using Silk.NET.Vulkan;
  9. using Silk.NET.Vulkan.Extensions.EXT;
  10. using Silk.NET.Vulkan.Extensions.KHR;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.Linq;
  14. using System.Runtime.InteropServices;
  15. namespace Ryujinx.Graphics.Vulkan
  16. {
  17. public sealed class VulkanRenderer : IRenderer
  18. {
  19. private Instance _instance;
  20. private SurfaceKHR _surface;
  21. private PhysicalDevice _physicalDevice;
  22. private Device _device;
  23. private WindowBase _window;
  24. private bool _initialized;
  25. internal FormatCapabilities FormatCapabilities { get; private set; }
  26. internal HardwareCapabilities Capabilities;
  27. internal Vk Api { get; private set; }
  28. internal KhrSurface SurfaceApi { get; private set; }
  29. internal KhrSwapchain SwapchainApi { get; private set; }
  30. internal ExtConditionalRendering ConditionalRenderingApi { get; private set; }
  31. internal ExtExtendedDynamicState ExtendedDynamicStateApi { get; private set; }
  32. internal KhrPushDescriptor PushDescriptorApi { get; private set; }
  33. internal ExtTransformFeedback TransformFeedbackApi { get; private set; }
  34. internal KhrDrawIndirectCount DrawIndirectCountApi { get; private set; }
  35. internal ExtDebugUtils DebugUtilsApi { get; private set; }
  36. internal uint QueueFamilyIndex { get; private set; }
  37. internal Queue Queue { get; private set; }
  38. internal Queue BackgroundQueue { get; private set; }
  39. internal object BackgroundQueueLock { get; private set; }
  40. internal object QueueLock { get; private set; }
  41. internal MemoryAllocator MemoryAllocator { get; private set; }
  42. internal CommandBufferPool CommandBufferPool { get; private set; }
  43. internal DescriptorSetManager DescriptorSetManager { get; private set; }
  44. internal PipelineLayoutCache PipelineLayoutCache { get; private set; }
  45. internal BackgroundResources BackgroundResources { get; private set; }
  46. internal Action<Action> InterruptAction { get; private set; }
  47. internal BufferManager BufferManager { get; private set; }
  48. internal HashSet<ShaderCollection> Shaders { get; }
  49. internal HashSet<ITexture> Textures { get; }
  50. internal HashSet<SamplerHolder> Samplers { get; }
  51. private Counters _counters;
  52. private SyncManager _syncManager;
  53. private PipelineFull _pipeline;
  54. private DebugUtilsMessengerEXT _debugUtilsMessenger;
  55. internal HelperShader HelperShader { get; private set; }
  56. internal PipelineFull PipelineInternal => _pipeline;
  57. public IPipeline Pipeline => _pipeline;
  58. public IWindow Window => _window;
  59. private readonly Func<Instance, Vk, SurfaceKHR> _getSurface;
  60. private readonly Func<string[]> _getRequiredExtensions;
  61. private readonly string _preferredGpuId;
  62. internal Vendor Vendor { get; private set; }
  63. internal bool IsAmdWindows { get; private set; }
  64. internal bool IsIntelWindows { get; private set; }
  65. internal bool IsAmdGcn { get; private set; }
  66. internal bool IsMoltenVk { get; private set; }
  67. internal bool IsTBDR { get; private set; }
  68. public string GpuVendor { get; private set; }
  69. public string GpuRenderer { get; private set; }
  70. public string GpuVersion { get; private set; }
  71. public bool PreferThreading => true;
  72. public event EventHandler<ScreenCaptureImageInfo> ScreenCaptured;
  73. public VulkanRenderer(Func<Instance, Vk, SurfaceKHR> surfaceFunc, Func<string[]> requiredExtensionsFunc, string preferredGpuId)
  74. {
  75. _getSurface = surfaceFunc;
  76. _getRequiredExtensions = requiredExtensionsFunc;
  77. _preferredGpuId = preferredGpuId;
  78. Shaders = new HashSet<ShaderCollection>();
  79. Textures = new HashSet<ITexture>();
  80. Samplers = new HashSet<SamplerHolder>();
  81. if (OperatingSystem.IsMacOS())
  82. {
  83. MVKInitialization.Initialize();
  84. // Any device running on MacOS is using MoltenVK, even Intel and AMD vendors.
  85. IsMoltenVk = true;
  86. }
  87. }
  88. private unsafe void LoadFeatures(string[] supportedExtensions, uint maxQueueCount, uint queueFamilyIndex)
  89. {
  90. FormatCapabilities = new FormatCapabilities(Api, _physicalDevice);
  91. var supportedFeatures = Api.GetPhysicalDeviceFeature(_physicalDevice);
  92. if (Api.TryGetDeviceExtension(_instance, _device, out ExtConditionalRendering conditionalRenderingApi))
  93. {
  94. ConditionalRenderingApi = conditionalRenderingApi;
  95. }
  96. if (Api.TryGetDeviceExtension(_instance, _device, out ExtExtendedDynamicState extendedDynamicStateApi))
  97. {
  98. ExtendedDynamicStateApi = extendedDynamicStateApi;
  99. }
  100. if (Api.TryGetDeviceExtension(_instance, _device, out KhrPushDescriptor pushDescriptorApi))
  101. {
  102. PushDescriptorApi = pushDescriptorApi;
  103. }
  104. if (Api.TryGetDeviceExtension(_instance, _device, out ExtTransformFeedback transformFeedbackApi))
  105. {
  106. TransformFeedbackApi = transformFeedbackApi;
  107. }
  108. if (Api.TryGetDeviceExtension(_instance, _device, out KhrDrawIndirectCount drawIndirectCountApi))
  109. {
  110. DrawIndirectCountApi = drawIndirectCountApi;
  111. }
  112. if (maxQueueCount >= 2)
  113. {
  114. Api.GetDeviceQueue(_device, queueFamilyIndex, 1, out var backgroundQueue);
  115. BackgroundQueue = backgroundQueue;
  116. BackgroundQueueLock = new object();
  117. }
  118. PhysicalDeviceProperties2 properties2 = new PhysicalDeviceProperties2()
  119. {
  120. SType = StructureType.PhysicalDeviceProperties2
  121. };
  122. PhysicalDeviceSubgroupSizeControlPropertiesEXT propertiesSubgroupSizeControl = new PhysicalDeviceSubgroupSizeControlPropertiesEXT()
  123. {
  124. SType = StructureType.PhysicalDeviceSubgroupSizeControlPropertiesExt
  125. };
  126. if (Capabilities.SupportsSubgroupSizeControl)
  127. {
  128. properties2.PNext = &propertiesSubgroupSizeControl;
  129. }
  130. bool supportsTransformFeedback = supportedExtensions.Contains(ExtTransformFeedback.ExtensionName);
  131. PhysicalDeviceTransformFeedbackPropertiesEXT propertiesTransformFeedback = new PhysicalDeviceTransformFeedbackPropertiesEXT()
  132. {
  133. SType = StructureType.PhysicalDeviceTransformFeedbackPropertiesExt
  134. };
  135. if (supportsTransformFeedback)
  136. {
  137. propertiesTransformFeedback.PNext = properties2.PNext;
  138. properties2.PNext = &propertiesTransformFeedback;
  139. }
  140. PhysicalDevicePortabilitySubsetPropertiesKHR propertiesPortabilitySubset = new PhysicalDevicePortabilitySubsetPropertiesKHR()
  141. {
  142. SType = StructureType.PhysicalDevicePortabilitySubsetPropertiesKhr
  143. };
  144. PhysicalDeviceFeatures2 features2 = new PhysicalDeviceFeatures2()
  145. {
  146. SType = StructureType.PhysicalDeviceFeatures2
  147. };
  148. PhysicalDeviceRobustness2FeaturesEXT featuresRobustness2 = new PhysicalDeviceRobustness2FeaturesEXT()
  149. {
  150. SType = StructureType.PhysicalDeviceRobustness2FeaturesExt
  151. };
  152. PhysicalDeviceShaderFloat16Int8FeaturesKHR featuresShaderInt8 = new PhysicalDeviceShaderFloat16Int8FeaturesKHR()
  153. {
  154. SType = StructureType.PhysicalDeviceShaderFloat16Int8Features
  155. };
  156. PhysicalDeviceCustomBorderColorFeaturesEXT featuresCustomBorderColor = new PhysicalDeviceCustomBorderColorFeaturesEXT()
  157. {
  158. SType = StructureType.PhysicalDeviceCustomBorderColorFeaturesExt
  159. };
  160. PhysicalDevicePortabilitySubsetFeaturesKHR featuresPortabilitySubset = new PhysicalDevicePortabilitySubsetFeaturesKHR()
  161. {
  162. SType = StructureType.PhysicalDevicePortabilitySubsetFeaturesKhr
  163. };
  164. if (supportedExtensions.Contains("VK_EXT_robustness2"))
  165. {
  166. features2.PNext = &featuresRobustness2;
  167. }
  168. if (supportedExtensions.Contains("VK_KHR_shader_float16_int8"))
  169. {
  170. featuresShaderInt8.PNext = features2.PNext;
  171. features2.PNext = &featuresShaderInt8;
  172. }
  173. if (supportedExtensions.Contains("VK_EXT_custom_border_color"))
  174. {
  175. featuresCustomBorderColor.PNext = features2.PNext;
  176. features2.PNext = &featuresCustomBorderColor;
  177. }
  178. bool usePortability = supportedExtensions.Contains("VK_KHR_portability_subset");
  179. if (usePortability)
  180. {
  181. propertiesPortabilitySubset.PNext = properties2.PNext;
  182. properties2.PNext = &propertiesPortabilitySubset;
  183. featuresPortabilitySubset.PNext = features2.PNext;
  184. features2.PNext = &featuresPortabilitySubset;
  185. }
  186. Api.GetPhysicalDeviceProperties2(_physicalDevice, &properties2);
  187. Api.GetPhysicalDeviceFeatures2(_physicalDevice, &features2);
  188. var portabilityFlags = PortabilitySubsetFlags.None;
  189. uint vertexBufferAlignment = 1;
  190. if (usePortability)
  191. {
  192. vertexBufferAlignment = propertiesPortabilitySubset.MinVertexInputBindingStrideAlignment;
  193. portabilityFlags |= featuresPortabilitySubset.TriangleFans ? 0 : PortabilitySubsetFlags.NoTriangleFans;
  194. portabilityFlags |= featuresPortabilitySubset.PointPolygons ? 0 : PortabilitySubsetFlags.NoPointMode;
  195. portabilityFlags |= featuresPortabilitySubset.ImageView2DOn3DImage ? 0 : PortabilitySubsetFlags.No3DImageView;
  196. portabilityFlags |= featuresPortabilitySubset.SamplerMipLodBias ? 0 : PortabilitySubsetFlags.NoLodBias;
  197. }
  198. bool customBorderColorSupported = supportedExtensions.Contains("VK_EXT_custom_border_color") &&
  199. featuresCustomBorderColor.CustomBorderColors &&
  200. featuresCustomBorderColor.CustomBorderColorWithoutFormat;
  201. ref var properties = ref properties2.Properties;
  202. SampleCountFlags supportedSampleCounts =
  203. properties.Limits.FramebufferColorSampleCounts &
  204. properties.Limits.FramebufferDepthSampleCounts &
  205. properties.Limits.FramebufferStencilSampleCounts;
  206. Capabilities = new HardwareCapabilities(
  207. supportedExtensions.Contains("VK_EXT_index_type_uint8"),
  208. customBorderColorSupported,
  209. supportedExtensions.Contains(KhrDrawIndirectCount.ExtensionName),
  210. supportedExtensions.Contains("VK_EXT_fragment_shader_interlock"),
  211. supportedExtensions.Contains("VK_NV_geometry_shader_passthrough"),
  212. supportedExtensions.Contains("VK_EXT_subgroup_size_control"),
  213. featuresShaderInt8.ShaderInt8,
  214. supportedExtensions.Contains("VK_EXT_shader_stencil_export"),
  215. supportedExtensions.Contains(ExtConditionalRendering.ExtensionName),
  216. supportedExtensions.Contains(ExtExtendedDynamicState.ExtensionName),
  217. features2.Features.MultiViewport,
  218. featuresRobustness2.NullDescriptor || IsMoltenVk,
  219. supportedExtensions.Contains(KhrPushDescriptor.ExtensionName),
  220. supportsTransformFeedback,
  221. propertiesTransformFeedback.TransformFeedbackQueries,
  222. features2.Features.OcclusionQueryPrecise,
  223. supportedFeatures.PipelineStatisticsQuery,
  224. supportedFeatures.GeometryShader,
  225. propertiesSubgroupSizeControl.MinSubgroupSize,
  226. propertiesSubgroupSizeControl.MaxSubgroupSize,
  227. propertiesSubgroupSizeControl.RequiredSubgroupSizeStages,
  228. supportedSampleCounts,
  229. portabilityFlags,
  230. vertexBufferAlignment);
  231. MemoryAllocator = new MemoryAllocator(Api, _physicalDevice, _device, properties.Limits.MaxMemoryAllocationCount);
  232. CommandBufferPool = VulkanInitialization.CreateCommandBufferPool(Api, _device, Queue, QueueLock, queueFamilyIndex);
  233. DescriptorSetManager = new DescriptorSetManager(_device);
  234. PipelineLayoutCache = new PipelineLayoutCache();
  235. BackgroundResources = new BackgroundResources(this, _device);
  236. BufferManager = new BufferManager(this, _device);
  237. _syncManager = new SyncManager(this, _device);
  238. _pipeline = new PipelineFull(this, _device);
  239. _pipeline.Initialize();
  240. HelperShader = new HelperShader(this, _device);
  241. _counters = new Counters(this, _device, _pipeline);
  242. }
  243. private unsafe void SetupContext(GraphicsDebugLevel logLevel)
  244. {
  245. var api = Vk.GetApi();
  246. Api = api;
  247. _instance = VulkanInitialization.CreateInstance(api, logLevel, _getRequiredExtensions(), out ExtDebugUtils debugUtils, out _debugUtilsMessenger);
  248. DebugUtilsApi = debugUtils;
  249. if (api.TryGetInstanceExtension(_instance, out KhrSurface surfaceApi))
  250. {
  251. SurfaceApi = surfaceApi;
  252. }
  253. _surface = _getSurface(_instance, api);
  254. _physicalDevice = VulkanInitialization.FindSuitablePhysicalDevice(api, _instance, _surface, _preferredGpuId);
  255. var queueFamilyIndex = VulkanInitialization.FindSuitableQueueFamily(api, _physicalDevice, _surface, out uint maxQueueCount);
  256. var supportedExtensions = VulkanInitialization.GetSupportedExtensions(api, _physicalDevice);
  257. _device = VulkanInitialization.CreateDevice(api, _physicalDevice, queueFamilyIndex, supportedExtensions, maxQueueCount);
  258. if (api.TryGetDeviceExtension(_instance, _device, out KhrSwapchain swapchainApi))
  259. {
  260. SwapchainApi = swapchainApi;
  261. }
  262. api.GetDeviceQueue(_device, queueFamilyIndex, 0, out var queue);
  263. Queue = queue;
  264. QueueLock = new object();
  265. LoadFeatures(supportedExtensions, maxQueueCount, queueFamilyIndex);
  266. _window = new Window(this, _surface, _physicalDevice, _device);
  267. _initialized = true;
  268. }
  269. public BufferHandle CreateBuffer(int size)
  270. {
  271. return BufferManager.CreateWithHandle(this, size, false);
  272. }
  273. public IProgram CreateProgram(ShaderSource[] sources, ShaderInfo info)
  274. {
  275. bool isCompute = sources.Length == 1 && sources[0].Stage == ShaderStage.Compute;
  276. if (info.State.HasValue || isCompute)
  277. {
  278. return new ShaderCollection(this, _device, sources, info.State ?? default, info.FromCache);
  279. }
  280. else
  281. {
  282. return new ShaderCollection(this, _device, sources);
  283. }
  284. }
  285. internal ShaderCollection CreateProgramWithMinimalLayout(ShaderSource[] sources, SpecDescription[] specDescription = null)
  286. {
  287. return new ShaderCollection(this, _device, sources, specDescription: specDescription, isMinimal: true);
  288. }
  289. public ISampler CreateSampler(GAL.SamplerCreateInfo info)
  290. {
  291. return new SamplerHolder(this, _device, info);
  292. }
  293. public ITexture CreateTexture(TextureCreateInfo info, float scale)
  294. {
  295. if (info.Target == Target.TextureBuffer)
  296. {
  297. return new TextureBuffer(this, info, scale);
  298. }
  299. return CreateTextureView(info, scale);
  300. }
  301. internal TextureView CreateTextureView(TextureCreateInfo info, float scale)
  302. {
  303. // This should be disposed when all views are destroyed.
  304. var storage = CreateTextureStorage(info, scale);
  305. return storage.CreateView(info, 0, 0);
  306. }
  307. internal TextureStorage CreateTextureStorage(TextureCreateInfo info, float scale)
  308. {
  309. return new TextureStorage(this, _device, info, scale);
  310. }
  311. public void DeleteBuffer(BufferHandle buffer)
  312. {
  313. BufferManager.Delete(buffer);
  314. }
  315. internal void FlushAllCommands()
  316. {
  317. _pipeline?.FlushCommandsImpl();
  318. }
  319. internal void RegisterFlush()
  320. {
  321. _syncManager.RegisterFlush();
  322. }
  323. public ReadOnlySpan<byte> GetBufferData(BufferHandle buffer, int offset, int size)
  324. {
  325. return BufferManager.GetData(buffer, offset, size);
  326. }
  327. public unsafe Capabilities GetCapabilities()
  328. {
  329. FormatFeatureFlags compressedFormatFeatureFlags =
  330. FormatFeatureFlags.SampledImageBit |
  331. FormatFeatureFlags.SampledImageFilterLinearBit |
  332. FormatFeatureFlags.BlitSrcBit |
  333. FormatFeatureFlags.TransferSrcBit |
  334. FormatFeatureFlags.TransferDstBit;
  335. bool supportsBc123CompressionFormat = FormatCapabilities.OptimalFormatsSupport(compressedFormatFeatureFlags,
  336. GAL.Format.Bc1RgbaSrgb,
  337. GAL.Format.Bc1RgbaUnorm,
  338. GAL.Format.Bc2Srgb,
  339. GAL.Format.Bc2Unorm,
  340. GAL.Format.Bc3Srgb,
  341. GAL.Format.Bc3Unorm);
  342. bool supportsBc45CompressionFormat = FormatCapabilities.OptimalFormatsSupport(compressedFormatFeatureFlags,
  343. GAL.Format.Bc4Snorm,
  344. GAL.Format.Bc4Unorm,
  345. GAL.Format.Bc5Snorm,
  346. GAL.Format.Bc5Unorm);
  347. bool supportsBc67CompressionFormat = FormatCapabilities.OptimalFormatsSupport(compressedFormatFeatureFlags,
  348. GAL.Format.Bc6HSfloat,
  349. GAL.Format.Bc6HUfloat,
  350. GAL.Format.Bc7Srgb,
  351. GAL.Format.Bc7Unorm);
  352. bool supportsEtc2CompressionFormat = FormatCapabilities.OptimalFormatsSupport(compressedFormatFeatureFlags,
  353. GAL.Format.Etc2RgbaSrgb,
  354. GAL.Format.Etc2RgbaUnorm,
  355. GAL.Format.Etc2RgbPtaSrgb,
  356. GAL.Format.Etc2RgbPtaUnorm,
  357. GAL.Format.Etc2RgbSrgb,
  358. GAL.Format.Etc2RgbUnorm);
  359. bool supports5BitComponentFormat = FormatCapabilities.OptimalFormatsSupport(compressedFormatFeatureFlags,
  360. GAL.Format.R5G6B5Unorm,
  361. GAL.Format.R5G5B5A1Unorm,
  362. GAL.Format.R5G5B5X1Unorm,
  363. GAL.Format.B5G6R5Unorm,
  364. GAL.Format.B5G5R5A1Unorm,
  365. GAL.Format.A1B5G5R5Unorm);
  366. bool supportsR4G4B4A4Format = FormatCapabilities.OptimalFormatsSupport(compressedFormatFeatureFlags,
  367. GAL.Format.R4G4B4A4Unorm);
  368. bool supportsAstcFormats = FormatCapabilities.OptimalFormatsSupport(compressedFormatFeatureFlags,
  369. GAL.Format.Astc4x4Unorm,
  370. GAL.Format.Astc5x4Unorm,
  371. GAL.Format.Astc5x5Unorm,
  372. GAL.Format.Astc6x5Unorm,
  373. GAL.Format.Astc6x6Unorm,
  374. GAL.Format.Astc8x5Unorm,
  375. GAL.Format.Astc8x6Unorm,
  376. GAL.Format.Astc8x8Unorm,
  377. GAL.Format.Astc10x5Unorm,
  378. GAL.Format.Astc10x6Unorm,
  379. GAL.Format.Astc10x8Unorm,
  380. GAL.Format.Astc10x10Unorm,
  381. GAL.Format.Astc12x10Unorm,
  382. GAL.Format.Astc12x12Unorm,
  383. GAL.Format.Astc4x4Srgb,
  384. GAL.Format.Astc5x4Srgb,
  385. GAL.Format.Astc5x5Srgb,
  386. GAL.Format.Astc6x5Srgb,
  387. GAL.Format.Astc6x6Srgb,
  388. GAL.Format.Astc8x5Srgb,
  389. GAL.Format.Astc8x6Srgb,
  390. GAL.Format.Astc8x8Srgb,
  391. GAL.Format.Astc10x5Srgb,
  392. GAL.Format.Astc10x6Srgb,
  393. GAL.Format.Astc10x8Srgb,
  394. GAL.Format.Astc10x10Srgb,
  395. GAL.Format.Astc12x10Srgb,
  396. GAL.Format.Astc12x12Srgb);
  397. PhysicalDeviceVulkan12Features featuresVk12 = new PhysicalDeviceVulkan12Features()
  398. {
  399. SType = StructureType.PhysicalDeviceVulkan12Features
  400. };
  401. PhysicalDeviceFeatures2 features2 = new PhysicalDeviceFeatures2()
  402. {
  403. SType = StructureType.PhysicalDeviceFeatures2,
  404. PNext = &featuresVk12
  405. };
  406. Api.GetPhysicalDeviceFeatures2(_physicalDevice, &features2);
  407. Api.GetPhysicalDeviceProperties(_physicalDevice, out var properties);
  408. var limits = properties.Limits;
  409. return new Capabilities(
  410. api: TargetApi.Vulkan,
  411. GpuVendor,
  412. hasFrontFacingBug: IsIntelWindows,
  413. hasVectorIndexingBug: Vendor == Vendor.Qualcomm,
  414. needsFragmentOutputSpecialization: IsMoltenVk,
  415. reduceShaderPrecision: IsMoltenVk,
  416. supportsAstcCompression: features2.Features.TextureCompressionAstcLdr && supportsAstcFormats,
  417. supportsBc123Compression: supportsBc123CompressionFormat,
  418. supportsBc45Compression: supportsBc45CompressionFormat,
  419. supportsBc67Compression: supportsBc67CompressionFormat,
  420. supportsEtc2Compression: supportsEtc2CompressionFormat,
  421. supports3DTextureCompression: true,
  422. supportsBgraFormat: true,
  423. supportsR4G4Format: false,
  424. supportsR4G4B4A4Format: supportsR4G4B4A4Format,
  425. supportsSnormBufferTextureFormat: true,
  426. supports5BitComponentFormat: supports5BitComponentFormat,
  427. supportsFragmentShaderInterlock: Capabilities.SupportsFragmentShaderInterlock,
  428. supportsFragmentShaderOrderingIntel: false,
  429. supportsGeometryShaderPassthrough: Capabilities.SupportsGeometryShaderPassthrough,
  430. supportsImageLoadFormatted: features2.Features.ShaderStorageImageReadWithoutFormat,
  431. supportsLayerVertexTessellation: featuresVk12.ShaderOutputLayer,
  432. supportsMismatchingViewFormat: true,
  433. supportsCubemapView: !IsAmdGcn,
  434. supportsNonConstantTextureOffset: false,
  435. supportsShaderBallot: false,
  436. supportsTextureShadowLod: false,
  437. supportsViewportIndex: featuresVk12.ShaderOutputViewportIndex,
  438. supportsViewportSwizzle: false,
  439. supportsIndirectParameters: true,
  440. maximumUniformBuffersPerStage: Constants.MaxUniformBuffersPerStage,
  441. maximumStorageBuffersPerStage: Constants.MaxStorageBuffersPerStage,
  442. maximumTexturesPerStage: Constants.MaxTexturesPerStage,
  443. maximumImagesPerStage: Constants.MaxImagesPerStage,
  444. maximumComputeSharedMemorySize: (int)limits.MaxComputeSharedMemorySize,
  445. maximumSupportedAnisotropy: (int)limits.MaxSamplerAnisotropy,
  446. storageBufferOffsetAlignment: (int)limits.MinStorageBufferOffsetAlignment);
  447. }
  448. public HardwareInfo GetHardwareInfo()
  449. {
  450. return new HardwareInfo(GpuVendor, GpuRenderer);
  451. }
  452. public static DeviceInfo[] GetPhysicalDevices()
  453. {
  454. try
  455. {
  456. return VulkanInitialization.GetSuitablePhysicalDevices(Vk.GetApi());
  457. }
  458. catch (Exception)
  459. {
  460. // If we got an exception here, Vulkan is most likely not supported.
  461. return Array.Empty<DeviceInfo>();
  462. }
  463. }
  464. private static string ParseStandardVulkanVersion(uint version)
  465. {
  466. return $"{version >> 22}.{(version >> 12) & 0x3FF}.{version & 0xFFF}";
  467. }
  468. private static string ParseDriverVersion(ref PhysicalDeviceProperties properties)
  469. {
  470. uint driverVersionRaw = properties.DriverVersion;
  471. // NVIDIA differ from the standard here and uses a different format.
  472. if (properties.VendorID == 0x10DE)
  473. {
  474. return $"{(driverVersionRaw >> 22) & 0x3FF}.{(driverVersionRaw >> 14) & 0xFF}.{(driverVersionRaw >> 6) & 0xFF}.{driverVersionRaw & 0x3F}";
  475. }
  476. else
  477. {
  478. return ParseStandardVulkanVersion(driverVersionRaw);
  479. }
  480. }
  481. private unsafe void PrintGpuInformation()
  482. {
  483. Api.GetPhysicalDeviceProperties(_physicalDevice, out var properties);
  484. string vendorName = VendorUtils.GetNameFromId(properties.VendorID);
  485. Vendor = VendorUtils.FromId(properties.VendorID);
  486. IsAmdWindows = Vendor == Vendor.Amd && OperatingSystem.IsWindows();
  487. IsIntelWindows = Vendor == Vendor.Intel && OperatingSystem.IsWindows();
  488. IsTBDR = IsMoltenVk ||
  489. Vendor == Vendor.Qualcomm ||
  490. Vendor == Vendor.ARM ||
  491. Vendor == Vendor.Broadcom ||
  492. Vendor == Vendor.ImgTec;
  493. GpuVendor = vendorName;
  494. GpuRenderer = Marshal.PtrToStringAnsi((IntPtr)properties.DeviceName);
  495. GpuVersion = $"Vulkan v{ParseStandardVulkanVersion(properties.ApiVersion)}, Driver v{ParseDriverVersion(ref properties)}";
  496. IsAmdGcn = !IsMoltenVk && Vendor == Vendor.Amd && VendorUtils.AmdGcnRegex().IsMatch(GpuRenderer);
  497. Logger.Notice.Print(LogClass.Gpu, $"{GpuVendor} {GpuRenderer} ({GpuVersion})");
  498. }
  499. public GAL.PrimitiveTopology TopologyRemap(GAL.PrimitiveTopology topology)
  500. {
  501. return topology switch
  502. {
  503. GAL.PrimitiveTopology.Quads => GAL.PrimitiveTopology.Triangles,
  504. GAL.PrimitiveTopology.QuadStrip => GAL.PrimitiveTopology.TriangleStrip,
  505. GAL.PrimitiveTopology.TriangleFan => Capabilities.PortabilitySubset.HasFlag(PortabilitySubsetFlags.NoTriangleFans) ? GAL.PrimitiveTopology.Triangles : topology,
  506. _ => topology
  507. };
  508. }
  509. public bool TopologyUnsupported(GAL.PrimitiveTopology topology)
  510. {
  511. return topology switch
  512. {
  513. GAL.PrimitiveTopology.Quads => true,
  514. GAL.PrimitiveTopology.TriangleFan => Capabilities.PortabilitySubset.HasFlag(PortabilitySubsetFlags.NoTriangleFans),
  515. _ => false
  516. };
  517. }
  518. public void Initialize(GraphicsDebugLevel logLevel)
  519. {
  520. SetupContext(logLevel);
  521. PrintGpuInformation();
  522. }
  523. internal bool NeedsVertexBufferAlignment(int attrScalarAlignment, out int alignment)
  524. {
  525. if (Capabilities.VertexBufferAlignment > 1)
  526. {
  527. alignment = (int)Capabilities.VertexBufferAlignment;
  528. return true;
  529. }
  530. else if (Vendor != Vendor.Nvidia)
  531. {
  532. // Vulkan requires that vertex attributes are globally aligned by their component size,
  533. // so buffer strides that don't divide by the largest scalar element are invalid.
  534. // Guest applications do this, NVIDIA GPUs are OK with it, others are not.
  535. alignment = attrScalarAlignment;
  536. return true;
  537. }
  538. alignment = 1;
  539. return false;
  540. }
  541. public void PreFrame()
  542. {
  543. _syncManager.Cleanup();
  544. }
  545. public ICounterEvent ReportCounter(CounterType type, EventHandler<ulong> resultHandler, bool hostReserved)
  546. {
  547. return _counters.QueueReport(type, resultHandler, hostReserved);
  548. }
  549. public void ResetCounter(CounterType type)
  550. {
  551. _counters.QueueReset(type);
  552. }
  553. public void SetBufferData(BufferHandle buffer, int offset, ReadOnlySpan<byte> data)
  554. {
  555. BufferManager.SetData(buffer, offset, data, _pipeline.CurrentCommandBuffer, _pipeline.EndRenderPass);
  556. }
  557. public void UpdateCounters()
  558. {
  559. _counters.Update();
  560. }
  561. public void ResetCounterPool()
  562. {
  563. _counters.ResetCounterPool();
  564. }
  565. public void ResetFutureCounters(CommandBuffer cmd, int count)
  566. {
  567. _counters?.ResetFutureCounters(cmd, count);
  568. }
  569. public void BackgroundContextAction(Action action, bool alwaysBackground = false)
  570. {
  571. action();
  572. }
  573. public void CreateSync(ulong id, bool strict)
  574. {
  575. _syncManager.Create(id, strict);
  576. }
  577. public IProgram LoadProgramBinary(byte[] programBinary, bool isFragment, ShaderInfo info)
  578. {
  579. throw new NotImplementedException();
  580. }
  581. public void WaitSync(ulong id)
  582. {
  583. _syncManager.Wait(id);
  584. }
  585. public ulong GetCurrentSync()
  586. {
  587. return _syncManager.GetCurrent();
  588. }
  589. public void SetInterruptAction(Action<Action> interruptAction)
  590. {
  591. InterruptAction = interruptAction;
  592. }
  593. public void Screenshot()
  594. {
  595. _window.ScreenCaptureRequested = true;
  596. }
  597. public void OnScreenCaptured(ScreenCaptureImageInfo bitmap)
  598. {
  599. ScreenCaptured?.Invoke(this, bitmap);
  600. }
  601. public unsafe void Dispose()
  602. {
  603. if (!_initialized)
  604. {
  605. return;
  606. }
  607. CommandBufferPool.Dispose();
  608. BackgroundResources.Dispose();
  609. _counters.Dispose();
  610. _window.Dispose();
  611. HelperShader.Dispose();
  612. _pipeline.Dispose();
  613. BufferManager.Dispose();
  614. DescriptorSetManager.Dispose();
  615. PipelineLayoutCache.Dispose();
  616. MemoryAllocator.Dispose();
  617. if (_debugUtilsMessenger.Handle != 0)
  618. {
  619. DebugUtilsApi.DestroyDebugUtilsMessenger(_instance, _debugUtilsMessenger, null);
  620. }
  621. foreach (var shader in Shaders)
  622. {
  623. shader.Dispose();
  624. }
  625. foreach (var texture in Textures)
  626. {
  627. texture.Release();
  628. }
  629. foreach (var sampler in Samplers)
  630. {
  631. sampler.Dispose();
  632. }
  633. SurfaceApi.DestroySurface(_instance, _surface, null);
  634. Api.DestroyDevice(_device, null);
  635. // Last step destroy the instance
  636. Api.DestroyInstance(_instance, null);
  637. }
  638. }
  639. }