rendering_device_driver_vulkan.h 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. /**************************************************************************/
  2. /* rendering_device_driver_vulkan.h */
  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. #pragma once
  31. #include "core/templates/hash_map.h"
  32. #include "core/templates/paged_allocator.h"
  33. #include "drivers/vulkan/rendering_context_driver_vulkan.h"
  34. #include "drivers/vulkan/rendering_shader_container_vulkan.h"
  35. #include "servers/rendering/rendering_device_driver.h"
  36. #ifdef DEBUG_ENABLED
  37. #ifndef _MSC_VER
  38. #define _DEBUG
  39. #endif
  40. #endif
  41. #include "thirdparty/vulkan/vk_mem_alloc.h"
  42. #include "drivers/vulkan/godot_vulkan.h"
  43. // Design principles:
  44. // - Vulkan structs are zero-initialized and fields not requiring a non-zero value are omitted (except in cases where expresivity reasons apply).
  45. class RenderingDeviceDriverVulkan : public RenderingDeviceDriver {
  46. /*****************/
  47. /**** GENERIC ****/
  48. /*****************/
  49. struct CommandQueue;
  50. struct SwapChain;
  51. struct CommandBufferInfo;
  52. struct RenderPassInfo;
  53. struct Framebuffer;
  54. struct Queue {
  55. VkQueue queue = VK_NULL_HANDLE;
  56. uint32_t virtual_count = 0;
  57. BinaryMutex submit_mutex;
  58. };
  59. struct SubgroupCapabilities {
  60. uint32_t size = 0;
  61. uint32_t min_size = 0;
  62. uint32_t max_size = 0;
  63. VkShaderStageFlags supported_stages = 0;
  64. VkSubgroupFeatureFlags supported_operations = 0;
  65. VkBool32 quad_operations_in_all_stages = false;
  66. bool size_control_is_supported = false;
  67. uint32_t supported_stages_flags_rd() const;
  68. String supported_stages_desc() const;
  69. uint32_t supported_operations_flags_rd() const;
  70. String supported_operations_desc() const;
  71. };
  72. struct ShaderCapabilities {
  73. bool shader_float16_is_supported = false;
  74. bool shader_int8_is_supported = false;
  75. };
  76. struct StorageBufferCapabilities {
  77. bool storage_buffer_16_bit_access_is_supported = false;
  78. bool uniform_and_storage_buffer_16_bit_access_is_supported = false;
  79. bool storage_push_constant_16_is_supported = false;
  80. bool storage_input_output_16 = false;
  81. };
  82. struct DeviceFunctions {
  83. PFN_vkCreateSwapchainKHR CreateSwapchainKHR = nullptr;
  84. PFN_vkDestroySwapchainKHR DestroySwapchainKHR = nullptr;
  85. PFN_vkGetSwapchainImagesKHR GetSwapchainImagesKHR = nullptr;
  86. PFN_vkAcquireNextImageKHR AcquireNextImageKHR = nullptr;
  87. PFN_vkQueuePresentKHR QueuePresentKHR = nullptr;
  88. PFN_vkCreateRenderPass2KHR CreateRenderPass2KHR = nullptr;
  89. PFN_vkCmdEndRenderPass2KHR EndRenderPass2KHR = nullptr;
  90. // Debug marker extensions.
  91. PFN_vkCmdDebugMarkerBeginEXT CmdDebugMarkerBeginEXT = nullptr;
  92. PFN_vkCmdDebugMarkerEndEXT CmdDebugMarkerEndEXT = nullptr;
  93. PFN_vkCmdDebugMarkerInsertEXT CmdDebugMarkerInsertEXT = nullptr;
  94. PFN_vkDebugMarkerSetObjectNameEXT DebugMarkerSetObjectNameEXT = nullptr;
  95. // Debug device fault.
  96. PFN_vkGetDeviceFaultInfoEXT GetDeviceFaultInfoEXT = nullptr;
  97. };
  98. // Debug marker extensions.
  99. VkDebugReportObjectTypeEXT _convert_to_debug_report_objectType(VkObjectType p_object_type);
  100. VkDevice vk_device = VK_NULL_HANDLE;
  101. RenderingContextDriverVulkan *context_driver = nullptr;
  102. RenderingContextDriver::Device context_device = {};
  103. uint32_t frame_count = 1;
  104. VkPhysicalDevice physical_device = VK_NULL_HANDLE;
  105. VkPhysicalDeviceProperties physical_device_properties = {};
  106. VkPhysicalDeviceFeatures physical_device_features = {};
  107. VkPhysicalDeviceFeatures requested_device_features = {};
  108. HashMap<CharString, bool> requested_device_extensions;
  109. HashSet<CharString> enabled_device_extension_names;
  110. TightLocalVector<TightLocalVector<Queue>> queue_families;
  111. TightLocalVector<VkQueueFamilyProperties> queue_family_properties;
  112. RDD::Capabilities device_capabilities;
  113. SubgroupCapabilities subgroup_capabilities;
  114. MultiviewCapabilities multiview_capabilities;
  115. FragmentShadingRateCapabilities fsr_capabilities;
  116. FragmentDensityMapCapabilities fdm_capabilities;
  117. ShaderCapabilities shader_capabilities;
  118. StorageBufferCapabilities storage_buffer_capabilities;
  119. RenderingShaderContainerFormatVulkan shader_container_format;
  120. bool buffer_device_address_support = false;
  121. bool vulkan_memory_model_support = false;
  122. bool vulkan_memory_model_device_scope_support = false;
  123. bool pipeline_cache_control_support = false;
  124. bool device_fault_support = false;
  125. #if defined(VK_TRACK_DEVICE_MEMORY)
  126. bool device_memory_report_support = false;
  127. #endif
  128. #if defined(SWAPPY_FRAME_PACING_ENABLED)
  129. // Swappy frame pacer for Android.
  130. bool swappy_frame_pacer_enable = false;
  131. uint8_t swappy_mode = 2; // See default value for display/window/frame_pacing/android/swappy_mode.
  132. #endif
  133. DeviceFunctions device_functions;
  134. void _register_requested_device_extension(const CharString &p_extension_name, bool p_required);
  135. Error _initialize_device_extensions();
  136. Error _check_device_features();
  137. Error _check_device_capabilities();
  138. void _choose_vrs_capabilities();
  139. Error _add_queue_create_info(LocalVector<VkDeviceQueueCreateInfo> &r_queue_create_info);
  140. Error _initialize_device(const LocalVector<VkDeviceQueueCreateInfo> &p_queue_create_info);
  141. Error _initialize_allocator();
  142. Error _initialize_pipeline_cache();
  143. VkResult _create_render_pass(VkDevice p_device, const VkRenderPassCreateInfo2 *p_create_info, const VkAllocationCallbacks *p_allocator, VkRenderPass *p_render_pass);
  144. bool _release_image_semaphore(CommandQueue *p_command_queue, uint32_t p_semaphore_index, bool p_release_on_swap_chain);
  145. bool _recreate_image_semaphore(CommandQueue *p_command_queue, uint32_t p_semaphore_index, bool p_release_on_swap_chain);
  146. void _set_object_name(VkObjectType p_object_type, uint64_t p_object_handle, String p_object_name);
  147. public:
  148. Error initialize(uint32_t p_device_index, uint32_t p_frame_count) override final;
  149. private:
  150. /****************/
  151. /**** MEMORY ****/
  152. /****************/
  153. VmaAllocator allocator = nullptr;
  154. HashMap<uint32_t, VmaPool> small_allocs_pools;
  155. VmaPool _find_or_create_small_allocs_pool(uint32_t p_mem_type_index);
  156. private:
  157. #if defined(DEBUG_ENABLED) || defined(DEV_ENABLED)
  158. // It's a circular buffer.
  159. BufferID breadcrumb_buffer;
  160. uint32_t breadcrumb_offset = 0u;
  161. uint32_t breadcrumb_id = 0u;
  162. #endif
  163. public:
  164. /*****************/
  165. /**** BUFFERS ****/
  166. /*****************/
  167. struct BufferInfo {
  168. VkBuffer vk_buffer = VK_NULL_HANDLE;
  169. struct {
  170. VmaAllocation handle = nullptr;
  171. uint64_t size = UINT64_MAX;
  172. } allocation;
  173. uint64_t size = 0;
  174. VkBufferView vk_view = VK_NULL_HANDLE; // For texel buffers.
  175. };
  176. virtual BufferID buffer_create(uint64_t p_size, BitField<BufferUsageBits> p_usage, MemoryAllocationType p_allocation_type) override final;
  177. virtual bool buffer_set_texel_format(BufferID p_buffer, DataFormat p_format) override final;
  178. virtual void buffer_free(BufferID p_buffer) override final;
  179. virtual uint64_t buffer_get_allocation_size(BufferID p_buffer) override final;
  180. virtual uint8_t *buffer_map(BufferID p_buffer) override final;
  181. virtual void buffer_unmap(BufferID p_buffer) override final;
  182. virtual uint64_t buffer_get_device_address(BufferID p_buffer) override final;
  183. /*****************/
  184. /**** TEXTURE ****/
  185. /*****************/
  186. struct TextureInfo {
  187. VkImage vk_image = VK_NULL_HANDLE;
  188. VkImageView vk_view = VK_NULL_HANDLE;
  189. DataFormat rd_format = DATA_FORMAT_MAX;
  190. VkImageCreateInfo vk_create_info = {};
  191. VkImageViewCreateInfo vk_view_create_info = {};
  192. struct {
  193. VmaAllocation handle = nullptr;
  194. VmaAllocationInfo info = {};
  195. } allocation; // All 0/null if just a view.
  196. #ifdef DEBUG_ENABLED
  197. bool created_from_extension = false;
  198. bool transient = false;
  199. #endif
  200. };
  201. VkSampleCountFlagBits _ensure_supported_sample_count(TextureSamples p_requested_sample_count);
  202. public:
  203. virtual TextureID texture_create(const TextureFormat &p_format, const TextureView &p_view) override final;
  204. virtual TextureID texture_create_from_extension(uint64_t p_native_texture, TextureType p_type, DataFormat p_format, uint32_t p_array_layers, bool p_depth_stencil, uint32_t p_mipmaps) override final;
  205. virtual TextureID texture_create_shared(TextureID p_original_texture, const TextureView &p_view) override final;
  206. virtual TextureID texture_create_shared_from_slice(TextureID p_original_texture, const TextureView &p_view, TextureSliceType p_slice_type, uint32_t p_layer, uint32_t p_layers, uint32_t p_mipmap, uint32_t p_mipmaps) override final;
  207. virtual void texture_free(TextureID p_texture) override final;
  208. virtual uint64_t texture_get_allocation_size(TextureID p_texture) override final;
  209. virtual void texture_get_copyable_layout(TextureID p_texture, const TextureSubresource &p_subresource, TextureCopyableLayout *r_layout) override final;
  210. virtual uint8_t *texture_map(TextureID p_texture, const TextureSubresource &p_subresource) override final;
  211. virtual void texture_unmap(TextureID p_texture) override final;
  212. virtual BitField<TextureUsageBits> texture_get_usages_supported_by_format(DataFormat p_format, bool p_cpu_readable) override final;
  213. virtual bool texture_can_make_shared_with_format(TextureID p_texture, DataFormat p_format, bool &r_raw_reinterpretation) override final;
  214. /*****************/
  215. /**** SAMPLER ****/
  216. /*****************/
  217. public:
  218. virtual SamplerID sampler_create(const SamplerState &p_state) final override;
  219. virtual void sampler_free(SamplerID p_sampler) final override;
  220. virtual bool sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_filter) override final;
  221. /**********************/
  222. /**** VERTEX ARRAY ****/
  223. /**********************/
  224. private:
  225. struct VertexFormatInfo {
  226. TightLocalVector<VkVertexInputBindingDescription> vk_bindings;
  227. TightLocalVector<VkVertexInputAttributeDescription> vk_attributes;
  228. VkPipelineVertexInputStateCreateInfo vk_create_info = {};
  229. };
  230. public:
  231. virtual VertexFormatID vertex_format_create(VectorView<VertexAttribute> p_vertex_attribs) override final;
  232. virtual void vertex_format_free(VertexFormatID p_vertex_format) override final;
  233. /******************/
  234. /**** BARRIERS ****/
  235. /******************/
  236. virtual void command_pipeline_barrier(
  237. CommandBufferID p_cmd_buffer,
  238. BitField<PipelineStageBits> p_src_stages,
  239. BitField<PipelineStageBits> p_dst_stages,
  240. VectorView<MemoryAccessBarrier> p_memory_barriers,
  241. VectorView<BufferBarrier> p_buffer_barriers,
  242. VectorView<TextureBarrier> p_texture_barriers) override final;
  243. /****************/
  244. /**** FENCES ****/
  245. /****************/
  246. private:
  247. struct Fence {
  248. VkFence vk_fence = VK_NULL_HANDLE;
  249. CommandQueue *queue_signaled_from = nullptr;
  250. };
  251. public:
  252. virtual FenceID fence_create() override final;
  253. virtual Error fence_wait(FenceID p_fence) override final;
  254. virtual void fence_free(FenceID p_fence) override final;
  255. /********************/
  256. /**** SEMAPHORES ****/
  257. /********************/
  258. virtual SemaphoreID semaphore_create() override final;
  259. virtual void semaphore_free(SemaphoreID p_semaphore) override final;
  260. /******************/
  261. /**** COMMANDS ****/
  262. /******************/
  263. // ----- QUEUE FAMILY -----
  264. virtual CommandQueueFamilyID command_queue_family_get(BitField<CommandQueueFamilyBits> p_cmd_queue_family_bits, RenderingContextDriver::SurfaceID p_surface = 0) override final;
  265. // ----- QUEUE -----
  266. private:
  267. struct CommandQueue {
  268. LocalVector<VkSemaphore> image_semaphores;
  269. LocalVector<SwapChain *> image_semaphores_swap_chains;
  270. LocalVector<uint32_t> pending_semaphores_for_execute;
  271. LocalVector<uint32_t> pending_semaphores_for_fence;
  272. LocalVector<uint32_t> free_image_semaphores;
  273. LocalVector<Pair<Fence *, uint32_t>> image_semaphores_for_fences;
  274. uint32_t queue_family = 0;
  275. uint32_t queue_index = 0;
  276. };
  277. public:
  278. virtual CommandQueueID command_queue_create(CommandQueueFamilyID p_cmd_queue_family, bool p_identify_as_main_queue = false) override final;
  279. virtual Error command_queue_execute_and_present(CommandQueueID p_cmd_queue, VectorView<SemaphoreID> p_wait_semaphores, VectorView<CommandBufferID> p_cmd_buffers, VectorView<SemaphoreID> p_cmd_semaphores, FenceID p_cmd_fence, VectorView<SwapChainID> p_swap_chains) override final;
  280. virtual void command_queue_free(CommandQueueID p_cmd_queue) override final;
  281. private:
  282. // ----- POOL -----
  283. struct CommandPool {
  284. VkCommandPool vk_command_pool = VK_NULL_HANDLE;
  285. CommandBufferType buffer_type = COMMAND_BUFFER_TYPE_PRIMARY;
  286. LocalVector<CommandBufferInfo *> command_buffers_created;
  287. };
  288. public:
  289. virtual CommandPoolID command_pool_create(CommandQueueFamilyID p_cmd_queue_family, CommandBufferType p_cmd_buffer_type) override final;
  290. virtual bool command_pool_reset(CommandPoolID p_cmd_pool) override final;
  291. virtual void command_pool_free(CommandPoolID p_cmd_pool) override final;
  292. private:
  293. // ----- BUFFER -----
  294. struct CommandBufferInfo {
  295. VkCommandBuffer vk_command_buffer = VK_NULL_HANDLE;
  296. Framebuffer *active_framebuffer = nullptr;
  297. RenderPassInfo *active_render_pass = nullptr;
  298. };
  299. public:
  300. virtual CommandBufferID command_buffer_create(CommandPoolID p_cmd_pool) override final;
  301. virtual bool command_buffer_begin(CommandBufferID p_cmd_buffer) override final;
  302. virtual bool command_buffer_begin_secondary(CommandBufferID p_cmd_buffer, RenderPassID p_render_pass, uint32_t p_subpass, FramebufferID p_framebuffer) override final;
  303. virtual void command_buffer_end(CommandBufferID p_cmd_buffer) override final;
  304. virtual void command_buffer_execute_secondary(CommandBufferID p_cmd_buffer, VectorView<CommandBufferID> p_secondary_cmd_buffers) override final;
  305. /********************/
  306. /**** SWAP CHAIN ****/
  307. /********************/
  308. private:
  309. struct SwapChain {
  310. VkSwapchainKHR vk_swapchain = VK_NULL_HANDLE;
  311. RenderingContextDriver::SurfaceID surface = RenderingContextDriver::SurfaceID();
  312. VkFormat format = VK_FORMAT_UNDEFINED;
  313. VkColorSpaceKHR color_space = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
  314. TightLocalVector<VkImage> images;
  315. TightLocalVector<VkImageView> image_views;
  316. TightLocalVector<VkSemaphore> present_semaphores;
  317. TightLocalVector<FramebufferID> framebuffers;
  318. LocalVector<CommandQueue *> command_queues_acquired;
  319. LocalVector<uint32_t> command_queues_acquired_semaphores;
  320. RenderPassID render_pass;
  321. int pre_transform_rotation_degrees = 0;
  322. uint32_t image_index = 0;
  323. #ifdef ANDROID_ENABLED
  324. uint64_t refresh_duration = 0;
  325. #endif
  326. };
  327. void _swap_chain_release(SwapChain *p_swap_chain);
  328. public:
  329. virtual SwapChainID swap_chain_create(RenderingContextDriver::SurfaceID p_surface) override final;
  330. virtual Error swap_chain_resize(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, uint32_t p_desired_framebuffer_count) override final;
  331. virtual FramebufferID swap_chain_acquire_framebuffer(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, bool &r_resize_required) override final;
  332. virtual RenderPassID swap_chain_get_render_pass(SwapChainID p_swap_chain) override final;
  333. virtual int swap_chain_get_pre_rotation_degrees(SwapChainID p_swap_chain) override final;
  334. virtual DataFormat swap_chain_get_format(SwapChainID p_swap_chain) override final;
  335. virtual void swap_chain_set_max_fps(SwapChainID p_swap_chain, int p_max_fps) override final;
  336. virtual void swap_chain_free(SwapChainID p_swap_chain) override final;
  337. private:
  338. /*********************/
  339. /**** FRAMEBUFFER ****/
  340. /*********************/
  341. struct Framebuffer {
  342. VkFramebuffer vk_framebuffer = VK_NULL_HANDLE;
  343. // Only filled in if the framebuffer uses a fragment density map with offsets. Unused otherwise.
  344. uint32_t fragment_density_map_offsets_layers = 0;
  345. // Only filled in by a framebuffer created by a swap chain. Unused otherwise.
  346. VkImage swap_chain_image = VK_NULL_HANDLE;
  347. VkImageSubresourceRange swap_chain_image_subresource_range = {};
  348. bool swap_chain_acquired = false;
  349. };
  350. public:
  351. virtual FramebufferID framebuffer_create(RenderPassID p_render_pass, VectorView<TextureID> p_attachments, uint32_t p_width, uint32_t p_height) override final;
  352. virtual void framebuffer_free(FramebufferID p_framebuffer) override final;
  353. /****************/
  354. /**** SHADER ****/
  355. /****************/
  356. private:
  357. struct ShaderInfo {
  358. VkShaderStageFlags vk_push_constant_stages = 0;
  359. TightLocalVector<VkPipelineShaderStageCreateInfo> vk_stages_create_info;
  360. TightLocalVector<VkDescriptorSetLayout> vk_descriptor_set_layouts;
  361. VkPipelineLayout vk_pipeline_layout = VK_NULL_HANDLE;
  362. };
  363. public:
  364. virtual ShaderID shader_create_from_container(const Ref<RenderingShaderContainer> &p_shader_container, const Vector<ImmutableSampler> &p_immutable_samplers) override final;
  365. virtual void shader_free(ShaderID p_shader) override final;
  366. virtual void shader_destroy_modules(ShaderID p_shader) override final;
  367. /*********************/
  368. /**** UNIFORM SET ****/
  369. /*********************/
  370. // Descriptor sets require allocation from a pool.
  371. // The documentation on how to use pools properly
  372. // is scarce, and the documentation is strange.
  373. //
  374. // Basically, you can mix and match pools as you
  375. // like, but you'll run into fragmentation issues.
  376. // Because of this, the recommended approach is to
  377. // create a pool for every descriptor set type, as
  378. // this prevents fragmentation.
  379. //
  380. // This is implemented here as a having a list of
  381. // pools (each can contain up to 64 sets) for each
  382. // set layout. The amount of sets for each type
  383. // is used as the key.
  384. private:
  385. static const uint32_t MAX_UNIFORM_POOL_ELEMENT = 65535;
  386. struct DescriptorSetPoolKey {
  387. uint16_t uniform_type[UNIFORM_TYPE_MAX] = {};
  388. bool operator<(const DescriptorSetPoolKey &p_other) const {
  389. return memcmp(uniform_type, p_other.uniform_type, sizeof(uniform_type)) < 0;
  390. }
  391. };
  392. using DescriptorSetPools = RBMap<DescriptorSetPoolKey, HashMap<VkDescriptorPool, uint32_t>>;
  393. DescriptorSetPools descriptor_set_pools;
  394. uint32_t max_descriptor_sets_per_pool = 0;
  395. HashMap<int, DescriptorSetPools> linear_descriptor_set_pools;
  396. bool linear_descriptor_pools_enabled = true;
  397. VkDescriptorPool _descriptor_set_pool_find_or_create(const DescriptorSetPoolKey &p_key, DescriptorSetPools::Iterator *r_pool_sets_it, int p_linear_pool_index);
  398. void _descriptor_set_pool_unreference(DescriptorSetPools::Iterator p_pool_sets_it, VkDescriptorPool p_vk_descriptor_pool, int p_linear_pool_index);
  399. // Global flag to toggle usage of immutable sampler when creating pipeline layouts.
  400. // It cannot change after creating the PSOs, since we need to skipping samplers when creating uniform sets.
  401. bool immutable_samplers_enabled = true;
  402. struct UniformSetInfo {
  403. VkDescriptorSet vk_descriptor_set = VK_NULL_HANDLE;
  404. VkDescriptorPool vk_descriptor_pool = VK_NULL_HANDLE;
  405. VkDescriptorPool vk_linear_descriptor_pool = VK_NULL_HANDLE;
  406. DescriptorSetPools::Iterator pool_sets_it;
  407. };
  408. public:
  409. virtual UniformSetID uniform_set_create(VectorView<BoundUniform> p_uniforms, ShaderID p_shader, uint32_t p_set_index, int p_linear_pool_index) override final;
  410. virtual void linear_uniform_set_pools_reset(int p_linear_pool_index) override final;
  411. virtual void uniform_set_free(UniformSetID p_uniform_set) override final;
  412. virtual bool uniform_sets_have_linear_pools() const override final;
  413. // ----- COMMANDS -----
  414. virtual void command_uniform_set_prepare_for_use(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) override final;
  415. /******************/
  416. /**** TRANSFER ****/
  417. /******************/
  418. virtual void command_clear_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, uint64_t p_offset, uint64_t p_size) override final;
  419. virtual void command_copy_buffer(CommandBufferID p_cmd_buffer, BufferID p_src_buffer, BufferID p_dst_buffer, VectorView<BufferCopyRegion> p_regions) override final;
  420. virtual void command_copy_texture(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, VectorView<TextureCopyRegion> p_regions) override final;
  421. virtual void command_resolve_texture(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, uint32_t p_src_layer, uint32_t p_src_mipmap, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, uint32_t p_dst_layer, uint32_t p_dst_mipmap) override final;
  422. virtual void command_clear_color_texture(CommandBufferID p_cmd_buffer, TextureID p_texture, TextureLayout p_texture_layout, const Color &p_color, const TextureSubresourceRange &p_subresources) override final;
  423. virtual void command_copy_buffer_to_texture(CommandBufferID p_cmd_buffer, BufferID p_src_buffer, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, VectorView<BufferTextureCopyRegion> p_regions) override final;
  424. virtual void command_copy_texture_to_buffer(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, BufferID p_dst_buffer, VectorView<BufferTextureCopyRegion> p_regions) override final;
  425. /******************/
  426. /**** PIPELINE ****/
  427. /******************/
  428. private:
  429. struct PipelineCacheHeader {
  430. uint32_t magic = 0;
  431. uint32_t data_size = 0;
  432. uint64_t data_hash = 0;
  433. uint32_t vendor_id = 0;
  434. uint32_t device_id = 0;
  435. uint32_t driver_version = 0;
  436. uint8_t uuid[VK_UUID_SIZE] = {};
  437. uint8_t driver_abi = 0;
  438. };
  439. struct PipelineCache {
  440. String file_path;
  441. size_t current_size = 0;
  442. Vector<uint8_t> buffer; // Header then data.
  443. VkPipelineCache vk_cache = VK_NULL_HANDLE;
  444. };
  445. static int caching_instance_count;
  446. PipelineCache pipelines_cache;
  447. String pipeline_cache_id;
  448. HashMap<uint64_t, bool> has_comp_alpha;
  449. public:
  450. virtual void pipeline_free(PipelineID p_pipeline) override final;
  451. // ----- BINDING -----
  452. virtual void command_bind_push_constants(CommandBufferID p_cmd_buffer, ShaderID p_shader, uint32_t p_first_index, VectorView<uint32_t> p_data) override final;
  453. // ----- CACHE -----
  454. virtual bool pipeline_cache_create(const Vector<uint8_t> &p_data) override final;
  455. virtual void pipeline_cache_free() override final;
  456. virtual size_t pipeline_cache_query_size() override final;
  457. virtual Vector<uint8_t> pipeline_cache_serialize() override final;
  458. /*******************/
  459. /**** RENDERING ****/
  460. /*******************/
  461. private:
  462. // ----- SUBPASS -----
  463. struct RenderPassInfo {
  464. VkRenderPass vk_render_pass = VK_NULL_HANDLE;
  465. bool uses_fragment_density_map_offsets = false;
  466. };
  467. public:
  468. virtual RenderPassID render_pass_create(VectorView<Attachment> p_attachments, VectorView<Subpass> p_subpasses, VectorView<SubpassDependency> p_subpass_dependencies, uint32_t p_view_count, AttachmentReference p_fragment_density_map_attachment) override final;
  469. virtual void render_pass_free(RenderPassID p_render_pass) override final;
  470. // ----- COMMANDS -----
  471. virtual void command_begin_render_pass(CommandBufferID p_cmd_buffer, RenderPassID p_render_pass, FramebufferID p_framebuffer, CommandBufferType p_cmd_buffer_type, const Rect2i &p_rect, VectorView<RenderPassClearValue> p_clear_values) override final;
  472. virtual void command_end_render_pass(CommandBufferID p_cmd_buffer) override final;
  473. virtual void command_next_render_subpass(CommandBufferID p_cmd_buffer, CommandBufferType p_cmd_buffer_type) override final;
  474. virtual void command_render_set_viewport(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_viewports) override final;
  475. virtual void command_render_set_scissor(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_scissors) override final;
  476. virtual void command_render_clear_attachments(CommandBufferID p_cmd_buffer, VectorView<AttachmentClear> p_attachment_clears, VectorView<Rect2i> p_rects) override final;
  477. // Binding.
  478. virtual void command_bind_render_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) override final;
  479. virtual void command_bind_render_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) override final;
  480. virtual void command_bind_render_uniform_sets(CommandBufferID p_cmd_buffer, VectorView<UniformSetID> p_uniform_sets, ShaderID p_shader, uint32_t p_first_set_index, uint32_t p_set_count) override final;
  481. // Drawing.
  482. virtual void command_render_draw(CommandBufferID p_cmd_buffer, uint32_t p_vertex_count, uint32_t p_instance_count, uint32_t p_base_vertex, uint32_t p_first_instance) override final;
  483. virtual void command_render_draw_indexed(CommandBufferID p_cmd_buffer, uint32_t p_index_count, uint32_t p_instance_count, uint32_t p_first_index, int32_t p_vertex_offset, uint32_t p_first_instance) override final;
  484. virtual void command_render_draw_indexed_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride) override final;
  485. virtual void command_render_draw_indexed_indirect_count(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, BufferID p_count_buffer, uint64_t p_count_buffer_offset, uint32_t p_max_draw_count, uint32_t p_stride) override final;
  486. virtual void command_render_draw_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride) override final;
  487. virtual void command_render_draw_indirect_count(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, BufferID p_count_buffer, uint64_t p_count_buffer_offset, uint32_t p_max_draw_count, uint32_t p_stride) override final;
  488. // Buffer binding.
  489. virtual void command_render_bind_vertex_buffers(CommandBufferID p_cmd_buffer, uint32_t p_binding_count, const BufferID *p_buffers, const uint64_t *p_offsets) override final;
  490. virtual void command_render_bind_index_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, IndexBufferFormat p_format, uint64_t p_offset) override final;
  491. // Dynamic state.
  492. virtual void command_render_set_blend_constants(CommandBufferID p_cmd_buffer, const Color &p_constants) override final;
  493. virtual void command_render_set_line_width(CommandBufferID p_cmd_buffer, float p_width) override final;
  494. // ----- PIPELINE -----
  495. virtual PipelineID render_pipeline_create(
  496. ShaderID p_shader,
  497. VertexFormatID p_vertex_format,
  498. RenderPrimitive p_render_primitive,
  499. PipelineRasterizationState p_rasterization_state,
  500. PipelineMultisampleState p_multisample_state,
  501. PipelineDepthStencilState p_depth_stencil_state,
  502. PipelineColorBlendState p_blend_state,
  503. VectorView<int32_t> p_color_attachments,
  504. BitField<PipelineDynamicStateFlags> p_dynamic_state,
  505. RenderPassID p_render_pass,
  506. uint32_t p_render_subpass,
  507. VectorView<PipelineSpecializationConstant> p_specialization_constants) override final;
  508. /*****************/
  509. /**** COMPUTE ****/
  510. /*****************/
  511. // ----- COMMANDS -----
  512. // Binding.
  513. virtual void command_bind_compute_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) override final;
  514. virtual void command_bind_compute_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) override final;
  515. virtual void command_bind_compute_uniform_sets(CommandBufferID p_cmd_buffer, VectorView<UniformSetID> p_uniform_sets, ShaderID p_shader, uint32_t p_first_set_index, uint32_t p_set_count) override final;
  516. // Dispatching.
  517. virtual void command_compute_dispatch(CommandBufferID p_cmd_buffer, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) override final;
  518. virtual void command_compute_dispatch_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset) override final;
  519. // ----- PIPELINE -----
  520. virtual PipelineID compute_pipeline_create(ShaderID p_shader, VectorView<PipelineSpecializationConstant> p_specialization_constants) override final;
  521. /*****************/
  522. /**** QUERIES ****/
  523. /*****************/
  524. // ----- TIMESTAMP -----
  525. // Basic.
  526. virtual QueryPoolID timestamp_query_pool_create(uint32_t p_query_count) override final;
  527. virtual void timestamp_query_pool_free(QueryPoolID p_pool_id) override final;
  528. virtual void timestamp_query_pool_get_results(QueryPoolID p_pool_id, uint32_t p_query_count, uint64_t *r_results) override final;
  529. virtual uint64_t timestamp_query_result_to_time(uint64_t p_result) override final;
  530. // Commands.
  531. virtual void command_timestamp_query_pool_reset(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_query_count) override final;
  532. virtual void command_timestamp_write(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_index) override final;
  533. /****************/
  534. /**** LABELS ****/
  535. /****************/
  536. virtual void command_begin_label(CommandBufferID p_cmd_buffer, const char *p_label_name, const Color &p_color) override final;
  537. virtual void command_end_label(CommandBufferID p_cmd_buffer) override final;
  538. /****************/
  539. /**** DEBUG *****/
  540. /****************/
  541. virtual void command_insert_breadcrumb(CommandBufferID p_cmd_buffer, uint32_t p_data) override final;
  542. void print_lost_device_info();
  543. void on_device_lost() const;
  544. static String get_vulkan_result(VkResult err);
  545. /********************/
  546. /**** SUBMISSION ****/
  547. /********************/
  548. virtual void begin_segment(uint32_t p_frame_index, uint32_t p_frames_drawn) override final;
  549. virtual void end_segment() override final;
  550. /**************/
  551. /**** MISC ****/
  552. /**************/
  553. virtual void set_object_name(ObjectType p_type, ID p_driver_id, const String &p_name) override final;
  554. virtual uint64_t get_resource_native_handle(DriverResource p_type, ID p_driver_id) override final;
  555. virtual uint64_t get_total_memory_used() override final;
  556. virtual uint64_t get_lazily_memory_used() override final;
  557. virtual uint64_t limit_get(Limit p_limit) override final;
  558. virtual uint64_t api_trait_get(ApiTrait p_trait) override final;
  559. virtual bool has_feature(Features p_feature) override final;
  560. virtual const MultiviewCapabilities &get_multiview_capabilities() override final;
  561. virtual const FragmentShadingRateCapabilities &get_fragment_shading_rate_capabilities() override final;
  562. virtual const FragmentDensityMapCapabilities &get_fragment_density_map_capabilities() override final;
  563. virtual String get_api_name() const override final;
  564. virtual String get_api_version() const override final;
  565. virtual String get_pipeline_cache_uuid() const override final;
  566. virtual const Capabilities &get_capabilities() const override final;
  567. virtual const RenderingShaderContainerFormat &get_shader_container_format() const override final;
  568. virtual bool is_composite_alpha_supported(CommandQueueID p_queue) const override final;
  569. private:
  570. /*********************/
  571. /**** BOOKKEEPING ****/
  572. /*********************/
  573. using VersatileResource = VersatileResourceTemplate<
  574. BufferInfo,
  575. TextureInfo,
  576. VertexFormatInfo,
  577. ShaderInfo,
  578. UniformSetInfo,
  579. RenderPassInfo,
  580. CommandBufferInfo>;
  581. PagedAllocator<VersatileResource, true> resources_allocator;
  582. /******************/
  583. public:
  584. RenderingDeviceDriverVulkan(RenderingContextDriverVulkan *p_context_driver);
  585. virtual ~RenderingDeviceDriverVulkan();
  586. };
  587. using VKC = RenderingContextDriverVulkan;