rendering_device.h 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664
  1. /**************************************************************************/
  2. /* rendering_device.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. #ifndef RENDERING_DEVICE_H
  31. #define RENDERING_DEVICE_H
  32. #include "core/object/worker_thread_pool.h"
  33. #include "core/os/condition_variable.h"
  34. #include "core/os/thread_safe.h"
  35. #include "core/templates/local_vector.h"
  36. #include "core/templates/rid_owner.h"
  37. #include "core/variant/typed_array.h"
  38. #include "servers/display_server.h"
  39. #include "servers/rendering/rendering_device_commons.h"
  40. #include "servers/rendering/rendering_device_driver.h"
  41. #include "servers/rendering/rendering_device_graph.h"
  42. class RDTextureFormat;
  43. class RDTextureView;
  44. class RDAttachmentFormat;
  45. class RDSamplerState;
  46. class RDVertexAttribute;
  47. class RDShaderSource;
  48. class RDShaderSPIRV;
  49. class RDUniform;
  50. class RDPipelineRasterizationState;
  51. class RDPipelineMultisampleState;
  52. class RDPipelineDepthStencilState;
  53. class RDPipelineColorBlendState;
  54. class RDFramebufferPass;
  55. class RDPipelineSpecializationConstant;
  56. class RenderingDevice : public RenderingDeviceCommons {
  57. GDCLASS(RenderingDevice, Object)
  58. _THREAD_SAFE_CLASS_
  59. private:
  60. Thread::ID render_thread_id;
  61. public:
  62. enum ShaderLanguage {
  63. SHADER_LANGUAGE_GLSL,
  64. SHADER_LANGUAGE_HLSL
  65. };
  66. typedef int64_t DrawListID;
  67. typedef int64_t ComputeListID;
  68. typedef String (*ShaderSPIRVGetCacheKeyFunction)(const RenderingDevice *p_render_device);
  69. typedef Vector<uint8_t> (*ShaderCompileToSPIRVFunction)(ShaderStage p_stage, const String &p_source_code, ShaderLanguage p_language, String *r_error, const RenderingDevice *p_render_device);
  70. typedef Vector<uint8_t> (*ShaderCacheFunction)(ShaderStage p_stage, const String &p_source_code, ShaderLanguage p_language);
  71. typedef void (*InvalidationCallback)(void *);
  72. private:
  73. static ShaderCompileToSPIRVFunction compile_to_spirv_function;
  74. static ShaderCacheFunction cache_function;
  75. static ShaderSPIRVGetCacheKeyFunction get_spirv_cache_key_function;
  76. static RenderingDevice *singleton;
  77. RenderingContextDriver *context = nullptr;
  78. RenderingDeviceDriver *driver = nullptr;
  79. RenderingContextDriver::Device device;
  80. bool local_device_processing = false;
  81. bool is_main_instance = false;
  82. protected:
  83. static void _bind_methods();
  84. #ifndef DISABLE_DEPRECATED
  85. RID _shader_create_from_bytecode_bind_compat_79606(const Vector<uint8_t> &p_shader_binary);
  86. static void _bind_compatibility_methods();
  87. #endif
  88. /***************************/
  89. /**** ID INFRASTRUCTURE ****/
  90. /***************************/
  91. public:
  92. //base numeric ID for all types
  93. enum {
  94. INVALID_FORMAT_ID = -1
  95. };
  96. enum IDType {
  97. ID_TYPE_FRAMEBUFFER_FORMAT,
  98. ID_TYPE_VERTEX_FORMAT,
  99. ID_TYPE_DRAW_LIST,
  100. ID_TYPE_COMPUTE_LIST = 4,
  101. ID_TYPE_MAX,
  102. ID_BASE_SHIFT = 58, // 5 bits for ID types.
  103. ID_MASK = (ID_BASE_SHIFT - 1),
  104. };
  105. private:
  106. HashMap<RID, HashSet<RID>> dependency_map; // IDs to IDs that depend on it.
  107. HashMap<RID, HashSet<RID>> reverse_dependency_map; // Same as above, but in reverse.
  108. void _add_dependency(RID p_id, RID p_depends_on);
  109. void _free_dependencies(RID p_id);
  110. private:
  111. /***************************/
  112. /**** BUFFER MANAGEMENT ****/
  113. /***************************/
  114. // These are temporary buffers on CPU memory that hold
  115. // the information until the CPU fetches it and places it
  116. // either on GPU buffers, or images (textures). It ensures
  117. // updates are properly synchronized with whatever the
  118. // GPU is doing.
  119. //
  120. // The logic here is as follows, only 3 of these
  121. // blocks are created at the beginning (one per frame)
  122. // they can each belong to a frame (assigned to current when
  123. // used) and they can only be reused after the same frame is
  124. // recycled.
  125. //
  126. // When CPU requires to allocate more than what is available,
  127. // more of these buffers are created. If a limit is reached,
  128. // then a fence will ensure will wait for blocks allocated
  129. // in previous frames are processed. If that fails, then
  130. // another fence will ensure everything pending for the current
  131. // frame is processed (effectively stalling).
  132. //
  133. // See the comments in the code to understand better how it works.
  134. enum StagingRequiredAction {
  135. STAGING_REQUIRED_ACTION_NONE,
  136. STAGING_REQUIRED_ACTION_FLUSH_AND_STALL_ALL,
  137. STAGING_REQUIRED_ACTION_STALL_PREVIOUS,
  138. };
  139. struct StagingBufferBlock {
  140. RDD::BufferID driver_id;
  141. uint64_t frame_used = 0;
  142. uint32_t fill_amount = 0;
  143. };
  144. struct StagingBuffers {
  145. Vector<StagingBufferBlock> blocks;
  146. int current = 0;
  147. uint32_t block_size = 0;
  148. uint64_t max_size = 0;
  149. BitField<RDD::BufferUsageBits> usage_bits;
  150. bool used = false;
  151. };
  152. Error _staging_buffer_allocate(StagingBuffers &p_staging_buffers, uint32_t p_amount, uint32_t p_required_align, uint32_t &r_alloc_offset, uint32_t &r_alloc_size, StagingRequiredAction &r_required_action, bool p_can_segment = true);
  153. void _staging_buffer_execute_required_action(StagingBuffers &p_staging_buffers, StagingRequiredAction p_required_action);
  154. Error _insert_staging_block(StagingBuffers &p_staging_buffers);
  155. StagingBuffers upload_staging_buffers;
  156. StagingBuffers download_staging_buffers;
  157. struct Buffer {
  158. RDD::BufferID driver_id;
  159. uint32_t size = 0;
  160. BitField<RDD::BufferUsageBits> usage;
  161. RDG::ResourceTracker *draw_tracker = nullptr;
  162. int32_t transfer_worker_index = -1;
  163. uint64_t transfer_worker_operation = 0;
  164. };
  165. Buffer *_get_buffer_from_owner(RID p_buffer);
  166. Error _buffer_initialize(Buffer *p_buffer, const uint8_t *p_data, size_t p_data_size, uint32_t p_required_align = 32);
  167. void update_perf_report();
  168. // Flag for batching descriptor sets.
  169. bool descriptor_set_batching = true;
  170. // When true, the final draw call that copies our offscreen result into the Swapchain is put into its
  171. // own cmd buffer, so that the whole rendering can start early instead of having to wait for the
  172. // swapchain semaphore to be signaled (which causes bubbles).
  173. bool split_swapchain_into_its_own_cmd_buffer = true;
  174. uint32_t gpu_copy_count = 0;
  175. uint32_t copy_bytes_count = 0;
  176. String perf_report_text;
  177. RID_Owner<Buffer, true> uniform_buffer_owner;
  178. RID_Owner<Buffer, true> storage_buffer_owner;
  179. RID_Owner<Buffer, true> texture_buffer_owner;
  180. struct BufferGetDataRequest {
  181. uint32_t frame_local_index = 0;
  182. uint32_t frame_local_count = 0;
  183. Callable callback;
  184. uint32_t size = 0;
  185. };
  186. public:
  187. Error buffer_copy(RID p_src_buffer, RID p_dst_buffer, uint32_t p_src_offset, uint32_t p_dst_offset, uint32_t p_size);
  188. Error buffer_update(RID p_buffer, uint32_t p_offset, uint32_t p_size, const void *p_data);
  189. Error buffer_clear(RID p_buffer, uint32_t p_offset, uint32_t p_size);
  190. Vector<uint8_t> buffer_get_data(RID p_buffer, uint32_t p_offset = 0, uint32_t p_size = 0); // This causes stall, only use to retrieve large buffers for saving.
  191. Error buffer_get_data_async(RID p_buffer, const Callable &p_callback, uint32_t p_offset = 0, uint32_t p_size = 0);
  192. /*****************/
  193. /**** TEXTURE ****/
  194. /*****************/
  195. // In modern APIs, the concept of textures may not exist;
  196. // instead there is the image (the memory pretty much,
  197. // the view (how the memory is interpreted) and the
  198. // sampler (how it's sampled from the shader).
  199. //
  200. // Texture here includes the first two stages, but
  201. // It's possible to create textures sharing the image
  202. // but with different views. The main use case for this
  203. // is textures that can be read as both SRGB/Linear,
  204. // or slices of a texture (a mipmap, a layer, a 3D slice)
  205. // for a framebuffer to render into it.
  206. struct Texture {
  207. struct SharedFallback {
  208. uint32_t revision = 1;
  209. RDD::TextureID texture;
  210. RDG::ResourceTracker *texture_tracker = nullptr;
  211. RDD::BufferID buffer;
  212. RDG::ResourceTracker *buffer_tracker = nullptr;
  213. bool raw_reinterpretation = false;
  214. };
  215. RDD::TextureID driver_id;
  216. TextureType type = TEXTURE_TYPE_MAX;
  217. DataFormat format = DATA_FORMAT_MAX;
  218. TextureSamples samples = TEXTURE_SAMPLES_MAX;
  219. TextureSliceType slice_type = TEXTURE_SLICE_MAX;
  220. Rect2i slice_rect;
  221. uint32_t width = 0;
  222. uint32_t height = 0;
  223. uint32_t depth = 0;
  224. uint32_t layers = 0;
  225. uint32_t mipmaps = 0;
  226. uint32_t usage_flags = 0;
  227. uint32_t base_mipmap = 0;
  228. uint32_t base_layer = 0;
  229. Vector<DataFormat> allowed_shared_formats;
  230. bool is_resolve_buffer = false;
  231. bool is_discardable = false;
  232. bool has_initial_data = false;
  233. BitField<RDD::TextureAspectBits> read_aspect_flags;
  234. BitField<RDD::TextureAspectBits> barrier_aspect_flags;
  235. bool bound = false; // Bound to framebuffer.
  236. RID owner;
  237. RDG::ResourceTracker *draw_tracker = nullptr;
  238. HashMap<Rect2i, RDG::ResourceTracker *> slice_trackers;
  239. SharedFallback *shared_fallback = nullptr;
  240. int32_t transfer_worker_index = -1;
  241. uint64_t transfer_worker_operation = 0;
  242. RDD::TextureSubresourceRange barrier_range() const {
  243. RDD::TextureSubresourceRange r;
  244. r.aspect = barrier_aspect_flags;
  245. r.base_mipmap = base_mipmap;
  246. r.mipmap_count = mipmaps;
  247. r.base_layer = base_layer;
  248. r.layer_count = layers;
  249. return r;
  250. }
  251. TextureFormat texture_format() const {
  252. TextureFormat tf;
  253. tf.format = format;
  254. tf.width = width;
  255. tf.height = height;
  256. tf.depth = depth;
  257. tf.array_layers = layers;
  258. tf.mipmaps = mipmaps;
  259. tf.texture_type = type;
  260. tf.samples = samples;
  261. tf.usage_bits = usage_flags;
  262. tf.shareable_formats = allowed_shared_formats;
  263. tf.is_resolve_buffer = is_resolve_buffer;
  264. tf.is_discardable = is_discardable;
  265. return tf;
  266. }
  267. };
  268. RID_Owner<Texture, true> texture_owner;
  269. uint32_t texture_upload_region_size_px = 0;
  270. uint32_t texture_download_region_size_px = 0;
  271. Vector<uint8_t> _texture_get_data(Texture *tex, uint32_t p_layer, bool p_2d = false);
  272. uint32_t _texture_layer_count(Texture *p_texture) const;
  273. uint32_t _texture_alignment(Texture *p_texture) const;
  274. Error _texture_initialize(RID p_texture, uint32_t p_layer, const Vector<uint8_t> &p_data);
  275. void _texture_check_shared_fallback(Texture *p_texture);
  276. void _texture_update_shared_fallback(RID p_texture_rid, Texture *p_texture, bool p_for_writing);
  277. void _texture_free_shared_fallback(Texture *p_texture);
  278. void _texture_copy_shared(RID p_src_texture_rid, Texture *p_src_texture, RID p_dst_texture_rid, Texture *p_dst_texture);
  279. void _texture_create_reinterpret_buffer(Texture *p_texture);
  280. struct TextureGetDataRequest {
  281. uint32_t frame_local_index = 0;
  282. uint32_t frame_local_count = 0;
  283. Callable callback;
  284. uint32_t width = 0;
  285. uint32_t height = 0;
  286. uint32_t depth = 0;
  287. uint32_t mipmaps = 0;
  288. RDD::DataFormat format = RDD::DATA_FORMAT_MAX;
  289. };
  290. public:
  291. struct TextureView {
  292. DataFormat format_override = DATA_FORMAT_MAX; // // Means, use same as format.
  293. TextureSwizzle swizzle_r = TEXTURE_SWIZZLE_R;
  294. TextureSwizzle swizzle_g = TEXTURE_SWIZZLE_G;
  295. TextureSwizzle swizzle_b = TEXTURE_SWIZZLE_B;
  296. TextureSwizzle swizzle_a = TEXTURE_SWIZZLE_A;
  297. bool operator==(const TextureView &p_other) const {
  298. if (format_override != p_other.format_override) {
  299. return false;
  300. } else if (swizzle_r != p_other.swizzle_r) {
  301. return false;
  302. } else if (swizzle_g != p_other.swizzle_g) {
  303. return false;
  304. } else if (swizzle_b != p_other.swizzle_b) {
  305. return false;
  306. } else if (swizzle_a != p_other.swizzle_a) {
  307. return false;
  308. } else {
  309. return true;
  310. }
  311. }
  312. };
  313. RID texture_create(const TextureFormat &p_format, const TextureView &p_view, const Vector<Vector<uint8_t>> &p_data = Vector<Vector<uint8_t>>());
  314. RID texture_create_shared(const TextureView &p_view, RID p_with_texture);
  315. RID texture_create_from_extension(TextureType p_type, DataFormat p_format, TextureSamples p_samples, BitField<RenderingDevice::TextureUsageBits> p_usage, uint64_t p_image, uint64_t p_width, uint64_t p_height, uint64_t p_depth, uint64_t p_layers);
  316. RID texture_create_shared_from_slice(const TextureView &p_view, RID p_with_texture, uint32_t p_layer, uint32_t p_mipmap, uint32_t p_mipmaps = 1, TextureSliceType p_slice_type = TEXTURE_SLICE_2D, uint32_t p_layers = 0);
  317. Error texture_update(RID p_texture, uint32_t p_layer, const Vector<uint8_t> &p_data);
  318. Vector<uint8_t> texture_get_data(RID p_texture, uint32_t p_layer); // CPU textures will return immediately, while GPU textures will most likely force a flush
  319. Error texture_get_data_async(RID p_texture, uint32_t p_layer, const Callable &p_callback);
  320. bool texture_is_format_supported_for_usage(DataFormat p_format, BitField<TextureUsageBits> p_usage) const;
  321. bool texture_is_shared(RID p_texture);
  322. bool texture_is_valid(RID p_texture);
  323. TextureFormat texture_get_format(RID p_texture);
  324. Size2i texture_size(RID p_texture);
  325. #ifndef DISABLE_DEPRECATED
  326. uint64_t texture_get_native_handle(RID p_texture);
  327. #endif
  328. 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);
  329. 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);
  330. Error texture_resolve_multisample(RID p_from_texture, RID p_to_texture);
  331. void texture_set_discardable(RID p_texture, bool p_discardable);
  332. bool texture_is_discardable(RID p_texture);
  333. /*********************/
  334. /**** FRAMEBUFFER ****/
  335. /*********************/
  336. // In modern APIs, generally, framebuffers work similar to how they
  337. // do in OpenGL, with the exception that
  338. // the "format" (RDD::RenderPassID) is not dynamic
  339. // and must be more or less the same as the one
  340. // used for the render pipelines.
  341. struct AttachmentFormat {
  342. enum : uint32_t {
  343. UNUSED_ATTACHMENT = 0xFFFFFFFF
  344. };
  345. DataFormat format;
  346. TextureSamples samples;
  347. uint32_t usage_flags;
  348. AttachmentFormat() {
  349. format = DATA_FORMAT_R8G8B8A8_UNORM;
  350. samples = TEXTURE_SAMPLES_1;
  351. usage_flags = 0;
  352. }
  353. };
  354. struct FramebufferPass {
  355. Vector<int32_t> color_attachments;
  356. Vector<int32_t> input_attachments;
  357. Vector<int32_t> resolve_attachments;
  358. Vector<int32_t> preserve_attachments;
  359. int32_t depth_attachment = ATTACHMENT_UNUSED;
  360. int32_t vrs_attachment = ATTACHMENT_UNUSED; // density map for VRS, only used if supported
  361. };
  362. typedef int64_t FramebufferFormatID;
  363. private:
  364. struct FramebufferFormatKey {
  365. Vector<AttachmentFormat> attachments;
  366. Vector<FramebufferPass> passes;
  367. uint32_t view_count = 1;
  368. bool operator<(const FramebufferFormatKey &p_key) const {
  369. if (view_count != p_key.view_count) {
  370. return view_count < p_key.view_count;
  371. }
  372. uint32_t pass_size = passes.size();
  373. uint32_t key_pass_size = p_key.passes.size();
  374. if (pass_size != key_pass_size) {
  375. return pass_size < key_pass_size;
  376. }
  377. const FramebufferPass *pass_ptr = passes.ptr();
  378. const FramebufferPass *key_pass_ptr = p_key.passes.ptr();
  379. for (uint32_t i = 0; i < pass_size; i++) {
  380. { // Compare color attachments.
  381. uint32_t attachment_size = pass_ptr[i].color_attachments.size();
  382. uint32_t key_attachment_size = key_pass_ptr[i].color_attachments.size();
  383. if (attachment_size != key_attachment_size) {
  384. return attachment_size < key_attachment_size;
  385. }
  386. const int32_t *pass_attachment_ptr = pass_ptr[i].color_attachments.ptr();
  387. const int32_t *key_pass_attachment_ptr = key_pass_ptr[i].color_attachments.ptr();
  388. for (uint32_t j = 0; j < attachment_size; j++) {
  389. if (pass_attachment_ptr[j] != key_pass_attachment_ptr[j]) {
  390. return pass_attachment_ptr[j] < key_pass_attachment_ptr[j];
  391. }
  392. }
  393. }
  394. { // Compare input attachments.
  395. uint32_t attachment_size = pass_ptr[i].input_attachments.size();
  396. uint32_t key_attachment_size = key_pass_ptr[i].input_attachments.size();
  397. if (attachment_size != key_attachment_size) {
  398. return attachment_size < key_attachment_size;
  399. }
  400. const int32_t *pass_attachment_ptr = pass_ptr[i].input_attachments.ptr();
  401. const int32_t *key_pass_attachment_ptr = key_pass_ptr[i].input_attachments.ptr();
  402. for (uint32_t j = 0; j < attachment_size; j++) {
  403. if (pass_attachment_ptr[j] != key_pass_attachment_ptr[j]) {
  404. return pass_attachment_ptr[j] < key_pass_attachment_ptr[j];
  405. }
  406. }
  407. }
  408. { // Compare resolve attachments.
  409. uint32_t attachment_size = pass_ptr[i].resolve_attachments.size();
  410. uint32_t key_attachment_size = key_pass_ptr[i].resolve_attachments.size();
  411. if (attachment_size != key_attachment_size) {
  412. return attachment_size < key_attachment_size;
  413. }
  414. const int32_t *pass_attachment_ptr = pass_ptr[i].resolve_attachments.ptr();
  415. const int32_t *key_pass_attachment_ptr = key_pass_ptr[i].resolve_attachments.ptr();
  416. for (uint32_t j = 0; j < attachment_size; j++) {
  417. if (pass_attachment_ptr[j] != key_pass_attachment_ptr[j]) {
  418. return pass_attachment_ptr[j] < key_pass_attachment_ptr[j];
  419. }
  420. }
  421. }
  422. { // Compare preserve attachments.
  423. uint32_t attachment_size = pass_ptr[i].preserve_attachments.size();
  424. uint32_t key_attachment_size = key_pass_ptr[i].preserve_attachments.size();
  425. if (attachment_size != key_attachment_size) {
  426. return attachment_size < key_attachment_size;
  427. }
  428. const int32_t *pass_attachment_ptr = pass_ptr[i].preserve_attachments.ptr();
  429. const int32_t *key_pass_attachment_ptr = key_pass_ptr[i].preserve_attachments.ptr();
  430. for (uint32_t j = 0; j < attachment_size; j++) {
  431. if (pass_attachment_ptr[j] != key_pass_attachment_ptr[j]) {
  432. return pass_attachment_ptr[j] < key_pass_attachment_ptr[j];
  433. }
  434. }
  435. }
  436. if (pass_ptr[i].depth_attachment != key_pass_ptr[i].depth_attachment) {
  437. return pass_ptr[i].depth_attachment < key_pass_ptr[i].depth_attachment;
  438. }
  439. }
  440. int as = attachments.size();
  441. int bs = p_key.attachments.size();
  442. if (as != bs) {
  443. return as < bs;
  444. }
  445. const AttachmentFormat *af_a = attachments.ptr();
  446. const AttachmentFormat *af_b = p_key.attachments.ptr();
  447. for (int i = 0; i < as; i++) {
  448. const AttachmentFormat &a = af_a[i];
  449. const AttachmentFormat &b = af_b[i];
  450. if (a.format != b.format) {
  451. return a.format < b.format;
  452. }
  453. if (a.samples != b.samples) {
  454. return a.samples < b.samples;
  455. }
  456. if (a.usage_flags != b.usage_flags) {
  457. return a.usage_flags < b.usage_flags;
  458. }
  459. }
  460. return false; // Equal.
  461. }
  462. };
  463. static RDD::RenderPassID _render_pass_create(RenderingDeviceDriver *p_driver, const Vector<AttachmentFormat> &p_attachments, const Vector<FramebufferPass> &p_passes, VectorView<RDD::AttachmentLoadOp> p_load_ops, VectorView<RDD::AttachmentStoreOp> p_store_ops, uint32_t p_view_count = 1, Vector<TextureSamples> *r_samples = nullptr);
  464. static RDD::RenderPassID _render_pass_create_from_graph(RenderingDeviceDriver *p_driver, VectorView<RDD::AttachmentLoadOp> p_load_ops, VectorView<RDD::AttachmentStoreOp> p_store_ops, void *p_user_data);
  465. // This is a cache and it's never freed, it ensures
  466. // IDs for a given format are always unique.
  467. RBMap<FramebufferFormatKey, FramebufferFormatID> framebuffer_format_cache;
  468. struct FramebufferFormat {
  469. const RBMap<FramebufferFormatKey, FramebufferFormatID>::Element *E;
  470. RDD::RenderPassID render_pass; // Here for constructing shaders, never used, see section (7.2. Render Pass Compatibility from Vulkan spec).
  471. Vector<TextureSamples> pass_samples;
  472. uint32_t view_count = 1; // Number of views.
  473. };
  474. HashMap<FramebufferFormatID, FramebufferFormat> framebuffer_formats;
  475. struct Framebuffer {
  476. RenderingDevice *rendering_device = nullptr;
  477. FramebufferFormatID format_id;
  478. uint32_t storage_mask = 0;
  479. Vector<RID> texture_ids;
  480. InvalidationCallback invalidated_callback = nullptr;
  481. void *invalidated_callback_userdata = nullptr;
  482. RDG::FramebufferCache *framebuffer_cache = nullptr;
  483. Size2 size;
  484. uint32_t view_count;
  485. };
  486. RID_Owner<Framebuffer, true> framebuffer_owner;
  487. public:
  488. // This ID is warranted to be unique for the same formats, does not need to be freed
  489. FramebufferFormatID framebuffer_format_create(const Vector<AttachmentFormat> &p_format, uint32_t p_view_count = 1);
  490. FramebufferFormatID framebuffer_format_create_multipass(const Vector<AttachmentFormat> &p_attachments, const Vector<FramebufferPass> &p_passes, uint32_t p_view_count = 1);
  491. FramebufferFormatID framebuffer_format_create_empty(TextureSamples p_samples = TEXTURE_SAMPLES_1);
  492. TextureSamples framebuffer_format_get_texture_samples(FramebufferFormatID p_format, uint32_t p_pass = 0);
  493. RID framebuffer_create(const Vector<RID> &p_texture_attachments, FramebufferFormatID p_format_check = INVALID_ID, uint32_t p_view_count = 1);
  494. RID framebuffer_create_multipass(const Vector<RID> &p_texture_attachments, const Vector<FramebufferPass> &p_passes, FramebufferFormatID p_format_check = INVALID_ID, uint32_t p_view_count = 1);
  495. RID framebuffer_create_empty(const Size2i &p_size, TextureSamples p_samples = TEXTURE_SAMPLES_1, FramebufferFormatID p_format_check = INVALID_ID);
  496. bool framebuffer_is_valid(RID p_framebuffer) const;
  497. void framebuffer_set_invalidation_callback(RID p_framebuffer, InvalidationCallback p_callback, void *p_userdata);
  498. FramebufferFormatID framebuffer_get_format(RID p_framebuffer);
  499. Size2 framebuffer_get_size(RID p_framebuffer);
  500. /*****************/
  501. /**** SAMPLER ****/
  502. /*****************/
  503. private:
  504. RID_Owner<RDD::SamplerID, true> sampler_owner;
  505. public:
  506. RID sampler_create(const SamplerState &p_state);
  507. bool sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_sampler_filter) const;
  508. /**********************/
  509. /**** VERTEX ARRAY ****/
  510. /**********************/
  511. typedef int64_t VertexFormatID;
  512. private:
  513. // Vertex buffers in Vulkan are similar to how
  514. // they work in OpenGL, except that instead of
  515. // an attribute index, there is a buffer binding
  516. // index (for binding the buffers in real-time)
  517. // and a location index (what is used in the shader).
  518. //
  519. // This mapping is done here internally, and it's not
  520. // exposed.
  521. RID_Owner<Buffer, true> vertex_buffer_owner;
  522. struct VertexDescriptionKey {
  523. Vector<VertexAttribute> vertex_formats;
  524. bool operator==(const VertexDescriptionKey &p_key) const {
  525. int vdc = vertex_formats.size();
  526. int vdck = p_key.vertex_formats.size();
  527. if (vdc != vdck) {
  528. return false;
  529. } else {
  530. const VertexAttribute *a_ptr = vertex_formats.ptr();
  531. const VertexAttribute *b_ptr = p_key.vertex_formats.ptr();
  532. for (int i = 0; i < vdc; i++) {
  533. const VertexAttribute &a = a_ptr[i];
  534. const VertexAttribute &b = b_ptr[i];
  535. if (a.location != b.location) {
  536. return false;
  537. }
  538. if (a.offset != b.offset) {
  539. return false;
  540. }
  541. if (a.format != b.format) {
  542. return false;
  543. }
  544. if (a.stride != b.stride) {
  545. return false;
  546. }
  547. if (a.frequency != b.frequency) {
  548. return false;
  549. }
  550. }
  551. return true; // They are equal.
  552. }
  553. }
  554. uint32_t hash() const {
  555. int vdc = vertex_formats.size();
  556. uint32_t h = hash_murmur3_one_32(vdc);
  557. const VertexAttribute *ptr = vertex_formats.ptr();
  558. for (int i = 0; i < vdc; i++) {
  559. const VertexAttribute &vd = ptr[i];
  560. h = hash_murmur3_one_32(vd.location, h);
  561. h = hash_murmur3_one_32(vd.offset, h);
  562. h = hash_murmur3_one_32(vd.format, h);
  563. h = hash_murmur3_one_32(vd.stride, h);
  564. h = hash_murmur3_one_32(vd.frequency, h);
  565. }
  566. return hash_fmix32(h);
  567. }
  568. };
  569. struct VertexDescriptionHash {
  570. static _FORCE_INLINE_ uint32_t hash(const VertexDescriptionKey &p_key) {
  571. return p_key.hash();
  572. }
  573. };
  574. // This is a cache and it's never freed, it ensures that
  575. // ID used for a specific format always remain the same.
  576. HashMap<VertexDescriptionKey, VertexFormatID, VertexDescriptionHash> vertex_format_cache;
  577. struct VertexDescriptionCache {
  578. Vector<VertexAttribute> vertex_formats;
  579. RDD::VertexFormatID driver_id;
  580. };
  581. HashMap<VertexFormatID, VertexDescriptionCache> vertex_formats;
  582. struct VertexArray {
  583. RID buffer;
  584. VertexFormatID description;
  585. int vertex_count = 0;
  586. uint32_t max_instances_allowed = 0;
  587. Vector<RDD::BufferID> buffers; // Not owned, just referenced.
  588. Vector<RDG::ResourceTracker *> draw_trackers; // Not owned, just referenced.
  589. Vector<uint64_t> offsets;
  590. Vector<int32_t> transfer_worker_indices;
  591. Vector<uint64_t> transfer_worker_operations;
  592. HashSet<RID> untracked_buffers;
  593. };
  594. RID_Owner<VertexArray, true> vertex_array_owner;
  595. struct IndexBuffer : public Buffer {
  596. uint32_t max_index = 0; // Used for validation.
  597. uint32_t index_count = 0;
  598. IndexBufferFormat format = INDEX_BUFFER_FORMAT_UINT16;
  599. bool supports_restart_indices = false;
  600. };
  601. RID_Owner<IndexBuffer, true> index_buffer_owner;
  602. struct IndexArray {
  603. uint32_t max_index = 0; // Remember the maximum index here too, for validation.
  604. RDD::BufferID driver_id; // Not owned, inherited from index buffer.
  605. RDG::ResourceTracker *draw_tracker = nullptr; // Not owned, inherited from index buffer.
  606. uint32_t offset = 0;
  607. uint32_t indices = 0;
  608. IndexBufferFormat format = INDEX_BUFFER_FORMAT_UINT16;
  609. bool supports_restart_indices = false;
  610. int32_t transfer_worker_index = -1;
  611. uint64_t transfer_worker_operation = 0;
  612. };
  613. RID_Owner<IndexArray, true> index_array_owner;
  614. public:
  615. RID vertex_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data = Vector<uint8_t>(), bool p_use_as_storage = false);
  616. // This ID is warranted to be unique for the same formats, does not need to be freed
  617. VertexFormatID vertex_format_create(const Vector<VertexAttribute> &p_vertex_descriptions);
  618. RID vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const Vector<RID> &p_src_buffers, const Vector<uint64_t> &p_offsets = Vector<uint64_t>());
  619. 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);
  620. RID index_array_create(RID p_index_buffer, uint32_t p_index_offset, uint32_t p_index_count);
  621. /****************/
  622. /**** SHADER ****/
  623. /****************/
  624. // Some APIs (e.g., Vulkan) specifies a really complex behavior for the application
  625. // in order to tell when descriptor sets need to be re-bound (or not).
  626. // "When binding a descriptor set (see Descriptor Set Binding) to set
  627. // number N, if the previously bound descriptor sets for sets zero
  628. // through N-1 were all bound using compatible pipeline layouts,
  629. // then performing this binding does not disturb any of the lower numbered sets.
  630. // If, additionally, the previous bound descriptor set for set N was
  631. // bound using a pipeline layout compatible for set N, then the bindings
  632. // in sets numbered greater than N are also not disturbed."
  633. // As a result, we need to figure out quickly when something is no longer "compatible".
  634. // in order to avoid costly rebinds.
  635. private:
  636. struct UniformSetFormat {
  637. Vector<ShaderUniform> uniforms;
  638. _FORCE_INLINE_ bool operator<(const UniformSetFormat &p_other) const {
  639. if (uniforms.size() != p_other.uniforms.size()) {
  640. return uniforms.size() < p_other.uniforms.size();
  641. }
  642. for (int i = 0; i < uniforms.size(); i++) {
  643. if (uniforms[i] < p_other.uniforms[i]) {
  644. return true;
  645. } else if (p_other.uniforms[i] < uniforms[i]) {
  646. return false;
  647. }
  648. }
  649. return false;
  650. }
  651. };
  652. // Always grows, never shrinks, ensuring unique IDs, but we assume
  653. // the amount of formats will never be a problem, as the amount of shaders
  654. // in a game is limited.
  655. RBMap<UniformSetFormat, uint32_t> uniform_set_format_cache;
  656. // Shaders in Vulkan are just pretty much
  657. // precompiled blocks of SPIR-V bytecode. They
  658. // are most likely not really compiled to host
  659. // assembly until a pipeline is created.
  660. //
  661. // When supplying the shaders, this implementation
  662. // will use the reflection abilities of glslang to
  663. // understand and cache everything required to
  664. // create and use the descriptor sets (Vulkan's
  665. // biggest pain).
  666. //
  667. // Additionally, hashes are created for every set
  668. // to do quick validation and ensuring the user
  669. // does not submit something invalid.
  670. struct Shader : public ShaderDescription {
  671. String name; // Used for debug.
  672. RDD::ShaderID driver_id;
  673. uint32_t layout_hash = 0;
  674. BitField<RDD::PipelineStageBits> stage_bits;
  675. Vector<uint32_t> set_formats;
  676. };
  677. String _shader_uniform_debug(RID p_shader, int p_set = -1);
  678. RID_Owner<Shader, true> shader_owner;
  679. #ifndef DISABLE_DEPRECATED
  680. public:
  681. enum BarrierMask {
  682. BARRIER_MASK_VERTEX = 1,
  683. BARRIER_MASK_FRAGMENT = 8,
  684. BARRIER_MASK_COMPUTE = 2,
  685. BARRIER_MASK_TRANSFER = 4,
  686. BARRIER_MASK_RASTER = BARRIER_MASK_VERTEX | BARRIER_MASK_FRAGMENT, // 9,
  687. BARRIER_MASK_ALL_BARRIERS = 0x7FFF, // all flags set
  688. BARRIER_MASK_NO_BARRIER = 0x8000,
  689. };
  690. enum InitialAction {
  691. INITIAL_ACTION_LOAD,
  692. INITIAL_ACTION_CLEAR,
  693. INITIAL_ACTION_DISCARD,
  694. INITIAL_ACTION_MAX,
  695. INITIAL_ACTION_CLEAR_REGION = INITIAL_ACTION_CLEAR,
  696. INITIAL_ACTION_CLEAR_REGION_CONTINUE = INITIAL_ACTION_CLEAR,
  697. INITIAL_ACTION_KEEP = INITIAL_ACTION_LOAD,
  698. INITIAL_ACTION_DROP = INITIAL_ACTION_DISCARD,
  699. INITIAL_ACTION_CONTINUE = INITIAL_ACTION_LOAD,
  700. };
  701. enum FinalAction {
  702. FINAL_ACTION_STORE,
  703. FINAL_ACTION_DISCARD,
  704. FINAL_ACTION_MAX,
  705. FINAL_ACTION_READ = FINAL_ACTION_STORE,
  706. FINAL_ACTION_CONTINUE = FINAL_ACTION_STORE,
  707. };
  708. void barrier(BitField<BarrierMask> p_from = BARRIER_MASK_ALL_BARRIERS, BitField<BarrierMask> p_to = BARRIER_MASK_ALL_BARRIERS);
  709. void full_barrier();
  710. void draw_command_insert_label(String p_label_name, const Color &p_color = Color(1, 1, 1, 1));
  711. 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(), const Vector<RID> &p_storage_textures = Vector<RID>());
  712. Error draw_list_switch_to_next_pass_split(uint32_t p_splits, DrawListID *r_split_ids);
  713. Vector<int64_t> _draw_list_begin_split(RID p_framebuffer, uint32_t p_splits, 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(), const TypedArray<RID> &p_storage_textures = TypedArray<RID>());
  714. Vector<int64_t> _draw_list_switch_to_next_pass_split(uint32_t p_splits);
  715. private:
  716. void _draw_list_end_bind_compat_81356(BitField<BarrierMask> p_post_barrier);
  717. void _compute_list_end_bind_compat_81356(BitField<BarrierMask> p_post_barrier);
  718. void _barrier_bind_compat_81356(BitField<BarrierMask> p_from, BitField<BarrierMask> p_to);
  719. void _draw_list_end_bind_compat_84976(BitField<BarrierMask> p_post_barrier);
  720. void _compute_list_end_bind_compat_84976(BitField<BarrierMask> p_post_barrier);
  721. InitialAction _convert_initial_action_84976(InitialAction p_old_initial_action);
  722. FinalAction _convert_final_action_84976(FinalAction p_old_final_action);
  723. DrawListID _draw_list_begin_bind_compat_84976(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, float p_clear_depth, uint32_t p_clear_stencil, const Rect2 &p_region, const TypedArray<RID> &p_storage_textures);
  724. ComputeListID _compute_list_begin_bind_compat_84976(bool p_allow_draw_overlap);
  725. Error _buffer_update_bind_compat_84976(RID p_buffer, uint32_t p_offset, uint32_t p_size, const Vector<uint8_t> &p_data, BitField<BarrierMask> p_post_barrier);
  726. Error _buffer_clear_bind_compat_84976(RID p_buffer, uint32_t p_offset, uint32_t p_size, BitField<BarrierMask> p_post_barrier);
  727. Error _texture_update_bind_compat_84976(RID p_texture, uint32_t p_layer, const Vector<uint8_t> &p_data, BitField<BarrierMask> p_post_barrier);
  728. Error _texture_copy_bind_compat_84976(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, BitField<BarrierMask> p_post_barrier);
  729. Error _texture_clear_bind_compat_84976(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, BitField<BarrierMask> p_post_barrier);
  730. Error _texture_resolve_multisample_bind_compat_84976(RID p_from_texture, RID p_to_texture, BitField<BarrierMask> p_post_barrier);
  731. FramebufferFormatID _screen_get_framebuffer_format_bind_compat_87340() const;
  732. DrawListID _draw_list_begin_bind_compat_90993(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, float p_clear_depth, uint32_t p_clear_stencil, const Rect2 &p_region);
  733. DrawListID _draw_list_begin_bind_compat_98670(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, float p_clear_depth, uint32_t p_clear_stencil, const Rect2 &p_region, uint32_t p_breadcrumb);
  734. #endif
  735. public:
  736. RenderingContextDriver *get_context_driver() const { return context; }
  737. const RDD::Capabilities &get_device_capabilities() const { return driver->get_capabilities(); }
  738. bool has_feature(const Features p_feature) const;
  739. Vector<uint8_t> shader_compile_spirv_from_source(ShaderStage p_stage, const String &p_source_code, ShaderLanguage p_language = SHADER_LANGUAGE_GLSL, String *r_error = nullptr, bool p_allow_cache = true);
  740. String shader_get_spirv_cache_key() const;
  741. static void shader_set_compile_to_spirv_function(ShaderCompileToSPIRVFunction p_function);
  742. static void shader_set_spirv_cache_function(ShaderCacheFunction p_function);
  743. static void shader_set_get_cache_key_function(ShaderSPIRVGetCacheKeyFunction p_function);
  744. String shader_get_binary_cache_key() const;
  745. Vector<uint8_t> shader_compile_binary_from_spirv(const Vector<ShaderStageSPIRVData> &p_spirv, const String &p_shader_name = "");
  746. RID shader_create_from_spirv(const Vector<ShaderStageSPIRVData> &p_spirv, const String &p_shader_name = "");
  747. RID shader_create_from_bytecode(const Vector<uint8_t> &p_shader_binary, RID p_placeholder = RID());
  748. RID shader_create_placeholder();
  749. void shader_destroy_modules(RID p_shader);
  750. uint64_t shader_get_vertex_input_attribute_mask(RID p_shader);
  751. /******************/
  752. /**** UNIFORMS ****/
  753. /******************/
  754. String get_perf_report() const;
  755. enum StorageBufferUsage {
  756. STORAGE_BUFFER_USAGE_DISPATCH_INDIRECT = 1,
  757. };
  758. /*****************/
  759. /**** BUFFERS ****/
  760. /*****************/
  761. RID uniform_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data = Vector<uint8_t>());
  762. RID storage_buffer_create(uint32_t p_size, const Vector<uint8_t> &p_data = Vector<uint8_t>(), BitField<StorageBufferUsage> p_usage = 0);
  763. RID texture_buffer_create(uint32_t p_size_elements, DataFormat p_format, const Vector<uint8_t> &p_data = Vector<uint8_t>());
  764. struct Uniform {
  765. UniformType uniform_type = UNIFORM_TYPE_IMAGE;
  766. uint32_t binding = 0; // Binding index as specified in shader.
  767. // This flag specifies that this is an immutable sampler to be set when creating pipeline layout.
  768. bool immutable_sampler = false;
  769. private:
  770. // In most cases only one ID is provided per binding, so avoid allocating memory unnecessarily for performance.
  771. RID id; // If only one is provided, this is used.
  772. Vector<RID> ids; // If multiple ones are provided, this is used instead.
  773. public:
  774. _FORCE_INLINE_ uint32_t get_id_count() const {
  775. return (id.is_valid() ? 1 : ids.size());
  776. }
  777. _FORCE_INLINE_ RID get_id(uint32_t p_idx) const {
  778. if (id.is_valid()) {
  779. ERR_FAIL_COND_V(p_idx != 0, RID());
  780. return id;
  781. } else {
  782. return ids[p_idx];
  783. }
  784. }
  785. _FORCE_INLINE_ void set_id(uint32_t p_idx, RID p_id) {
  786. if (id.is_valid()) {
  787. ERR_FAIL_COND(p_idx != 0);
  788. id = p_id;
  789. } else {
  790. ids.write[p_idx] = p_id;
  791. }
  792. }
  793. _FORCE_INLINE_ void append_id(RID p_id) {
  794. if (ids.is_empty()) {
  795. if (id == RID()) {
  796. id = p_id;
  797. } else {
  798. ids.push_back(id);
  799. ids.push_back(p_id);
  800. id = RID();
  801. }
  802. } else {
  803. ids.push_back(p_id);
  804. }
  805. }
  806. _FORCE_INLINE_ void clear_ids() {
  807. id = RID();
  808. ids.clear();
  809. }
  810. _FORCE_INLINE_ Uniform(UniformType p_type, int p_binding, RID p_id) {
  811. uniform_type = p_type;
  812. binding = p_binding;
  813. id = p_id;
  814. }
  815. _FORCE_INLINE_ Uniform(UniformType p_type, int p_binding, const Vector<RID> &p_ids) {
  816. uniform_type = p_type;
  817. binding = p_binding;
  818. ids = p_ids;
  819. }
  820. _FORCE_INLINE_ Uniform() = default;
  821. };
  822. typedef Uniform PipelineImmutableSampler;
  823. RID shader_create_from_bytecode_with_samplers(const Vector<uint8_t> &p_shader_binary, RID p_placeholder = RID(), const Vector<PipelineImmutableSampler> &p_immutable_samplers = Vector<PipelineImmutableSampler>());
  824. private:
  825. static const uint32_t MAX_UNIFORM_SETS = 16;
  826. static const uint32_t MAX_PUSH_CONSTANT_SIZE = 128;
  827. // This structure contains the descriptor set. They _need_ to be allocated
  828. // for a shader (and will be erased when this shader is erased), but should
  829. // work for other shaders as long as the hash matches. This covers using
  830. // them in shader variants.
  831. //
  832. // Keep also in mind that you can share buffers between descriptor sets, so
  833. // the above restriction is not too serious.
  834. struct UniformSet {
  835. uint32_t format = 0;
  836. RID shader_id;
  837. uint32_t shader_set = 0;
  838. RDD::UniformSetID driver_id;
  839. struct AttachableTexture {
  840. uint32_t bind = 0;
  841. RID texture;
  842. };
  843. struct SharedTexture {
  844. uint32_t writing = 0;
  845. RID texture;
  846. };
  847. LocalVector<AttachableTexture> attachable_textures; // Used for validation.
  848. Vector<RDG::ResourceTracker *> draw_trackers;
  849. Vector<RDG::ResourceUsage> draw_trackers_usage;
  850. HashMap<RID, RDG::ResourceUsage> untracked_usage;
  851. LocalVector<SharedTexture> shared_textures_to_update;
  852. InvalidationCallback invalidated_callback = nullptr;
  853. void *invalidated_callback_userdata = nullptr;
  854. };
  855. RID_Owner<UniformSet, true> uniform_set_owner;
  856. void _uniform_set_update_shared(UniformSet *p_uniform_set);
  857. public:
  858. /** Bake a set of uniforms that can be bound at runtime with the given shader.
  859. * @remark Setting p_linear_pool = true while keeping the RID around for longer than the current frame will result in undefined behavior.
  860. * @param p_uniforms The uniforms to bake into a set.
  861. * @param p_shader The shader you intend to bind these uniforms with.
  862. * @param p_set_index The set. Should be in range [0; 4)
  863. * The value 4 comes from physical_device_properties.limits.maxBoundDescriptorSets. Vulkan only guarantees maxBoundDescriptorSets >= 4 (== 4 is very common on Mobile).
  864. * @param p_linear_pool If you call this function every frame (and free the returned RID within the same frame!), set it to true for better performance.
  865. * If you plan on keeping the return value around for more than one frame (e.g. Sets that are created once and reused forever) you MUST set it to false.
  866. * @return Baked descriptor set.
  867. */
  868. template <typename Collection>
  869. RID uniform_set_create(const Collection &p_uniforms, RID p_shader, uint32_t p_shader_set, bool p_linear_pool = false);
  870. bool uniform_set_is_valid(RID p_uniform_set);
  871. void uniform_set_set_invalidation_callback(RID p_uniform_set, InvalidationCallback p_callback, void *p_userdata);
  872. bool uniform_sets_have_linear_pools() const;
  873. /*******************/
  874. /**** PIPELINES ****/
  875. /*******************/
  876. // Render pipeline contains ALL the
  877. // information required for drawing.
  878. // This includes all the rasterizer state
  879. // as well as shader used, framebuffer format,
  880. // etc.
  881. // While the pipeline is just a single object
  882. // (VkPipeline) a lot of values are also saved
  883. // here to do validation (vulkan does none by
  884. // default) and warn the user if something
  885. // was not supplied as intended.
  886. private:
  887. struct RenderPipeline {
  888. // Cached values for validation.
  889. #ifdef DEBUG_ENABLED
  890. struct Validation {
  891. FramebufferFormatID framebuffer_format;
  892. uint32_t render_pass = 0;
  893. uint32_t dynamic_state = 0;
  894. VertexFormatID vertex_format;
  895. bool uses_restart_indices = false;
  896. uint32_t primitive_minimum = 0;
  897. uint32_t primitive_divisor = 0;
  898. } validation;
  899. #endif
  900. // Actual pipeline.
  901. RID shader;
  902. RDD::ShaderID shader_driver_id;
  903. uint32_t shader_layout_hash = 0;
  904. Vector<uint32_t> set_formats;
  905. RDD::PipelineID driver_id;
  906. BitField<RDD::PipelineStageBits> stage_bits;
  907. uint32_t push_constant_size = 0;
  908. };
  909. RID_Owner<RenderPipeline, true> render_pipeline_owner;
  910. bool pipeline_cache_enabled = false;
  911. size_t pipeline_cache_size = 0;
  912. String pipeline_cache_file_path;
  913. WorkerThreadPool::TaskID pipeline_cache_save_task = WorkerThreadPool::INVALID_TASK_ID;
  914. Vector<uint8_t> _load_pipeline_cache();
  915. void _update_pipeline_cache(bool p_closing = false);
  916. static void _save_pipeline_cache(void *p_data);
  917. struct ComputePipeline {
  918. RID shader;
  919. RDD::ShaderID shader_driver_id;
  920. uint32_t shader_layout_hash = 0;
  921. Vector<uint32_t> set_formats;
  922. RDD::PipelineID driver_id;
  923. uint32_t push_constant_size = 0;
  924. uint32_t local_group_size[3] = { 0, 0, 0 };
  925. };
  926. RID_Owner<ComputePipeline, true> compute_pipeline_owner;
  927. public:
  928. 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, BitField<PipelineDynamicStateFlags> p_dynamic_state_flags = 0, uint32_t p_for_render_pass = 0, const Vector<PipelineSpecializationConstant> &p_specialization_constants = Vector<PipelineSpecializationConstant>());
  929. bool render_pipeline_is_valid(RID p_pipeline);
  930. RID compute_pipeline_create(RID p_shader, const Vector<PipelineSpecializationConstant> &p_specialization_constants = Vector<PipelineSpecializationConstant>());
  931. bool compute_pipeline_is_valid(RID p_pipeline);
  932. private:
  933. /****************/
  934. /**** SCREEN ****/
  935. /****************/
  936. HashMap<DisplayServer::WindowID, RDD::SwapChainID> screen_swap_chains;
  937. HashMap<DisplayServer::WindowID, RDD::FramebufferID> screen_framebuffers;
  938. uint32_t _get_swap_chain_desired_count() const;
  939. public:
  940. Error screen_create(DisplayServer::WindowID p_screen = DisplayServer::MAIN_WINDOW_ID);
  941. Error screen_prepare_for_drawing(DisplayServer::WindowID p_screen = DisplayServer::MAIN_WINDOW_ID);
  942. int screen_get_width(DisplayServer::WindowID p_screen = DisplayServer::MAIN_WINDOW_ID) const;
  943. int screen_get_height(DisplayServer::WindowID p_screen = DisplayServer::MAIN_WINDOW_ID) const;
  944. int screen_get_pre_rotation_degrees(DisplayServer::WindowID p_screen = DisplayServer::MAIN_WINDOW_ID) const;
  945. FramebufferFormatID screen_get_framebuffer_format(DisplayServer::WindowID p_screen = DisplayServer::MAIN_WINDOW_ID) const;
  946. Error screen_free(DisplayServer::WindowID p_screen = DisplayServer::MAIN_WINDOW_ID);
  947. /*************************/
  948. /**** DRAW LISTS (II) ****/
  949. /*************************/
  950. private:
  951. // Draw list contains both the command buffer
  952. // used for drawing as well as a LOT of
  953. // information used for validation. This
  954. // validation is cheap so most of it can
  955. // also run in release builds.
  956. struct DrawList {
  957. Rect2i viewport;
  958. bool viewport_set = false;
  959. struct SetState {
  960. uint32_t pipeline_expected_format = 0;
  961. uint32_t uniform_set_format = 0;
  962. RDD::UniformSetID uniform_set_driver_id;
  963. RID uniform_set;
  964. bool bound = false;
  965. };
  966. struct State {
  967. SetState sets[MAX_UNIFORM_SETS];
  968. uint32_t set_count = 0;
  969. RID pipeline;
  970. RID pipeline_shader;
  971. RDD::ShaderID pipeline_shader_driver_id;
  972. uint32_t pipeline_shader_layout_hash = 0;
  973. uint32_t pipeline_push_constant_size = 0;
  974. RID vertex_array;
  975. RID index_array;
  976. uint32_t draw_count = 0;
  977. } state;
  978. #ifdef DEBUG_ENABLED
  979. struct Validation {
  980. bool active = true; // Means command buffer was not closed, so you can keep adding things.
  981. // Actual render pass values.
  982. uint32_t dynamic_state = 0;
  983. VertexFormatID vertex_format = INVALID_ID;
  984. uint32_t vertex_array_size = 0;
  985. uint32_t vertex_max_instances_allowed = 0xFFFFFFFF;
  986. bool index_buffer_uses_restart_indices = false;
  987. uint32_t index_array_count = 0;
  988. uint32_t index_array_max_index = 0;
  989. Vector<uint32_t> set_formats;
  990. Vector<bool> set_bound;
  991. Vector<RID> set_rids;
  992. // Last pipeline set values.
  993. bool pipeline_active = false;
  994. uint32_t pipeline_dynamic_state = 0;
  995. VertexFormatID pipeline_vertex_format = INVALID_ID;
  996. RID pipeline_shader;
  997. bool pipeline_uses_restart_indices = false;
  998. uint32_t pipeline_primitive_divisor = 0;
  999. uint32_t pipeline_primitive_minimum = 0;
  1000. uint32_t pipeline_push_constant_size = 0;
  1001. bool pipeline_push_constant_supplied = false;
  1002. } validation;
  1003. #else
  1004. struct Validation {
  1005. uint32_t vertex_array_size = 0;
  1006. uint32_t index_array_count = 0;
  1007. } validation;
  1008. #endif
  1009. };
  1010. DrawList *draw_list = nullptr;
  1011. uint32_t draw_list_subpass_count = 0;
  1012. #ifdef DEBUG_ENABLED
  1013. FramebufferFormatID draw_list_framebuffer_format = INVALID_ID;
  1014. #endif
  1015. uint32_t draw_list_current_subpass = 0;
  1016. Vector<RID> draw_list_bound_textures;
  1017. _FORCE_INLINE_ DrawList *_get_draw_list_ptr(DrawListID p_id);
  1018. Error _draw_list_allocate(const Rect2i &p_viewport, uint32_t p_subpass);
  1019. void _draw_list_free(Rect2i *r_last_viewport = nullptr);
  1020. public:
  1021. enum DrawFlags {
  1022. DRAW_DEFAULT_ALL = 0,
  1023. DRAW_CLEAR_COLOR_0 = (1 << 0),
  1024. DRAW_CLEAR_COLOR_1 = (1 << 1),
  1025. DRAW_CLEAR_COLOR_2 = (1 << 2),
  1026. DRAW_CLEAR_COLOR_3 = (1 << 3),
  1027. DRAW_CLEAR_COLOR_4 = (1 << 4),
  1028. DRAW_CLEAR_COLOR_5 = (1 << 5),
  1029. DRAW_CLEAR_COLOR_6 = (1 << 6),
  1030. DRAW_CLEAR_COLOR_7 = (1 << 7),
  1031. DRAW_CLEAR_COLOR_MASK = 0xFF,
  1032. DRAW_CLEAR_COLOR_ALL = DRAW_CLEAR_COLOR_MASK,
  1033. DRAW_IGNORE_COLOR_0 = (1 << 8),
  1034. DRAW_IGNORE_COLOR_1 = (1 << 9),
  1035. DRAW_IGNORE_COLOR_2 = (1 << 10),
  1036. DRAW_IGNORE_COLOR_3 = (1 << 11),
  1037. DRAW_IGNORE_COLOR_4 = (1 << 12),
  1038. DRAW_IGNORE_COLOR_5 = (1 << 13),
  1039. DRAW_IGNORE_COLOR_6 = (1 << 14),
  1040. DRAW_IGNORE_COLOR_7 = (1 << 15),
  1041. DRAW_IGNORE_COLOR_MASK = 0xFF00,
  1042. DRAW_IGNORE_COLOR_ALL = DRAW_IGNORE_COLOR_MASK,
  1043. DRAW_CLEAR_DEPTH = (1 << 16),
  1044. DRAW_IGNORE_DEPTH = (1 << 17),
  1045. DRAW_CLEAR_STENCIL = (1 << 18),
  1046. DRAW_IGNORE_STENCIL = (1 << 19),
  1047. DRAW_CLEAR_ALL = DRAW_CLEAR_COLOR_ALL | DRAW_CLEAR_DEPTH | DRAW_CLEAR_STENCIL,
  1048. DRAW_IGNORE_ALL = DRAW_IGNORE_COLOR_ALL | DRAW_IGNORE_DEPTH | DRAW_IGNORE_STENCIL
  1049. };
  1050. DrawListID draw_list_begin_for_screen(DisplayServer::WindowID p_screen = 0, const Color &p_clear_color = Color());
  1051. DrawListID draw_list_begin(RID p_framebuffer, BitField<DrawFlags> p_draw_flags = DRAW_DEFAULT_ALL, const Vector<Color> &p_clear_color_values = Vector<Color>(), float p_clear_depth_value = 1.0f, uint32_t p_clear_stencil_value = 0, const Rect2 &p_region = Rect2(), uint32_t p_breadcrumb = 0);
  1052. void draw_list_set_blend_constants(DrawListID p_list, const Color &p_color);
  1053. void draw_list_bind_render_pipeline(DrawListID p_list, RID p_render_pipeline);
  1054. void draw_list_bind_uniform_set(DrawListID p_list, RID p_uniform_set, uint32_t p_index);
  1055. void draw_list_bind_vertex_array(DrawListID p_list, RID p_vertex_array);
  1056. void draw_list_bind_index_array(DrawListID p_list, RID p_index_array);
  1057. void draw_list_set_line_width(DrawListID p_list, float p_width);
  1058. void draw_list_set_push_constant(DrawListID p_list, const void *p_data, uint32_t p_data_size);
  1059. void draw_list_draw(DrawListID p_list, bool p_use_indices, uint32_t p_instances = 1, uint32_t p_procedural_vertices = 0);
  1060. void draw_list_draw_indirect(DrawListID p_list, bool p_use_indices, RID p_buffer, uint32_t p_offset = 0, uint32_t p_draw_count = 1, uint32_t p_stride = 0);
  1061. void draw_list_set_viewport(DrawListID p_list, const Rect2 &p_rect);
  1062. void draw_list_enable_scissor(DrawListID p_list, const Rect2 &p_rect);
  1063. void draw_list_disable_scissor(DrawListID p_list);
  1064. uint32_t draw_list_get_current_pass();
  1065. DrawListID draw_list_switch_to_next_pass();
  1066. void draw_list_end();
  1067. private:
  1068. /***********************/
  1069. /**** COMPUTE LISTS ****/
  1070. /***********************/
  1071. struct ComputeList {
  1072. struct SetState {
  1073. uint32_t pipeline_expected_format = 0;
  1074. uint32_t uniform_set_format = 0;
  1075. RDD::UniformSetID uniform_set_driver_id;
  1076. RID uniform_set;
  1077. bool bound = false;
  1078. };
  1079. struct State {
  1080. SetState sets[MAX_UNIFORM_SETS];
  1081. uint32_t set_count = 0;
  1082. RID pipeline;
  1083. RID pipeline_shader;
  1084. RDD::ShaderID pipeline_shader_driver_id;
  1085. uint32_t pipeline_shader_layout_hash = 0;
  1086. uint32_t local_group_size[3] = { 0, 0, 0 };
  1087. uint8_t push_constant_data[MAX_PUSH_CONSTANT_SIZE] = {};
  1088. uint32_t push_constant_size = 0;
  1089. uint32_t dispatch_count = 0;
  1090. } state;
  1091. #ifdef DEBUG_ENABLED
  1092. struct Validation {
  1093. bool active = true; // Means command buffer was not closed, so you can keep adding things.
  1094. Vector<uint32_t> set_formats;
  1095. Vector<bool> set_bound;
  1096. Vector<RID> set_rids;
  1097. // Last pipeline set values.
  1098. bool pipeline_active = false;
  1099. RID pipeline_shader;
  1100. uint32_t invalid_set_from = 0;
  1101. uint32_t pipeline_push_constant_size = 0;
  1102. bool pipeline_push_constant_supplied = false;
  1103. } validation;
  1104. #endif
  1105. };
  1106. ComputeList *compute_list = nullptr;
  1107. ComputeList::State compute_list_barrier_state;
  1108. public:
  1109. ComputeListID compute_list_begin();
  1110. void compute_list_bind_compute_pipeline(ComputeListID p_list, RID p_compute_pipeline);
  1111. void compute_list_bind_uniform_set(ComputeListID p_list, RID p_uniform_set, uint32_t p_index);
  1112. void compute_list_set_push_constant(ComputeListID p_list, const void *p_data, uint32_t p_data_size);
  1113. void compute_list_dispatch(ComputeListID p_list, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups);
  1114. void compute_list_dispatch_threads(ComputeListID p_list, uint32_t p_x_threads, uint32_t p_y_threads, uint32_t p_z_threads);
  1115. void compute_list_dispatch_indirect(ComputeListID p_list, RID p_buffer, uint32_t p_offset);
  1116. void compute_list_add_barrier(ComputeListID p_list);
  1117. void compute_list_end();
  1118. private:
  1119. /*************************/
  1120. /**** TRANSFER WORKER ****/
  1121. /*************************/
  1122. struct TransferWorker {
  1123. uint32_t index = 0;
  1124. RDD::BufferID staging_buffer;
  1125. uint32_t max_transfer_size = 0;
  1126. uint32_t staging_buffer_size_in_use = 0;
  1127. uint32_t staging_buffer_size_allocated = 0;
  1128. RDD::CommandBufferID command_buffer;
  1129. RDD::CommandPoolID command_pool;
  1130. RDD::FenceID command_fence;
  1131. LocalVector<RDD::TextureBarrier> texture_barriers;
  1132. bool recording = false;
  1133. bool submitted = false;
  1134. BinaryMutex thread_mutex;
  1135. uint64_t operations_processed = 0;
  1136. uint64_t operations_submitted = 0;
  1137. uint64_t operations_counter = 0;
  1138. BinaryMutex operations_mutex;
  1139. };
  1140. LocalVector<TransferWorker *> transfer_worker_pool;
  1141. uint32_t transfer_worker_pool_max_size = 1;
  1142. LocalVector<uint64_t> transfer_worker_operation_used_by_draw;
  1143. LocalVector<uint32_t> transfer_worker_pool_available_list;
  1144. LocalVector<RDD::TextureBarrier> transfer_worker_pool_texture_barriers;
  1145. BinaryMutex transfer_worker_pool_mutex;
  1146. BinaryMutex transfer_worker_pool_texture_barriers_mutex;
  1147. ConditionVariable transfer_worker_pool_condition;
  1148. TransferWorker *_acquire_transfer_worker(uint32_t p_transfer_size, uint32_t p_required_align, uint32_t &r_staging_offset);
  1149. void _release_transfer_worker(TransferWorker *p_transfer_worker);
  1150. void _end_transfer_worker(TransferWorker *p_transfer_worker);
  1151. void _submit_transfer_worker(TransferWorker *p_transfer_worker, VectorView<RDD::SemaphoreID> p_signal_semaphores = VectorView<RDD::SemaphoreID>());
  1152. void _wait_for_transfer_worker(TransferWorker *p_transfer_worker);
  1153. void _flush_barriers_for_transfer_worker(TransferWorker *p_transfer_worker);
  1154. void _check_transfer_worker_operation(uint32_t p_transfer_worker_index, uint64_t p_transfer_worker_operation);
  1155. void _check_transfer_worker_buffer(Buffer *p_buffer);
  1156. void _check_transfer_worker_texture(Texture *p_texture);
  1157. void _check_transfer_worker_vertex_array(VertexArray *p_vertex_array);
  1158. void _check_transfer_worker_index_array(IndexArray *p_index_array);
  1159. void _submit_transfer_workers(RDD::CommandBufferID p_draw_command_buffer = RDD::CommandBufferID());
  1160. void _submit_transfer_barriers(RDD::CommandBufferID p_draw_command_buffer);
  1161. void _wait_for_transfer_workers();
  1162. void _free_transfer_workers();
  1163. /***********************/
  1164. /**** COMMAND GRAPH ****/
  1165. /***********************/
  1166. bool _texture_make_mutable(Texture *p_texture, RID p_texture_id);
  1167. bool _buffer_make_mutable(Buffer *p_buffer, RID p_buffer_id);
  1168. bool _vertex_array_make_mutable(VertexArray *p_vertex_array, RID p_resource_id, RDG::ResourceTracker *p_resource_tracker);
  1169. bool _index_array_make_mutable(IndexArray *p_index_array, RDG::ResourceTracker *p_resource_tracker);
  1170. bool _uniform_set_make_mutable(UniformSet *p_uniform_set, RID p_resource_id, RDG::ResourceTracker *p_resource_tracker);
  1171. bool _dependency_make_mutable(RID p_id, RID p_resource_id, RDG::ResourceTracker *p_resource_tracker);
  1172. bool _dependencies_make_mutable_recursive(RID p_id, RDG::ResourceTracker *p_resource_tracker);
  1173. bool _dependencies_make_mutable(RID p_id, RDG::ResourceTracker *p_resource_tracker);
  1174. RenderingDeviceGraph draw_graph;
  1175. /**************************/
  1176. /**** QUEUE MANAGEMENT ****/
  1177. /**************************/
  1178. RDD::CommandQueueFamilyID main_queue_family;
  1179. RDD::CommandQueueFamilyID transfer_queue_family;
  1180. RDD::CommandQueueFamilyID present_queue_family;
  1181. RDD::CommandQueueID main_queue;
  1182. RDD::CommandQueueID transfer_queue;
  1183. RDD::CommandQueueID present_queue;
  1184. /**************************/
  1185. /**** FRAME MANAGEMENT ****/
  1186. /**************************/
  1187. // This is the frame structure. There are normally
  1188. // 3 of these (used for triple buffering), or 2
  1189. // (double buffering). They are cycled constantly.
  1190. //
  1191. // It contains two command buffers, one that is
  1192. // used internally for setting up (creating stuff)
  1193. // and another used mostly for drawing.
  1194. //
  1195. // They also contains a list of things that need
  1196. // to be disposed of when deleted, which can't
  1197. // happen immediately due to the asynchronous
  1198. // nature of the GPU. They will get deleted
  1199. // when the frame is cycled.
  1200. struct Frame {
  1201. // List in usage order, from last to free to first to free.
  1202. List<Buffer> buffers_to_dispose_of;
  1203. List<Texture> textures_to_dispose_of;
  1204. List<Framebuffer> framebuffers_to_dispose_of;
  1205. List<RDD::SamplerID> samplers_to_dispose_of;
  1206. List<Shader> shaders_to_dispose_of;
  1207. List<UniformSet> uniform_sets_to_dispose_of;
  1208. List<RenderPipeline> render_pipelines_to_dispose_of;
  1209. List<ComputePipeline> compute_pipelines_to_dispose_of;
  1210. // Pending asynchronous data transfer for buffers.
  1211. LocalVector<RDD::BufferID> download_buffer_staging_buffers;
  1212. LocalVector<RDD::BufferCopyRegion> download_buffer_copy_regions;
  1213. LocalVector<BufferGetDataRequest> download_buffer_get_data_requests;
  1214. // Pending asynchronous data transfer for textures.
  1215. LocalVector<RDD::BufferID> download_texture_staging_buffers;
  1216. LocalVector<RDD::BufferTextureCopyRegion> download_buffer_texture_copy_regions;
  1217. LocalVector<uint32_t> download_texture_mipmap_offsets;
  1218. LocalVector<TextureGetDataRequest> download_texture_get_data_requests;
  1219. // The command pool used by the command buffer.
  1220. RDD::CommandPoolID command_pool;
  1221. // The command buffer used by the main thread when recording the frame.
  1222. RDD::CommandBufferID command_buffer;
  1223. // Signaled by the command buffer submission. Present must wait on this semaphore.
  1224. RDD::SemaphoreID semaphore;
  1225. // Signaled by the command buffer submission. Must wait on this fence before beginning command recording for the frame.
  1226. RDD::FenceID fence;
  1227. bool fence_signaled = false;
  1228. // Semaphores the frame must wait on before executing the command buffer.
  1229. LocalVector<RDD::SemaphoreID> semaphores_to_wait_on;
  1230. // Swap chains prepared for drawing during the frame that must be presented.
  1231. LocalVector<RDD::SwapChainID> swap_chains_to_present;
  1232. // Semaphores the transfer workers can use to wait before rendering the frame.
  1233. // This must have the same size of the transfer worker pool.
  1234. TightLocalVector<RDD::SemaphoreID> transfer_worker_semaphores;
  1235. // Extra command buffer pool used for driver workarounds or to reduce GPU bubbles by
  1236. // splitting the final render pass to the swapchain into its own cmd buffer.
  1237. RDG::CommandBufferPool command_buffer_pool;
  1238. struct Timestamp {
  1239. String description;
  1240. uint64_t value = 0;
  1241. };
  1242. RDD::QueryPoolID timestamp_pool;
  1243. TightLocalVector<String> timestamp_names;
  1244. TightLocalVector<uint64_t> timestamp_cpu_values;
  1245. uint32_t timestamp_count = 0;
  1246. TightLocalVector<String> timestamp_result_names;
  1247. TightLocalVector<uint64_t> timestamp_cpu_result_values;
  1248. TightLocalVector<uint64_t> timestamp_result_values;
  1249. uint32_t timestamp_result_count = 0;
  1250. uint64_t index = 0;
  1251. };
  1252. uint32_t max_timestamp_query_elements = 0;
  1253. int frame = 0;
  1254. TightLocalVector<Frame> frames;
  1255. uint64_t frames_drawn = 0;
  1256. // Whenever logic/physics request a graphics operation (not just deleting a resource) that requires
  1257. // us to flush all graphics commands, we must set frames_pending_resources_for_processing = frames.size().
  1258. // This is important for when the user requested for the logic loop to still be updated while
  1259. // graphics should not (e.g. headless Multiplayer servers, minimized windows that need to still
  1260. // process something on the background).
  1261. uint32_t frames_pending_resources_for_processing = 0u;
  1262. public:
  1263. bool has_pending_resources_for_processing() const { return frames_pending_resources_for_processing != 0u; }
  1264. private:
  1265. void _free_pending_resources(int p_frame);
  1266. uint64_t texture_memory = 0;
  1267. uint64_t buffer_memory = 0;
  1268. protected:
  1269. void execute_chained_cmds(bool p_present_swap_chain,
  1270. RenderingDeviceDriver::FenceID p_draw_fence,
  1271. RenderingDeviceDriver::SemaphoreID p_dst_draw_semaphore_to_signal);
  1272. public:
  1273. void _free_internal(RID p_id);
  1274. void _begin_frame(bool p_presented = false);
  1275. void _end_frame();
  1276. void _execute_frame(bool p_present);
  1277. void _stall_for_frame(uint32_t p_frame);
  1278. void _stall_for_previous_frames();
  1279. void _flush_and_stall_for_all_frames();
  1280. template <typename T>
  1281. void _free_rids(T &p_owner, const char *p_type);
  1282. #ifdef DEV_ENABLED
  1283. HashMap<RID, String> resource_names;
  1284. #endif
  1285. public:
  1286. Error initialize(RenderingContextDriver *p_context, DisplayServer::WindowID p_main_window = DisplayServer::INVALID_WINDOW_ID);
  1287. void finalize();
  1288. void _set_max_fps(int p_max_fps);
  1289. void free(RID p_id);
  1290. /****************/
  1291. /**** Timing ****/
  1292. /****************/
  1293. void capture_timestamp(const String &p_name);
  1294. uint32_t get_captured_timestamps_count() const;
  1295. uint64_t get_captured_timestamps_frame() const;
  1296. uint64_t get_captured_timestamp_gpu_time(uint32_t p_index) const;
  1297. uint64_t get_captured_timestamp_cpu_time(uint32_t p_index) const;
  1298. String get_captured_timestamp_name(uint32_t p_index) const;
  1299. /****************/
  1300. /**** LIMITS ****/
  1301. /****************/
  1302. uint64_t limit_get(Limit p_limit) const;
  1303. void swap_buffers(bool p_present);
  1304. uint32_t get_frame_delay() const;
  1305. void submit();
  1306. void sync();
  1307. enum MemoryType {
  1308. MEMORY_TEXTURES,
  1309. MEMORY_BUFFERS,
  1310. MEMORY_TOTAL
  1311. };
  1312. uint64_t get_memory_usage(MemoryType p_type) const;
  1313. RenderingDevice *create_local_device();
  1314. void set_resource_name(RID p_id, const String &p_name);
  1315. void draw_command_begin_label(String p_label_name, const Color &p_color = Color(1, 1, 1, 1));
  1316. void draw_command_end_label();
  1317. String get_device_vendor_name() const;
  1318. String get_device_name() const;
  1319. DeviceType get_device_type() const;
  1320. String get_device_api_name() const;
  1321. String get_device_api_version() const;
  1322. String get_device_pipeline_cache_uuid() const;
  1323. bool is_composite_alpha_supported() const;
  1324. uint64_t get_driver_resource(DriverResource p_resource, RID p_rid = RID(), uint64_t p_index = 0);
  1325. String get_driver_and_device_memory_report() const;
  1326. String get_tracked_object_name(uint32_t p_type_index) const;
  1327. uint64_t get_tracked_object_type_count() const;
  1328. uint64_t get_driver_total_memory() const;
  1329. uint64_t get_driver_allocation_count() const;
  1330. uint64_t get_driver_memory_by_object_type(uint32_t p_type) const;
  1331. uint64_t get_driver_allocs_by_object_type(uint32_t p_type) const;
  1332. uint64_t get_device_total_memory() const;
  1333. uint64_t get_device_allocation_count() const;
  1334. uint64_t get_device_memory_by_object_type(uint32_t p_type) const;
  1335. uint64_t get_device_allocs_by_object_type(uint32_t p_type) const;
  1336. static RenderingDevice *get_singleton();
  1337. void make_current();
  1338. RenderingDevice();
  1339. ~RenderingDevice();
  1340. private:
  1341. /*****************/
  1342. /**** BINDERS ****/
  1343. /*****************/
  1344. RID _texture_create(const Ref<RDTextureFormat> &p_format, const Ref<RDTextureView> &p_view, const TypedArray<PackedByteArray> &p_data = Array());
  1345. RID _texture_create_shared(const Ref<RDTextureView> &p_view, RID p_with_texture);
  1346. RID _texture_create_shared_from_slice(const Ref<RDTextureView> &p_view, RID p_with_texture, uint32_t p_layer, uint32_t p_mipmap, uint32_t p_mipmaps = 1, TextureSliceType p_slice_type = TEXTURE_SLICE_2D);
  1347. Ref<RDTextureFormat> _texture_get_format(RID p_rd_texture);
  1348. FramebufferFormatID _framebuffer_format_create(const TypedArray<RDAttachmentFormat> &p_attachments, uint32_t p_view_count);
  1349. FramebufferFormatID _framebuffer_format_create_multipass(const TypedArray<RDAttachmentFormat> &p_attachments, const TypedArray<RDFramebufferPass> &p_passes, uint32_t p_view_count);
  1350. RID _framebuffer_create(const TypedArray<RID> &p_textures, FramebufferFormatID p_format_check = INVALID_ID, uint32_t p_view_count = 1);
  1351. RID _framebuffer_create_multipass(const TypedArray<RID> &p_textures, const TypedArray<RDFramebufferPass> &p_passes, FramebufferFormatID p_format_check = INVALID_ID, uint32_t p_view_count = 1);
  1352. RID _sampler_create(const Ref<RDSamplerState> &p_state);
  1353. VertexFormatID _vertex_format_create(const TypedArray<RDVertexAttribute> &p_vertex_formats);
  1354. RID _vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const TypedArray<RID> &p_src_buffers, const Vector<int64_t> &p_offsets = Vector<int64_t>());
  1355. Ref<RDShaderSPIRV> _shader_compile_spirv_from_source(const Ref<RDShaderSource> &p_source, bool p_allow_cache = true);
  1356. Vector<uint8_t> _shader_compile_binary_from_spirv(const Ref<RDShaderSPIRV> &p_bytecode, const String &p_shader_name = "");
  1357. RID _shader_create_from_spirv(const Ref<RDShaderSPIRV> &p_spirv, const String &p_shader_name = "");
  1358. RID _uniform_set_create(const TypedArray<RDUniform> &p_uniforms, RID p_shader, uint32_t p_shader_set);
  1359. Error _buffer_update_bind(RID p_buffer, uint32_t p_offset, uint32_t p_size, const Vector<uint8_t> &p_data);
  1360. RID _render_pipeline_create(RID p_shader, FramebufferFormatID p_framebuffer_format, VertexFormatID p_vertex_format, RenderPrimitive p_render_primitive, const Ref<RDPipelineRasterizationState> &p_rasterization_state, const Ref<RDPipelineMultisampleState> &p_multisample_state, const Ref<RDPipelineDepthStencilState> &p_depth_stencil_state, const Ref<RDPipelineColorBlendState> &p_blend_state, BitField<PipelineDynamicStateFlags> p_dynamic_state_flags, uint32_t p_for_render_pass, const TypedArray<RDPipelineSpecializationConstant> &p_specialization_constants);
  1361. RID _compute_pipeline_create(RID p_shader, const TypedArray<RDPipelineSpecializationConstant> &p_specialization_constants);
  1362. void _draw_list_set_push_constant(DrawListID p_list, const Vector<uint8_t> &p_data, uint32_t p_data_size);
  1363. void _compute_list_set_push_constant(ComputeListID p_list, const Vector<uint8_t> &p_data, uint32_t p_data_size);
  1364. };
  1365. VARIANT_ENUM_CAST(RenderingDevice::DeviceType)
  1366. VARIANT_ENUM_CAST(RenderingDevice::DriverResource)
  1367. VARIANT_ENUM_CAST(RenderingDevice::ShaderStage)
  1368. VARIANT_ENUM_CAST(RenderingDevice::ShaderLanguage)
  1369. VARIANT_ENUM_CAST(RenderingDevice::CompareOperator)
  1370. VARIANT_ENUM_CAST(RenderingDevice::DataFormat)
  1371. VARIANT_ENUM_CAST(RenderingDevice::TextureType)
  1372. VARIANT_ENUM_CAST(RenderingDevice::TextureSamples)
  1373. VARIANT_BITFIELD_CAST(RenderingDevice::TextureUsageBits)
  1374. VARIANT_ENUM_CAST(RenderingDevice::TextureSwizzle)
  1375. VARIANT_ENUM_CAST(RenderingDevice::TextureSliceType)
  1376. VARIANT_ENUM_CAST(RenderingDevice::SamplerFilter)
  1377. VARIANT_ENUM_CAST(RenderingDevice::SamplerRepeatMode)
  1378. VARIANT_ENUM_CAST(RenderingDevice::SamplerBorderColor)
  1379. VARIANT_ENUM_CAST(RenderingDevice::VertexFrequency)
  1380. VARIANT_ENUM_CAST(RenderingDevice::IndexBufferFormat)
  1381. VARIANT_BITFIELD_CAST(RenderingDevice::StorageBufferUsage)
  1382. VARIANT_ENUM_CAST(RenderingDevice::UniformType)
  1383. VARIANT_ENUM_CAST(RenderingDevice::RenderPrimitive)
  1384. VARIANT_ENUM_CAST(RenderingDevice::PolygonCullMode)
  1385. VARIANT_ENUM_CAST(RenderingDevice::PolygonFrontFace)
  1386. VARIANT_ENUM_CAST(RenderingDevice::StencilOperation)
  1387. VARIANT_ENUM_CAST(RenderingDevice::LogicOperation)
  1388. VARIANT_ENUM_CAST(RenderingDevice::BlendFactor)
  1389. VARIANT_ENUM_CAST(RenderingDevice::BlendOperation)
  1390. VARIANT_BITFIELD_CAST(RenderingDevice::PipelineDynamicStateFlags)
  1391. VARIANT_ENUM_CAST(RenderingDevice::PipelineSpecializationConstantType)
  1392. VARIANT_ENUM_CAST(RenderingDevice::Limit)
  1393. VARIANT_ENUM_CAST(RenderingDevice::MemoryType)
  1394. VARIANT_ENUM_CAST(RenderingDevice::Features)
  1395. VARIANT_ENUM_CAST(RenderingDevice::BreadcrumbMarker)
  1396. VARIANT_BITFIELD_CAST(RenderingDevice::DrawFlags);
  1397. #ifndef DISABLE_DEPRECATED
  1398. VARIANT_BITFIELD_CAST(RenderingDevice::BarrierMask);
  1399. VARIANT_ENUM_CAST(RenderingDevice::InitialAction)
  1400. VARIANT_ENUM_CAST(RenderingDevice::FinalAction)
  1401. #endif
  1402. typedef RenderingDevice RD;
  1403. #endif // RENDERING_DEVICE_H