Debian Codegraph @

servers/rendering/rendering_device.h

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