rendering_context_driver_vulkan.cpp 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  1. /**************************************************************************/
  2. /* rendering_context_driver_vulkan.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #ifdef VULKAN_ENABLED
  31. #include "rendering_context_driver_vulkan.h"
  32. #include "vk_enum_string_helper.h"
  33. #include "core/config/project_settings.h"
  34. #include "core/version.h"
  35. #include "rendering_device_driver_vulkan.h"
  36. #include "vulkan_hooks.h"
  37. #if defined(VK_TRACK_DRIVER_MEMORY)
  38. /*************************************************/
  39. // Driver memory tracking
  40. /*************************************************/
  41. // Total driver memory and allocation amount.
  42. SafeNumeric<size_t> driver_memory_total_memory;
  43. SafeNumeric<size_t> driver_memory_total_alloc_count;
  44. // Amount of driver memory for every object type.
  45. SafeNumeric<size_t> driver_memory_tracker[RenderingContextDriverVulkan::VK_TRACKED_OBJECT_TYPE_COUNT][RenderingContextDriverVulkan::VK_TRACKED_SYSTEM_ALLOCATION_SCOPE_COUNT];
  46. // Amount of allocations for every object type.
  47. SafeNumeric<uint32_t> driver_memory_allocation_count[RenderingContextDriverVulkan::VK_TRACKED_OBJECT_TYPE_COUNT][RenderingContextDriverVulkan::VK_TRACKED_SYSTEM_ALLOCATION_SCOPE_COUNT];
  48. #endif
  49. #if defined(VK_TRACK_DEVICE_MEMORY)
  50. /*************************************************/
  51. // Device memory report
  52. /*************************************************/
  53. // Total device memory and allocation amount.
  54. HashMap<uint64_t, size_t> memory_report_table;
  55. // Total memory and allocation amount.
  56. SafeNumeric<uint64_t> memory_report_total_memory;
  57. SafeNumeric<uint64_t> memory_report_total_alloc_count;
  58. // Amount of device memory for every object type.
  59. SafeNumeric<size_t> memory_report_mem_usage[RenderingContextDriverVulkan::VK_TRACKED_OBJECT_TYPE_COUNT];
  60. // Amount of device memory allocations for every object type.
  61. SafeNumeric<size_t> memory_report_allocation_count[RenderingContextDriverVulkan::VK_TRACKED_OBJECT_TYPE_COUNT];
  62. #endif
  63. const char *RenderingContextDriverVulkan::get_tracked_object_name(uint32_t p_type_index) const {
  64. #if defined(VK_TRACK_DRIVER_MEMORY) || defined(VK_TRACK_DEVICE_MEMORY)
  65. static constexpr const char *vkTrackedObjectTypeNames[] = { "UNKNOWN",
  66. "INSTANCE",
  67. "PHYSICAL_DEVICE",
  68. "DEVICE",
  69. "QUEUE",
  70. "SEMAPHORE",
  71. "COMMAND_BUFFER",
  72. "FENCE",
  73. "DEVICE_MEMORY",
  74. "BUFFER",
  75. "IMAGE",
  76. "EVENT",
  77. "QUERY_POOL",
  78. "BUFFER_VIEW",
  79. "IMAGE_VIEW",
  80. "SHADER_MODULE",
  81. "PIPELINE_CACHE",
  82. "PIPELINE_LAYOUT",
  83. "RENDER_PASS",
  84. "PIPELINE",
  85. "DESCRIPTOR_SET_LAYOUT",
  86. "SAMPLER",
  87. "DESCRIPTOR_POOL",
  88. "DESCRIPTOR_SET",
  89. "FRAMEBUFFER",
  90. "COMMAND_POOL",
  91. "DESCRIPTOR_UPDATE_TEMPLATE_KHR",
  92. "SURFACE_KHR",
  93. "SWAPCHAIN_KHR",
  94. "DEBUG_UTILS_MESSENGER_EXT",
  95. "DEBUG_REPORT_CALLBACK_EXT",
  96. "ACCELERATION_STRUCTURE",
  97. "VMA_BUFFER_OR_IMAGE" };
  98. return vkTrackedObjectTypeNames[p_type_index];
  99. #else
  100. return "VK_TRACK_DRIVER_* disabled at build time";
  101. #endif
  102. }
  103. #if defined(VK_TRACK_DRIVER_MEMORY) || defined(VK_TRACK_DEVICE_MEMORY)
  104. uint64_t RenderingContextDriverVulkan::get_tracked_object_type_count() const {
  105. return VK_TRACKED_OBJECT_TYPE_COUNT;
  106. }
  107. #endif
  108. #if defined(VK_TRACK_DRIVER_MEMORY) || defined(VK_TRACK_DEVICE_MEMORY)
  109. RenderingContextDriverVulkan::VkTrackedObjectType vk_object_to_tracked_object(VkObjectType p_type) {
  110. if (p_type > VK_OBJECT_TYPE_COMMAND_POOL && p_type != (VkObjectType)RenderingContextDriverVulkan::VK_TRACKED_OBJECT_TYPE_VMA) {
  111. switch (p_type) {
  112. case VK_OBJECT_TYPE_SURFACE_KHR:
  113. return RenderingContextDriverVulkan::VK_TRACKED_OBJECT_TYPE_SURFACE;
  114. case VK_OBJECT_TYPE_SWAPCHAIN_KHR:
  115. return RenderingContextDriverVulkan::VK_TRACKED_OBJECT_TYPE_SWAPCHAIN;
  116. case VK_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT:
  117. return RenderingContextDriverVulkan::VK_TRACKED_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT;
  118. case VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT:
  119. return RenderingContextDriverVulkan::VK_TRACKED_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT;
  120. default:
  121. _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Unknown VkObjectType enum value " + itos((uint32_t)p_type) + ".Please add it to VkTrackedObjectType, switch statement in "
  122. "vk_object_to_tracked_object and get_tracked_object_name.",
  123. (int)p_type);
  124. return (RenderingContextDriverVulkan::VkTrackedObjectType)VK_OBJECT_TYPE_UNKNOWN;
  125. }
  126. }
  127. return (RenderingContextDriverVulkan::VkTrackedObjectType)p_type;
  128. }
  129. #endif
  130. #if defined(VK_TRACK_DEVICE_MEMORY)
  131. uint64_t RenderingContextDriverVulkan::get_device_total_memory() const {
  132. return memory_report_total_memory.get();
  133. }
  134. uint64_t RenderingContextDriverVulkan::get_device_allocation_count() const {
  135. return memory_report_total_alloc_count.get();
  136. }
  137. uint64_t RenderingContextDriverVulkan::get_device_memory_by_object_type(uint32_t p_type) const {
  138. return memory_report_mem_usage[p_type].get();
  139. }
  140. uint64_t RenderingContextDriverVulkan::get_device_allocs_by_object_type(uint32_t p_type) const {
  141. return memory_report_allocation_count[p_type].get();
  142. }
  143. #endif
  144. #if defined(VK_TRACK_DRIVER_MEMORY)
  145. uint64_t RenderingContextDriverVulkan::get_driver_total_memory() const {
  146. return driver_memory_total_memory.get();
  147. }
  148. uint64_t RenderingContextDriverVulkan::get_driver_allocation_count() const {
  149. return driver_memory_total_alloc_count.get();
  150. }
  151. uint64_t RenderingContextDriverVulkan::get_driver_memory_by_object_type(uint32_t p_type) const {
  152. uint64_t ret = 0;
  153. for (uint32_t i = 0; i < VK_TRACKED_SYSTEM_ALLOCATION_SCOPE_COUNT; i++) {
  154. ret += driver_memory_tracker[p_type][i].get();
  155. }
  156. return ret;
  157. }
  158. uint64_t RenderingContextDriverVulkan::get_driver_allocs_by_object_type(uint32_t p_type) const {
  159. uint64_t ret = 0;
  160. for (uint32_t i = 0; i < VK_TRACKED_SYSTEM_ALLOCATION_SCOPE_COUNT; i++) {
  161. ret += driver_memory_allocation_count[p_type][i].get();
  162. }
  163. return ret;
  164. }
  165. #endif
  166. #if defined(VK_TRACK_DEVICE_MEMORY)
  167. void RenderingContextDriverVulkan::memory_report_callback(const VkDeviceMemoryReportCallbackDataEXT *p_callback_data, void *p_user_data) {
  168. if (!p_callback_data) {
  169. return;
  170. }
  171. const RenderingContextDriverVulkan::VkTrackedObjectType obj_type = vk_object_to_tracked_object(p_callback_data->objectType);
  172. uint64_t obj_id = p_callback_data->memoryObjectId;
  173. if (p_callback_data->type == VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_ALLOCATE_EXT) {
  174. // Realloc, update size
  175. if (memory_report_table.has(obj_id)) {
  176. memory_report_total_memory.sub(memory_report_table[obj_id]);
  177. memory_report_mem_usage[obj_type].sub(memory_report_table[obj_id]);
  178. memory_report_total_memory.add(p_callback_data->size);
  179. memory_report_mem_usage[obj_type].add(p_callback_data->size);
  180. memory_report_table[p_callback_data->memoryObjectId] = p_callback_data->size;
  181. } else {
  182. memory_report_table[obj_id] = p_callback_data->size;
  183. memory_report_total_alloc_count.increment();
  184. memory_report_allocation_count[obj_type].increment();
  185. memory_report_mem_usage[obj_type].add(p_callback_data->size);
  186. memory_report_total_memory.add(p_callback_data->size);
  187. }
  188. } else if (p_callback_data->type == VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_FREE_EXT) {
  189. if (memory_report_table.has(obj_id)) {
  190. memory_report_total_alloc_count.decrement();
  191. memory_report_allocation_count[obj_type].decrement();
  192. memory_report_mem_usage[obj_type].sub(p_callback_data->size);
  193. memory_report_total_memory.sub(p_callback_data->size);
  194. memory_report_table.remove(memory_report_table.find(obj_id));
  195. }
  196. }
  197. }
  198. #endif
  199. VkAllocationCallbacks *RenderingContextDriverVulkan::get_allocation_callbacks(VkObjectType p_type) {
  200. #if !defined(VK_TRACK_DRIVER_MEMORY)
  201. return nullptr;
  202. #else
  203. #ifdef _MSC_VER
  204. #define LAMBDA_VK_CALL_CONV
  205. #else
  206. #define LAMBDA_VK_CALL_CONV VKAPI_PTR
  207. #endif
  208. struct TrackedMemHeader {
  209. size_t size;
  210. VkSystemAllocationScope allocation_scope;
  211. VkTrackedObjectType type;
  212. };
  213. VkAllocationCallbacks tracking_callbacks = {
  214. // Allocation function
  215. nullptr,
  216. [](
  217. void *p_user_data,
  218. size_t size,
  219. size_t alignment,
  220. VkSystemAllocationScope allocation_scope) LAMBDA_VK_CALL_CONV -> void * {
  221. static constexpr size_t tracking_data_size = 32;
  222. VkTrackedObjectType type = static_cast<VkTrackedObjectType>(*reinterpret_cast<VkTrackedObjectType *>(p_user_data));
  223. driver_memory_total_memory.add(size);
  224. driver_memory_total_alloc_count.increment();
  225. driver_memory_tracker[type][allocation_scope].add(size);
  226. driver_memory_allocation_count[type][allocation_scope].increment();
  227. alignment = MAX(alignment, tracking_data_size);
  228. uint8_t *ret = reinterpret_cast<uint8_t *>(Memory::alloc_aligned_static(size + alignment, alignment));
  229. if (ret == nullptr) {
  230. return nullptr;
  231. }
  232. // Track allocation
  233. TrackedMemHeader *header = reinterpret_cast<TrackedMemHeader *>(ret);
  234. header->size = size;
  235. header->allocation_scope = allocation_scope;
  236. header->type = type;
  237. *reinterpret_cast<size_t *>(ret + alignment - sizeof(size_t)) = alignment;
  238. // Return first available chunk of memory
  239. return ret + alignment;
  240. },
  241. // Reallocation function
  242. [](
  243. void *p_user_data,
  244. void *p_original,
  245. size_t size,
  246. size_t alignment,
  247. VkSystemAllocationScope allocation_scope) LAMBDA_VK_CALL_CONV -> void * {
  248. if (p_original == nullptr) {
  249. VkObjectType type = static_cast<VkObjectType>(*reinterpret_cast<uint32_t *>(p_user_data));
  250. return get_allocation_callbacks(type)->pfnAllocation(p_user_data, size, alignment, allocation_scope);
  251. }
  252. uint8_t *mem = reinterpret_cast<uint8_t *>(p_original);
  253. // Retrieve alignment
  254. alignment = *reinterpret_cast<size_t *>(mem - sizeof(size_t));
  255. // Retrieve allocation data
  256. TrackedMemHeader *header = reinterpret_cast<TrackedMemHeader *>(mem - alignment);
  257. // Update allocation size
  258. driver_memory_total_memory.sub(header->size);
  259. driver_memory_total_memory.add(size);
  260. driver_memory_tracker[header->type][header->allocation_scope].sub(header->size);
  261. driver_memory_tracker[header->type][header->allocation_scope].add(size);
  262. uint8_t *ret = reinterpret_cast<uint8_t *>(Memory::realloc_aligned_static(header, size + alignment, header->size + alignment, alignment));
  263. if (ret == nullptr) {
  264. return nullptr;
  265. }
  266. // Update tracker
  267. header = reinterpret_cast<TrackedMemHeader *>(ret);
  268. header->size = size;
  269. return ret + alignment;
  270. },
  271. // Free function
  272. [](
  273. void *p_user_data,
  274. void *p_memory) LAMBDA_VK_CALL_CONV {
  275. if (!p_memory) {
  276. return;
  277. }
  278. uint8_t *mem = reinterpret_cast<uint8_t *>(p_memory);
  279. size_t alignment = *reinterpret_cast<size_t *>(mem - sizeof(size_t));
  280. TrackedMemHeader *header = reinterpret_cast<TrackedMemHeader *>(mem - alignment);
  281. driver_memory_total_alloc_count.decrement();
  282. driver_memory_total_memory.sub(header->size);
  283. driver_memory_tracker[header->type][header->allocation_scope].sub(header->size);
  284. driver_memory_allocation_count[header->type][header->allocation_scope].decrement();
  285. Memory::free_aligned_static(header);
  286. },
  287. // Internal allocation / deallocation. We don't track them as they cannot really be controlled or optimized by the programmer.
  288. [](
  289. void *p_user_data,
  290. size_t size,
  291. VkInternalAllocationType allocation_type,
  292. VkSystemAllocationScope allocation_scope) LAMBDA_VK_CALL_CONV {
  293. },
  294. [](
  295. void *p_user_data,
  296. size_t size,
  297. VkInternalAllocationType allocation_type,
  298. VkSystemAllocationScope allocation_scope) LAMBDA_VK_CALL_CONV {
  299. },
  300. };
  301. // Create a callback per object type
  302. static VkAllocationCallbacks object_callbacks[VK_TRACKED_OBJECT_TYPE_COUNT] = {};
  303. static uint32_t object_user_data[VK_TRACKED_OBJECT_TYPE_COUNT] = {};
  304. // Only build the first time
  305. if (!object_callbacks[0].pfnAllocation) {
  306. for (uint32_t c = 0; c < VK_TRACKED_OBJECT_TYPE_COUNT; ++c) {
  307. object_callbacks[c] = tracking_callbacks;
  308. object_user_data[c] = c;
  309. object_callbacks[c].pUserData = &object_user_data[c];
  310. for (uint32_t i = 0; i < VK_TRACKED_SYSTEM_ALLOCATION_SCOPE_COUNT; i++) {
  311. driver_memory_tracker[c][i].set(0);
  312. driver_memory_allocation_count[c][i].set(0);
  313. }
  314. }
  315. }
  316. uint32_t type_index = vk_object_to_tracked_object(p_type);
  317. return &object_callbacks[type_index];
  318. #endif
  319. }
  320. RenderingContextDriverVulkan::RenderingContextDriverVulkan() {
  321. // Empty constructor.
  322. }
  323. RenderingContextDriverVulkan::~RenderingContextDriverVulkan() {
  324. if (debug_messenger != VK_NULL_HANDLE && functions.DestroyDebugUtilsMessengerEXT != nullptr) {
  325. functions.DestroyDebugUtilsMessengerEXT(instance, debug_messenger, get_allocation_callbacks(VK_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT));
  326. }
  327. if (debug_report != VK_NULL_HANDLE && functions.DestroyDebugReportCallbackEXT != nullptr) {
  328. functions.DestroyDebugReportCallbackEXT(instance, debug_report, get_allocation_callbacks(VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT));
  329. }
  330. if (instance != VK_NULL_HANDLE) {
  331. vkDestroyInstance(instance, get_allocation_callbacks(VK_OBJECT_TYPE_INSTANCE));
  332. }
  333. }
  334. Error RenderingContextDriverVulkan::_initialize_vulkan_version() {
  335. // https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VkApplicationInfo.html#_description
  336. // For Vulkan 1.0 vkEnumerateInstanceVersion is not available, including not in the loader we compile against on Android.
  337. typedef VkResult(VKAPI_PTR * _vkEnumerateInstanceVersion)(uint32_t *);
  338. _vkEnumerateInstanceVersion func = (_vkEnumerateInstanceVersion)vkGetInstanceProcAddr(nullptr, "vkEnumerateInstanceVersion");
  339. if (func != nullptr) {
  340. uint32_t api_version;
  341. VkResult res = func(&api_version);
  342. if (res == VK_SUCCESS) {
  343. instance_api_version = api_version;
  344. } else {
  345. // According to the documentation this shouldn't fail with anything except a memory allocation error
  346. // in which case we're in deep trouble anyway.
  347. ERR_FAIL_V(ERR_CANT_CREATE);
  348. }
  349. } else {
  350. print_line("vkEnumerateInstanceVersion not available, assuming Vulkan 1.0.");
  351. instance_api_version = VK_API_VERSION_1_0;
  352. }
  353. return OK;
  354. }
  355. void RenderingContextDriverVulkan::_register_requested_instance_extension(const CharString &p_extension_name, bool p_required) {
  356. ERR_FAIL_COND(requested_instance_extensions.has(p_extension_name));
  357. requested_instance_extensions[p_extension_name] = p_required;
  358. }
  359. Error RenderingContextDriverVulkan::_initialize_instance_extensions() {
  360. enabled_instance_extension_names.clear();
  361. // The surface extension and the platform-specific surface extension are core requirements.
  362. _register_requested_instance_extension(VK_KHR_SURFACE_EXTENSION_NAME, true);
  363. if (_get_platform_surface_extension()) {
  364. _register_requested_instance_extension(_get_platform_surface_extension(), true);
  365. }
  366. if (_use_validation_layers()) {
  367. _register_requested_instance_extension(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, false);
  368. }
  369. // This extension allows us to use the properties2 features to query additional device capabilities.
  370. _register_requested_instance_extension(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, false);
  371. #if defined(USE_VOLK) && (defined(MACOS_ENABLED) || defined(IOS_ENABLED))
  372. _register_requested_instance_extension(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME, true);
  373. #endif
  374. // Only enable debug utils in verbose mode or DEV_ENABLED.
  375. // End users would get spammed with messages of varying verbosity due to the
  376. // mess that thirdparty layers/extensions and drivers seem to leave in their
  377. // wake, making the Windows registry a bottomless pit of broken layer JSON.
  378. #ifdef DEV_ENABLED
  379. bool want_debug_utils = true;
  380. #else
  381. bool want_debug_utils = OS::get_singleton()->is_stdout_verbose();
  382. #endif
  383. if (want_debug_utils) {
  384. _register_requested_instance_extension(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, false);
  385. }
  386. // Load instance extensions that are available.
  387. uint32_t instance_extension_count = 0;
  388. VkResult err = vkEnumerateInstanceExtensionProperties(nullptr, &instance_extension_count, nullptr);
  389. ERR_FAIL_COND_V(err != VK_SUCCESS && err != VK_INCOMPLETE, ERR_CANT_CREATE);
  390. ERR_FAIL_COND_V_MSG(instance_extension_count == 0, ERR_CANT_CREATE, "No instance extensions were found.");
  391. TightLocalVector<VkExtensionProperties> instance_extensions;
  392. instance_extensions.resize(instance_extension_count);
  393. err = vkEnumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.ptr());
  394. if (err != VK_SUCCESS && err != VK_INCOMPLETE) {
  395. ERR_FAIL_V(ERR_CANT_CREATE);
  396. }
  397. #ifdef DEV_ENABLED
  398. for (uint32_t i = 0; i < instance_extension_count; i++) {
  399. print_verbose(String("VULKAN: Found instance extension ") + String::utf8(instance_extensions[i].extensionName) + String("."));
  400. }
  401. #endif
  402. // Enable all extensions that are supported and requested.
  403. for (uint32_t i = 0; i < instance_extension_count; i++) {
  404. CharString extension_name(instance_extensions[i].extensionName);
  405. if (requested_instance_extensions.has(extension_name)) {
  406. enabled_instance_extension_names.insert(extension_name);
  407. }
  408. }
  409. // Now check our requested extensions.
  410. for (KeyValue<CharString, bool> &requested_extension : requested_instance_extensions) {
  411. if (!enabled_instance_extension_names.has(requested_extension.key)) {
  412. if (requested_extension.value) {
  413. ERR_FAIL_V_MSG(ERR_BUG, String("Required extension ") + String::utf8(requested_extension.key) + String(" not found."));
  414. } else {
  415. print_verbose(String("Optional extension ") + String::utf8(requested_extension.key) + String(" not found."));
  416. }
  417. }
  418. }
  419. return OK;
  420. }
  421. Error RenderingContextDriverVulkan::_find_validation_layers(TightLocalVector<const char *> &r_layer_names) const {
  422. r_layer_names.clear();
  423. uint32_t instance_layer_count = 0;
  424. VkResult err = vkEnumerateInstanceLayerProperties(&instance_layer_count, nullptr);
  425. ERR_FAIL_COND_V(err != VK_SUCCESS, ERR_CANT_CREATE);
  426. if (instance_layer_count > 0) {
  427. TightLocalVector<VkLayerProperties> layer_properties;
  428. layer_properties.resize(instance_layer_count);
  429. err = vkEnumerateInstanceLayerProperties(&instance_layer_count, layer_properties.ptr());
  430. ERR_FAIL_COND_V(err != VK_SUCCESS, ERR_CANT_CREATE);
  431. // Preferred set of validation layers.
  432. const std::initializer_list<const char *> preferred = { "VK_LAYER_KHRONOS_validation" };
  433. // Alternative (deprecated, removed in SDK 1.1.126.0) set of validation layers.
  434. const std::initializer_list<const char *> lunarg = { "VK_LAYER_LUNARG_standard_validation" };
  435. // Alternative (deprecated, removed in SDK 1.1.121.1) set of validation layers.
  436. const std::initializer_list<const char *> google = { "VK_LAYER_GOOGLE_threading", "VK_LAYER_LUNARG_parameter_validation", "VK_LAYER_LUNARG_object_tracker", "VK_LAYER_LUNARG_core_validation", "VK_LAYER_GOOGLE_unique_objects" };
  437. // Verify all the layers of the list are present.
  438. for (const std::initializer_list<const char *> &list : { preferred, lunarg, google }) {
  439. bool layers_found = false;
  440. for (const char *layer_name : list) {
  441. layers_found = false;
  442. for (const VkLayerProperties &properties : layer_properties) {
  443. if (!strcmp(properties.layerName, layer_name)) {
  444. layers_found = true;
  445. break;
  446. }
  447. }
  448. if (!layers_found) {
  449. break;
  450. }
  451. }
  452. if (layers_found) {
  453. r_layer_names.reserve(list.size());
  454. for (const char *layer_name : list) {
  455. r_layer_names.push_back(layer_name);
  456. }
  457. break;
  458. }
  459. }
  460. }
  461. return OK;
  462. }
  463. VKAPI_ATTR VkBool32 VKAPI_CALL RenderingContextDriverVulkan::_debug_messenger_callback(VkDebugUtilsMessageSeverityFlagBitsEXT p_message_severity, VkDebugUtilsMessageTypeFlagsEXT p_message_type, const VkDebugUtilsMessengerCallbackDataEXT *p_callback_data, void *p_user_data) {
  464. // This error needs to be ignored because the AMD allocator will mix up memory types on IGP processors.
  465. if (strstr(p_callback_data->pMessage, "Mapping an image with layout") != nullptr && strstr(p_callback_data->pMessage, "can result in undefined behavior if this memory is used by the device") != nullptr) {
  466. return VK_FALSE;
  467. }
  468. // This needs to be ignored because Validator is wrong here.
  469. if (strstr(p_callback_data->pMessage, "Invalid SPIR-V binary version 1.3") != nullptr) {
  470. return VK_FALSE;
  471. }
  472. // This needs to be ignored because Validator is wrong here.
  473. if (strstr(p_callback_data->pMessage, "Shader requires flag") != nullptr) {
  474. return VK_FALSE;
  475. }
  476. // This needs to be ignored because Validator is wrong here.
  477. if (strstr(p_callback_data->pMessage, "SPIR-V module not valid: Pointer operand") != nullptr && strstr(p_callback_data->pMessage, "must be a memory object") != nullptr) {
  478. return VK_FALSE;
  479. }
  480. if (p_callback_data->pMessageIdName && strstr(p_callback_data->pMessageIdName, "UNASSIGNED-CoreValidation-DrawState-ClearCmdBeforeDraw") != nullptr) {
  481. return VK_FALSE;
  482. }
  483. String type_string;
  484. switch (p_message_type) {
  485. case (VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT):
  486. type_string = "GENERAL";
  487. break;
  488. case (VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT):
  489. type_string = "VALIDATION";
  490. break;
  491. case (VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT):
  492. type_string = "PERFORMANCE";
  493. break;
  494. case (VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT & VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT):
  495. type_string = "VALIDATION|PERFORMANCE";
  496. break;
  497. }
  498. String objects_string;
  499. if (p_callback_data->objectCount > 0) {
  500. objects_string = "\n\tObjects - " + String::num_int64(p_callback_data->objectCount);
  501. for (uint32_t object = 0; object < p_callback_data->objectCount; ++object) {
  502. objects_string +=
  503. "\n\t\tObject[" + String::num_int64(object) + "]" +
  504. " - " + string_VkObjectType(p_callback_data->pObjects[object].objectType) +
  505. ", Handle " + String::num_int64(p_callback_data->pObjects[object].objectHandle);
  506. if (p_callback_data->pObjects[object].pObjectName != nullptr && strlen(p_callback_data->pObjects[object].pObjectName) > 0) {
  507. objects_string += ", Name \"" + String(p_callback_data->pObjects[object].pObjectName) + "\"";
  508. }
  509. }
  510. }
  511. String labels_string;
  512. if (p_callback_data->cmdBufLabelCount > 0) {
  513. labels_string = "\n\tCommand Buffer Labels - " + String::num_int64(p_callback_data->cmdBufLabelCount);
  514. for (uint32_t cmd_buf_label = 0; cmd_buf_label < p_callback_data->cmdBufLabelCount; ++cmd_buf_label) {
  515. labels_string +=
  516. "\n\t\tLabel[" + String::num_int64(cmd_buf_label) + "]" +
  517. " - " + p_callback_data->pCmdBufLabels[cmd_buf_label].pLabelName +
  518. "{ ";
  519. for (int color_idx = 0; color_idx < 4; ++color_idx) {
  520. labels_string += String::num(p_callback_data->pCmdBufLabels[cmd_buf_label].color[color_idx]);
  521. if (color_idx < 3) {
  522. labels_string += ", ";
  523. }
  524. }
  525. labels_string += " }";
  526. }
  527. }
  528. String error_message(type_string +
  529. " - Message Id Number: " + String::num_int64(p_callback_data->messageIdNumber) +
  530. " | Message Id Name: " + p_callback_data->pMessageIdName +
  531. "\n\t" + p_callback_data->pMessage +
  532. objects_string + labels_string);
  533. // Convert VK severity to our own log macros.
  534. switch (p_message_severity) {
  535. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT:
  536. print_verbose(error_message);
  537. break;
  538. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT:
  539. print_line(error_message);
  540. break;
  541. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT:
  542. WARN_PRINT(error_message);
  543. break;
  544. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT:
  545. ERR_PRINT(error_message);
  546. CRASH_COND_MSG(Engine::get_singleton()->is_abort_on_gpu_errors_enabled(), "Crashing, because abort on GPU errors is enabled.");
  547. break;
  548. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_FLAG_BITS_MAX_ENUM_EXT:
  549. break; // Shouldn't happen, only handling to make compilers happy.
  550. }
  551. return VK_FALSE;
  552. }
  553. VKAPI_ATTR VkBool32 VKAPI_CALL RenderingContextDriverVulkan::_debug_report_callback(VkDebugReportFlagsEXT p_flags, VkDebugReportObjectTypeEXT p_object_type, uint64_t p_object, size_t p_location, int32_t p_message_code, const char *p_layer_prefix, const char *p_message, void *p_user_data) {
  554. String debug_message = String("Vulkan Debug Report: object - ") + String::num_int64(p_object) + "\n" + p_message;
  555. switch (p_flags) {
  556. case VK_DEBUG_REPORT_DEBUG_BIT_EXT:
  557. case VK_DEBUG_REPORT_INFORMATION_BIT_EXT:
  558. print_line(debug_message);
  559. break;
  560. case VK_DEBUG_REPORT_WARNING_BIT_EXT:
  561. case VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT:
  562. WARN_PRINT(debug_message);
  563. break;
  564. case VK_DEBUG_REPORT_ERROR_BIT_EXT:
  565. ERR_PRINT(debug_message);
  566. break;
  567. }
  568. return VK_FALSE;
  569. }
  570. Error RenderingContextDriverVulkan::_initialize_instance() {
  571. Error err;
  572. TightLocalVector<const char *> enabled_extension_names;
  573. enabled_extension_names.reserve(enabled_instance_extension_names.size());
  574. for (const CharString &extension_name : enabled_instance_extension_names) {
  575. enabled_extension_names.push_back(extension_name.ptr());
  576. }
  577. // We'll set application version to the Vulkan version we're developing against, even if our instance is based on an older Vulkan
  578. // version, devices can still support newer versions of Vulkan. The exception is when we're on Vulkan 1.0, we should not set this
  579. // to anything but 1.0. Note that this value is only used by validation layers to warn us about version issues.
  580. uint32_t application_api_version = instance_api_version == VK_API_VERSION_1_0 ? VK_API_VERSION_1_0 : VK_API_VERSION_1_2;
  581. CharString cs = GLOBAL_GET("application/config/name").operator String().utf8();
  582. VkApplicationInfo app_info = {};
  583. app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
  584. app_info.pApplicationName = cs.get_data();
  585. app_info.pEngineName = VERSION_NAME;
  586. app_info.engineVersion = VK_MAKE_VERSION(VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH);
  587. app_info.apiVersion = application_api_version;
  588. TightLocalVector<const char *> enabled_layer_names;
  589. if (_use_validation_layers()) {
  590. err = _find_validation_layers(enabled_layer_names);
  591. ERR_FAIL_COND_V(err != OK, err);
  592. }
  593. VkInstanceCreateInfo instance_info = {};
  594. instance_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
  595. #if defined(USE_VOLK) && (defined(MACOS_ENABLED) || defined(IOS_ENABLED))
  596. instance_info.flags = VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR;
  597. #endif
  598. instance_info.pApplicationInfo = &app_info;
  599. instance_info.enabledExtensionCount = enabled_extension_names.size();
  600. instance_info.ppEnabledExtensionNames = enabled_extension_names.ptr();
  601. instance_info.enabledLayerCount = enabled_layer_names.size();
  602. instance_info.ppEnabledLayerNames = enabled_layer_names.ptr();
  603. // This is info for a temp callback to use during CreateInstance. After the instance is created, we use the instance-based function to register the final callback.
  604. VkDebugUtilsMessengerCreateInfoEXT debug_messenger_create_info = {};
  605. VkDebugReportCallbackCreateInfoEXT debug_report_callback_create_info = {};
  606. const bool has_debug_utils_extension = enabled_instance_extension_names.has(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
  607. const bool has_debug_report_extension = enabled_instance_extension_names.has(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
  608. if (has_debug_utils_extension) {
  609. debug_messenger_create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
  610. debug_messenger_create_info.pNext = nullptr;
  611. debug_messenger_create_info.flags = 0;
  612. debug_messenger_create_info.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
  613. debug_messenger_create_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
  614. debug_messenger_create_info.pfnUserCallback = _debug_messenger_callback;
  615. debug_messenger_create_info.pUserData = this;
  616. instance_info.pNext = &debug_messenger_create_info;
  617. } else if (has_debug_report_extension) {
  618. debug_report_callback_create_info.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT;
  619. debug_report_callback_create_info.flags = VK_DEBUG_REPORT_INFORMATION_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT | VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_DEBUG_BIT_EXT;
  620. debug_report_callback_create_info.pfnCallback = _debug_report_callback;
  621. debug_report_callback_create_info.pUserData = this;
  622. instance_info.pNext = &debug_report_callback_create_info;
  623. }
  624. err = _create_vulkan_instance(&instance_info, &instance);
  625. ERR_FAIL_COND_V(err != OK, err);
  626. #ifdef USE_VOLK
  627. volkLoadInstance(instance);
  628. #endif
  629. // Physical device.
  630. if (enabled_instance_extension_names.has(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
  631. functions.GetPhysicalDeviceFeatures2 = PFN_vkGetPhysicalDeviceFeatures2(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceFeatures2"));
  632. functions.GetPhysicalDeviceProperties2 = PFN_vkGetPhysicalDeviceProperties2(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceProperties2"));
  633. // In Vulkan 1.0, the functions might be accessible under their original extension names.
  634. if (functions.GetPhysicalDeviceFeatures2 == nullptr) {
  635. functions.GetPhysicalDeviceFeatures2 = PFN_vkGetPhysicalDeviceFeatures2(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceFeatures2KHR"));
  636. }
  637. if (functions.GetPhysicalDeviceProperties2 == nullptr) {
  638. functions.GetPhysicalDeviceProperties2 = PFN_vkGetPhysicalDeviceProperties2(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceProperties2KHR"));
  639. }
  640. }
  641. // Device.
  642. functions.GetDeviceProcAddr = PFN_vkGetDeviceProcAddr(vkGetInstanceProcAddr(instance, "vkGetDeviceProcAddr"));
  643. // Surfaces.
  644. functions.GetPhysicalDeviceSurfaceSupportKHR = PFN_vkGetPhysicalDeviceSurfaceSupportKHR(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfaceSupportKHR"));
  645. functions.GetPhysicalDeviceSurfaceFormatsKHR = PFN_vkGetPhysicalDeviceSurfaceFormatsKHR(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfaceFormatsKHR"));
  646. functions.GetPhysicalDeviceSurfaceCapabilitiesKHR = PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfaceCapabilitiesKHR"));
  647. functions.GetPhysicalDeviceSurfacePresentModesKHR = PFN_vkGetPhysicalDeviceSurfacePresentModesKHR(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfacePresentModesKHR"));
  648. // Debug utils and report.
  649. if (has_debug_utils_extension) {
  650. // Setup VK_EXT_debug_utils function pointers always (we use them for debug labels and names).
  651. functions.CreateDebugUtilsMessengerEXT = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT");
  652. functions.DestroyDebugUtilsMessengerEXT = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT");
  653. functions.CmdBeginDebugUtilsLabelEXT = (PFN_vkCmdBeginDebugUtilsLabelEXT)vkGetInstanceProcAddr(instance, "vkCmdBeginDebugUtilsLabelEXT");
  654. functions.CmdEndDebugUtilsLabelEXT = (PFN_vkCmdEndDebugUtilsLabelEXT)vkGetInstanceProcAddr(instance, "vkCmdEndDebugUtilsLabelEXT");
  655. functions.SetDebugUtilsObjectNameEXT = (PFN_vkSetDebugUtilsObjectNameEXT)vkGetInstanceProcAddr(instance, "vkSetDebugUtilsObjectNameEXT");
  656. if (!functions.debug_util_functions_available()) {
  657. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "GetProcAddr: Failed to init VK_EXT_debug_utils\nGetProcAddr: Failure");
  658. }
  659. VkResult res = functions.CreateDebugUtilsMessengerEXT(instance, &debug_messenger_create_info, get_allocation_callbacks(VK_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT), &debug_messenger);
  660. switch (res) {
  661. case VK_SUCCESS:
  662. break;
  663. case VK_ERROR_OUT_OF_HOST_MEMORY:
  664. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "CreateDebugUtilsMessengerEXT: out of host memory\nCreateDebugUtilsMessengerEXT Failure");
  665. break;
  666. default:
  667. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "CreateDebugUtilsMessengerEXT: unknown failure\nCreateDebugUtilsMessengerEXT Failure");
  668. break;
  669. }
  670. } else if (has_debug_report_extension) {
  671. functions.CreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT");
  672. functions.DebugReportMessageEXT = (PFN_vkDebugReportMessageEXT)vkGetInstanceProcAddr(instance, "vkDebugReportMessageEXT");
  673. functions.DestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT");
  674. if (!functions.debug_report_functions_available()) {
  675. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "GetProcAddr: Failed to init VK_EXT_debug_report\nGetProcAddr: Failure");
  676. }
  677. VkResult res = functions.CreateDebugReportCallbackEXT(instance, &debug_report_callback_create_info, get_allocation_callbacks(VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT), &debug_report);
  678. switch (res) {
  679. case VK_SUCCESS:
  680. break;
  681. case VK_ERROR_OUT_OF_HOST_MEMORY:
  682. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "CreateDebugReportCallbackEXT: out of host memory\nCreateDebugReportCallbackEXT Failure");
  683. break;
  684. default:
  685. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "CreateDebugReportCallbackEXT: unknown failure\nCreateDebugReportCallbackEXT Failure");
  686. break;
  687. }
  688. }
  689. return OK;
  690. }
  691. Error RenderingContextDriverVulkan::_initialize_devices() {
  692. if (VulkanHooks::get_singleton() != nullptr) {
  693. VkPhysicalDevice physical_device;
  694. bool device_retrieved = VulkanHooks::get_singleton()->get_physical_device(&physical_device);
  695. ERR_FAIL_COND_V(!device_retrieved, ERR_CANT_CREATE);
  696. // When a hook is active, pretend the device returned by the hook is the only device available.
  697. driver_devices.resize(1);
  698. physical_devices.resize(1);
  699. device_queue_families.resize(1);
  700. physical_devices[0] = physical_device;
  701. } else {
  702. uint32_t physical_device_count = 0;
  703. VkResult err = vkEnumeratePhysicalDevices(instance, &physical_device_count, nullptr);
  704. ERR_FAIL_COND_V(err != VK_SUCCESS, ERR_CANT_CREATE);
  705. ERR_FAIL_COND_V_MSG(physical_device_count == 0, ERR_CANT_CREATE, "vkEnumeratePhysicalDevices reported zero accessible devices.\n\nDo you have a compatible Vulkan installable client driver (ICD) installed?\nvkEnumeratePhysicalDevices Failure.");
  706. driver_devices.resize(physical_device_count);
  707. physical_devices.resize(physical_device_count);
  708. device_queue_families.resize(physical_device_count);
  709. err = vkEnumeratePhysicalDevices(instance, &physical_device_count, physical_devices.ptr());
  710. ERR_FAIL_COND_V(err != VK_SUCCESS, ERR_CANT_CREATE);
  711. }
  712. // Fill the list of driver devices with the properties from the physical devices.
  713. for (uint32_t i = 0; i < physical_devices.size(); i++) {
  714. VkPhysicalDeviceProperties props;
  715. vkGetPhysicalDeviceProperties(physical_devices[i], &props);
  716. Device &driver_device = driver_devices[i];
  717. driver_device.name = String::utf8(props.deviceName);
  718. driver_device.vendor = Vendor(props.vendorID);
  719. driver_device.type = DeviceType(props.deviceType);
  720. driver_device.workarounds = Workarounds();
  721. _check_driver_workarounds(props, driver_device);
  722. uint32_t queue_family_properties_count = 0;
  723. vkGetPhysicalDeviceQueueFamilyProperties(physical_devices[i], &queue_family_properties_count, nullptr);
  724. if (queue_family_properties_count > 0) {
  725. device_queue_families[i].properties.resize(queue_family_properties_count);
  726. vkGetPhysicalDeviceQueueFamilyProperties(physical_devices[i], &queue_family_properties_count, device_queue_families[i].properties.ptr());
  727. }
  728. }
  729. return OK;
  730. }
  731. void RenderingContextDriverVulkan::_check_driver_workarounds(const VkPhysicalDeviceProperties &p_device_properties, Device &r_device) {
  732. // Workaround for the Adreno 6XX family of devices.
  733. //
  734. // There's a known issue with the Vulkan driver in this family of devices where it'll crash if a dynamic state for drawing is
  735. // used in a command buffer before a dispatch call is issued. As both dynamic scissor and viewport are basic requirements for
  736. // the engine to not bake this state into the PSO, the only known way to fix this issue is to reset the command buffer entirely.
  737. //
  738. // As the render graph has no built in limitations of whether it'll issue compute work before anything needs to draw on the
  739. // frame, and there's no guarantee that compute work will never be dependent on rasterization in the future, this workaround
  740. // will end recording on the current command buffer any time a compute list is encountered after a draw list was executed.
  741. // A new command buffer will be created afterwards and the appropriate synchronization primitives will be inserted.
  742. //
  743. // Executing this workaround has the added cost of synchronization between all the command buffers that are created as well as
  744. // all the individual submissions. This performance hit is accepted for the sake of being able to support these devices without
  745. // limiting the design of the renderer.
  746. //
  747. // This bug was fixed in driver version 512.503.0, so we only enabled it on devices older than this.
  748. //
  749. r_device.workarounds.avoid_compute_after_draw =
  750. r_device.vendor == VENDOR_QUALCOMM &&
  751. p_device_properties.deviceID >= 0x6000000 && // Adreno 6xx
  752. p_device_properties.driverVersion < VK_MAKE_VERSION(512, 503, 0) &&
  753. r_device.name.find("Turnip") < 0;
  754. }
  755. bool RenderingContextDriverVulkan::_use_validation_layers() const {
  756. return Engine::get_singleton()->is_validation_layers_enabled();
  757. }
  758. Error RenderingContextDriverVulkan::_create_vulkan_instance(const VkInstanceCreateInfo *p_create_info, VkInstance *r_instance) {
  759. if (VulkanHooks::get_singleton() != nullptr) {
  760. return VulkanHooks::get_singleton()->create_vulkan_instance(p_create_info, r_instance) ? OK : ERR_CANT_CREATE;
  761. } else {
  762. VkResult err = vkCreateInstance(p_create_info, get_allocation_callbacks(VK_OBJECT_TYPE_INSTANCE), r_instance);
  763. ERR_FAIL_COND_V_MSG(err == VK_ERROR_INCOMPATIBLE_DRIVER, ERR_CANT_CREATE,
  764. "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
  765. "vkCreateInstance Failure");
  766. ERR_FAIL_COND_V_MSG(err == VK_ERROR_EXTENSION_NOT_PRESENT, ERR_CANT_CREATE,
  767. "Cannot find a specified extension library.\n"
  768. "Make sure your layers path is set appropriately.\n"
  769. "vkCreateInstance Failure");
  770. ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE,
  771. "vkCreateInstance failed.\n\n"
  772. "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
  773. "Please look at the Getting Started guide for additional information.\n"
  774. "vkCreateInstance Failure");
  775. }
  776. return OK;
  777. }
  778. Error RenderingContextDriverVulkan::initialize() {
  779. Error err;
  780. #ifdef USE_VOLK
  781. if (volkInitialize() != VK_SUCCESS) {
  782. return FAILED;
  783. }
  784. #endif
  785. err = _initialize_vulkan_version();
  786. ERR_FAIL_COND_V(err != OK, err);
  787. err = _initialize_instance_extensions();
  788. ERR_FAIL_COND_V(err != OK, err);
  789. err = _initialize_instance();
  790. ERR_FAIL_COND_V(err != OK, err);
  791. err = _initialize_devices();
  792. ERR_FAIL_COND_V(err != OK, err);
  793. return OK;
  794. }
  795. const RenderingContextDriver::Device &RenderingContextDriverVulkan::device_get(uint32_t p_device_index) const {
  796. DEV_ASSERT(p_device_index < driver_devices.size());
  797. return driver_devices[p_device_index];
  798. }
  799. uint32_t RenderingContextDriverVulkan::device_get_count() const {
  800. return driver_devices.size();
  801. }
  802. bool RenderingContextDriverVulkan::device_supports_present(uint32_t p_device_index, SurfaceID p_surface) const {
  803. DEV_ASSERT(p_device_index < physical_devices.size());
  804. // Check if any of the queues supported by the device supports presenting to the window's surface.
  805. const VkPhysicalDevice physical_device = physical_devices[p_device_index];
  806. const DeviceQueueFamilies &queue_families = device_queue_families[p_device_index];
  807. for (uint32_t i = 0; i < queue_families.properties.size(); i++) {
  808. if ((queue_families.properties[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) && queue_family_supports_present(physical_device, i, p_surface)) {
  809. return true;
  810. }
  811. }
  812. return false;
  813. }
  814. RenderingDeviceDriver *RenderingContextDriverVulkan::driver_create() {
  815. return memnew(RenderingDeviceDriverVulkan(this));
  816. }
  817. void RenderingContextDriverVulkan::driver_free(RenderingDeviceDriver *p_driver) {
  818. memdelete(p_driver);
  819. }
  820. RenderingContextDriver::SurfaceID RenderingContextDriverVulkan::surface_create(const void *p_platform_data) {
  821. DEV_ASSERT(false && "Surface creation should not be called on the platform-agnostic version of the driver.");
  822. return SurfaceID();
  823. }
  824. void RenderingContextDriverVulkan::surface_set_size(SurfaceID p_surface, uint32_t p_width, uint32_t p_height) {
  825. Surface *surface = (Surface *)(p_surface);
  826. surface->width = p_width;
  827. surface->height = p_height;
  828. surface->needs_resize = true;
  829. }
  830. void RenderingContextDriverVulkan::surface_set_vsync_mode(SurfaceID p_surface, DisplayServer::VSyncMode p_vsync_mode) {
  831. Surface *surface = (Surface *)(p_surface);
  832. surface->vsync_mode = p_vsync_mode;
  833. surface->needs_resize = true;
  834. }
  835. DisplayServer::VSyncMode RenderingContextDriverVulkan::surface_get_vsync_mode(SurfaceID p_surface) const {
  836. Surface *surface = (Surface *)(p_surface);
  837. return surface->vsync_mode;
  838. }
  839. uint32_t RenderingContextDriverVulkan::surface_get_width(SurfaceID p_surface) const {
  840. Surface *surface = (Surface *)(p_surface);
  841. return surface->width;
  842. }
  843. uint32_t RenderingContextDriverVulkan::surface_get_height(SurfaceID p_surface) const {
  844. Surface *surface = (Surface *)(p_surface);
  845. return surface->height;
  846. }
  847. void RenderingContextDriverVulkan::surface_set_needs_resize(SurfaceID p_surface, bool p_needs_resize) {
  848. Surface *surface = (Surface *)(p_surface);
  849. surface->needs_resize = p_needs_resize;
  850. }
  851. bool RenderingContextDriverVulkan::surface_get_needs_resize(SurfaceID p_surface) const {
  852. Surface *surface = (Surface *)(p_surface);
  853. return surface->needs_resize;
  854. }
  855. void RenderingContextDriverVulkan::surface_destroy(SurfaceID p_surface) {
  856. Surface *surface = (Surface *)(p_surface);
  857. vkDestroySurfaceKHR(instance, surface->vk_surface, get_allocation_callbacks(VK_OBJECT_TYPE_SURFACE_KHR));
  858. memdelete(surface);
  859. }
  860. bool RenderingContextDriverVulkan::is_debug_utils_enabled() const {
  861. return enabled_instance_extension_names.has(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
  862. }
  863. VkInstance RenderingContextDriverVulkan::instance_get() const {
  864. return instance;
  865. }
  866. VkPhysicalDevice RenderingContextDriverVulkan::physical_device_get(uint32_t p_device_index) const {
  867. DEV_ASSERT(p_device_index < physical_devices.size());
  868. return physical_devices[p_device_index];
  869. }
  870. uint32_t RenderingContextDriverVulkan::queue_family_get_count(uint32_t p_device_index) const {
  871. DEV_ASSERT(p_device_index < physical_devices.size());
  872. return device_queue_families[p_device_index].properties.size();
  873. }
  874. VkQueueFamilyProperties RenderingContextDriverVulkan::queue_family_get(uint32_t p_device_index, uint32_t p_queue_family_index) const {
  875. DEV_ASSERT(p_device_index < physical_devices.size());
  876. DEV_ASSERT(p_queue_family_index < queue_family_get_count(p_device_index));
  877. return device_queue_families[p_device_index].properties[p_queue_family_index];
  878. }
  879. bool RenderingContextDriverVulkan::queue_family_supports_present(VkPhysicalDevice p_physical_device, uint32_t p_queue_family_index, SurfaceID p_surface) const {
  880. DEV_ASSERT(p_physical_device != VK_NULL_HANDLE);
  881. DEV_ASSERT(p_surface != 0);
  882. Surface *surface = (Surface *)(p_surface);
  883. VkBool32 present_supported = false;
  884. VkResult err = vkGetPhysicalDeviceSurfaceSupportKHR(p_physical_device, p_queue_family_index, surface->vk_surface, &present_supported);
  885. return err == VK_SUCCESS && present_supported;
  886. }
  887. const RenderingContextDriverVulkan::Functions &RenderingContextDriverVulkan::functions_get() const {
  888. return functions;
  889. }
  890. #endif // VULKAN_ENABLED