Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/drivers/d3d12/rendering_device_driver_d3d12.h
9973 views
1
/**************************************************************************/
2
/* rendering_device_driver_d3d12.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/templates/hash_map.h"
34
#include "core/templates/paged_allocator.h"
35
#include "core/templates/self_list.h"
36
#include "rendering_shader_container_d3d12.h"
37
#include "servers/rendering/rendering_device_driver.h"
38
39
#ifndef _MSC_VER
40
// Match current version used by MinGW, MSVC and Direct3D 12 headers use 500.
41
#define __REQUIRED_RPCNDR_H_VERSION__ 475
42
#endif
43
44
#include <d3dx12.h>
45
#include <dxgi1_6.h>
46
#define D3D12MA_D3D12_HEADERS_ALREADY_INCLUDED
47
#include <D3D12MemAlloc.h>
48
49
#include <wrl/client.h>
50
51
#if defined(_MSC_VER) && defined(MemoryBarrier)
52
// Annoying define from winnt.h. Reintroduced by some of the headers above.
53
#undef MemoryBarrier
54
#endif
55
56
using Microsoft::WRL::ComPtr;
57
58
#ifdef DEV_ENABLED
59
#define CUSTOM_INFO_QUEUE_ENABLED 0
60
#endif
61
62
class RenderingContextDriverD3D12;
63
64
// Design principles:
65
// - D3D12 structs are zero-initialized and fields not requiring a non-zero value are omitted (except in cases where expresivity reasons apply).
66
class RenderingDeviceDriverD3D12 : public RenderingDeviceDriver {
67
/*****************/
68
/**** GENERIC ****/
69
/*****************/
70
71
struct D3D12Format {
72
DXGI_FORMAT family = DXGI_FORMAT_UNKNOWN;
73
DXGI_FORMAT general_format = DXGI_FORMAT_UNKNOWN;
74
UINT swizzle = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
75
DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN;
76
};
77
78
static const D3D12Format RD_TO_D3D12_FORMAT[RDD::DATA_FORMAT_MAX];
79
80
struct DeviceLimits {
81
uint64_t max_srvs_per_shader_stage = 0;
82
uint64_t max_cbvs_per_shader_stage = 0;
83
uint64_t max_samplers_across_all_stages = 0;
84
uint64_t max_uavs_across_all_stages = 0;
85
uint64_t timestamp_frequency = 0;
86
};
87
88
struct SubgroupCapabilities {
89
uint32_t size = 0;
90
bool wave_ops_supported = false;
91
uint32_t supported_stages_flags_rd() const;
92
uint32_t supported_operations_flags_rd() const;
93
};
94
95
struct ShaderCapabilities {
96
D3D_SHADER_MODEL shader_model = (D3D_SHADER_MODEL)0;
97
bool native_16bit_ops = false;
98
};
99
100
struct StorageBufferCapabilities {
101
bool storage_buffer_16_bit_access_is_supported = false;
102
};
103
104
struct FormatCapabilities {
105
bool relaxed_casting_supported = false;
106
};
107
108
struct BarrierCapabilities {
109
bool enhanced_barriers_supported = false;
110
};
111
112
struct MiscFeaturesSupport {
113
bool depth_bounds_supported = false;
114
};
115
116
RenderingContextDriverD3D12 *context_driver = nullptr;
117
RenderingContextDriver::Device context_device;
118
ComPtr<IDXGIAdapter> adapter;
119
DXGI_ADAPTER_DESC adapter_desc;
120
ComPtr<ID3D12Device> device;
121
DeviceLimits device_limits;
122
RDD::Capabilities device_capabilities;
123
uint32_t feature_level = 0; // Major * 10 + minor.
124
SubgroupCapabilities subgroup_capabilities;
125
RDD::MultiviewCapabilities multiview_capabilities;
126
FragmentShadingRateCapabilities fsr_capabilities;
127
FragmentDensityMapCapabilities fdm_capabilities;
128
ShaderCapabilities shader_capabilities;
129
StorageBufferCapabilities storage_buffer_capabilities;
130
FormatCapabilities format_capabilities;
131
BarrierCapabilities barrier_capabilities;
132
MiscFeaturesSupport misc_features_support;
133
RenderingShaderContainerFormatD3D12 shader_container_format;
134
String pipeline_cache_id;
135
136
class DescriptorsHeap {
137
D3D12_DESCRIPTOR_HEAP_DESC desc = {};
138
ComPtr<ID3D12DescriptorHeap> heap;
139
uint32_t handle_size = 0;
140
141
public:
142
class Walker { // Texas Ranger.
143
friend class DescriptorsHeap;
144
145
uint32_t handle_size = 0;
146
uint32_t handle_count = 0;
147
D3D12_CPU_DESCRIPTOR_HANDLE first_cpu_handle = {};
148
D3D12_GPU_DESCRIPTOR_HANDLE first_gpu_handle = {};
149
uint32_t handle_index = 0;
150
151
public:
152
D3D12_CPU_DESCRIPTOR_HANDLE get_curr_cpu_handle();
153
D3D12_GPU_DESCRIPTOR_HANDLE get_curr_gpu_handle();
154
_FORCE_INLINE_ void rewind() { handle_index = 0; }
155
void advance(uint32_t p_count = 1);
156
uint32_t get_current_handle_index() const { return handle_index; }
157
uint32_t get_free_handles() { return handle_count - handle_index; }
158
bool is_at_eof() { return handle_index == handle_count; }
159
};
160
161
Error allocate(ID3D12Device *m_device, D3D12_DESCRIPTOR_HEAP_TYPE m_type, uint32_t m_descriptor_count, bool p_for_gpu);
162
uint32_t get_descriptor_count() const { return desc.NumDescriptors; }
163
ID3D12DescriptorHeap *get_heap() const { return heap.Get(); }
164
165
Walker make_walker() const;
166
};
167
168
struct {
169
ComPtr<ID3D12CommandSignature> draw;
170
ComPtr<ID3D12CommandSignature> draw_indexed;
171
ComPtr<ID3D12CommandSignature> dispatch;
172
} indirect_cmd_signatures;
173
174
static void STDMETHODCALLTYPE _debug_message_func(D3D12_MESSAGE_CATEGORY p_category, D3D12_MESSAGE_SEVERITY p_severity, D3D12_MESSAGE_ID p_id, LPCSTR p_description, void *p_context);
175
void _set_object_name(ID3D12Object *p_object, String p_object_name);
176
Error _initialize_device();
177
Error _check_capabilities();
178
Error _get_device_limits();
179
Error _initialize_allocator();
180
Error _initialize_frames(uint32_t p_frame_count);
181
Error _initialize_command_signatures();
182
183
public:
184
Error initialize(uint32_t p_device_index, uint32_t p_frame_count) override final;
185
186
private:
187
/****************/
188
/**** MEMORY ****/
189
/****************/
190
191
ComPtr<D3D12MA::Allocator> allocator;
192
193
/******************/
194
/**** RESOURCE ****/
195
/******************/
196
197
struct ResourceInfo {
198
struct States {
199
// As many subresources as mipmaps * layers; planes (for depth-stencil) are tracked together.
200
TightLocalVector<D3D12_RESOURCE_STATES> subresource_states; // Used only if not a view.
201
uint32_t last_batch_with_uav_barrier = 0;
202
};
203
204
ID3D12Resource *resource = nullptr; // Non-null even if not owned.
205
struct {
206
ComPtr<ID3D12Resource> resource;
207
ComPtr<D3D12MA::Allocation> allocation;
208
States states;
209
} owner_info; // All empty if the resource is not owned.
210
States *states_ptr = nullptr; // Own or from another if it doesn't own the D3D12 resource.
211
};
212
213
struct BarrierRequest {
214
static const uint32_t MAX_GROUPS = 4;
215
// Maybe this is too much data to have it locally. Benchmarking may reveal that
216
// cache would be used better by having a maximum of local subresource masks and beyond
217
// that have an allocated vector with the rest.
218
static const uint32_t MAX_SUBRESOURCES = 4096;
219
ID3D12Resource *dx_resource = nullptr;
220
uint8_t subres_mask_qwords = 0;
221
uint8_t planes = 0;
222
struct Group {
223
D3D12_RESOURCE_STATES states = {};
224
static_assert(MAX_SUBRESOURCES % 64 == 0);
225
uint64_t subres_mask[MAX_SUBRESOURCES / 64] = {};
226
} groups[MAX_GROUPS];
227
uint8_t groups_count = 0;
228
static const D3D12_RESOURCE_STATES DELETED_GROUP = D3D12_RESOURCE_STATES(0xFFFFFFFFU);
229
};
230
231
struct CommandBufferInfo;
232
233
void _resource_transition_batch(CommandBufferInfo *p_command_buffer, ResourceInfo *p_resource, uint32_t p_subresource, uint32_t p_num_planes, D3D12_RESOURCE_STATES p_new_state);
234
void _resource_transitions_flush(CommandBufferInfo *p_command_buffer);
235
236
/*****************/
237
/**** BUFFERS ****/
238
/*****************/
239
240
struct BufferInfo : public ResourceInfo {
241
DataFormat texel_format = DATA_FORMAT_MAX;
242
uint64_t size = 0;
243
struct {
244
bool usable_as_uav : 1;
245
} flags = {};
246
};
247
248
public:
249
virtual BufferID buffer_create(uint64_t p_size, BitField<BufferUsageBits> p_usage, MemoryAllocationType p_allocation_type) override final;
250
virtual bool buffer_set_texel_format(BufferID p_buffer, DataFormat p_format) override final;
251
virtual void buffer_free(BufferID p_buffer) override final;
252
virtual uint64_t buffer_get_allocation_size(BufferID p_buffer) override final;
253
virtual uint8_t *buffer_map(BufferID p_buffer) override final;
254
virtual void buffer_unmap(BufferID p_buffer) override final;
255
virtual uint64_t buffer_get_device_address(BufferID p_buffer) override final;
256
257
/*****************/
258
/**** TEXTURE ****/
259
/*****************/
260
private:
261
struct TextureInfo : public ResourceInfo {
262
DataFormat format = DATA_FORMAT_MAX;
263
CD3DX12_RESOURCE_DESC desc = {};
264
uint32_t base_layer = 0;
265
uint32_t layers = 0;
266
uint32_t base_mip = 0;
267
uint32_t mipmaps = 0;
268
269
struct {
270
D3D12_SHADER_RESOURCE_VIEW_DESC srv;
271
D3D12_UNORDERED_ACCESS_VIEW_DESC uav;
272
} view_descs = {};
273
274
TextureInfo *main_texture = nullptr;
275
276
UINT mapped_subresource = UINT_MAX;
277
SelfList<TextureInfo> pending_clear{ this };
278
#ifdef DEBUG_ENABLED
279
bool created_from_extension = false;
280
#endif
281
};
282
SelfList<TextureInfo>::List textures_pending_clear;
283
284
HashMap<DXGI_FORMAT, uint32_t> format_sample_counts_mask_cache;
285
Mutex format_sample_counts_mask_cache_mutex;
286
287
uint32_t _find_max_common_supported_sample_count(VectorView<DXGI_FORMAT> p_formats);
288
UINT _compute_component_mapping(const TextureView &p_view);
289
UINT _compute_plane_slice(DataFormat p_format, BitField<TextureAspectBits> p_aspect_bits);
290
UINT _compute_plane_slice(DataFormat p_format, TextureAspect p_aspect);
291
UINT _compute_subresource_from_layers(TextureInfo *p_texture, const TextureSubresourceLayers &p_layers, uint32_t p_layer_offset);
292
293
void _discard_texture_subresources(const TextureInfo *p_tex_info, const CommandBufferInfo *p_cmd_buf_info);
294
295
protected:
296
virtual bool _unordered_access_supported_by_format(DataFormat p_format);
297
298
public:
299
virtual TextureID texture_create(const TextureFormat &p_format, const TextureView &p_view) override final;
300
virtual TextureID texture_create_from_extension(uint64_t p_native_texture, TextureType p_type, DataFormat p_format, uint32_t p_array_layers, bool p_depth_stencil, uint32_t p_mipmaps) override final;
301
virtual TextureID texture_create_shared(TextureID p_original_texture, const TextureView &p_view) override final;
302
virtual TextureID texture_create_shared_from_slice(TextureID p_original_texture, const TextureView &p_view, TextureSliceType p_slice_type, uint32_t p_layer, uint32_t p_layers, uint32_t p_mipmap, uint32_t p_mipmaps) override final;
303
virtual void texture_free(TextureID p_texture) override final;
304
virtual uint64_t texture_get_allocation_size(TextureID p_texture) override final;
305
virtual void texture_get_copyable_layout(TextureID p_texture, const TextureSubresource &p_subresource, TextureCopyableLayout *r_layout) override final;
306
virtual uint8_t *texture_map(TextureID p_texture, const TextureSubresource &p_subresource) override final;
307
virtual void texture_unmap(TextureID p_texture) override final;
308
virtual BitField<TextureUsageBits> texture_get_usages_supported_by_format(DataFormat p_format, bool p_cpu_readable) override final;
309
virtual bool texture_can_make_shared_with_format(TextureID p_texture, DataFormat p_format, bool &r_raw_reinterpretation) override final;
310
311
private:
312
TextureID _texture_create_shared_from_slice(TextureID p_original_texture, const TextureView &p_view, TextureSliceType p_slice_type, uint32_t p_layer, uint32_t p_layers, uint32_t p_mipmap, uint32_t p_mipmaps);
313
314
public:
315
/*****************/
316
/**** SAMPLER ****/
317
/*****************/
318
private:
319
LocalVector<D3D12_SAMPLER_DESC> samplers;
320
321
public:
322
virtual SamplerID sampler_create(const SamplerState &p_state) final override;
323
virtual void sampler_free(SamplerID p_sampler) final override;
324
virtual bool sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_filter) override final;
325
326
/**********************/
327
/**** VERTEX ARRAY ****/
328
/**********************/
329
private:
330
struct VertexFormatInfo {
331
TightLocalVector<D3D12_INPUT_ELEMENT_DESC> input_elem_descs;
332
TightLocalVector<UINT> vertex_buffer_strides;
333
};
334
335
public:
336
virtual VertexFormatID vertex_format_create(VectorView<VertexAttribute> p_vertex_attribs) override final;
337
virtual void vertex_format_free(VertexFormatID p_vertex_format) override final;
338
339
/******************/
340
/**** BARRIERS ****/
341
/******************/
342
343
virtual void command_pipeline_barrier(
344
CommandBufferID p_cmd_buffer,
345
BitField<PipelineStageBits> p_src_stages,
346
BitField<PipelineStageBits> p_dst_stages,
347
VectorView<RDD::MemoryBarrier> p_memory_barriers,
348
VectorView<RDD::BufferBarrier> p_buffer_barriers,
349
VectorView<RDD::TextureBarrier> p_texture_barriers) override final;
350
351
private:
352
/****************/
353
/**** FENCES ****/
354
/****************/
355
356
struct FenceInfo {
357
ComPtr<ID3D12Fence> d3d_fence = nullptr;
358
HANDLE event_handle = nullptr;
359
UINT64 fence_value = 0;
360
};
361
362
public:
363
virtual FenceID fence_create() override;
364
virtual Error fence_wait(FenceID p_fence) override;
365
virtual void fence_free(FenceID p_fence) override;
366
367
private:
368
/********************/
369
/**** SEMAPHORES ****/
370
/********************/
371
372
struct SemaphoreInfo {
373
ComPtr<ID3D12Fence> d3d_fence = nullptr;
374
UINT64 fence_value = 0;
375
};
376
377
virtual SemaphoreID semaphore_create() override;
378
virtual void semaphore_free(SemaphoreID p_semaphore) override;
379
380
/******************/
381
/**** COMMANDS ****/
382
/******************/
383
384
// ----- QUEUE FAMILY -----
385
386
virtual CommandQueueFamilyID command_queue_family_get(BitField<CommandQueueFamilyBits> p_cmd_queue_family_bits, RenderingContextDriver::SurfaceID p_surface = 0) override;
387
388
private:
389
// ----- QUEUE -----
390
391
struct CommandQueueInfo {
392
ComPtr<ID3D12CommandQueue> d3d_queue;
393
};
394
395
public:
396
virtual CommandQueueID command_queue_create(CommandQueueFamilyID p_cmd_queue_family, bool p_identify_as_main_queue = false) override;
397
virtual Error command_queue_execute_and_present(CommandQueueID p_cmd_queue, VectorView<SemaphoreID> p_wait_semaphores, VectorView<CommandBufferID> p_cmd_buffers, VectorView<SemaphoreID> p_cmd_semaphores, FenceID p_cmd_fence, VectorView<SwapChainID> p_swap_chains) override;
398
virtual void command_queue_free(CommandQueueID p_cmd_queue) override;
399
400
private:
401
// ----- POOL -----
402
struct CommandPoolInfo {
403
CommandQueueFamilyID queue_family;
404
CommandBufferType buffer_type = COMMAND_BUFFER_TYPE_PRIMARY;
405
// Since there are no command pools in D3D12, we need to track the command buffers created by this pool
406
// so that we can free them when the pool is freed.
407
SelfList<CommandBufferInfo>::List command_buffers;
408
};
409
410
public:
411
virtual CommandPoolID command_pool_create(CommandQueueFamilyID p_cmd_queue_family, CommandBufferType p_cmd_buffer_type) override final;
412
virtual bool command_pool_reset(CommandPoolID p_cmd_pool) override final;
413
virtual void command_pool_free(CommandPoolID p_cmd_pool) override final;
414
415
// ----- BUFFER -----
416
417
private:
418
// Belongs to RENDERING-SUBPASS, but needed here.
419
struct FramebufferInfo;
420
struct RenderPassInfo;
421
struct RenderPassState {
422
uint32_t current_subpass = UINT32_MAX;
423
const FramebufferInfo *fb_info = nullptr;
424
const RenderPassInfo *pass_info = nullptr;
425
CD3DX12_RECT region_rect = {};
426
bool region_is_all = false;
427
428
const VertexFormatInfo *vf_info = nullptr;
429
D3D12_VERTEX_BUFFER_VIEW vertex_buffer_views[8] = {};
430
uint32_t vertex_buffer_count = 0;
431
};
432
433
// Leveraging knowledge of actual usage and D3D12 specifics (namely, command lists from the same allocator
434
// can't be freely begun and ended), an allocator per list works better.
435
struct CommandBufferInfo {
436
// Store a self list reference to be used by the command pool.
437
SelfList<CommandBufferInfo> command_buffer_info_elem{ this };
438
439
ComPtr<ID3D12CommandAllocator> cmd_allocator;
440
ComPtr<ID3D12GraphicsCommandList> cmd_list;
441
442
ID3D12PipelineState *graphics_pso = nullptr;
443
ID3D12PipelineState *compute_pso = nullptr;
444
445
uint32_t graphics_root_signature_crc = 0;
446
uint32_t compute_root_signature_crc = 0;
447
448
RenderPassState render_pass_state;
449
bool descriptor_heaps_set = false;
450
451
HashMap<ResourceInfo::States *, BarrierRequest> res_barriers_requests;
452
LocalVector<D3D12_RESOURCE_BARRIER> res_barriers;
453
uint32_t res_barriers_count = 0;
454
uint32_t res_barriers_batch = 0;
455
};
456
457
public:
458
virtual CommandBufferID command_buffer_create(CommandPoolID p_cmd_pool) override final;
459
virtual bool command_buffer_begin(CommandBufferID p_cmd_buffer) override final;
460
virtual bool command_buffer_begin_secondary(CommandBufferID p_cmd_buffer, RenderPassID p_render_pass, uint32_t p_subpass, FramebufferID p_framebuffer) override final;
461
virtual void command_buffer_end(CommandBufferID p_cmd_buffer) override final;
462
virtual void command_buffer_execute_secondary(CommandBufferID p_cmd_buffer, VectorView<CommandBufferID> p_secondary_cmd_buffers) override final;
463
464
private:
465
/********************/
466
/**** SWAP CHAIN ****/
467
/********************/
468
469
struct SwapChain {
470
ComPtr<IDXGISwapChain3> d3d_swap_chain;
471
RenderingContextDriver::SurfaceID surface = RenderingContextDriver::SurfaceID();
472
UINT present_flags = 0;
473
UINT sync_interval = 1;
474
UINT creation_flags = 0;
475
RenderPassID render_pass;
476
TightLocalVector<ID3D12Resource *> render_targets;
477
TightLocalVector<TextureInfo> render_targets_info;
478
TightLocalVector<FramebufferID> framebuffers;
479
RDD::DataFormat data_format = DATA_FORMAT_MAX;
480
};
481
482
void _swap_chain_release(SwapChain *p_swap_chain);
483
void _swap_chain_release_buffers(SwapChain *p_swap_chain);
484
485
public:
486
virtual SwapChainID swap_chain_create(RenderingContextDriver::SurfaceID p_surface) override;
487
virtual Error swap_chain_resize(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, uint32_t p_desired_framebuffer_count) override;
488
virtual FramebufferID swap_chain_acquire_framebuffer(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, bool &r_resize_required) override;
489
virtual RenderPassID swap_chain_get_render_pass(SwapChainID p_swap_chain) override;
490
virtual DataFormat swap_chain_get_format(SwapChainID p_swap_chain) override;
491
virtual void swap_chain_free(SwapChainID p_swap_chain) override;
492
493
/*********************/
494
/**** FRAMEBUFFER ****/
495
/*********************/
496
private:
497
struct FramebufferInfo {
498
bool is_screen = false;
499
Size2i size;
500
TightLocalVector<uint32_t> attachments_handle_inds; // RTV heap index for color; DSV heap index for DSV.
501
DescriptorsHeap rtv_heap;
502
DescriptorsHeap dsv_heap; // Used only if not for screen and some depth-stencil attachments.
503
504
TightLocalVector<TextureID> attachments; // Color and depth-stencil. Used if not screen.
505
TextureID vrs_attachment;
506
};
507
508
D3D12_RENDER_TARGET_VIEW_DESC _make_rtv_for_texture(const TextureInfo *p_texture_info, uint32_t p_mipmap_offset, uint32_t p_layer_offset, uint32_t p_layers, bool p_add_bases = true);
509
D3D12_UNORDERED_ACCESS_VIEW_DESC _make_ranged_uav_for_texture(const TextureInfo *p_texture_info, uint32_t p_mipmap_offset, uint32_t p_layer_offset, uint32_t p_layers, bool p_add_bases = true);
510
D3D12_DEPTH_STENCIL_VIEW_DESC _make_dsv_for_texture(const TextureInfo *p_texture_info);
511
512
FramebufferID _framebuffer_create(RenderPassID p_render_pass, VectorView<TextureID> p_attachments, uint32_t p_width, uint32_t p_height, bool p_is_screen);
513
514
public:
515
virtual FramebufferID framebuffer_create(RenderPassID p_render_pass, VectorView<TextureID> p_attachments, uint32_t p_width, uint32_t p_height) override final;
516
virtual void framebuffer_free(FramebufferID p_framebuffer) override final;
517
518
/****************/
519
/**** SHADER ****/
520
/****************/
521
522
private:
523
static const uint32_t ROOT_SIGNATURE_SIZE = 256;
524
static const uint32_t PUSH_CONSTANT_SIZE = 128; // Mimicking Vulkan.
525
526
enum {
527
// We can only aim to set a maximum here, since depending on the shader
528
// there may be more or less root signature free for descriptor tables.
529
// Therefore, we'll have to rely on the final check at runtime, when building
530
// the root signature structure for a given shader.
531
// To be precise, these may be present or not, and their size vary statically:
532
// - Push constant (we'll assume this is always present to avoid reserving much
533
// more space for descriptor sets than needed for almost any imaginable case,
534
// given that most shader templates feature push constants).
535
// - NIR-DXIL runtime data.
536
MAX_UNIFORM_SETS = (ROOT_SIGNATURE_SIZE - PUSH_CONSTANT_SIZE) / sizeof(uint32_t),
537
};
538
539
struct ShaderInfo {
540
uint32_t dxil_push_constant_size = 0;
541
uint32_t nir_runtime_data_root_param_idx = UINT32_MAX;
542
bool is_compute = false;
543
544
struct UniformBindingInfo {
545
uint32_t stages = 0; // Actual shader stages using the uniform (0 if totally optimized out).
546
ResourceClass res_class = RES_CLASS_INVALID;
547
UniformType type = UNIFORM_TYPE_MAX;
548
uint32_t length = UINT32_MAX;
549
#ifdef DEV_ENABLED
550
bool writable = false;
551
#endif
552
struct RootSignatureLocation {
553
uint32_t root_param_idx = UINT32_MAX;
554
uint32_t range_idx = UINT32_MAX;
555
};
556
struct {
557
RootSignatureLocation resource;
558
RootSignatureLocation sampler;
559
} root_sig_locations;
560
};
561
562
struct UniformSet {
563
TightLocalVector<UniformBindingInfo> bindings;
564
struct {
565
uint32_t resources = 0;
566
uint32_t samplers = 0;
567
} num_root_params;
568
};
569
570
TightLocalVector<UniformSet> sets;
571
572
struct SpecializationConstant {
573
uint32_t constant_id = UINT32_MAX;
574
uint32_t int_value = UINT32_MAX;
575
uint64_t stages_bit_offsets[D3D12_BITCODE_OFFSETS_NUM_STAGES] = {};
576
};
577
578
TightLocalVector<SpecializationConstant> specialization_constants;
579
uint32_t spirv_specialization_constants_ids_mask = 0;
580
581
HashMap<ShaderStage, Vector<uint8_t>> stages_bytecode;
582
583
ComPtr<ID3D12RootSignature> root_signature;
584
ComPtr<ID3D12RootSignatureDeserializer> root_signature_deserializer;
585
const D3D12_ROOT_SIGNATURE_DESC *root_signature_desc = nullptr; // Owned by the deserializer.
586
uint32_t root_signature_crc = 0;
587
};
588
589
bool _shader_apply_specialization_constants(
590
const ShaderInfo *p_shader_info,
591
VectorView<PipelineSpecializationConstant> p_specialization_constants,
592
HashMap<ShaderStage, Vector<uint8_t>> &r_final_stages_bytecode);
593
594
public:
595
virtual ShaderID shader_create_from_container(const Ref<RenderingShaderContainer> &p_shader_container, const Vector<ImmutableSampler> &p_immutable_samplers) override final;
596
virtual uint32_t shader_get_layout_hash(ShaderID p_shader) override final;
597
virtual void shader_free(ShaderID p_shader) override final;
598
virtual void shader_destroy_modules(ShaderID p_shader) override final;
599
600
/*********************/
601
/**** UNIFORM SET ****/
602
/*********************/
603
604
private:
605
struct RootDescriptorTable {
606
uint32_t root_param_idx = UINT32_MAX;
607
D3D12_GPU_DESCRIPTOR_HANDLE start_gpu_handle = {};
608
};
609
610
struct UniformSetInfo {
611
struct {
612
DescriptorsHeap resources;
613
DescriptorsHeap samplers;
614
} desc_heaps;
615
616
struct StateRequirement {
617
ResourceInfo *resource = nullptr;
618
bool is_buffer = false;
619
D3D12_RESOURCE_STATES states = {};
620
uint64_t shader_uniform_idx_mask = 0;
621
};
622
TightLocalVector<StateRequirement> resource_states;
623
624
struct RecentBind {
625
uint64_t segment_serial = 0;
626
uint32_t root_signature_crc = 0;
627
struct {
628
TightLocalVector<RootDescriptorTable> resources;
629
TightLocalVector<RootDescriptorTable> samplers;
630
} root_tables;
631
int uses = 0;
632
} recent_binds[4]; // A better amount may be empirically found.
633
634
#ifdef DEV_ENABLED
635
// Filthy, but useful for dev.
636
struct ResourceDescInfo {
637
D3D12_DESCRIPTOR_RANGE_TYPE type;
638
D3D12_SRV_DIMENSION srv_dimension;
639
};
640
TightLocalVector<ResourceDescInfo> resources_desc_info;
641
#endif
642
};
643
644
public:
645
virtual UniformSetID uniform_set_create(VectorView<BoundUniform> p_uniforms, ShaderID p_shader, uint32_t p_set_index, int p_linear_pool_index) override final;
646
virtual void uniform_set_free(UniformSetID p_uniform_set) override final;
647
648
// ----- COMMANDS -----
649
650
virtual void command_uniform_set_prepare_for_use(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) override final;
651
652
private:
653
void _command_check_descriptor_sets(CommandBufferID p_cmd_buffer);
654
void _command_bind_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index, bool p_for_compute);
655
void _command_bind_uniform_sets(CommandBufferID p_cmd_buffer, VectorView<UniformSetID> p_uniform_sets, ShaderID p_shader, uint32_t p_first_set_index, uint32_t p_set_count, bool p_for_compute);
656
657
public:
658
/******************/
659
/**** TRANSFER ****/
660
/******************/
661
662
virtual void command_clear_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, uint64_t p_offset, uint64_t p_size) override final;
663
virtual void command_copy_buffer(CommandBufferID p_cmd_buffer, BufferID p_src_buffer, BufferID p_dst_buffer, VectorView<BufferCopyRegion> p_regions) override final;
664
665
virtual void command_copy_texture(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, VectorView<TextureCopyRegion> p_regions) override final;
666
virtual void command_resolve_texture(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, uint32_t p_src_layer, uint32_t p_src_mipmap, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, uint32_t p_dst_layer, uint32_t p_dst_mipmap) override final;
667
virtual void command_clear_color_texture(CommandBufferID p_cmd_buffer, TextureID p_texture, TextureLayout p_texture_layout, const Color &p_color, const TextureSubresourceRange &p_subresources) override final;
668
669
public:
670
virtual void command_copy_buffer_to_texture(CommandBufferID p_cmd_buffer, BufferID p_src_buffer, TextureID p_dst_texture, TextureLayout p_dst_texture_layout, VectorView<BufferTextureCopyRegion> p_regions) override final;
671
virtual void command_copy_texture_to_buffer(CommandBufferID p_cmd_buffer, TextureID p_src_texture, TextureLayout p_src_texture_layout, BufferID p_dst_buffer, VectorView<BufferTextureCopyRegion> p_regions) override final;
672
673
/******************/
674
/**** PIPELINE ****/
675
/******************/
676
677
struct RenderPipelineInfo {
678
const VertexFormatInfo *vf_info = nullptr;
679
680
struct {
681
D3D12_PRIMITIVE_TOPOLOGY primitive_topology = {};
682
Color blend_constant;
683
float depth_bounds_min = 0.0f;
684
float depth_bounds_max = 0.0f;
685
uint32_t stencil_reference = 0;
686
} dyn_params;
687
};
688
689
struct PipelineInfo {
690
ID3D12PipelineState *pso = nullptr;
691
const ShaderInfo *shader_info = nullptr;
692
RenderPipelineInfo render_info;
693
};
694
695
virtual void pipeline_free(PipelineID p_pipeline) override final;
696
697
public:
698
// ----- BINDING -----
699
700
virtual void command_bind_push_constants(CommandBufferID p_cmd_buffer, ShaderID p_shader, uint32_t p_dst_first_index, VectorView<uint32_t> p_data) override final;
701
702
// ----- CACHE -----
703
704
virtual bool pipeline_cache_create(const Vector<uint8_t> &p_data) override final;
705
virtual void pipeline_cache_free() override final;
706
virtual size_t pipeline_cache_query_size() override final;
707
virtual Vector<uint8_t> pipeline_cache_serialize() override final;
708
709
/*******************/
710
/**** RENDERING ****/
711
/*******************/
712
713
// ----- SUBPASS -----
714
715
private:
716
struct RenderPassInfo {
717
TightLocalVector<Attachment> attachments;
718
TightLocalVector<Subpass> subpasses;
719
uint32_t view_count = 0;
720
uint32_t max_supported_sample_count = 0;
721
};
722
723
public:
724
virtual RenderPassID render_pass_create(VectorView<Attachment> p_attachments, VectorView<Subpass> p_subpasses, VectorView<SubpassDependency> p_subpass_dependencies, uint32_t p_view_count, AttachmentReference p_fragment_density_map_attachment) override final;
725
virtual void render_pass_free(RenderPassID p_render_pass) override final;
726
727
// ----- COMMANDS -----
728
729
virtual void command_begin_render_pass(CommandBufferID p_cmd_buffer, RenderPassID p_render_pass, FramebufferID p_framebuffer, CommandBufferType p_cmd_buffer_type, const Rect2i &p_rect, VectorView<RenderPassClearValue> p_clear_values) override final;
730
731
private:
732
void _end_render_pass(CommandBufferID p_cmd_buffer);
733
734
public:
735
virtual void command_end_render_pass(CommandBufferID p_cmd_buffer) override final;
736
virtual void command_next_render_subpass(CommandBufferID p_cmd_buffer, CommandBufferType p_cmd_buffer_type) override final;
737
virtual void command_render_set_viewport(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_viewports) override final;
738
virtual void command_render_set_scissor(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_scissors) override final;
739
740
virtual void command_render_clear_attachments(CommandBufferID p_cmd_buffer, VectorView<AttachmentClear> p_attachment_clears, VectorView<Rect2i> p_rects) override final;
741
742
// Binding.
743
virtual void command_bind_render_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) override final;
744
virtual void command_bind_render_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) override final;
745
virtual void command_bind_render_uniform_sets(CommandBufferID p_cmd_buffer, VectorView<UniformSetID> p_uniform_sets, ShaderID p_shader, uint32_t p_first_set_index, uint32_t p_set_count) override final;
746
747
// Drawing.
748
virtual void command_render_draw(CommandBufferID p_cmd_buffer, uint32_t p_vertex_count, uint32_t p_instance_count, uint32_t p_base_vertex, uint32_t p_first_instance) override final;
749
virtual void command_render_draw_indexed(CommandBufferID p_cmd_buffer, uint32_t p_index_count, uint32_t p_instance_count, uint32_t p_first_index, int32_t p_vertex_offset, uint32_t p_first_instance) override final;
750
virtual void command_render_draw_indexed_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride) override final;
751
virtual void command_render_draw_indexed_indirect_count(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, BufferID p_count_buffer, uint64_t p_count_buffer_offset, uint32_t p_max_draw_count, uint32_t p_stride) override final;
752
virtual void command_render_draw_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride) override final;
753
virtual void command_render_draw_indirect_count(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset, BufferID p_count_buffer, uint64_t p_count_buffer_offset, uint32_t p_max_draw_count, uint32_t p_stride) override final;
754
755
// Buffer binding.
756
virtual void command_render_bind_vertex_buffers(CommandBufferID p_cmd_buffer, uint32_t p_binding_count, const BufferID *p_buffers, const uint64_t *p_offsets) override final;
757
virtual void command_render_bind_index_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, IndexBufferFormat p_format, uint64_t p_offset) override final;
758
759
private:
760
void _bind_vertex_buffers(CommandBufferInfo *p_cmd_buf_info);
761
762
public:
763
// Dynamic state.
764
virtual void command_render_set_blend_constants(CommandBufferID p_cmd_buffer, const Color &p_constants) override final;
765
virtual void command_render_set_line_width(CommandBufferID p_cmd_buffer, float p_width) override final;
766
767
// ----- PIPELINE -----
768
769
public:
770
virtual PipelineID render_pipeline_create(
771
ShaderID p_shader,
772
VertexFormatID p_vertex_format,
773
RenderPrimitive p_render_primitive,
774
PipelineRasterizationState p_rasterization_state,
775
PipelineMultisampleState p_multisample_state,
776
PipelineDepthStencilState p_depth_stencil_state,
777
PipelineColorBlendState p_blend_state,
778
VectorView<int32_t> p_color_attachments,
779
BitField<PipelineDynamicStateFlags> p_dynamic_state,
780
RenderPassID p_render_pass,
781
uint32_t p_render_subpass,
782
VectorView<PipelineSpecializationConstant> p_specialization_constants) override final;
783
784
/*****************/
785
/**** COMPUTE ****/
786
/*****************/
787
788
// ----- COMMANDS -----
789
790
// Binding.
791
virtual void command_bind_compute_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) override final;
792
virtual void command_bind_compute_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) override final;
793
virtual void command_bind_compute_uniform_sets(CommandBufferID p_cmd_buffer, VectorView<UniformSetID> p_uniform_sets, ShaderID p_shader, uint32_t p_first_set_index, uint32_t p_set_count) override final;
794
795
// Dispatching.
796
virtual void command_compute_dispatch(CommandBufferID p_cmd_buffer, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) override final;
797
virtual void command_compute_dispatch_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset) override final;
798
799
// ----- PIPELINE -----
800
801
virtual PipelineID compute_pipeline_create(ShaderID p_shader, VectorView<PipelineSpecializationConstant> p_specialization_constants) override final;
802
803
/*****************/
804
/**** QUERIES ****/
805
/*****************/
806
807
// ----- TIMESTAMP -----
808
809
private:
810
struct TimestampQueryPoolInfo {
811
ComPtr<ID3D12QueryHeap> query_heap;
812
uint32_t query_count = 0;
813
ComPtr<D3D12MA::Allocation> results_buffer_allocation;
814
};
815
816
public:
817
// Basic.
818
virtual QueryPoolID timestamp_query_pool_create(uint32_t p_query_count) override final;
819
virtual void timestamp_query_pool_free(QueryPoolID p_pool_id) override final;
820
virtual void timestamp_query_pool_get_results(QueryPoolID p_pool_id, uint32_t p_query_count, uint64_t *r_results) override final;
821
virtual uint64_t timestamp_query_result_to_time(uint64_t p_result) override final;
822
823
// Commands.
824
virtual void command_timestamp_query_pool_reset(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_query_count) override final;
825
virtual void command_timestamp_write(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_index) override final;
826
827
/****************/
828
/**** LABELS ****/
829
/****************/
830
831
virtual void command_begin_label(CommandBufferID p_cmd_buffer, const char *p_label_name, const Color &p_color) override final;
832
virtual void command_end_label(CommandBufferID p_cmd_buffer) override final;
833
834
/****************/
835
/**** DEBUG *****/
836
/****************/
837
virtual void command_insert_breadcrumb(CommandBufferID p_cmd_buffer, uint32_t p_data) override final;
838
839
/********************/
840
/**** SUBMISSION ****/
841
/********************/
842
private:
843
struct FrameInfo {
844
struct {
845
DescriptorsHeap resources;
846
DescriptorsHeap samplers;
847
DescriptorsHeap aux;
848
DescriptorsHeap rtv;
849
} desc_heaps;
850
struct {
851
DescriptorsHeap::Walker resources;
852
DescriptorsHeap::Walker samplers;
853
DescriptorsHeap::Walker aux;
854
DescriptorsHeap::Walker rtv;
855
} desc_heap_walkers;
856
struct {
857
bool resources = false;
858
bool samplers = false;
859
bool aux = false;
860
bool rtv = false;
861
} desc_heaps_exhausted_reported;
862
CD3DX12_CPU_DESCRIPTOR_HANDLE null_rtv_handle = {}; // For [[MANUAL_SUBPASSES]].
863
uint32_t segment_serial = 0;
864
865
#ifdef DEV_ENABLED
866
uint32_t uniform_set_reused = 0;
867
#endif
868
};
869
TightLocalVector<FrameInfo> frames;
870
uint32_t frame_idx = 0;
871
uint32_t frames_drawn = 0;
872
uint32_t segment_serial = 0;
873
bool segment_begun = false;
874
HashMap<uint64_t, bool> has_comp_alpha;
875
876
public:
877
virtual void begin_segment(uint32_t p_frame_index, uint32_t p_frames_drawn) override final;
878
virtual void end_segment() override final;
879
880
/**************/
881
/**** MISC ****/
882
/**************/
883
884
virtual void set_object_name(ObjectType p_type, ID p_driver_id, const String &p_name) override final;
885
virtual uint64_t get_resource_native_handle(DriverResource p_type, ID p_driver_id) override final;
886
virtual uint64_t get_total_memory_used() override final;
887
virtual uint64_t get_lazily_memory_used() override final;
888
virtual uint64_t limit_get(Limit p_limit) override final;
889
virtual uint64_t api_trait_get(ApiTrait p_trait) override final;
890
virtual bool has_feature(Features p_feature) override final;
891
virtual const MultiviewCapabilities &get_multiview_capabilities() override final;
892
virtual const FragmentShadingRateCapabilities &get_fragment_shading_rate_capabilities() override final;
893
virtual const FragmentDensityMapCapabilities &get_fragment_density_map_capabilities() override final;
894
virtual String get_api_name() const override final;
895
virtual String get_api_version() const override final;
896
virtual String get_pipeline_cache_uuid() const override final;
897
virtual const Capabilities &get_capabilities() const override final;
898
virtual const RenderingShaderContainerFormat &get_shader_container_format() const override final;
899
900
virtual bool is_composite_alpha_supported(CommandQueueID p_queue) const override final;
901
902
static bool is_in_developer_mode();
903
904
private:
905
/*********************/
906
/**** BOOKKEEPING ****/
907
/*********************/
908
909
using VersatileResource = VersatileResourceTemplate<
910
BufferInfo,
911
TextureInfo,
912
TextureInfo,
913
TextureInfo,
914
VertexFormatInfo,
915
CommandBufferInfo,
916
FramebufferInfo,
917
ShaderInfo,
918
UniformSetInfo,
919
RenderPassInfo,
920
TimestampQueryPoolInfo>;
921
PagedAllocator<VersatileResource, true> resources_allocator;
922
923
/******************/
924
925
public:
926
RenderingDeviceDriverD3D12(RenderingContextDriverD3D12 *p_context_driver);
927
virtual ~RenderingDeviceDriverD3D12();
928
};
929
930