VulkanInitialization.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. using Ryujinx.Common.Configuration;
  2. using Ryujinx.Common.Logging;
  3. using Ryujinx.Graphics.GAL;
  4. using Silk.NET.Vulkan;
  5. using Silk.NET.Vulkan.Extensions.EXT;
  6. using Silk.NET.Vulkan.Extensions.KHR;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Runtime.InteropServices;
  11. namespace Ryujinx.Graphics.Vulkan
  12. {
  13. public unsafe static class VulkanInitialization
  14. {
  15. private const uint InvalidIndex = uint.MaxValue;
  16. private static uint MinimalVulkanVersion = Vk.Version11.Value;
  17. private static uint MinimalInstanceVulkanVersion = Vk.Version12.Value;
  18. private static uint MaximumVulkanVersion = Vk.Version12.Value;
  19. private const string AppName = "Ryujinx.Graphics.Vulkan";
  20. private const int QueuesCount = 2;
  21. private static readonly string[] _desirableExtensions = new string[]
  22. {
  23. ExtConditionalRendering.ExtensionName,
  24. ExtExtendedDynamicState.ExtensionName,
  25. ExtTransformFeedback.ExtensionName,
  26. KhrDrawIndirectCount.ExtensionName,
  27. KhrPushDescriptor.ExtensionName,
  28. "VK_EXT_blend_operation_advanced",
  29. "VK_EXT_custom_border_color",
  30. "VK_EXT_descriptor_indexing", // Enabling this works around an issue with disposed buffer bindings on RADV.
  31. "VK_EXT_fragment_shader_interlock",
  32. "VK_EXT_index_type_uint8",
  33. "VK_EXT_primitive_topology_list_restart",
  34. "VK_EXT_robustness2",
  35. "VK_EXT_shader_stencil_export",
  36. "VK_KHR_shader_float16_int8",
  37. "VK_EXT_shader_subgroup_ballot",
  38. "VK_EXT_subgroup_size_control",
  39. "VK_NV_geometry_shader_passthrough",
  40. "VK_KHR_portability_subset", // By spec, we should enable this if present.
  41. };
  42. private static readonly string[] _requiredExtensions = new string[]
  43. {
  44. KhrSwapchain.ExtensionName
  45. };
  46. internal static VulkanInstance CreateInstance(Vk api, GraphicsDebugLevel logLevel, string[] requiredExtensions)
  47. {
  48. var enabledLayers = new List<string>();
  49. var instanceExtensions = VulkanInstance.GetInstanceExtensions(api);
  50. var instanceLayers = VulkanInstance.GetInstanceLayers(api);
  51. void AddAvailableLayer(string layerName)
  52. {
  53. if (instanceLayers.Contains(layerName))
  54. {
  55. enabledLayers.Add(layerName);
  56. }
  57. else
  58. {
  59. Logger.Warning?.Print(LogClass.Gpu, $"Missing layer {layerName}");
  60. }
  61. }
  62. if (logLevel != GraphicsDebugLevel.None)
  63. {
  64. AddAvailableLayer("VK_LAYER_KHRONOS_validation");
  65. }
  66. var enabledExtensions = requiredExtensions;
  67. if (instanceExtensions.Contains("VK_EXT_debug_utils"))
  68. {
  69. enabledExtensions = enabledExtensions.Append(ExtDebugUtils.ExtensionName).ToArray();
  70. }
  71. var appName = Marshal.StringToHGlobalAnsi(AppName);
  72. var applicationInfo = new ApplicationInfo
  73. {
  74. PApplicationName = (byte*)appName,
  75. ApplicationVersion = 1,
  76. PEngineName = (byte*)appName,
  77. EngineVersion = 1,
  78. ApiVersion = MaximumVulkanVersion
  79. };
  80. IntPtr* ppEnabledExtensions = stackalloc IntPtr[enabledExtensions.Length];
  81. IntPtr* ppEnabledLayers = stackalloc IntPtr[enabledLayers.Count];
  82. for (int i = 0; i < enabledExtensions.Length; i++)
  83. {
  84. ppEnabledExtensions[i] = Marshal.StringToHGlobalAnsi(enabledExtensions[i]);
  85. }
  86. for (int i = 0; i < enabledLayers.Count; i++)
  87. {
  88. ppEnabledLayers[i] = Marshal.StringToHGlobalAnsi(enabledLayers[i]);
  89. }
  90. var instanceCreateInfo = new InstanceCreateInfo
  91. {
  92. SType = StructureType.InstanceCreateInfo,
  93. PApplicationInfo = &applicationInfo,
  94. PpEnabledExtensionNames = (byte**)ppEnabledExtensions,
  95. PpEnabledLayerNames = (byte**)ppEnabledLayers,
  96. EnabledExtensionCount = (uint)enabledExtensions.Length,
  97. EnabledLayerCount = (uint)enabledLayers.Count
  98. };
  99. Result result = VulkanInstance.Create(api, ref instanceCreateInfo, out var instance);
  100. Marshal.FreeHGlobal(appName);
  101. for (int i = 0; i < enabledExtensions.Length; i++)
  102. {
  103. Marshal.FreeHGlobal(ppEnabledExtensions[i]);
  104. }
  105. for (int i = 0; i < enabledLayers.Count; i++)
  106. {
  107. Marshal.FreeHGlobal(ppEnabledLayers[i]);
  108. }
  109. result.ThrowOnError();
  110. return instance;
  111. }
  112. internal static VulkanPhysicalDevice FindSuitablePhysicalDevice(Vk api, VulkanInstance instance, SurfaceKHR surface, string preferredGpuId)
  113. {
  114. instance.EnumeratePhysicalDevices(out var physicalDevices).ThrowOnError();
  115. // First we try to pick the the user preferred GPU.
  116. for (int i = 0; i < physicalDevices.Length; i++)
  117. {
  118. if (IsPreferredAndSuitableDevice(api, physicalDevices[i], surface, preferredGpuId))
  119. {
  120. return physicalDevices[i];
  121. }
  122. }
  123. // If we fail to do that, just use the first compatible GPU.
  124. for (int i = 0; i < physicalDevices.Length; i++)
  125. {
  126. if (IsSuitableDevice(api, physicalDevices[i], surface))
  127. {
  128. return physicalDevices[i];
  129. }
  130. }
  131. throw new VulkanException("Initialization failed, none of the available GPUs meets the minimum requirements.");
  132. }
  133. internal static DeviceInfo[] GetSuitablePhysicalDevices(Vk api)
  134. {
  135. var appName = Marshal.StringToHGlobalAnsi(AppName);
  136. var applicationInfo = new ApplicationInfo
  137. {
  138. PApplicationName = (byte*)appName,
  139. ApplicationVersion = 1,
  140. PEngineName = (byte*)appName,
  141. EngineVersion = 1,
  142. ApiVersion = MaximumVulkanVersion
  143. };
  144. var instanceCreateInfo = new InstanceCreateInfo
  145. {
  146. SType = StructureType.InstanceCreateInfo,
  147. PApplicationInfo = &applicationInfo,
  148. PpEnabledExtensionNames = null,
  149. PpEnabledLayerNames = null,
  150. EnabledExtensionCount = 0,
  151. EnabledLayerCount = 0
  152. };
  153. Result result = VulkanInstance.Create(api, ref instanceCreateInfo, out var rawInstance);
  154. Marshal.FreeHGlobal(appName);
  155. result.ThrowOnError();
  156. using VulkanInstance instance = rawInstance;
  157. // We currently assume that the instance is compatible with Vulkan 1.2
  158. // TODO: Remove this once we relax our initialization codepaths.
  159. if (instance.InstanceVersion < MinimalInstanceVulkanVersion)
  160. {
  161. return Array.Empty<DeviceInfo>();
  162. }
  163. instance.EnumeratePhysicalDevices(out VulkanPhysicalDevice[] physicalDevices).ThrowOnError();
  164. List<DeviceInfo> deviceInfos = new List<DeviceInfo>();
  165. foreach (VulkanPhysicalDevice physicalDevice in physicalDevices)
  166. {
  167. if (physicalDevice.PhysicalDeviceProperties.ApiVersion < MinimalVulkanVersion)
  168. {
  169. continue;
  170. }
  171. deviceInfos.Add(physicalDevice.ToDeviceInfo());
  172. }
  173. return deviceInfos.ToArray();
  174. }
  175. private static bool IsPreferredAndSuitableDevice(Vk api, VulkanPhysicalDevice physicalDevice, SurfaceKHR surface, string preferredGpuId)
  176. {
  177. if (physicalDevice.Id != preferredGpuId)
  178. {
  179. return false;
  180. }
  181. return IsSuitableDevice(api, physicalDevice, surface);
  182. }
  183. private static bool IsSuitableDevice(Vk api, VulkanPhysicalDevice physicalDevice, SurfaceKHR surface)
  184. {
  185. int extensionMatches = 0;
  186. foreach (string requiredExtension in _requiredExtensions)
  187. {
  188. if (physicalDevice.IsDeviceExtensionPresent(requiredExtension))
  189. {
  190. extensionMatches++;
  191. }
  192. }
  193. return extensionMatches == _requiredExtensions.Length && FindSuitableQueueFamily(api, physicalDevice, surface, out _) != InvalidIndex;
  194. }
  195. internal static uint FindSuitableQueueFamily(Vk api, VulkanPhysicalDevice physicalDevice, SurfaceKHR surface, out uint queueCount)
  196. {
  197. const QueueFlags RequiredFlags = QueueFlags.GraphicsBit | QueueFlags.ComputeBit;
  198. var khrSurface = new KhrSurface(api.Context);
  199. for (uint index = 0; index < physicalDevice.QueueFamilyProperties.Length; index++)
  200. {
  201. ref QueueFamilyProperties property = ref physicalDevice.QueueFamilyProperties[index];
  202. khrSurface.GetPhysicalDeviceSurfaceSupport(physicalDevice.PhysicalDevice, index, surface, out var surfaceSupported).ThrowOnError();
  203. if (property.QueueFlags.HasFlag(RequiredFlags) && surfaceSupported)
  204. {
  205. queueCount = property.QueueCount;
  206. return index;
  207. }
  208. }
  209. queueCount = 0;
  210. return InvalidIndex;
  211. }
  212. internal static Device CreateDevice(Vk api, VulkanPhysicalDevice physicalDevice, uint queueFamilyIndex, uint queueCount)
  213. {
  214. if (queueCount > QueuesCount)
  215. {
  216. queueCount = QueuesCount;
  217. }
  218. float* queuePriorities = stackalloc float[(int)queueCount];
  219. for (int i = 0; i < queueCount; i++)
  220. {
  221. queuePriorities[i] = 1f;
  222. }
  223. var queueCreateInfo = new DeviceQueueCreateInfo()
  224. {
  225. SType = StructureType.DeviceQueueCreateInfo,
  226. QueueFamilyIndex = queueFamilyIndex,
  227. QueueCount = queueCount,
  228. PQueuePriorities = queuePriorities
  229. };
  230. bool useRobustBufferAccess = VendorUtils.FromId(physicalDevice.PhysicalDeviceProperties.VendorID) == Vendor.Nvidia;
  231. PhysicalDeviceFeatures2 features2 = new PhysicalDeviceFeatures2()
  232. {
  233. SType = StructureType.PhysicalDeviceFeatures2
  234. };
  235. PhysicalDeviceVulkan11Features supportedFeaturesVk11 = new PhysicalDeviceVulkan11Features()
  236. {
  237. SType = StructureType.PhysicalDeviceVulkan11Features,
  238. PNext = features2.PNext
  239. };
  240. features2.PNext = &supportedFeaturesVk11;
  241. PhysicalDeviceCustomBorderColorFeaturesEXT supportedFeaturesCustomBorderColor = new PhysicalDeviceCustomBorderColorFeaturesEXT()
  242. {
  243. SType = StructureType.PhysicalDeviceCustomBorderColorFeaturesExt,
  244. PNext = features2.PNext
  245. };
  246. if (physicalDevice.IsDeviceExtensionPresent("VK_EXT_custom_border_color"))
  247. {
  248. features2.PNext = &supportedFeaturesCustomBorderColor;
  249. }
  250. PhysicalDevicePrimitiveTopologyListRestartFeaturesEXT supportedFeaturesPrimitiveTopologyListRestart = new PhysicalDevicePrimitiveTopologyListRestartFeaturesEXT()
  251. {
  252. SType = StructureType.PhysicalDevicePrimitiveTopologyListRestartFeaturesExt,
  253. PNext = features2.PNext
  254. };
  255. if (physicalDevice.IsDeviceExtensionPresent("VK_EXT_primitive_topology_list_restart"))
  256. {
  257. features2.PNext = &supportedFeaturesPrimitiveTopologyListRestart;
  258. }
  259. PhysicalDeviceTransformFeedbackFeaturesEXT supportedFeaturesTransformFeedback = new PhysicalDeviceTransformFeedbackFeaturesEXT()
  260. {
  261. SType = StructureType.PhysicalDeviceTransformFeedbackFeaturesExt,
  262. PNext = features2.PNext
  263. };
  264. if (physicalDevice.IsDeviceExtensionPresent(ExtTransformFeedback.ExtensionName))
  265. {
  266. features2.PNext = &supportedFeaturesTransformFeedback;
  267. }
  268. PhysicalDeviceRobustness2FeaturesEXT supportedFeaturesRobustness2 = new PhysicalDeviceRobustness2FeaturesEXT()
  269. {
  270. SType = StructureType.PhysicalDeviceRobustness2FeaturesExt
  271. };
  272. if (physicalDevice.IsDeviceExtensionPresent("VK_EXT_robustness2"))
  273. {
  274. supportedFeaturesRobustness2.PNext = features2.PNext;
  275. features2.PNext = &supportedFeaturesRobustness2;
  276. }
  277. api.GetPhysicalDeviceFeatures2(physicalDevice.PhysicalDevice, &features2);
  278. var supportedFeatures = features2.Features;
  279. var features = new PhysicalDeviceFeatures()
  280. {
  281. DepthBiasClamp = true,
  282. DepthClamp = supportedFeatures.DepthClamp,
  283. DualSrcBlend = supportedFeatures.DualSrcBlend,
  284. FragmentStoresAndAtomics = true,
  285. GeometryShader = supportedFeatures.GeometryShader,
  286. ImageCubeArray = true,
  287. IndependentBlend = true,
  288. LogicOp = supportedFeatures.LogicOp,
  289. OcclusionQueryPrecise = supportedFeatures.OcclusionQueryPrecise,
  290. MultiViewport = supportedFeatures.MultiViewport,
  291. PipelineStatisticsQuery = supportedFeatures.PipelineStatisticsQuery,
  292. SamplerAnisotropy = true,
  293. ShaderClipDistance = true,
  294. ShaderFloat64 = supportedFeatures.ShaderFloat64,
  295. ShaderImageGatherExtended = supportedFeatures.ShaderImageGatherExtended,
  296. ShaderStorageImageMultisample = supportedFeatures.ShaderStorageImageMultisample,
  297. // ShaderStorageImageReadWithoutFormat = true,
  298. // ShaderStorageImageWriteWithoutFormat = true,
  299. TessellationShader = supportedFeatures.TessellationShader,
  300. VertexPipelineStoresAndAtomics = true,
  301. RobustBufferAccess = useRobustBufferAccess
  302. };
  303. void* pExtendedFeatures = null;
  304. PhysicalDeviceTransformFeedbackFeaturesEXT featuresTransformFeedback;
  305. if (physicalDevice.IsDeviceExtensionPresent(ExtTransformFeedback.ExtensionName))
  306. {
  307. featuresTransformFeedback = new PhysicalDeviceTransformFeedbackFeaturesEXT()
  308. {
  309. SType = StructureType.PhysicalDeviceTransformFeedbackFeaturesExt,
  310. PNext = pExtendedFeatures,
  311. TransformFeedback = supportedFeaturesTransformFeedback.TransformFeedback
  312. };
  313. pExtendedFeatures = &featuresTransformFeedback;
  314. }
  315. PhysicalDevicePrimitiveTopologyListRestartFeaturesEXT featuresPrimitiveTopologyListRestart;
  316. if (physicalDevice.IsDeviceExtensionPresent("VK_EXT_primitive_topology_list_restart"))
  317. {
  318. featuresPrimitiveTopologyListRestart = new PhysicalDevicePrimitiveTopologyListRestartFeaturesEXT()
  319. {
  320. SType = StructureType.PhysicalDevicePrimitiveTopologyListRestartFeaturesExt,
  321. PNext = pExtendedFeatures,
  322. PrimitiveTopologyListRestart = supportedFeaturesPrimitiveTopologyListRestart.PrimitiveTopologyListRestart,
  323. PrimitiveTopologyPatchListRestart = supportedFeaturesPrimitiveTopologyListRestart.PrimitiveTopologyPatchListRestart
  324. };
  325. pExtendedFeatures = &featuresPrimitiveTopologyListRestart;
  326. }
  327. PhysicalDeviceRobustness2FeaturesEXT featuresRobustness2;
  328. if (physicalDevice.IsDeviceExtensionPresent("VK_EXT_robustness2"))
  329. {
  330. featuresRobustness2 = new PhysicalDeviceRobustness2FeaturesEXT()
  331. {
  332. SType = StructureType.PhysicalDeviceRobustness2FeaturesExt,
  333. PNext = pExtendedFeatures,
  334. NullDescriptor = supportedFeaturesRobustness2.NullDescriptor
  335. };
  336. pExtendedFeatures = &featuresRobustness2;
  337. }
  338. var featuresExtendedDynamicState = new PhysicalDeviceExtendedDynamicStateFeaturesEXT()
  339. {
  340. SType = StructureType.PhysicalDeviceExtendedDynamicStateFeaturesExt,
  341. PNext = pExtendedFeatures,
  342. ExtendedDynamicState = physicalDevice.IsDeviceExtensionPresent(ExtExtendedDynamicState.ExtensionName)
  343. };
  344. pExtendedFeatures = &featuresExtendedDynamicState;
  345. var featuresVk11 = new PhysicalDeviceVulkan11Features()
  346. {
  347. SType = StructureType.PhysicalDeviceVulkan11Features,
  348. PNext = pExtendedFeatures,
  349. ShaderDrawParameters = supportedFeaturesVk11.ShaderDrawParameters
  350. };
  351. pExtendedFeatures = &featuresVk11;
  352. var featuresVk12 = new PhysicalDeviceVulkan12Features()
  353. {
  354. SType = StructureType.PhysicalDeviceVulkan12Features,
  355. PNext = pExtendedFeatures,
  356. DescriptorIndexing = physicalDevice.IsDeviceExtensionPresent("VK_EXT_descriptor_indexing"),
  357. DrawIndirectCount = physicalDevice.IsDeviceExtensionPresent(KhrDrawIndirectCount.ExtensionName),
  358. UniformBufferStandardLayout = physicalDevice.IsDeviceExtensionPresent("VK_KHR_uniform_buffer_standard_layout")
  359. };
  360. pExtendedFeatures = &featuresVk12;
  361. PhysicalDeviceIndexTypeUint8FeaturesEXT featuresIndexU8;
  362. if (physicalDevice.IsDeviceExtensionPresent("VK_EXT_index_type_uint8"))
  363. {
  364. featuresIndexU8 = new PhysicalDeviceIndexTypeUint8FeaturesEXT()
  365. {
  366. SType = StructureType.PhysicalDeviceIndexTypeUint8FeaturesExt,
  367. PNext = pExtendedFeatures,
  368. IndexTypeUint8 = true
  369. };
  370. pExtendedFeatures = &featuresIndexU8;
  371. }
  372. PhysicalDeviceFragmentShaderInterlockFeaturesEXT featuresFragmentShaderInterlock;
  373. if (physicalDevice.IsDeviceExtensionPresent("VK_EXT_fragment_shader_interlock"))
  374. {
  375. featuresFragmentShaderInterlock = new PhysicalDeviceFragmentShaderInterlockFeaturesEXT()
  376. {
  377. SType = StructureType.PhysicalDeviceFragmentShaderInterlockFeaturesExt,
  378. PNext = pExtendedFeatures,
  379. FragmentShaderPixelInterlock = true
  380. };
  381. pExtendedFeatures = &featuresFragmentShaderInterlock;
  382. }
  383. PhysicalDeviceSubgroupSizeControlFeaturesEXT featuresSubgroupSizeControl;
  384. if (physicalDevice.IsDeviceExtensionPresent("VK_EXT_subgroup_size_control"))
  385. {
  386. featuresSubgroupSizeControl = new PhysicalDeviceSubgroupSizeControlFeaturesEXT()
  387. {
  388. SType = StructureType.PhysicalDeviceSubgroupSizeControlFeaturesExt,
  389. PNext = pExtendedFeatures,
  390. SubgroupSizeControl = true
  391. };
  392. pExtendedFeatures = &featuresSubgroupSizeControl;
  393. }
  394. PhysicalDeviceCustomBorderColorFeaturesEXT featuresCustomBorderColor;
  395. if (physicalDevice.IsDeviceExtensionPresent("VK_EXT_custom_border_color") &&
  396. supportedFeaturesCustomBorderColor.CustomBorderColors &&
  397. supportedFeaturesCustomBorderColor.CustomBorderColorWithoutFormat)
  398. {
  399. featuresCustomBorderColor = new PhysicalDeviceCustomBorderColorFeaturesEXT()
  400. {
  401. SType = StructureType.PhysicalDeviceCustomBorderColorFeaturesExt,
  402. PNext = pExtendedFeatures,
  403. CustomBorderColors = true,
  404. CustomBorderColorWithoutFormat = true,
  405. };
  406. pExtendedFeatures = &featuresCustomBorderColor;
  407. }
  408. var enabledExtensions = _requiredExtensions.Union(_desirableExtensions.Intersect(physicalDevice.DeviceExtensions)).ToArray();
  409. IntPtr* ppEnabledExtensions = stackalloc IntPtr[enabledExtensions.Length];
  410. for (int i = 0; i < enabledExtensions.Length; i++)
  411. {
  412. ppEnabledExtensions[i] = Marshal.StringToHGlobalAnsi(enabledExtensions[i]);
  413. }
  414. var deviceCreateInfo = new DeviceCreateInfo()
  415. {
  416. SType = StructureType.DeviceCreateInfo,
  417. PNext = pExtendedFeatures,
  418. QueueCreateInfoCount = 1,
  419. PQueueCreateInfos = &queueCreateInfo,
  420. PpEnabledExtensionNames = (byte**)ppEnabledExtensions,
  421. EnabledExtensionCount = (uint)enabledExtensions.Length,
  422. PEnabledFeatures = &features
  423. };
  424. api.CreateDevice(physicalDevice.PhysicalDevice, in deviceCreateInfo, null, out var device).ThrowOnError();
  425. for (int i = 0; i < enabledExtensions.Length; i++)
  426. {
  427. Marshal.FreeHGlobal(ppEnabledExtensions[i]);
  428. }
  429. return device;
  430. }
  431. }
  432. }