rendering_device_vulkan.h 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  1. /*************************************************************************/
  2. /* rendering_device_vulkan.h */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  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. #ifndef RENDERING_DEVICE_VULKAN_H
  31. #define RENDERING_DEVICE_VULKAN_H
  32. #include "core/oa_hash_map.h"
  33. #include "core/os/thread_safe.h"
  34. #include "core/rid_owner.h"
  35. #include "servers/visual/rendering_device.h"
  36. #ifdef DEBUG_ENABLED
  37. #define _DEBUG
  38. #endif
  39. #include "vk_mem_alloc.h"
  40. #include <vulkan/vulkan.h>
  41. //todo:
  42. //compute
  43. //push constants
  44. //views of texture slices
  45. class VulkanContext;
  46. class RenderingDeviceVulkan : public RenderingDevice {
  47. _THREAD_SAFE_CLASS_
  48. // Miscellaneous tables that map
  49. // our enums to enums used
  50. // by vulkan.
  51. VkPhysicalDeviceLimits limits;
  52. static const VkFormat vulkan_formats[DATA_FORMAT_MAX];
  53. static const char *named_formats[DATA_FORMAT_MAX];
  54. static const VkCompareOp compare_operators[COMPARE_OP_MAX];
  55. static const VkStencilOp stencil_operations[STENCIL_OP_MAX];
  56. static const VkSampleCountFlagBits rasterization_sample_count[TEXTURE_SAMPLES_MAX];
  57. static const VkLogicOp logic_operations[RenderingDevice::LOGIC_OP_MAX];
  58. static const VkBlendFactor blend_factors[RenderingDevice::BLEND_FACTOR_MAX];
  59. static const VkBlendOp blend_operations[RenderingDevice::BLEND_OP_MAX];
  60. static const VkSamplerAddressMode address_modes[SAMPLER_REPEAT_MODE_MAX];
  61. static const VkBorderColor sampler_border_colors[SAMPLER_BORDER_COLOR_MAX];
  62. static const VkImageType vulkan_image_type[TEXTURE_TYPE_MAX];
  63. // Functions used for format
  64. // validation, and ensures the
  65. // user passes valid data.
  66. static int get_format_vertex_size(DataFormat p_format);
  67. static uint32_t get_image_format_pixel_size(DataFormat p_format);
  68. static void get_compressed_image_format_block_dimensions(DataFormat p_format, uint32_t &r_w, uint32_t &r_h);
  69. uint32_t get_compressed_image_format_block_byte_size(DataFormat p_format);
  70. static uint32_t get_compressed_image_format_pixel_rshift(DataFormat p_format);
  71. static uint32_t get_image_format_required_size(DataFormat p_format, uint32_t p_width, uint32_t p_height, uint32_t p_depth, uint32_t p_mipmaps, uint32_t *r_blockw = NULL, uint32_t *r_blockh = NULL, uint32_t *r_depth = NULL);
  72. static uint32_t get_image_required_mipmaps(uint32_t p_width, uint32_t p_height, uint32_t p_depth);
  73. static bool format_has_stencil(DataFormat p_format);
  74. /***************************/
  75. /**** ID INFRASTRUCTURE ****/
  76. /***************************/
  77. enum IDType {
  78. ID_TYPE_FRAMEBUFFER_FORMAT,
  79. ID_TYPE_VERTEX_FORMAT,
  80. ID_TYPE_DRAW_LIST,
  81. ID_TYPE_SPLIT_DRAW_LIST,
  82. ID_TYPE_COMPUTE_LIST,
  83. ID_TYPE_MAX,
  84. ID_BASE_SHIFT = 58 //5 bits for ID types
  85. };
  86. VkDevice device;
  87. Map<RID, Set<RID> > dependency_map; //IDs to IDs that depend on it
  88. Map<RID, Set<RID> > reverse_dependency_map; //same as above, but in reverse
  89. void _add_dependency(RID p_id, RID p_depends_on);
  90. void _free_dependencies(RID p_id);
  91. /*****************/
  92. /**** TEXTURE ****/
  93. /*****************/
  94. // In Vulkan, the concept of textures does not exist,
  95. // intead there is the image (the memory prety much,
  96. // the view (how the memory is interpreted) and the
  97. // sampler (how it's sampled from the shader).
  98. //
  99. // Texture here includes the first two stages, but
  100. // It's possible to create textures sharing the image
  101. // but with different views. The main use case for this
  102. // is textures that can be read as both SRGB/Linear,
  103. // or slices of a texture (a mipmap, a layer, a 3D slice)
  104. // for a framebuffer to render into it.
  105. struct Texture {
  106. VkImage image;
  107. VmaAllocation allocation;
  108. VmaAllocationInfo allocation_info;
  109. VkImageView view;
  110. TextureType type;
  111. DataFormat format;
  112. TextureSamples samples;
  113. uint32_t width;
  114. uint32_t height;
  115. uint32_t depth;
  116. uint32_t layers;
  117. uint32_t mipmaps;
  118. uint32_t usage_flags;
  119. Vector<DataFormat> allowed_shared_formats;
  120. VkImageLayout layout;
  121. uint32_t read_aspect_mask;
  122. uint32_t barrier_aspect_mask;
  123. bool bound; //bound to framebffer
  124. RID owner;
  125. };
  126. RID_Owner<Texture, true> texture_owner;
  127. uint32_t texture_upload_region_size_px;
  128. Vector<uint8_t> _texture_get_data_from_image(Texture *tex, VkImage p_image, VmaAllocation p_allocation, uint32_t p_layer, bool p_2d = false);
  129. /*****************/
  130. /**** SAMPLER ****/
  131. /*****************/
  132. RID_Owner<VkSampler> sampler_owner;
  133. /***************************/
  134. /**** BUFFER MANAGEMENT ****/
  135. /***************************/
  136. // These are temporary buffers on CPU memory that hold
  137. // the information until the CPU fetches it and places it
  138. // either on GPU buffers, or images (textures). It ensures
  139. // updates are properly synchronized with whathever the
  140. // GPU is doing.
  141. //
  142. // The logic here is as follows, only 3 of these
  143. // blocks are created at the beginning (one per frame)
  144. // they can each belong to a frame (assigned to current when
  145. // used) and they can only be reused after the same frame is
  146. // recycled.
  147. //
  148. // When CPU requires to allocate more than what is available,
  149. // more of these buffers are created. If a limit is reached,
  150. // then a fence will ensure will wait for blocks allocated
  151. // in previous frames are processed. If that fails, then
  152. // another fence will ensure everything pending for the current
  153. // frame is processed (effectively stalling).
  154. //
  155. // See the comments in the code to understand better how it works.
  156. struct StagingBufferBlock {
  157. VkBuffer buffer;
  158. VmaAllocation allocation;
  159. uint64_t frame_used;
  160. uint32_t fill_amount;
  161. };
  162. Vector<StagingBufferBlock> staging_buffer_blocks;
  163. int staging_buffer_current;
  164. uint32_t staging_buffer_block_size;
  165. uint64_t staging_buffer_max_size;
  166. bool staging_buffer_used;
  167. Error _staging_buffer_allocate(uint32_t p_amount, uint32_t p_required_align, uint32_t &r_alloc_offset, uint32_t &r_alloc_size, bool p_can_segment = true, bool p_on_draw_command_buffer = false);
  168. Error _insert_staging_block();
  169. struct Buffer {
  170. uint32_t size;
  171. VkBuffer buffer;
  172. VmaAllocation allocation;
  173. VkDescriptorBufferInfo buffer_info; //used for binding
  174. Buffer() {
  175. size = 0;
  176. buffer = NULL;
  177. allocation = NULL;
  178. }
  179. };
  180. Error _buffer_allocate(Buffer *p_buffer, uint32_t p_size, uint32_t p_usage, VmaMemoryUsage p_mapping);
  181. Error _buffer_free(Buffer *p_buffer);
  182. Error _buffer_update(Buffer *p_buffer, size_t p_offset, const uint8_t *p_data, size_t p_data_size, bool p_use_draw_command_buffer = false, uint32_t p_required_align = 32);
  183. void _full_barrier(bool p_sync_with_draw);
  184. void _memory_barrier(VkPipelineStageFlags p_src_stage_mask, VkPipelineStageFlags p_dst_stage_mask, VkAccessFlags p_src_access, VkAccessFlags p_dst_sccess, bool p_sync_with_draw);
  185. void _buffer_memory_barrier(VkBuffer buffer, uint64_t p_from, uint64_t p_size, VkPipelineStageFlags p_src_stage_mask, VkPipelineStageFlags p_dst_stage_mask, VkAccessFlags p_src_access, VkAccessFlags p_dst_sccess, bool p_sync_with_draw);
  186. /*********************/
  187. /**** FRAMEBUFFER ****/
  188. /*********************/
  189. // In Vulkan, framebuffers work similar to how they
  190. // do in OpenGL, with the exception that
  191. // the "format" (vkRenderPass) is not dynamic
  192. // and must be more or less the same as the one
  193. // used for the render pipelines.
  194. struct FramebufferFormatKey {
  195. Vector<AttachmentFormat> attachments;
  196. bool operator<(const FramebufferFormatKey &p_key) const {
  197. int as = attachments.size();
  198. int bs = p_key.attachments.size();
  199. if (as != bs) {
  200. return as < bs;
  201. }
  202. const AttachmentFormat *af_a = attachments.ptr();
  203. const AttachmentFormat *af_b = p_key.attachments.ptr();
  204. for (int i = 0; i < as; i++) {
  205. const AttachmentFormat &a = af_a[i];
  206. const AttachmentFormat &b = af_b[i];
  207. if (a.format != b.format) {
  208. return a.format < b.format;
  209. }
  210. if (a.samples != b.samples) {
  211. return a.samples < b.samples;
  212. }
  213. if (a.usage_flags != b.usage_flags) {
  214. return a.usage_flags < b.usage_flags;
  215. }
  216. }
  217. return false; //equal
  218. }
  219. };
  220. VkRenderPass _render_pass_create(const Vector<AttachmentFormat> &p_format, InitialAction p_initial_action, FinalAction p_final_action, InitialAction p_initial_depth_action, FinalAction p_final_depthcolor_action, int *r_color_attachment_count = NULL);
  221. // This is a cache and it's never freed, it ensures
  222. // IDs for a given format are always unique.
  223. Map<FramebufferFormatKey, FramebufferFormatID> framebuffer_format_cache;
  224. struct FramebufferFormat {
  225. const Map<FramebufferFormatKey, FramebufferFormatID>::Element *E;
  226. VkRenderPass render_pass; //here for constructing shaders, never used, see section (7.2. Render Pass Compatibility from Vulkan spec)
  227. int color_attachments; //used for pipeline validation
  228. TextureSamples samples;
  229. };
  230. Map<FramebufferFormatID, FramebufferFormat> framebuffer_formats;
  231. struct Framebuffer {
  232. FramebufferFormatID format_id;
  233. struct VersionKey {
  234. InitialAction initial_color_action;
  235. FinalAction final_color_action;
  236. InitialAction initial_depth_action;
  237. FinalAction final_depth_action;
  238. bool operator<(const VersionKey &p_key) const {
  239. if (initial_color_action == p_key.initial_color_action) {
  240. if (final_color_action == p_key.final_color_action) {
  241. if (initial_depth_action == p_key.initial_depth_action) {
  242. return final_depth_action < p_key.final_depth_action;
  243. } else {
  244. return initial_depth_action < p_key.initial_depth_action;
  245. }
  246. } else {
  247. return final_color_action < p_key.final_color_action;
  248. }
  249. } else {
  250. return initial_color_action < p_key.initial_color_action;
  251. }
  252. }
  253. };
  254. uint32_t storage_mask;
  255. Vector<RID> texture_ids;
  256. struct Version {
  257. VkFramebuffer framebuffer;
  258. VkRenderPass render_pass; //this one is owned
  259. };
  260. Map<VersionKey, Version> framebuffers;
  261. Size2 size;
  262. };
  263. RID_Owner<Framebuffer, true> framebuffer_owner;
  264. /***********************/
  265. /**** VERTEX BUFFER ****/
  266. /***********************/
  267. // Vertex buffers in Vulkan are similar to how
  268. // they work in OpenGL, except that instead of
  269. // an attribtue index, there is a buffer binding
  270. // index (for binding the buffers in real-time)
  271. // and a location index (what is used in the shader).
  272. //
  273. // This mapping is done here internally, and it's not
  274. // exposed.
  275. RID_Owner<Buffer, true> vertex_buffer_owner;
  276. struct VertexDescriptionKey {
  277. Vector<VertexDescription> vertex_formats;
  278. bool operator==(const VertexDescriptionKey &p_key) const {
  279. int vdc = vertex_formats.size();
  280. int vdck = p_key.vertex_formats.size();
  281. if (vdc != vdck) {
  282. return false;
  283. } else {
  284. const VertexDescription *a_ptr = vertex_formats.ptr();
  285. const VertexDescription *b_ptr = p_key.vertex_formats.ptr();
  286. for (int i = 0; i < vdc; i++) {
  287. const VertexDescription &a = a_ptr[i];
  288. const VertexDescription &b = b_ptr[i];
  289. if (a.location != b.location) {
  290. return false;
  291. }
  292. if (a.offset != b.offset) {
  293. return false;
  294. }
  295. if (a.format != b.format) {
  296. return false;
  297. }
  298. if (a.stride != b.stride) {
  299. return false;
  300. }
  301. return a.frequency != b.frequency;
  302. }
  303. return true; //they are equal
  304. }
  305. }
  306. uint32_t hash() const {
  307. int vdc = vertex_formats.size();
  308. uint32_t h = hash_djb2_one_32(vdc);
  309. const VertexDescription *ptr = vertex_formats.ptr();
  310. for (int i = 0; i < vdc; i++) {
  311. const VertexDescription &vd = ptr[i];
  312. h = hash_djb2_one_32(vd.location, h);
  313. h = hash_djb2_one_32(vd.offset, h);
  314. h = hash_djb2_one_32(vd.format, h);
  315. h = hash_djb2_one_32(vd.stride, h);
  316. h = hash_djb2_one_32(vd.frequency, h);
  317. }
  318. return h;
  319. }
  320. };
  321. struct VertexDescriptionHash {
  322. static _FORCE_INLINE_ uint32_t hash(const VertexDescriptionKey &p_key) {
  323. return p_key.hash();
  324. }
  325. };
  326. // This is a cache and it's never freed, it ensures that
  327. // ID used for a specific format always remain the same.
  328. HashMap<VertexDescriptionKey, VertexFormatID, VertexDescriptionHash> vertex_format_cache;
  329. struct VertexDescriptionCache {
  330. Vector<VertexDescription> vertex_formats;
  331. VkVertexInputBindingDescription *bindings;
  332. VkVertexInputAttributeDescription *attributes;
  333. VkPipelineVertexInputStateCreateInfo create_info;
  334. };
  335. Map<VertexFormatID, VertexDescriptionCache> vertex_formats;
  336. struct VertexArray {
  337. RID buffer;
  338. VertexFormatID description;
  339. int vertex_count;
  340. uint32_t max_instances_allowed;
  341. Vector<VkBuffer> buffers; //not owned, just referenced
  342. Vector<VkDeviceSize> offsets;
  343. };
  344. RID_Owner<VertexArray, true> vertex_array_owner;
  345. struct IndexBuffer : public Buffer {
  346. uint32_t max_index; //used for validation
  347. uint32_t index_count;
  348. VkIndexType index_type;
  349. bool supports_restart_indices;
  350. };
  351. RID_Owner<IndexBuffer, true> index_buffer_owner;
  352. struct IndexArray {
  353. uint32_t max_index; //remember the maximum index here too, for validation
  354. VkBuffer buffer; //not owned, inherited from index buffer
  355. uint32_t offset;
  356. uint32_t indices;
  357. VkIndexType index_type;
  358. bool supports_restart_indices;
  359. };
  360. RID_Owner<IndexArray, true> index_array_owner;
  361. /****************/
  362. /**** SHADER ****/
  363. /****************/
  364. // Vulkan specifies a really complex behavior for the application
  365. // in order to tell when descriptor sets need to be re-bound (or not).
  366. // "When binding a descriptor set (see Descriptor Set Binding) to set
  367. // number N, if the previously bound descriptor sets for sets zero
  368. // through N-1 were all bound using compatible pipeline layouts,
  369. // then performing this binding does not disturb any of the lower numbered sets.
  370. // If, additionally, the previous bound descriptor set for set N was
  371. // bound using a pipeline layout compatible for set N, then the bindings
  372. // in sets numbered greater than N are also not disturbed."
  373. // As a result, we need to figure out quickly when something is no longer "compatible".
  374. // in order to avoid costly rebinds.
  375. enum {
  376. MAX_UNIFORM_SETS = 16
  377. };
  378. struct UniformInfo {
  379. UniformType type;
  380. int binding;
  381. uint32_t stages;
  382. int length; //size of arrays (in total elements), or ubos (in bytes * total elements)
  383. bool operator!=(const UniformInfo &p_info) const {
  384. return (binding != p_info.binding || type != p_info.type || stages != p_info.stages || length != p_info.length);
  385. }
  386. bool operator<(const UniformInfo &p_info) const {
  387. if (binding != p_info.binding) {
  388. return binding < p_info.binding;
  389. }
  390. if (type != p_info.type) {
  391. return type < p_info.type;
  392. }
  393. if (stages != p_info.stages) {
  394. return stages < p_info.stages;
  395. }
  396. return length < p_info.length;
  397. }
  398. };
  399. struct UniformSetFormat {
  400. Vector<UniformInfo> uniform_info;
  401. bool operator<(const UniformSetFormat &p_format) const {
  402. uint32_t size = uniform_info.size();
  403. uint32_t psize = p_format.uniform_info.size();
  404. if (size != psize) {
  405. return size < psize;
  406. }
  407. const UniformInfo *infoptr = uniform_info.ptr();
  408. const UniformInfo *pinfoptr = p_format.uniform_info.ptr();
  409. for (uint32_t i = 0; i < size; i++) {
  410. if (infoptr[i] != pinfoptr[i]) {
  411. return infoptr[i] < pinfoptr[i];
  412. }
  413. }
  414. return false;
  415. }
  416. };
  417. // Always grows, never shrinks, ensuring unique IDs, but we assume
  418. // the amount of formats will never be a problem, as the amount of shaders
  419. // in a game is limited.
  420. Map<UniformSetFormat, uint32_t> uniform_set_format_cache;
  421. // Shaders in Vulkan are just pretty much
  422. // precompiled blocks of SPIR-V bytecode. They
  423. // are most likely not really compiled to host
  424. // assembly until a pipeline is created.
  425. //
  426. // When supplying the shaders, this implementation
  427. // will use the reflection abilities of glslang to
  428. // understand and cache everything required to
  429. // create and use the descriptor sets (Vulkan's
  430. // biggest pain).
  431. //
  432. // Additionally, hashes are created for every set
  433. // to do quick validation and ensuring the user
  434. // does not submit something invalid.
  435. struct Shader {
  436. struct Set {
  437. Vector<UniformInfo> uniform_info;
  438. VkDescriptorSetLayout descriptor_set_layout;
  439. };
  440. uint32_t vertex_input_mask; //inputs used, this is mostly for validation
  441. int fragment_outputs;
  442. struct PushConstant {
  443. uint32_t push_constant_size;
  444. uint32_t push_constants_vk_stage;
  445. };
  446. PushConstant push_constant;
  447. bool is_compute = false;
  448. int max_output;
  449. Vector<Set> sets;
  450. Vector<uint32_t> set_formats;
  451. Vector<VkPipelineShaderStageCreateInfo> pipeline_stages;
  452. VkPipelineLayout pipeline_layout;
  453. };
  454. String _shader_uniform_debug(RID p_shader, int p_set = -1);
  455. RID_Owner<Shader, true> shader_owner;
  456. /******************/
  457. /**** UNIFORMS ****/
  458. /******************/
  459. // Descriptor sets require allocation from a pool.
  460. // The documentation on how to use pools properly
  461. // is scarce, and the documentation is strange.
  462. //
  463. // Basically, you can mix and match pools as you
  464. // like, but you'll run into fragmentation issues.
  465. // Because of this, the recommended approach is to
  466. // create a a pool for every descriptor set type,
  467. // as this prevents fragmentation.
  468. //
  469. // This is implemented here as a having a list of
  470. // pools (each can contain up to 64 sets) for each
  471. // set layout. The amount of sets for each type
  472. // is used as the key.
  473. enum {
  474. MAX_DESCRIPTOR_POOL_ELEMENT = 65535
  475. };
  476. struct DescriptorPoolKey {
  477. union {
  478. struct {
  479. uint16_t uniform_type[UNIFORM_TYPE_MAX]; //using 16 bits because, for sending arrays, each element is a pool set.
  480. };
  481. struct {
  482. uint64_t key1;
  483. uint64_t key2;
  484. uint64_t key3;
  485. };
  486. };
  487. bool operator<(const DescriptorPoolKey &p_key) const {
  488. if (key1 != p_key.key1) {
  489. return key1 < p_key.key1;
  490. }
  491. if (key2 != p_key.key2) {
  492. return key2 < p_key.key2;
  493. }
  494. return key3 < p_key.key3;
  495. }
  496. DescriptorPoolKey() {
  497. key1 = 0;
  498. key2 = 0;
  499. key3 = 0;
  500. }
  501. };
  502. struct DescriptorPool {
  503. VkDescriptorPool pool;
  504. uint32_t usage;
  505. };
  506. Map<DescriptorPoolKey, Set<DescriptorPool *> > descriptor_pools;
  507. uint32_t max_descriptors_per_pool;
  508. DescriptorPool *_descriptor_pool_allocate(const DescriptorPoolKey &p_key);
  509. void _descriptor_pool_free(const DescriptorPoolKey &p_key, DescriptorPool *p_pool);
  510. RID_Owner<Buffer, true> uniform_buffer_owner;
  511. RID_Owner<Buffer, true> storage_buffer_owner;
  512. //texture buffer needs a view
  513. struct TextureBuffer {
  514. Buffer buffer;
  515. VkBufferView view;
  516. };
  517. RID_Owner<TextureBuffer, true> texture_buffer_owner;
  518. // This structure contains the descriptor set. They _need_ to be allocated
  519. // for a shader (and will be erased when this shader is erased), but should
  520. // work for other shaders as long as the hash matches. This covers using
  521. // them in shader variants.
  522. //
  523. // Keep also in mind that you can share buffers between descriptor sets, so
  524. // the above restriction is not too serious.
  525. struct UniformSet {
  526. uint32_t format;
  527. RID shader_id;
  528. uint32_t shader_set;
  529. DescriptorPool *pool;
  530. DescriptorPoolKey pool_key;
  531. VkDescriptorSet descriptor_set;
  532. //VkPipelineLayout pipeline_layout; //not owned, inherited from shader
  533. Vector<RID> attachable_textures; //used for validation
  534. Vector<Texture *> mutable_sampled_textures; //used for layout change
  535. Vector<Texture *> mutable_storage_textures; //used for layout change
  536. };
  537. RID_Owner<UniformSet, true> uniform_set_owner;
  538. /*******************/
  539. /**** PIPELINES ****/
  540. /*******************/
  541. // Render pipeline contains ALL the
  542. // information required for drawing.
  543. // This includes all the rasterizer state
  544. // as well as shader used, framebuffer format,
  545. // etc.
  546. // While the pipeline is just a single object
  547. // (VkPipeline) a lot of values are also saved
  548. // here to do validation (vulkan does none by
  549. // default) and warn the user if something
  550. // was not supplied as intended.
  551. struct RenderPipeline {
  552. //Cached values for validation
  553. #ifdef DEBUG_ENABLED
  554. struct Validation {
  555. FramebufferFormatID framebuffer_format;
  556. uint32_t dynamic_state;
  557. VertexFormatID vertex_format;
  558. bool uses_restart_indices;
  559. uint32_t primitive_minimum;
  560. uint32_t primitive_divisor;
  561. } validation;
  562. #endif
  563. //Actual pipeline
  564. RID shader;
  565. Vector<uint32_t> set_formats;
  566. VkPipelineLayout pipeline_layout; // not owned, needed for push constants
  567. VkPipeline pipeline;
  568. uint32_t push_constant_size;
  569. uint32_t push_constant_stages;
  570. };
  571. RID_Owner<RenderPipeline, true> render_pipeline_owner;
  572. struct ComputePipeline {
  573. RID shader;
  574. Vector<uint32_t> set_formats;
  575. VkPipelineLayout pipeline_layout; // not owned, needed for push constants
  576. VkPipeline pipeline;
  577. uint32_t push_constant_size;
  578. uint32_t push_constant_stages;
  579. };
  580. RID_Owner<ComputePipeline, true> compute_pipeline_owner;
  581. /*******************/
  582. /**** DRAW LIST ****/
  583. /*******************/
  584. // Draw list contains both the command buffer
  585. // used for drawing as well as a LOT of
  586. // information used for validation. This
  587. // validation is cheap so most of it can
  588. // also run in release builds.
  589. // When using split command lists, this is
  590. // implemented internally using secondary command
  591. // buffers. As they can be created in threads,
  592. // each needs it's own command pool.
  593. struct SplitDrawListAllocator {
  594. VkCommandPool command_pool;
  595. Vector<VkCommandBuffer> command_buffers; //one for each frame
  596. };
  597. Vector<SplitDrawListAllocator> split_draw_list_allocators;
  598. struct DrawList {
  599. VkCommandBuffer command_buffer; //if persistent, this is owned, otherwise it's shared with the ringbuffer
  600. Rect2i viewport;
  601. struct SetState {
  602. uint32_t pipeline_expected_format;
  603. uint32_t uniform_set_format;
  604. VkDescriptorSet descriptor_set;
  605. RID uniform_set;
  606. bool bound;
  607. SetState() {
  608. bound = false;
  609. pipeline_expected_format = 0;
  610. uniform_set_format = 0;
  611. descriptor_set = VK_NULL_HANDLE;
  612. }
  613. };
  614. struct State {
  615. SetState sets[MAX_UNIFORM_SETS];
  616. uint32_t set_count;
  617. RID pipeline;
  618. RID pipeline_shader;
  619. VkPipelineLayout pipeline_layout;
  620. RID vertex_array;
  621. RID index_array;
  622. uint32_t pipeline_push_constant_stages;
  623. State() {
  624. set_count = 0;
  625. pipeline_layout = VK_NULL_HANDLE;
  626. pipeline_push_constant_stages = 0;
  627. }
  628. } state;
  629. #ifdef DEBUG_ENABLED
  630. struct Validation {
  631. bool active; //means command buffer was not closes, so you can keep adding things
  632. FramebufferFormatID framebuffer_format;
  633. //actual render pass values
  634. uint32_t dynamic_state;
  635. VertexFormatID vertex_format; //INVALID_ID if not set
  636. uint32_t vertex_array_size; //0 if not set
  637. uint32_t vertex_max_instances_allowed;
  638. bool index_buffer_uses_restart_indices;
  639. uint32_t index_array_size; //0 if index buffer not set
  640. uint32_t index_array_max_index;
  641. uint32_t index_array_offset;
  642. Vector<uint32_t> set_formats;
  643. Vector<bool> set_bound;
  644. Vector<RID> set_rids;
  645. //last pipeline set values
  646. bool pipeline_active;
  647. uint32_t pipeline_dynamic_state;
  648. VertexFormatID pipeline_vertex_format;
  649. RID pipeline_shader;
  650. uint32_t invalid_set_from;
  651. bool pipeline_uses_restart_indices;
  652. uint32_t pipeline_primitive_divisor;
  653. uint32_t pipeline_primitive_minimum;
  654. Vector<uint32_t> pipeline_set_formats;
  655. uint32_t pipeline_push_constant_size;
  656. bool pipeline_push_constant_suppplied;
  657. Validation() {
  658. active = true;
  659. dynamic_state = 0;
  660. vertex_format = INVALID_ID;
  661. vertex_array_size = 0;
  662. vertex_max_instances_allowed = 0xFFFFFFFF;
  663. framebuffer_format = INVALID_ID;
  664. index_array_size = 0; //not sent
  665. index_array_max_index = 0; //not set
  666. index_buffer_uses_restart_indices = false;
  667. invalid_set_from = 0;
  668. //pipeline state initalize
  669. pipeline_active = false;
  670. pipeline_dynamic_state = 0;
  671. pipeline_vertex_format = INVALID_ID;
  672. pipeline_uses_restart_indices = false;
  673. pipeline_push_constant_size = 0;
  674. pipeline_push_constant_suppplied = false;
  675. }
  676. } validation;
  677. #else
  678. struct Validation {
  679. uint32_t vertex_array_size; //0 if not set
  680. uint32_t index_array_size; //0 if index buffer not set
  681. uint32_t index_array_offset;
  682. Validation() {
  683. vertex_array_size = 0;
  684. index_array_size = 0; //not sent
  685. }
  686. } validation;
  687. #endif
  688. };
  689. DrawList *draw_list; //one for regular draw lists, multiple for split.
  690. uint32_t draw_list_count;
  691. bool draw_list_split;
  692. Vector<RID> draw_list_bound_textures;
  693. bool draw_list_unbind_color_textures;
  694. bool draw_list_unbind_depth_textures;
  695. void _draw_list_insert_clear_region(DrawList *draw_list, Framebuffer *framebuffer, Point2i viewport_offset, Point2i viewport_size, bool p_clear_color, const Vector<Color> &p_clear_colors, bool p_clear_depth, float p_depth, uint32_t p_stencil);
  696. Error _draw_list_setup_framebuffer(Framebuffer *p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, VkFramebuffer *r_framebuffer, VkRenderPass *r_render_pass);
  697. Error _draw_list_render_pass_begin(Framebuffer *framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector<Color> &p_clear_colors, float p_clear_depth, uint32_t p_clear_stencil, Point2i viewport_offset, Point2i viewport_size, VkFramebuffer vkframebuffer, VkRenderPass render_pass, VkCommandBuffer command_buffer, VkSubpassContents subpass_contents);
  698. _FORCE_INLINE_ DrawList *_get_draw_list_ptr(DrawListID p_id);
  699. /**********************/
  700. /**** COMPUTE LIST ****/
  701. /**********************/
  702. struct ComputeList {
  703. VkCommandBuffer command_buffer; //if persistent, this is owned, otherwise it's shared with the ringbuffer
  704. struct SetState {
  705. uint32_t pipeline_expected_format;
  706. uint32_t uniform_set_format;
  707. VkDescriptorSet descriptor_set;
  708. RID uniform_set;
  709. bool bound;
  710. SetState() {
  711. bound = false;
  712. pipeline_expected_format = 0;
  713. uniform_set_format = 0;
  714. descriptor_set = VK_NULL_HANDLE;
  715. }
  716. };
  717. struct State {
  718. Set<Texture *> textures_to_sampled_layout;
  719. SetState sets[MAX_UNIFORM_SETS];
  720. uint32_t set_count;
  721. RID pipeline;
  722. RID pipeline_shader;
  723. VkPipelineLayout pipeline_layout;
  724. uint32_t pipeline_push_constant_stages;
  725. State() {
  726. set_count = 0;
  727. pipeline_layout = VK_NULL_HANDLE;
  728. pipeline_push_constant_stages = 0;
  729. }
  730. } state;
  731. #ifdef DEBUG_ENABLED
  732. struct Validation {
  733. bool active; //means command buffer was not closes, so you can keep adding things
  734. Vector<uint32_t> set_formats;
  735. Vector<bool> set_bound;
  736. Vector<RID> set_rids;
  737. //last pipeline set values
  738. bool pipeline_active;
  739. RID pipeline_shader;
  740. uint32_t invalid_set_from;
  741. Vector<uint32_t> pipeline_set_formats;
  742. uint32_t pipeline_push_constant_size;
  743. bool pipeline_push_constant_suppplied;
  744. Validation() {
  745. active = true;
  746. invalid_set_from = 0;
  747. //pipeline state initalize
  748. pipeline_active = false;
  749. pipeline_push_constant_size = 0;
  750. pipeline_push_constant_suppplied = false;
  751. }
  752. } validation;
  753. #endif
  754. };
  755. ComputeList *compute_list;
  756. /**************************/
  757. /**** FRAME MANAGEMENT ****/
  758. /**************************/
  759. // This is the frame structure. There are normally
  760. // 3 of these (used for triple buffering), or 2
  761. // (double buffering). They are cycled constantly.
  762. //
  763. // It contains two command buffers, one that is
  764. // used internally for setting up (creating stuff)
  765. // and another used mostly for drawing.
  766. //
  767. // They also contains a list of things that need
  768. // to be disposed of when deleted, which can't
  769. // happen immediately due to the asynchronous
  770. // nature of the GPU. They will get deleted
  771. // when the frame is cycled.
  772. struct Frame {
  773. //list in usage order, from last to free to first to free
  774. List<Buffer> buffers_to_dispose_of;
  775. List<Texture> textures_to_dispose_of;
  776. List<Framebuffer> framebuffers_to_dispose_of;
  777. List<VkSampler> samplers_to_dispose_of;
  778. List<Shader> shaders_to_dispose_of;
  779. List<VkBufferView> buffer_views_to_dispose_of;
  780. List<UniformSet> uniform_sets_to_dispose_of;
  781. List<RenderPipeline> render_pipelines_to_dispose_of;
  782. List<ComputePipeline> compute_pipelines_to_dispose_of;
  783. VkCommandPool command_pool;
  784. VkCommandBuffer setup_command_buffer; //used at the begining of every frame for set-up
  785. VkCommandBuffer draw_command_buffer; //used at the begining of every frame for set-up
  786. struct Timestamp {
  787. String description;
  788. uint64_t value;
  789. };
  790. VkQueryPool timestamp_pool;
  791. String *timestamp_names;
  792. uint64_t *timestamp_cpu_values;
  793. uint32_t timestamp_count;
  794. String *timestamp_result_names;
  795. uint64_t *timestamp_cpu_result_values;
  796. uint64_t *timestamp_result_values;
  797. uint32_t timestamp_result_count;
  798. uint64_t index;
  799. };
  800. uint32_t max_timestamp_query_elements;
  801. Frame *frames; //frames available, they are cycled (usually 3)
  802. int frame; //current frame
  803. int frame_count; //total amount of frames
  804. uint64_t frames_drawn;
  805. void _free_pending_resources(int p_frame);
  806. VmaAllocator allocator;
  807. VulkanContext *context;
  808. void _free_internal(RID p_id);
  809. void _flush(bool p_current_frame);
  810. bool screen_prepared;
  811. template <class T>
  812. void _free_rids(T &p_owner, const char *p_type);
  813. public:
  814. virtual RID texture_create(const TextureFormat &p_format, const TextureView &p_view, const Vector<Vector<uint8_t> > &p_data = Vector<Vector<uint8_t> >());
  815. virtual RID texture_create_shared(const TextureView &p_view, RID p_with_texture);
  816. virtual RID texture_create_shared_from_slice(const TextureView &p_view, RID p_with_texture, uint32_t p_layer, uint32_t p_mipmap, TextureSliceType p_slice_type = TEXTURE_SLICE_2D);
  817. virtual Error texture_update(RID p_texture, uint32_t p_layer, const Vector<uint8_t> &p_data, bool p_sync_with_draw = false);
  818. virtual Vector<uint8_t> texture_get_data(RID p_texture, uint32_t p_layer);
  819. virtual bool texture_is_format_supported_for_usage(DataFormat p_format, uint32_t p_usage) const;
  820. virtual bool texture_is_shared(RID p_texture);
  821. virtual bool texture_is_valid(RID p_texture);
  822. virtual Error texture_copy(RID p_from_texture, RID p_to_texture, const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_size, uint32_t p_src_mipmap, uint32_t p_dst_mipmap, uint32_t p_src_layer, uint32_t p_dst_layer, bool p_sync_with_draw = false);
  823. virtual Error texture_clear(RID p_texture, const Color &p_color, uint32_t p_base_mipmap, uint32_t p_mipmaps, uint32_t p_base_layer, uint32_t p_layers, bool p_sync_with_draw = false);
  824. /*********************/
  825. /**** FRAMEBUFFER ****/
  826. /*********************/
  827. virtual FramebufferFormatID framebuffer_format_create(const Vector<AttachmentFormat> &p_format);
  828. virtual TextureSamples framebuffer_format_get_texture_samples(FramebufferFormatID p_format);
  829. virtual RID framebuffer_create(const Vector<RID> &p_texture_attachments, FramebufferFormatID p_format_check = INVALID_ID);
  830. virtual FramebufferFormatID framebuffer_get_format(RID p_framebuffer);
  831. /*****************/
  832. /**** SAMPLER ****/
  833. /*****************/
  834. virtual RID sampler_create(const SamplerState &p_state);
  835. /**********************/
  836. /**** VERTEX ARRAY ****/
  837. /**********************/
  838. virtual RID vertex_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data = Vector<uint8_t>());
  839. // Internally reference counted, this ID is warranted to be unique for the same description, but needs to be freed as many times as it was allocated
  840. virtual VertexFormatID vertex_format_create(const Vector<VertexDescription> &p_vertex_formats);
  841. virtual RID vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const Vector<RID> &p_src_buffers);
  842. virtual RID index_buffer_create(uint32_t p_size_indices, IndexBufferFormat p_format, const Vector<uint8_t> &p_data = Vector<uint8_t>(), bool p_use_restart_indices = false);
  843. virtual RID index_array_create(RID p_index_buffer, uint32_t p_index_offset, uint32_t p_index_count);
  844. /****************/
  845. /**** SHADER ****/
  846. /****************/
  847. virtual RID shader_create(const Vector<ShaderStageData> &p_stages);
  848. virtual uint32_t shader_get_vertex_input_attribute_mask(RID p_shader);
  849. /*****************/
  850. /**** UNIFORM ****/
  851. /*****************/
  852. virtual RID uniform_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data = Vector<uint8_t>());
  853. virtual RID storage_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data = Vector<uint8_t>());
  854. virtual RID texture_buffer_create(uint32_t p_size_elements, DataFormat p_format, const Vector<uint8_t> &p_data = Vector<uint8_t>());
  855. virtual RID uniform_set_create(const Vector<Uniform> &p_uniforms, RID p_shader, uint32_t p_shader_set);
  856. virtual bool uniform_set_is_valid(RID p_uniform_set);
  857. virtual Error buffer_update(RID p_buffer, uint32_t p_offset, uint32_t p_size, const void *p_data, bool p_sync_with_draw = false); //works for any buffer
  858. virtual Vector<uint8_t> buffer_get_data(RID p_buffer);
  859. /*************************/
  860. /**** RENDER PIPELINE ****/
  861. /*************************/
  862. virtual RID render_pipeline_create(RID p_shader, FramebufferFormatID p_framebuffer_format, VertexFormatID p_vertex_format, RenderPrimitive p_render_primitive, const PipelineRasterizationState &p_rasterization_state, const PipelineMultisampleState &p_multisample_state, const PipelineDepthStencilState &p_depth_stencil_state, const PipelineColorBlendState &p_blend_state, int p_dynamic_state_flags = 0);
  863. virtual bool render_pipeline_is_valid(RID p_pipeline);
  864. /**************************/
  865. /**** COMPUTE PIPELINE ****/
  866. /**************************/
  867. virtual RID compute_pipeline_create(RID p_shader);
  868. virtual bool compute_pipeline_is_valid(RID p_pipeline);
  869. /****************/
  870. /**** SCREEN ****/
  871. /****************/
  872. virtual int screen_get_width(int p_screen = 0) const;
  873. virtual int screen_get_height(int p_screen = 0) const;
  874. virtual FramebufferFormatID screen_get_framebuffer_format() const;
  875. /********************/
  876. /**** DRAW LISTS ****/
  877. /********************/
  878. virtual DrawListID draw_list_begin_for_screen(int p_screen = 0, const Color &p_clear_color = Color());
  879. virtual DrawListID draw_list_begin(RID p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector<Color> &p_clear_color_values = Vector<Color>(), float p_clear_depth = 1.0, uint32_t p_clear_stencil = 0, const Rect2 &p_region = Rect2());
  880. virtual Error draw_list_begin_split(RID p_framebuffer, uint32_t p_splits, DrawListID *r_split_ids, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector<Color> &p_clear_color_values = Vector<Color>(), float p_clear_depth = 1.0, uint32_t p_clear_stencil = 0, const Rect2 &p_region = Rect2());
  881. virtual void draw_list_bind_render_pipeline(DrawListID p_list, RID p_render_pipeline);
  882. virtual void draw_list_bind_uniform_set(DrawListID p_list, RID p_uniform_set, uint32_t p_index);
  883. virtual void draw_list_bind_vertex_array(DrawListID p_list, RID p_vertex_array);
  884. virtual void draw_list_bind_index_array(DrawListID p_list, RID p_index_array);
  885. virtual void draw_list_set_line_width(DrawListID p_list, float p_width);
  886. virtual void draw_list_set_push_constant(DrawListID p_list, void *p_data, uint32_t p_data_size);
  887. virtual void draw_list_draw(DrawListID p_list, bool p_use_indices, uint32_t p_instances = 1, uint32_t p_procedural_vertices = 0);
  888. virtual void draw_list_enable_scissor(DrawListID p_list, const Rect2 &p_rect);
  889. virtual void draw_list_disable_scissor(DrawListID p_list);
  890. virtual void draw_list_end();
  891. /***********************/
  892. /**** COMPUTE LISTS ****/
  893. /***********************/
  894. virtual ComputeListID compute_list_begin();
  895. virtual void compute_list_bind_compute_pipeline(ComputeListID p_list, RID p_compute_pipeline);
  896. virtual void compute_list_bind_uniform_set(ComputeListID p_list, RID p_uniform_set, uint32_t p_index);
  897. virtual void compute_list_set_push_constant(ComputeListID p_list, void *p_data, uint32_t p_data_size);
  898. virtual void compute_list_add_barrier(ComputeListID p_list);
  899. virtual void compute_list_dispatch(ComputeListID p_list, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups);
  900. virtual void compute_list_end();
  901. /**************/
  902. /**** FREE ****/
  903. /**************/
  904. virtual void free(RID p_id);
  905. /****************/
  906. /**** Timing ****/
  907. /****************/
  908. virtual void capture_timestamp(const String &p_name, bool p_sync_to_draw);
  909. virtual uint32_t get_captured_timestamps_count() const;
  910. virtual uint64_t get_captured_timestamps_frame() const;
  911. virtual uint64_t get_captured_timestamp_gpu_time(uint32_t p_index) const;
  912. virtual uint64_t get_captured_timestamp_cpu_time(uint32_t p_index) const;
  913. virtual String get_captured_timestamp_name(uint32_t p_index) const;
  914. /****************/
  915. /**** Limits ****/
  916. /****************/
  917. virtual int limit_get(Limit p_limit);
  918. virtual void prepare_screen_for_drawing();
  919. void initialize(VulkanContext *p_context);
  920. void finalize();
  921. virtual void swap_buffers();
  922. virtual uint32_t get_frame_delay() const;
  923. RenderingDeviceVulkan();
  924. };
  925. #endif // RENDERING_DEVICE_VULKAN_H