VulkanInitialization.cs 28 KB

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