VulkanInitialization.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  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. public static string[] DesirableExtensions { get; } = new string[]
  22. {
  23. ExtConditionalRendering.ExtensionName,
  24. ExtExtendedDynamicState.ExtensionName,
  25. ExtTransformFeedback.ExtensionName,
  26. KhrDrawIndirectCount.ExtensionName,
  27. KhrPushDescriptor.ExtensionName,
  28. "VK_EXT_custom_border_color",
  29. "VK_EXT_descriptor_indexing", // Enabling this works around an issue with disposed buffer bindings on RADV.
  30. "VK_EXT_fragment_shader_interlock",
  31. "VK_EXT_index_type_uint8",
  32. "VK_EXT_robustness2",
  33. "VK_EXT_shader_stencil_export",
  34. "VK_KHR_shader_float16_int8",
  35. "VK_EXT_shader_subgroup_ballot",
  36. "VK_EXT_subgroup_size_control",
  37. "VK_NV_geometry_shader_passthrough",
  38. "VK_KHR_portability_subset", // By spec, we should enable this if present.
  39. };
  40. public static string[] RequiredExtensions { get; } = new string[]
  41. {
  42. KhrSwapchain.ExtensionName
  43. };
  44. private static string[] _excludedMessages = new string[]
  45. {
  46. // NOTE: Done on purpose right now.
  47. "UNASSIGNED-CoreValidation-Shader-OutputNotConsumed",
  48. // TODO: Figure out if fixable
  49. "VUID-vkCmdDrawIndexed-None-04584",
  50. // TODO: Might be worth looking into making this happy to possibly optimize copies.
  51. "UNASSIGNED-CoreValidation-DrawState-InvalidImageLayout",
  52. // TODO: Fix this, it's causing too much noise right now.
  53. "VUID-VkSubpassDependency-srcSubpass-00867"
  54. };
  55. internal static Instance CreateInstance(Vk api, GraphicsDebugLevel logLevel, string[] requiredExtensions, out ExtDebugUtils debugUtils, out DebugUtilsMessengerEXT debugUtilsMessenger)
  56. {
  57. var enabledLayers = new List<string>();
  58. void AddAvailableLayer(string layerName)
  59. {
  60. uint layerPropertiesCount;
  61. api.EnumerateInstanceLayerProperties(&layerPropertiesCount, null).ThrowOnError();
  62. LayerProperties[] layerProperties = new LayerProperties[layerPropertiesCount];
  63. fixed (LayerProperties* pLayerProperties = layerProperties)
  64. {
  65. api.EnumerateInstanceLayerProperties(&layerPropertiesCount, layerProperties).ThrowOnError();
  66. for (int i = 0; i < layerPropertiesCount; i++)
  67. {
  68. string currentLayerName = Marshal.PtrToStringAnsi((IntPtr)pLayerProperties[i].LayerName);
  69. if (currentLayerName == layerName)
  70. {
  71. enabledLayers.Add(layerName);
  72. return;
  73. }
  74. }
  75. }
  76. Logger.Warning?.Print(LogClass.Gpu, $"Missing layer {layerName}");
  77. }
  78. if (logLevel != GraphicsDebugLevel.None)
  79. {
  80. AddAvailableLayer("VK_LAYER_KHRONOS_validation");
  81. }
  82. var enabledExtensions = requiredExtensions.Append(ExtDebugUtils.ExtensionName).ToArray();
  83. var appName = Marshal.StringToHGlobalAnsi(AppName);
  84. var applicationInfo = new ApplicationInfo
  85. {
  86. PApplicationName = (byte*)appName,
  87. ApplicationVersion = 1,
  88. PEngineName = (byte*)appName,
  89. EngineVersion = 1,
  90. ApiVersion = MaximumVulkanVersion
  91. };
  92. IntPtr* ppEnabledExtensions = stackalloc IntPtr[enabledExtensions.Length];
  93. IntPtr* ppEnabledLayers = stackalloc IntPtr[enabledLayers.Count];
  94. for (int i = 0; i < enabledExtensions.Length; i++)
  95. {
  96. ppEnabledExtensions[i] = Marshal.StringToHGlobalAnsi(enabledExtensions[i]);
  97. }
  98. for (int i = 0; i < enabledLayers.Count; i++)
  99. {
  100. ppEnabledLayers[i] = Marshal.StringToHGlobalAnsi(enabledLayers[i]);
  101. }
  102. var instanceCreateInfo = new InstanceCreateInfo
  103. {
  104. SType = StructureType.InstanceCreateInfo,
  105. PApplicationInfo = &applicationInfo,
  106. PpEnabledExtensionNames = (byte**)ppEnabledExtensions,
  107. PpEnabledLayerNames = (byte**)ppEnabledLayers,
  108. EnabledExtensionCount = (uint)enabledExtensions.Length,
  109. EnabledLayerCount = (uint)enabledLayers.Count
  110. };
  111. api.CreateInstance(in instanceCreateInfo, null, out var instance).ThrowOnError();
  112. Marshal.FreeHGlobal(appName);
  113. for (int i = 0; i < enabledExtensions.Length; i++)
  114. {
  115. Marshal.FreeHGlobal(ppEnabledExtensions[i]);
  116. }
  117. for (int i = 0; i < enabledLayers.Count; i++)
  118. {
  119. Marshal.FreeHGlobal(ppEnabledLayers[i]);
  120. }
  121. CreateDebugMessenger(api, logLevel, instance, out debugUtils, out debugUtilsMessenger);
  122. return instance;
  123. }
  124. private unsafe static uint DebugMessenger(
  125. DebugUtilsMessageSeverityFlagsEXT messageSeverity,
  126. DebugUtilsMessageTypeFlagsEXT messageTypes,
  127. DebugUtilsMessengerCallbackDataEXT* pCallbackData,
  128. void* pUserData)
  129. {
  130. var msg = Marshal.PtrToStringAnsi((IntPtr)pCallbackData->PMessage);
  131. foreach (string excludedMessagePart in _excludedMessages)
  132. {
  133. if (msg.Contains(excludedMessagePart))
  134. {
  135. return 0;
  136. }
  137. }
  138. if (messageSeverity.HasFlag(DebugUtilsMessageSeverityFlagsEXT.ErrorBitExt))
  139. {
  140. Logger.Error?.Print(LogClass.Gpu, msg);
  141. }
  142. else if (messageSeverity.HasFlag(DebugUtilsMessageSeverityFlagsEXT.WarningBitExt))
  143. {
  144. Logger.Warning?.Print(LogClass.Gpu, msg);
  145. }
  146. else if (messageSeverity.HasFlag(DebugUtilsMessageSeverityFlagsEXT.InfoBitExt))
  147. {
  148. Logger.Info?.Print(LogClass.Gpu, msg);
  149. }
  150. else // if (messageSeverity.HasFlag(DebugUtilsMessageSeverityFlagsEXT.VerboseBitExt))
  151. {
  152. Logger.Debug?.Print(LogClass.Gpu, msg);
  153. }
  154. return 0;
  155. }
  156. internal static PhysicalDevice FindSuitablePhysicalDevice(Vk api, Instance instance, SurfaceKHR surface, string preferredGpuId)
  157. {
  158. uint physicalDeviceCount;
  159. api.EnumeratePhysicalDevices(instance, &physicalDeviceCount, null).ThrowOnError();
  160. PhysicalDevice[] physicalDevices = new PhysicalDevice[physicalDeviceCount];
  161. fixed (PhysicalDevice* pPhysicalDevices = physicalDevices)
  162. {
  163. api.EnumeratePhysicalDevices(instance, &physicalDeviceCount, pPhysicalDevices).ThrowOnError();
  164. }
  165. // First we try to pick the the user preferred GPU.
  166. for (int i = 0; i < physicalDevices.Length; i++)
  167. {
  168. if (IsPreferredAndSuitableDevice(api, physicalDevices[i], surface, preferredGpuId))
  169. {
  170. return physicalDevices[i];
  171. }
  172. }
  173. // If we fail to do that, just use the first compatible GPU.
  174. for (int i = 0; i < physicalDevices.Length; i++)
  175. {
  176. if (IsSuitableDevice(api, physicalDevices[i], surface))
  177. {
  178. return physicalDevices[i];
  179. }
  180. }
  181. throw new VulkanException("Initialization failed, none of the available GPUs meets the minimum requirements.");
  182. }
  183. internal static DeviceInfo[] GetSuitablePhysicalDevices(Vk api)
  184. {
  185. var appName = Marshal.StringToHGlobalAnsi(AppName);
  186. var applicationInfo = new ApplicationInfo
  187. {
  188. PApplicationName = (byte*)appName,
  189. ApplicationVersion = 1,
  190. PEngineName = (byte*)appName,
  191. EngineVersion = 1,
  192. ApiVersion = MaximumVulkanVersion
  193. };
  194. var instanceCreateInfo = new InstanceCreateInfo
  195. {
  196. SType = StructureType.InstanceCreateInfo,
  197. PApplicationInfo = &applicationInfo,
  198. PpEnabledExtensionNames = null,
  199. PpEnabledLayerNames = null,
  200. EnabledExtensionCount = 0,
  201. EnabledLayerCount = 0
  202. };
  203. api.CreateInstance(in instanceCreateInfo, null, out var instance).ThrowOnError();
  204. // We ensure that vkEnumerateInstanceVersion is present (added in 1.1).
  205. // If the instance doesn't support it, no device is going to be 1.1 compatible.
  206. if (api.GetInstanceProcAddr(instance, "vkEnumerateInstanceVersion") == IntPtr.Zero)
  207. {
  208. api.DestroyInstance(instance, null);
  209. return Array.Empty<DeviceInfo>();
  210. }
  211. // We currently assume that the instance is compatible with Vulkan 1.2
  212. // TODO: Remove this once we relax our initialization codepaths.
  213. uint instanceApiVerison = 0;
  214. api.EnumerateInstanceVersion(ref instanceApiVerison).ThrowOnError();
  215. if (instanceApiVerison < MinimalInstanceVulkanVersion)
  216. {
  217. api.DestroyInstance(instance, null);
  218. return Array.Empty<DeviceInfo>();
  219. }
  220. Marshal.FreeHGlobal(appName);
  221. uint physicalDeviceCount;
  222. api.EnumeratePhysicalDevices(instance, &physicalDeviceCount, null).ThrowOnError();
  223. PhysicalDevice[] physicalDevices = new PhysicalDevice[physicalDeviceCount];
  224. fixed (PhysicalDevice* pPhysicalDevices = physicalDevices)
  225. {
  226. api.EnumeratePhysicalDevices(instance, &physicalDeviceCount, pPhysicalDevices).ThrowOnError();
  227. }
  228. DeviceInfo[] devices = new DeviceInfo[physicalDevices.Length];
  229. for (int i = 0; i < physicalDevices.Length; i++)
  230. {
  231. var physicalDevice = physicalDevices[i];
  232. api.GetPhysicalDeviceProperties(physicalDevice, out var properties);
  233. if (properties.ApiVersion < MinimalVulkanVersion)
  234. {
  235. continue;
  236. }
  237. devices[i] = new DeviceInfo(
  238. StringFromIdPair(properties.VendorID, properties.DeviceID),
  239. VendorUtils.GetNameFromId(properties.VendorID),
  240. Marshal.PtrToStringAnsi((IntPtr)properties.DeviceName),
  241. properties.DeviceType == PhysicalDeviceType.DiscreteGpu);
  242. }
  243. api.DestroyInstance(instance, null);
  244. return devices;
  245. }
  246. public static string StringFromIdPair(uint vendorId, uint deviceId)
  247. {
  248. return $"0x{vendorId:X}_0x{deviceId:X}";
  249. }
  250. private static bool IsPreferredAndSuitableDevice(Vk api, PhysicalDevice physicalDevice, SurfaceKHR surface, string preferredGpuId)
  251. {
  252. api.GetPhysicalDeviceProperties(physicalDevice, out var properties);
  253. if (StringFromIdPair(properties.VendorID, properties.DeviceID) != preferredGpuId)
  254. {
  255. return false;
  256. }
  257. return IsSuitableDevice(api, physicalDevice, surface);
  258. }
  259. private static bool IsSuitableDevice(Vk api, PhysicalDevice physicalDevice, SurfaceKHR surface)
  260. {
  261. int extensionMatches = 0;
  262. uint propertiesCount;
  263. api.EnumerateDeviceExtensionProperties(physicalDevice, (byte*)null, &propertiesCount, null).ThrowOnError();
  264. ExtensionProperties[] extensionProperties = new ExtensionProperties[propertiesCount];
  265. fixed (ExtensionProperties* pExtensionProperties = extensionProperties)
  266. {
  267. api.EnumerateDeviceExtensionProperties(physicalDevice, (byte*)null, &propertiesCount, pExtensionProperties).ThrowOnError();
  268. for (int i = 0; i < propertiesCount; i++)
  269. {
  270. string extensionName = Marshal.PtrToStringAnsi((IntPtr)pExtensionProperties[i].ExtensionName);
  271. if (RequiredExtensions.Contains(extensionName))
  272. {
  273. extensionMatches++;
  274. }
  275. }
  276. }
  277. return extensionMatches == RequiredExtensions.Length && FindSuitableQueueFamily(api, physicalDevice, surface, out _) != InvalidIndex;
  278. }
  279. internal static uint FindSuitableQueueFamily(Vk api, PhysicalDevice physicalDevice, SurfaceKHR surface, out uint queueCount)
  280. {
  281. const QueueFlags RequiredFlags = QueueFlags.GraphicsBit | QueueFlags.ComputeBit;
  282. var khrSurface = new KhrSurface(api.Context);
  283. uint propertiesCount;
  284. api.GetPhysicalDeviceQueueFamilyProperties(physicalDevice, &propertiesCount, null);
  285. QueueFamilyProperties[] properties = new QueueFamilyProperties[propertiesCount];
  286. fixed (QueueFamilyProperties* pProperties = properties)
  287. {
  288. api.GetPhysicalDeviceQueueFamilyProperties(physicalDevice, &propertiesCount, pProperties);
  289. }
  290. for (uint index = 0; index < propertiesCount; index++)
  291. {
  292. var queueFlags = properties[index].QueueFlags;
  293. khrSurface.GetPhysicalDeviceSurfaceSupport(physicalDevice, index, surface, out var surfaceSupported).ThrowOnError();
  294. if (queueFlags.HasFlag(RequiredFlags) && surfaceSupported)
  295. {
  296. queueCount = properties[index].QueueCount;
  297. return index;
  298. }
  299. }
  300. queueCount = 0;
  301. return InvalidIndex;
  302. }
  303. public static Device CreateDevice(Vk api, PhysicalDevice physicalDevice, uint queueFamilyIndex, string[] supportedExtensions, uint queueCount)
  304. {
  305. if (queueCount > QueuesCount)
  306. {
  307. queueCount = QueuesCount;
  308. }
  309. float* queuePriorities = stackalloc float[(int)queueCount];
  310. for (int i = 0; i < queueCount; i++)
  311. {
  312. queuePriorities[i] = 1f;
  313. }
  314. var queueCreateInfo = new DeviceQueueCreateInfo()
  315. {
  316. SType = StructureType.DeviceQueueCreateInfo,
  317. QueueFamilyIndex = queueFamilyIndex,
  318. QueueCount = queueCount,
  319. PQueuePriorities = queuePriorities
  320. };
  321. api.GetPhysicalDeviceProperties(physicalDevice, out var properties);
  322. bool useRobustBufferAccess = VendorUtils.FromId(properties.VendorID) == Vendor.Nvidia;
  323. PhysicalDeviceFeatures2 features2 = new PhysicalDeviceFeatures2()
  324. {
  325. SType = StructureType.PhysicalDeviceFeatures2
  326. };
  327. PhysicalDeviceVulkan11Features supportedFeaturesVk11 = new PhysicalDeviceVulkan11Features()
  328. {
  329. SType = StructureType.PhysicalDeviceVulkan11Features,
  330. PNext = features2.PNext
  331. };
  332. features2.PNext = &supportedFeaturesVk11;
  333. PhysicalDeviceCustomBorderColorFeaturesEXT supportedFeaturesCustomBorderColor = new PhysicalDeviceCustomBorderColorFeaturesEXT()
  334. {
  335. SType = StructureType.PhysicalDeviceCustomBorderColorFeaturesExt,
  336. PNext = features2.PNext
  337. };
  338. if (supportedExtensions.Contains("VK_EXT_custom_border_color"))
  339. {
  340. features2.PNext = &supportedFeaturesCustomBorderColor;
  341. }
  342. PhysicalDeviceTransformFeedbackFeaturesEXT supportedFeaturesTransformFeedback = new PhysicalDeviceTransformFeedbackFeaturesEXT()
  343. {
  344. SType = StructureType.PhysicalDeviceTransformFeedbackFeaturesExt,
  345. PNext = features2.PNext
  346. };
  347. if (supportedExtensions.Contains(ExtTransformFeedback.ExtensionName))
  348. {
  349. features2.PNext = &supportedFeaturesTransformFeedback;
  350. }
  351. PhysicalDeviceRobustness2FeaturesEXT supportedFeaturesRobustness2 = new PhysicalDeviceRobustness2FeaturesEXT()
  352. {
  353. SType = StructureType.PhysicalDeviceRobustness2FeaturesExt
  354. };
  355. if (supportedExtensions.Contains("VK_EXT_robustness2"))
  356. {
  357. supportedFeaturesRobustness2.PNext = features2.PNext;
  358. features2.PNext = &supportedFeaturesRobustness2;
  359. }
  360. api.GetPhysicalDeviceFeatures2(physicalDevice, &features2);
  361. var supportedFeatures = features2.Features;
  362. var features = new PhysicalDeviceFeatures()
  363. {
  364. DepthBiasClamp = true,
  365. DepthClamp = supportedFeatures.DepthClamp,
  366. DualSrcBlend = supportedFeatures.DualSrcBlend,
  367. FragmentStoresAndAtomics = true,
  368. GeometryShader = supportedFeatures.GeometryShader,
  369. ImageCubeArray = true,
  370. IndependentBlend = true,
  371. LogicOp = supportedFeatures.LogicOp,
  372. OcclusionQueryPrecise = supportedFeatures.OcclusionQueryPrecise,
  373. MultiViewport = supportedFeatures.MultiViewport,
  374. PipelineStatisticsQuery = supportedFeatures.PipelineStatisticsQuery,
  375. SamplerAnisotropy = true,
  376. ShaderClipDistance = true,
  377. ShaderFloat64 = supportedFeatures.ShaderFloat64,
  378. ShaderImageGatherExtended = supportedFeatures.ShaderImageGatherExtended,
  379. ShaderStorageImageMultisample = supportedFeatures.ShaderStorageImageMultisample,
  380. // ShaderStorageImageReadWithoutFormat = true,
  381. // ShaderStorageImageWriteWithoutFormat = true,
  382. TessellationShader = supportedFeatures.TessellationShader,
  383. VertexPipelineStoresAndAtomics = true,
  384. RobustBufferAccess = useRobustBufferAccess
  385. };
  386. void* pExtendedFeatures = null;
  387. PhysicalDeviceTransformFeedbackFeaturesEXT featuresTransformFeedback;
  388. if (supportedExtensions.Contains(ExtTransformFeedback.ExtensionName))
  389. {
  390. featuresTransformFeedback = new PhysicalDeviceTransformFeedbackFeaturesEXT()
  391. {
  392. SType = StructureType.PhysicalDeviceTransformFeedbackFeaturesExt,
  393. PNext = pExtendedFeatures,
  394. TransformFeedback = supportedFeaturesTransformFeedback.TransformFeedback
  395. };
  396. pExtendedFeatures = &featuresTransformFeedback;
  397. }
  398. PhysicalDeviceRobustness2FeaturesEXT featuresRobustness2;
  399. if (supportedExtensions.Contains("VK_EXT_robustness2"))
  400. {
  401. featuresRobustness2 = new PhysicalDeviceRobustness2FeaturesEXT()
  402. {
  403. SType = StructureType.PhysicalDeviceRobustness2FeaturesExt,
  404. PNext = pExtendedFeatures,
  405. NullDescriptor = supportedFeaturesRobustness2.NullDescriptor
  406. };
  407. pExtendedFeatures = &featuresRobustness2;
  408. }
  409. var featuresExtendedDynamicState = new PhysicalDeviceExtendedDynamicStateFeaturesEXT()
  410. {
  411. SType = StructureType.PhysicalDeviceExtendedDynamicStateFeaturesExt,
  412. PNext = pExtendedFeatures,
  413. ExtendedDynamicState = supportedExtensions.Contains(ExtExtendedDynamicState.ExtensionName)
  414. };
  415. pExtendedFeatures = &featuresExtendedDynamicState;
  416. var featuresVk11 = new PhysicalDeviceVulkan11Features()
  417. {
  418. SType = StructureType.PhysicalDeviceVulkan11Features,
  419. PNext = pExtendedFeatures,
  420. ShaderDrawParameters = supportedFeaturesVk11.ShaderDrawParameters
  421. };
  422. pExtendedFeatures = &featuresVk11;
  423. var featuresVk12 = new PhysicalDeviceVulkan12Features()
  424. {
  425. SType = StructureType.PhysicalDeviceVulkan12Features,
  426. PNext = pExtendedFeatures,
  427. DescriptorIndexing = supportedExtensions.Contains("VK_EXT_descriptor_indexing"),
  428. DrawIndirectCount = supportedExtensions.Contains(KhrDrawIndirectCount.ExtensionName),
  429. UniformBufferStandardLayout = supportedExtensions.Contains("VK_KHR_uniform_buffer_standard_layout")
  430. };
  431. pExtendedFeatures = &featuresVk12;
  432. PhysicalDeviceIndexTypeUint8FeaturesEXT featuresIndexU8;
  433. if (supportedExtensions.Contains("VK_EXT_index_type_uint8"))
  434. {
  435. featuresIndexU8 = new PhysicalDeviceIndexTypeUint8FeaturesEXT()
  436. {
  437. SType = StructureType.PhysicalDeviceIndexTypeUint8FeaturesExt,
  438. PNext = pExtendedFeatures,
  439. IndexTypeUint8 = true
  440. };
  441. pExtendedFeatures = &featuresIndexU8;
  442. }
  443. PhysicalDeviceFragmentShaderInterlockFeaturesEXT featuresFragmentShaderInterlock;
  444. if (supportedExtensions.Contains("VK_EXT_fragment_shader_interlock"))
  445. {
  446. featuresFragmentShaderInterlock = new PhysicalDeviceFragmentShaderInterlockFeaturesEXT()
  447. {
  448. SType = StructureType.PhysicalDeviceFragmentShaderInterlockFeaturesExt,
  449. PNext = pExtendedFeatures,
  450. FragmentShaderPixelInterlock = true
  451. };
  452. pExtendedFeatures = &featuresFragmentShaderInterlock;
  453. }
  454. PhysicalDeviceSubgroupSizeControlFeaturesEXT featuresSubgroupSizeControl;
  455. if (supportedExtensions.Contains("VK_EXT_subgroup_size_control"))
  456. {
  457. featuresSubgroupSizeControl = new PhysicalDeviceSubgroupSizeControlFeaturesEXT()
  458. {
  459. SType = StructureType.PhysicalDeviceSubgroupSizeControlFeaturesExt,
  460. PNext = pExtendedFeatures,
  461. SubgroupSizeControl = true
  462. };
  463. pExtendedFeatures = &featuresSubgroupSizeControl;
  464. }
  465. PhysicalDeviceCustomBorderColorFeaturesEXT featuresCustomBorderColor;
  466. if (supportedExtensions.Contains("VK_EXT_custom_border_color") &&
  467. supportedFeaturesCustomBorderColor.CustomBorderColors &&
  468. supportedFeaturesCustomBorderColor.CustomBorderColorWithoutFormat)
  469. {
  470. featuresCustomBorderColor = new PhysicalDeviceCustomBorderColorFeaturesEXT()
  471. {
  472. SType = StructureType.PhysicalDeviceCustomBorderColorFeaturesExt,
  473. PNext = pExtendedFeatures,
  474. CustomBorderColors = true,
  475. CustomBorderColorWithoutFormat = true,
  476. };
  477. pExtendedFeatures = &featuresCustomBorderColor;
  478. }
  479. var enabledExtensions = RequiredExtensions.Union(DesirableExtensions.Intersect(supportedExtensions)).ToArray();
  480. IntPtr* ppEnabledExtensions = stackalloc IntPtr[enabledExtensions.Length];
  481. for (int i = 0; i < enabledExtensions.Length; i++)
  482. {
  483. ppEnabledExtensions[i] = Marshal.StringToHGlobalAnsi(enabledExtensions[i]);
  484. }
  485. var deviceCreateInfo = new DeviceCreateInfo()
  486. {
  487. SType = StructureType.DeviceCreateInfo,
  488. PNext = pExtendedFeatures,
  489. QueueCreateInfoCount = 1,
  490. PQueueCreateInfos = &queueCreateInfo,
  491. PpEnabledExtensionNames = (byte**)ppEnabledExtensions,
  492. EnabledExtensionCount = (uint)enabledExtensions.Length,
  493. PEnabledFeatures = &features
  494. };
  495. api.CreateDevice(physicalDevice, in deviceCreateInfo, null, out var device).ThrowOnError();
  496. for (int i = 0; i < enabledExtensions.Length; i++)
  497. {
  498. Marshal.FreeHGlobal(ppEnabledExtensions[i]);
  499. }
  500. return device;
  501. }
  502. public static string[] GetSupportedExtensions(Vk api, PhysicalDevice physicalDevice)
  503. {
  504. uint propertiesCount;
  505. api.EnumerateDeviceExtensionProperties(physicalDevice, (byte*)null, &propertiesCount, null).ThrowOnError();
  506. ExtensionProperties[] extensionProperties = new ExtensionProperties[propertiesCount];
  507. fixed (ExtensionProperties* pExtensionProperties = extensionProperties)
  508. {
  509. api.EnumerateDeviceExtensionProperties(physicalDevice, (byte*)null, &propertiesCount, pExtensionProperties).ThrowOnError();
  510. }
  511. return extensionProperties.Select(x => Marshal.PtrToStringAnsi((IntPtr)x.ExtensionName)).ToArray();
  512. }
  513. internal static CommandBufferPool CreateCommandBufferPool(Vk api, Device device, Queue queue, object queueLock, uint queueFamilyIndex)
  514. {
  515. return new CommandBufferPool(api, device, queue, queueLock, queueFamilyIndex);
  516. }
  517. internal unsafe static void CreateDebugMessenger(
  518. Vk api,
  519. GraphicsDebugLevel logLevel,
  520. Instance instance,
  521. out ExtDebugUtils debugUtils,
  522. out DebugUtilsMessengerEXT debugUtilsMessenger)
  523. {
  524. debugUtils = default;
  525. if (logLevel != GraphicsDebugLevel.None)
  526. {
  527. if (!api.TryGetInstanceExtension(instance, out debugUtils))
  528. {
  529. debugUtilsMessenger = default;
  530. return;
  531. }
  532. var filterLogType = logLevel switch
  533. {
  534. GraphicsDebugLevel.Error => DebugUtilsMessageTypeFlagsEXT.ValidationBitExt,
  535. GraphicsDebugLevel.Slowdowns => DebugUtilsMessageTypeFlagsEXT.ValidationBitExt |
  536. DebugUtilsMessageTypeFlagsEXT.PerformanceBitExt,
  537. GraphicsDebugLevel.All => DebugUtilsMessageTypeFlagsEXT.GeneralBitExt |
  538. DebugUtilsMessageTypeFlagsEXT.ValidationBitExt |
  539. DebugUtilsMessageTypeFlagsEXT.PerformanceBitExt,
  540. _ => throw new ArgumentException($"Invalid log level \"{logLevel}\".")
  541. };
  542. var filterLogSeverity = logLevel switch
  543. {
  544. GraphicsDebugLevel.Error => DebugUtilsMessageSeverityFlagsEXT.ErrorBitExt,
  545. GraphicsDebugLevel.Slowdowns => DebugUtilsMessageSeverityFlagsEXT.ErrorBitExt |
  546. DebugUtilsMessageSeverityFlagsEXT.WarningBitExt,
  547. GraphicsDebugLevel.All => DebugUtilsMessageSeverityFlagsEXT.InfoBitExt |
  548. DebugUtilsMessageSeverityFlagsEXT.WarningBitExt |
  549. DebugUtilsMessageSeverityFlagsEXT.VerboseBitExt |
  550. DebugUtilsMessageSeverityFlagsEXT.ErrorBitExt,
  551. _ => throw new ArgumentException($"Invalid log level \"{logLevel}\".")
  552. };
  553. var debugUtilsMessengerCreateInfo = new DebugUtilsMessengerCreateInfoEXT()
  554. {
  555. SType = StructureType.DebugUtilsMessengerCreateInfoExt,
  556. MessageType = filterLogType,
  557. MessageSeverity = filterLogSeverity,
  558. PfnUserCallback = new PfnDebugUtilsMessengerCallbackEXT(DebugMessenger)
  559. };
  560. debugUtils.CreateDebugUtilsMessenger(instance, in debugUtilsMessengerCreateInfo, null, out debugUtilsMessenger).ThrowOnError();
  561. }
  562. else
  563. {
  564. debugUtilsMessenger = default;
  565. }
  566. }
  567. }
  568. }