VulkanInitialization.cs 27 KB

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