rendering_context_driver_vulkan.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  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. RenderingContextDriverVulkan::RenderingContextDriverVulkan() {
  38. // Empty constructor.
  39. }
  40. RenderingContextDriverVulkan::~RenderingContextDriverVulkan() {
  41. if (debug_messenger != VK_NULL_HANDLE && functions.DestroyDebugUtilsMessengerEXT != nullptr) {
  42. functions.DestroyDebugUtilsMessengerEXT(instance, debug_messenger, nullptr);
  43. }
  44. if (debug_report != VK_NULL_HANDLE && functions.DestroyDebugReportCallbackEXT != nullptr) {
  45. functions.DestroyDebugReportCallbackEXT(instance, debug_report, nullptr);
  46. }
  47. if (instance != VK_NULL_HANDLE) {
  48. vkDestroyInstance(instance, nullptr);
  49. }
  50. }
  51. Error RenderingContextDriverVulkan::_initialize_vulkan_version() {
  52. // https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VkApplicationInfo.html#_description
  53. // For Vulkan 1.0 vkEnumerateInstanceVersion is not available, including not in the loader we compile against on Android.
  54. typedef VkResult(VKAPI_PTR * _vkEnumerateInstanceVersion)(uint32_t *);
  55. _vkEnumerateInstanceVersion func = (_vkEnumerateInstanceVersion)vkGetInstanceProcAddr(nullptr, "vkEnumerateInstanceVersion");
  56. if (func != nullptr) {
  57. uint32_t api_version;
  58. VkResult res = func(&api_version);
  59. if (res == VK_SUCCESS) {
  60. instance_api_version = api_version;
  61. } else {
  62. // According to the documentation this shouldn't fail with anything except a memory allocation error
  63. // in which case we're in deep trouble anyway.
  64. ERR_FAIL_V(ERR_CANT_CREATE);
  65. }
  66. } else {
  67. print_line("vkEnumerateInstanceVersion not available, assuming Vulkan 1.0.");
  68. instance_api_version = VK_API_VERSION_1_0;
  69. }
  70. return OK;
  71. }
  72. void RenderingContextDriverVulkan::_register_requested_instance_extension(const CharString &p_extension_name, bool p_required) {
  73. ERR_FAIL_COND(requested_instance_extensions.has(p_extension_name));
  74. requested_instance_extensions[p_extension_name] = p_required;
  75. }
  76. Error RenderingContextDriverVulkan::_initialize_instance_extensions() {
  77. enabled_instance_extension_names.clear();
  78. // The surface extension and the platform-specific surface extension are core requirements.
  79. _register_requested_instance_extension(VK_KHR_SURFACE_EXTENSION_NAME, true);
  80. if (_get_platform_surface_extension()) {
  81. _register_requested_instance_extension(_get_platform_surface_extension(), true);
  82. }
  83. if (_use_validation_layers()) {
  84. _register_requested_instance_extension(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, false);
  85. }
  86. // This extension allows us to use the properties2 features to query additional device capabilities.
  87. _register_requested_instance_extension(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, false);
  88. #if defined(USE_VOLK) && (defined(MACOS_ENABLED) || defined(IOS_ENABLED))
  89. _register_requested_instance_extension(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME, true);
  90. #endif
  91. // Only enable debug utils in verbose mode or DEV_ENABLED.
  92. // End users would get spammed with messages of varying verbosity due to the
  93. // mess that thirdparty layers/extensions and drivers seem to leave in their
  94. // wake, making the Windows registry a bottomless pit of broken layer JSON.
  95. #ifdef DEV_ENABLED
  96. bool want_debug_utils = true;
  97. #else
  98. bool want_debug_utils = OS::get_singleton()->is_stdout_verbose();
  99. #endif
  100. if (want_debug_utils) {
  101. _register_requested_instance_extension(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, false);
  102. }
  103. // Load instance extensions that are available.
  104. uint32_t instance_extension_count = 0;
  105. VkResult err = vkEnumerateInstanceExtensionProperties(nullptr, &instance_extension_count, nullptr);
  106. ERR_FAIL_COND_V(err != VK_SUCCESS && err != VK_INCOMPLETE, ERR_CANT_CREATE);
  107. ERR_FAIL_COND_V_MSG(instance_extension_count == 0, ERR_CANT_CREATE, "No instance extensions were found.");
  108. TightLocalVector<VkExtensionProperties> instance_extensions;
  109. instance_extensions.resize(instance_extension_count);
  110. err = vkEnumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.ptr());
  111. if (err != VK_SUCCESS && err != VK_INCOMPLETE) {
  112. ERR_FAIL_V(ERR_CANT_CREATE);
  113. }
  114. #ifdef DEV_ENABLED
  115. for (uint32_t i = 0; i < instance_extension_count; i++) {
  116. print_verbose(String("VULKAN: Found instance extension ") + String::utf8(instance_extensions[i].extensionName) + String("."));
  117. }
  118. #endif
  119. // Enable all extensions that are supported and requested.
  120. for (uint32_t i = 0; i < instance_extension_count; i++) {
  121. CharString extension_name(instance_extensions[i].extensionName);
  122. if (requested_instance_extensions.has(extension_name)) {
  123. enabled_instance_extension_names.insert(extension_name);
  124. }
  125. }
  126. // Now check our requested extensions.
  127. for (KeyValue<CharString, bool> &requested_extension : requested_instance_extensions) {
  128. if (!enabled_instance_extension_names.has(requested_extension.key)) {
  129. if (requested_extension.value) {
  130. ERR_FAIL_V_MSG(ERR_BUG, String("Required extension ") + String::utf8(requested_extension.key) + String(" not found."));
  131. } else {
  132. print_verbose(String("Optional extension ") + String::utf8(requested_extension.key) + String(" not found."));
  133. }
  134. }
  135. }
  136. return OK;
  137. }
  138. Error RenderingContextDriverVulkan::_find_validation_layers(TightLocalVector<const char *> &r_layer_names) const {
  139. r_layer_names.clear();
  140. uint32_t instance_layer_count = 0;
  141. VkResult err = vkEnumerateInstanceLayerProperties(&instance_layer_count, nullptr);
  142. ERR_FAIL_COND_V(err != VK_SUCCESS, ERR_CANT_CREATE);
  143. if (instance_layer_count > 0) {
  144. TightLocalVector<VkLayerProperties> layer_properties;
  145. layer_properties.resize(instance_layer_count);
  146. err = vkEnumerateInstanceLayerProperties(&instance_layer_count, layer_properties.ptr());
  147. ERR_FAIL_COND_V(err != VK_SUCCESS, ERR_CANT_CREATE);
  148. // Preferred set of validation layers.
  149. const std::initializer_list<const char *> preferred = { "VK_LAYER_KHRONOS_validation" };
  150. // Alternative (deprecated, removed in SDK 1.1.126.0) set of validation layers.
  151. const std::initializer_list<const char *> lunarg = { "VK_LAYER_LUNARG_standard_validation" };
  152. // Alternative (deprecated, removed in SDK 1.1.121.1) set of validation layers.
  153. 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" };
  154. // Verify all the layers of the list are present.
  155. for (const std::initializer_list<const char *> &list : { preferred, lunarg, google }) {
  156. bool layers_found = false;
  157. for (const char *layer_name : list) {
  158. layers_found = false;
  159. for (const VkLayerProperties &properties : layer_properties) {
  160. if (!strcmp(properties.layerName, layer_name)) {
  161. layers_found = true;
  162. break;
  163. }
  164. }
  165. if (!layers_found) {
  166. break;
  167. }
  168. }
  169. if (layers_found) {
  170. r_layer_names.reserve(list.size());
  171. for (const char *layer_name : list) {
  172. r_layer_names.push_back(layer_name);
  173. }
  174. break;
  175. }
  176. }
  177. }
  178. return OK;
  179. }
  180. 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) {
  181. // This error needs to be ignored because the AMD allocator will mix up memory types on IGP processors.
  182. 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) {
  183. return VK_FALSE;
  184. }
  185. // This needs to be ignored because Validator is wrong here.
  186. if (strstr(p_callback_data->pMessage, "Invalid SPIR-V binary version 1.3") != nullptr) {
  187. return VK_FALSE;
  188. }
  189. // This needs to be ignored because Validator is wrong here.
  190. if (strstr(p_callback_data->pMessage, "Shader requires flag") != nullptr) {
  191. return VK_FALSE;
  192. }
  193. // This needs to be ignored because Validator is wrong here.
  194. 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) {
  195. return VK_FALSE;
  196. }
  197. if (p_callback_data->pMessageIdName && strstr(p_callback_data->pMessageIdName, "UNASSIGNED-CoreValidation-DrawState-ClearCmdBeforeDraw") != nullptr) {
  198. return VK_FALSE;
  199. }
  200. String type_string;
  201. switch (p_message_type) {
  202. case (VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT):
  203. type_string = "GENERAL";
  204. break;
  205. case (VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT):
  206. type_string = "VALIDATION";
  207. break;
  208. case (VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT):
  209. type_string = "PERFORMANCE";
  210. break;
  211. case (VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT & VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT):
  212. type_string = "VALIDATION|PERFORMANCE";
  213. break;
  214. }
  215. String objects_string;
  216. if (p_callback_data->objectCount > 0) {
  217. objects_string = "\n\tObjects - " + String::num_int64(p_callback_data->objectCount);
  218. for (uint32_t object = 0; object < p_callback_data->objectCount; ++object) {
  219. objects_string +=
  220. "\n\t\tObject[" + String::num_int64(object) + "]" +
  221. " - " + string_VkObjectType(p_callback_data->pObjects[object].objectType) +
  222. ", Handle " + String::num_int64(p_callback_data->pObjects[object].objectHandle);
  223. if (p_callback_data->pObjects[object].pObjectName != nullptr && strlen(p_callback_data->pObjects[object].pObjectName) > 0) {
  224. objects_string += ", Name \"" + String(p_callback_data->pObjects[object].pObjectName) + "\"";
  225. }
  226. }
  227. }
  228. String labels_string;
  229. if (p_callback_data->cmdBufLabelCount > 0) {
  230. labels_string = "\n\tCommand Buffer Labels - " + String::num_int64(p_callback_data->cmdBufLabelCount);
  231. for (uint32_t cmd_buf_label = 0; cmd_buf_label < p_callback_data->cmdBufLabelCount; ++cmd_buf_label) {
  232. labels_string +=
  233. "\n\t\tLabel[" + String::num_int64(cmd_buf_label) + "]" +
  234. " - " + p_callback_data->pCmdBufLabels[cmd_buf_label].pLabelName +
  235. "{ ";
  236. for (int color_idx = 0; color_idx < 4; ++color_idx) {
  237. labels_string += String::num(p_callback_data->pCmdBufLabels[cmd_buf_label].color[color_idx]);
  238. if (color_idx < 3) {
  239. labels_string += ", ";
  240. }
  241. }
  242. labels_string += " }";
  243. }
  244. }
  245. String error_message(type_string +
  246. " - Message Id Number: " + String::num_int64(p_callback_data->messageIdNumber) +
  247. " | Message Id Name: " + p_callback_data->pMessageIdName +
  248. "\n\t" + p_callback_data->pMessage +
  249. objects_string + labels_string);
  250. // Convert VK severity to our own log macros.
  251. switch (p_message_severity) {
  252. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT:
  253. print_verbose(error_message);
  254. break;
  255. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT:
  256. print_line(error_message);
  257. break;
  258. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT:
  259. WARN_PRINT(error_message);
  260. break;
  261. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT:
  262. ERR_PRINT(error_message);
  263. CRASH_COND_MSG(Engine::get_singleton()->is_abort_on_gpu_errors_enabled(), "Crashing, because abort on GPU errors is enabled.");
  264. break;
  265. case VK_DEBUG_UTILS_MESSAGE_SEVERITY_FLAG_BITS_MAX_ENUM_EXT:
  266. break; // Shouldn't happen, only handling to make compilers happy.
  267. }
  268. return VK_FALSE;
  269. }
  270. 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) {
  271. String debug_message = String("Vulkan Debug Report: object - ") + String::num_int64(p_object) + "\n" + p_message;
  272. switch (p_flags) {
  273. case VK_DEBUG_REPORT_DEBUG_BIT_EXT:
  274. case VK_DEBUG_REPORT_INFORMATION_BIT_EXT:
  275. print_line(debug_message);
  276. break;
  277. case VK_DEBUG_REPORT_WARNING_BIT_EXT:
  278. case VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT:
  279. WARN_PRINT(debug_message);
  280. break;
  281. case VK_DEBUG_REPORT_ERROR_BIT_EXT:
  282. ERR_PRINT(debug_message);
  283. break;
  284. }
  285. return VK_FALSE;
  286. }
  287. Error RenderingContextDriverVulkan::_initialize_instance() {
  288. Error err;
  289. TightLocalVector<const char *> enabled_extension_names;
  290. enabled_extension_names.reserve(enabled_instance_extension_names.size());
  291. for (const CharString &extension_name : enabled_instance_extension_names) {
  292. enabled_extension_names.push_back(extension_name.ptr());
  293. }
  294. // We'll set application version to the Vulkan version we're developing against, even if our instance is based on an older Vulkan
  295. // version, devices can still support newer versions of Vulkan. The exception is when we're on Vulkan 1.0, we should not set this
  296. // to anything but 1.0. Note that this value is only used by validation layers to warn us about version issues.
  297. uint32_t application_api_version = instance_api_version == VK_API_VERSION_1_0 ? VK_API_VERSION_1_0 : VK_API_VERSION_1_2;
  298. CharString cs = GLOBAL_GET("application/config/name").operator String().utf8();
  299. VkApplicationInfo app_info = {};
  300. app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
  301. app_info.pApplicationName = cs.get_data();
  302. app_info.pEngineName = VERSION_NAME;
  303. app_info.engineVersion = VK_MAKE_VERSION(VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH);
  304. app_info.apiVersion = application_api_version;
  305. TightLocalVector<const char *> enabled_layer_names;
  306. if (_use_validation_layers()) {
  307. err = _find_validation_layers(enabled_layer_names);
  308. ERR_FAIL_COND_V(err != OK, err);
  309. }
  310. VkInstanceCreateInfo instance_info = {};
  311. instance_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
  312. #if defined(USE_VOLK) && (defined(MACOS_ENABLED) || defined(IOS_ENABLED))
  313. instance_info.flags = VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR;
  314. #endif
  315. instance_info.pApplicationInfo = &app_info;
  316. instance_info.enabledExtensionCount = enabled_extension_names.size();
  317. instance_info.ppEnabledExtensionNames = enabled_extension_names.ptr();
  318. instance_info.enabledLayerCount = enabled_layer_names.size();
  319. instance_info.ppEnabledLayerNames = enabled_layer_names.ptr();
  320. // 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.
  321. VkDebugUtilsMessengerCreateInfoEXT debug_messenger_create_info = {};
  322. VkDebugReportCallbackCreateInfoEXT debug_report_callback_create_info = {};
  323. const bool has_debug_utils_extension = enabled_instance_extension_names.has(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
  324. const bool has_debug_report_extension = enabled_instance_extension_names.has(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
  325. if (has_debug_utils_extension) {
  326. debug_messenger_create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
  327. debug_messenger_create_info.pNext = nullptr;
  328. debug_messenger_create_info.flags = 0;
  329. debug_messenger_create_info.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
  330. 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;
  331. debug_messenger_create_info.pfnUserCallback = _debug_messenger_callback;
  332. debug_messenger_create_info.pUserData = this;
  333. instance_info.pNext = &debug_messenger_create_info;
  334. } else if (has_debug_report_extension) {
  335. debug_report_callback_create_info.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT;
  336. 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;
  337. debug_report_callback_create_info.pfnCallback = _debug_report_callback;
  338. debug_report_callback_create_info.pUserData = this;
  339. instance_info.pNext = &debug_report_callback_create_info;
  340. }
  341. err = _create_vulkan_instance(&instance_info, &instance);
  342. ERR_FAIL_COND_V(err != OK, err);
  343. #ifdef USE_VOLK
  344. volkLoadInstance(instance);
  345. #endif
  346. // Physical device.
  347. if (enabled_instance_extension_names.has(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
  348. functions.GetPhysicalDeviceFeatures2 = PFN_vkGetPhysicalDeviceFeatures2(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceFeatures2"));
  349. functions.GetPhysicalDeviceProperties2 = PFN_vkGetPhysicalDeviceProperties2(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceProperties2"));
  350. // In Vulkan 1.0, the functions might be accessible under their original extension names.
  351. if (functions.GetPhysicalDeviceFeatures2 == nullptr) {
  352. functions.GetPhysicalDeviceFeatures2 = PFN_vkGetPhysicalDeviceFeatures2(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceFeatures2KHR"));
  353. }
  354. if (functions.GetPhysicalDeviceProperties2 == nullptr) {
  355. functions.GetPhysicalDeviceProperties2 = PFN_vkGetPhysicalDeviceProperties2(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceProperties2KHR"));
  356. }
  357. }
  358. // Device.
  359. functions.GetDeviceProcAddr = PFN_vkGetDeviceProcAddr(vkGetInstanceProcAddr(instance, "vkGetDeviceProcAddr"));
  360. // Surfaces.
  361. functions.GetPhysicalDeviceSurfaceSupportKHR = PFN_vkGetPhysicalDeviceSurfaceSupportKHR(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfaceSupportKHR"));
  362. functions.GetPhysicalDeviceSurfaceFormatsKHR = PFN_vkGetPhysicalDeviceSurfaceFormatsKHR(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfaceFormatsKHR"));
  363. functions.GetPhysicalDeviceSurfaceCapabilitiesKHR = PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfaceCapabilitiesKHR"));
  364. functions.GetPhysicalDeviceSurfacePresentModesKHR = PFN_vkGetPhysicalDeviceSurfacePresentModesKHR(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfacePresentModesKHR"));
  365. // Debug utils and report.
  366. if (has_debug_utils_extension) {
  367. // Setup VK_EXT_debug_utils function pointers always (we use them for debug labels and names).
  368. functions.CreateDebugUtilsMessengerEXT = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT");
  369. functions.DestroyDebugUtilsMessengerEXT = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT");
  370. functions.CmdBeginDebugUtilsLabelEXT = (PFN_vkCmdBeginDebugUtilsLabelEXT)vkGetInstanceProcAddr(instance, "vkCmdBeginDebugUtilsLabelEXT");
  371. functions.CmdEndDebugUtilsLabelEXT = (PFN_vkCmdEndDebugUtilsLabelEXT)vkGetInstanceProcAddr(instance, "vkCmdEndDebugUtilsLabelEXT");
  372. functions.SetDebugUtilsObjectNameEXT = (PFN_vkSetDebugUtilsObjectNameEXT)vkGetInstanceProcAddr(instance, "vkSetDebugUtilsObjectNameEXT");
  373. if (!functions.debug_util_functions_available()) {
  374. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "GetProcAddr: Failed to init VK_EXT_debug_utils\nGetProcAddr: Failure");
  375. }
  376. VkResult res = functions.CreateDebugUtilsMessengerEXT(instance, &debug_messenger_create_info, nullptr, &debug_messenger);
  377. switch (res) {
  378. case VK_SUCCESS:
  379. break;
  380. case VK_ERROR_OUT_OF_HOST_MEMORY:
  381. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "CreateDebugUtilsMessengerEXT: out of host memory\nCreateDebugUtilsMessengerEXT Failure");
  382. break;
  383. default:
  384. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "CreateDebugUtilsMessengerEXT: unknown failure\nCreateDebugUtilsMessengerEXT Failure");
  385. break;
  386. }
  387. } else if (has_debug_report_extension) {
  388. functions.CreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT");
  389. functions.DebugReportMessageEXT = (PFN_vkDebugReportMessageEXT)vkGetInstanceProcAddr(instance, "vkDebugReportMessageEXT");
  390. functions.DestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT");
  391. if (!functions.debug_report_functions_available()) {
  392. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "GetProcAddr: Failed to init VK_EXT_debug_report\nGetProcAddr: Failure");
  393. }
  394. VkResult res = functions.CreateDebugReportCallbackEXT(instance, &debug_report_callback_create_info, nullptr, &debug_report);
  395. switch (res) {
  396. case VK_SUCCESS:
  397. break;
  398. case VK_ERROR_OUT_OF_HOST_MEMORY:
  399. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "CreateDebugReportCallbackEXT: out of host memory\nCreateDebugReportCallbackEXT Failure");
  400. break;
  401. default:
  402. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "CreateDebugReportCallbackEXT: unknown failure\nCreateDebugReportCallbackEXT Failure");
  403. break;
  404. }
  405. }
  406. return OK;
  407. }
  408. Error RenderingContextDriverVulkan::_initialize_devices() {
  409. if (VulkanHooks::get_singleton() != nullptr) {
  410. VkPhysicalDevice physical_device;
  411. bool device_retrieved = VulkanHooks::get_singleton()->get_physical_device(&physical_device);
  412. ERR_FAIL_COND_V(!device_retrieved, ERR_CANT_CREATE);
  413. // When a hook is active, pretend the device returned by the hook is the only device available.
  414. driver_devices.resize(1);
  415. physical_devices.resize(1);
  416. device_queue_families.resize(1);
  417. physical_devices[0] = physical_device;
  418. } else {
  419. uint32_t physical_device_count = 0;
  420. VkResult err = vkEnumeratePhysicalDevices(instance, &physical_device_count, nullptr);
  421. ERR_FAIL_COND_V(err != VK_SUCCESS, ERR_CANT_CREATE);
  422. 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.");
  423. driver_devices.resize(physical_device_count);
  424. physical_devices.resize(physical_device_count);
  425. device_queue_families.resize(physical_device_count);
  426. err = vkEnumeratePhysicalDevices(instance, &physical_device_count, physical_devices.ptr());
  427. ERR_FAIL_COND_V(err != VK_SUCCESS, ERR_CANT_CREATE);
  428. }
  429. // Fill the list of driver devices with the properties from the physical devices.
  430. for (uint32_t i = 0; i < physical_devices.size(); i++) {
  431. VkPhysicalDeviceProperties props;
  432. vkGetPhysicalDeviceProperties(physical_devices[i], &props);
  433. Device &driver_device = driver_devices[i];
  434. driver_device.name = String::utf8(props.deviceName);
  435. driver_device.vendor = Vendor(props.vendorID);
  436. driver_device.type = DeviceType(props.deviceType);
  437. driver_device.workarounds = Workarounds();
  438. _check_driver_workarounds(props, driver_device);
  439. uint32_t queue_family_properties_count = 0;
  440. vkGetPhysicalDeviceQueueFamilyProperties(physical_devices[i], &queue_family_properties_count, nullptr);
  441. if (queue_family_properties_count > 0) {
  442. device_queue_families[i].properties.resize(queue_family_properties_count);
  443. vkGetPhysicalDeviceQueueFamilyProperties(physical_devices[i], &queue_family_properties_count, device_queue_families[i].properties.ptr());
  444. }
  445. }
  446. return OK;
  447. }
  448. void RenderingContextDriverVulkan::_check_driver_workarounds(const VkPhysicalDeviceProperties &p_device_properties, Device &r_device) {
  449. // Workaround for the Adreno 6XX family of devices.
  450. //
  451. // 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
  452. // used in a command buffer before a dispatch call is issued. As both dynamic scissor and viewport are basic requirements for
  453. // 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.
  454. //
  455. // As the render graph has no built in limitations of whether it'll issue compute work before anything needs to draw on the
  456. // frame, and there's no guarantee that compute work will never be dependent on rasterization in the future, this workaround
  457. // will end recording on the current command buffer any time a compute list is encountered after a draw list was executed.
  458. // A new command buffer will be created afterwards and the appropriate synchronization primitives will be inserted.
  459. //
  460. // Executing this workaround has the added cost of synchronization between all the command buffers that are created as well as
  461. // all the individual submissions. This performance hit is accepted for the sake of being able to support these devices without
  462. // limiting the design of the renderer.
  463. //
  464. // This bug was fixed in driver version 512.503.0, so we only enabled it on devices older than this.
  465. //
  466. r_device.workarounds.avoid_compute_after_draw =
  467. r_device.vendor == VENDOR_QUALCOMM &&
  468. p_device_properties.deviceID >= 0x6000000 && // Adreno 6xx
  469. p_device_properties.driverVersion < VK_MAKE_VERSION(512, 503, 0) &&
  470. r_device.name.find("Turnip") < 0;
  471. }
  472. bool RenderingContextDriverVulkan::_use_validation_layers() const {
  473. return Engine::get_singleton()->is_validation_layers_enabled();
  474. }
  475. Error RenderingContextDriverVulkan::_create_vulkan_instance(const VkInstanceCreateInfo *p_create_info, VkInstance *r_instance) {
  476. if (VulkanHooks::get_singleton() != nullptr) {
  477. return VulkanHooks::get_singleton()->create_vulkan_instance(p_create_info, r_instance) ? OK : ERR_CANT_CREATE;
  478. } else {
  479. VkResult err = vkCreateInstance(p_create_info, nullptr, r_instance);
  480. ERR_FAIL_COND_V_MSG(err == VK_ERROR_INCOMPATIBLE_DRIVER, ERR_CANT_CREATE,
  481. "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
  482. "vkCreateInstance Failure");
  483. ERR_FAIL_COND_V_MSG(err == VK_ERROR_EXTENSION_NOT_PRESENT, ERR_CANT_CREATE,
  484. "Cannot find a specified extension library.\n"
  485. "Make sure your layers path is set appropriately.\n"
  486. "vkCreateInstance Failure");
  487. ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE,
  488. "vkCreateInstance failed.\n\n"
  489. "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
  490. "Please look at the Getting Started guide for additional information.\n"
  491. "vkCreateInstance Failure");
  492. }
  493. return OK;
  494. }
  495. Error RenderingContextDriverVulkan::initialize() {
  496. Error err;
  497. #ifdef USE_VOLK
  498. if (volkInitialize() != VK_SUCCESS) {
  499. return FAILED;
  500. }
  501. #endif
  502. err = _initialize_vulkan_version();
  503. ERR_FAIL_COND_V(err != OK, err);
  504. err = _initialize_instance_extensions();
  505. ERR_FAIL_COND_V(err != OK, err);
  506. err = _initialize_instance();
  507. ERR_FAIL_COND_V(err != OK, err);
  508. err = _initialize_devices();
  509. ERR_FAIL_COND_V(err != OK, err);
  510. return OK;
  511. }
  512. const RenderingContextDriver::Device &RenderingContextDriverVulkan::device_get(uint32_t p_device_index) const {
  513. DEV_ASSERT(p_device_index < driver_devices.size());
  514. return driver_devices[p_device_index];
  515. }
  516. uint32_t RenderingContextDriverVulkan::device_get_count() const {
  517. return driver_devices.size();
  518. }
  519. bool RenderingContextDriverVulkan::device_supports_present(uint32_t p_device_index, SurfaceID p_surface) const {
  520. DEV_ASSERT(p_device_index < physical_devices.size());
  521. // Check if any of the queues supported by the device supports presenting to the window's surface.
  522. const VkPhysicalDevice physical_device = physical_devices[p_device_index];
  523. const DeviceQueueFamilies &queue_families = device_queue_families[p_device_index];
  524. for (uint32_t i = 0; i < queue_families.properties.size(); i++) {
  525. if ((queue_families.properties[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) && queue_family_supports_present(physical_device, i, p_surface)) {
  526. return true;
  527. }
  528. }
  529. return false;
  530. }
  531. RenderingDeviceDriver *RenderingContextDriverVulkan::driver_create() {
  532. return memnew(RenderingDeviceDriverVulkan(this));
  533. }
  534. void RenderingContextDriverVulkan::driver_free(RenderingDeviceDriver *p_driver) {
  535. memdelete(p_driver);
  536. }
  537. RenderingContextDriver::SurfaceID RenderingContextDriverVulkan::surface_create(const void *p_platform_data) {
  538. DEV_ASSERT(false && "Surface creation should not be called on the platform-agnostic version of the driver.");
  539. return SurfaceID();
  540. }
  541. void RenderingContextDriverVulkan::surface_set_size(SurfaceID p_surface, uint32_t p_width, uint32_t p_height) {
  542. Surface *surface = (Surface *)(p_surface);
  543. surface->width = p_width;
  544. surface->height = p_height;
  545. surface->needs_resize = true;
  546. }
  547. void RenderingContextDriverVulkan::surface_set_vsync_mode(SurfaceID p_surface, DisplayServer::VSyncMode p_vsync_mode) {
  548. Surface *surface = (Surface *)(p_surface);
  549. surface->vsync_mode = p_vsync_mode;
  550. surface->needs_resize = true;
  551. }
  552. DisplayServer::VSyncMode RenderingContextDriverVulkan::surface_get_vsync_mode(SurfaceID p_surface) const {
  553. Surface *surface = (Surface *)(p_surface);
  554. return surface->vsync_mode;
  555. }
  556. uint32_t RenderingContextDriverVulkan::surface_get_width(SurfaceID p_surface) const {
  557. Surface *surface = (Surface *)(p_surface);
  558. return surface->width;
  559. }
  560. uint32_t RenderingContextDriverVulkan::surface_get_height(SurfaceID p_surface) const {
  561. Surface *surface = (Surface *)(p_surface);
  562. return surface->height;
  563. }
  564. void RenderingContextDriverVulkan::surface_set_needs_resize(SurfaceID p_surface, bool p_needs_resize) {
  565. Surface *surface = (Surface *)(p_surface);
  566. surface->needs_resize = p_needs_resize;
  567. }
  568. bool RenderingContextDriverVulkan::surface_get_needs_resize(SurfaceID p_surface) const {
  569. Surface *surface = (Surface *)(p_surface);
  570. return surface->needs_resize;
  571. }
  572. void RenderingContextDriverVulkan::surface_destroy(SurfaceID p_surface) {
  573. Surface *surface = (Surface *)(p_surface);
  574. vkDestroySurfaceKHR(instance, surface->vk_surface, nullptr);
  575. memdelete(surface);
  576. }
  577. bool RenderingContextDriverVulkan::is_debug_utils_enabled() const {
  578. return enabled_instance_extension_names.has(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
  579. }
  580. VkInstance RenderingContextDriverVulkan::instance_get() const {
  581. return instance;
  582. }
  583. VkPhysicalDevice RenderingContextDriverVulkan::physical_device_get(uint32_t p_device_index) const {
  584. DEV_ASSERT(p_device_index < physical_devices.size());
  585. return physical_devices[p_device_index];
  586. }
  587. uint32_t RenderingContextDriverVulkan::queue_family_get_count(uint32_t p_device_index) const {
  588. DEV_ASSERT(p_device_index < physical_devices.size());
  589. return device_queue_families[p_device_index].properties.size();
  590. }
  591. VkQueueFamilyProperties RenderingContextDriverVulkan::queue_family_get(uint32_t p_device_index, uint32_t p_queue_family_index) const {
  592. DEV_ASSERT(p_device_index < physical_devices.size());
  593. DEV_ASSERT(p_queue_family_index < queue_family_get_count(p_device_index));
  594. return device_queue_families[p_device_index].properties[p_queue_family_index];
  595. }
  596. bool RenderingContextDriverVulkan::queue_family_supports_present(VkPhysicalDevice p_physical_device, uint32_t p_queue_family_index, SurfaceID p_surface) const {
  597. DEV_ASSERT(p_physical_device != VK_NULL_HANDLE);
  598. DEV_ASSERT(p_surface != 0);
  599. Surface *surface = (Surface *)(p_surface);
  600. VkBool32 present_supported = false;
  601. VkResult err = vkGetPhysicalDeviceSurfaceSupportKHR(p_physical_device, p_queue_family_index, surface->vk_surface, &present_supported);
  602. return err == VK_SUCCESS && present_supported;
  603. }
  604. const RenderingContextDriverVulkan::Functions &RenderingContextDriverVulkan::functions_get() const {
  605. return functions;
  606. }
  607. #endif // VULKAN_ENABLED