Path: blob/master/drivers/d3d12/rendering_device_driver_d3d12.h
21436 views
/**************************************************************************/1/* rendering_device_driver_d3d12.h */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#pragma once3132#include "core/templates/a_hash_map.h"33#include "core/templates/hash_map.h"34#include "core/templates/paged_allocator.h"35#include "core/templates/rb_map.h"36#include "core/templates/self_list.h"37#include "rendering_shader_container_d3d12.h"38#include "servers/rendering/rendering_device_driver.h"3940#if !defined(_MSC_VER) && !defined(__REQUIRED_RPCNDR_H_VERSION__)41// Match current version used by MinGW, MSVC and Direct3D 12 headers use 500.42#define __REQUIRED_RPCNDR_H_VERSION__ 47543#endif // !defined(_MSC_VER) && !defined(__REQUIRED_RPCNDR_H_VERSION__)4445GODOT_GCC_WARNING_PUSH46GODOT_GCC_WARNING_IGNORE("-Wimplicit-fallthrough")47GODOT_GCC_WARNING_IGNORE("-Wmissing-field-initializers")48GODOT_GCC_WARNING_IGNORE("-Wnon-virtual-dtor")49GODOT_GCC_WARNING_IGNORE("-Wshadow")50GODOT_GCC_WARNING_IGNORE("-Wswitch")51GODOT_CLANG_WARNING_PUSH52GODOT_CLANG_WARNING_IGNORE("-Wimplicit-fallthrough")53GODOT_CLANG_WARNING_IGNORE("-Wmissing-field-initializers")54GODOT_CLANG_WARNING_IGNORE("-Wnon-virtual-dtor")55GODOT_CLANG_WARNING_IGNORE("-Wstring-plus-int")56GODOT_CLANG_WARNING_IGNORE("-Wswitch")5758#include <thirdparty/directx_headers/include/directx/d3dx12.h>5960GODOT_GCC_WARNING_POP61GODOT_CLANG_WARNING_POP6263#include <wrl/client.h>6465#ifdef DEV_ENABLED66#define CUSTOM_INFO_QUEUE_ENABLED 067#endif6869class RenderingContextDriverD3D12;7071namespace D3D12MA {72class Allocation;73class Allocator;74class VirtualBlock;75}; // namespace D3D12MA7677struct IDXGIAdapter;78struct IDXGISwapChain3;7980// Design principles:81// - D3D12 structs are zero-initialized and fields not requiring a non-zero value are omitted (except in cases where expresivity reasons apply).82class RenderingDeviceDriverD3D12 : public RenderingDeviceDriver {83/*****************/84/**** GENERIC ****/85/*****************/8687struct D3D12Format {88DXGI_FORMAT family = DXGI_FORMAT_UNKNOWN;89DXGI_FORMAT general_format = DXGI_FORMAT_UNKNOWN;90UINT swizzle = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;91DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN;92};9394static const D3D12Format RD_TO_D3D12_FORMAT[RDD::DATA_FORMAT_MAX];9596struct DeviceLimits {97uint64_t max_srvs_per_shader_stage = 0;98uint64_t max_cbvs_per_shader_stage = 0;99uint64_t max_samplers_across_all_stages = 0;100uint64_t max_uavs_across_all_stages = 0;101uint64_t timestamp_frequency = 0;102};103104struct SubgroupCapabilities {105uint32_t size = 0;106bool wave_ops_supported = false;107uint32_t supported_stages_flags_rd() const;108uint32_t supported_operations_flags_rd() const;109};110111struct ShaderCapabilities {112D3D_SHADER_MODEL shader_model = (D3D_SHADER_MODEL)0;113bool native_16bit_ops = false;114};115116struct FormatCapabilities {117bool relaxed_casting_supported = false;118};119120struct BarrierCapabilities {121bool enhanced_barriers_supported = false;122};123124struct MiscFeaturesSupport {125bool depth_bounds_supported = false;126};127128struct SamplerCapabilities {129bool aniso_filter_with_point_mip_supported = false;130};131132RenderingContextDriverD3D12 *context_driver = nullptr;133RenderingContextDriver::Device context_device;134Microsoft::WRL::ComPtr<IDXGIAdapter> adapter;135Microsoft::WRL::ComPtr<ID3D12Device> device;136DeviceLimits device_limits;137RDD::Capabilities device_capabilities;138uint32_t feature_level = 0; // Major * 10 + minor.139SubgroupCapabilities subgroup_capabilities;140RDD::MultiviewCapabilities multiview_capabilities;141FragmentShadingRateCapabilities fsr_capabilities;142FragmentDensityMapCapabilities fdm_capabilities;143ShaderCapabilities shader_capabilities;144FormatCapabilities format_capabilities;145BarrierCapabilities barrier_capabilities;146MiscFeaturesSupport misc_features_support;147SamplerCapabilities sampler_capabilities;148RenderingShaderContainerFormatD3D12 shader_container_format;149String pipeline_cache_id;150D3D12_HEAP_TYPE dynamic_persistent_upload_heap = D3D12_HEAP_TYPE_UPLOAD;151152struct DescriptorHeap {153struct Allocation {154uint64_t virtual_alloc_handle = {}; // This is the handle value in "D3D12MA::VirtualAllocation".155D3D12_CPU_DESCRIPTOR_HANDLE cpu_handle = {};156D3D12_GPU_DESCRIPTOR_HANDLE gpu_handle = {};157};158159Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> heap;160D3D12_CPU_DESCRIPTOR_HANDLE cpu_handle = {};161D3D12_GPU_DESCRIPTOR_HANDLE gpu_handle = {};162uint32_t increment_size = 0;163164Microsoft::WRL::ComPtr<D3D12MA::VirtualBlock> virtual_block;165166Error initialize(ID3D12Device *p_device, D3D12_DESCRIPTOR_HEAP_TYPE p_type, uint32_t p_num_descriptors, bool p_shader_visible);167168Error allocate(uint32_t p_descriptor_count, Allocation &r_allocation);169void free(const Allocation &p_allocation);170};171172// Some IHVs do not allow creating descriptor heaps beyond a certain limit, so they must be pooled.173struct CPUDescriptorHeapPool {174struct Allocation : DescriptorHeap::Allocation {175uint32_t heap_index = UINT_MAX;176};177178BinaryMutex mutex;179LocalVector<DescriptorHeap> heaps;180181D3D12_DESCRIPTOR_HEAP_TYPE type = {};182uint32_t increment_size = 0;183184void initialize(ID3D12Device *p_device, D3D12_DESCRIPTOR_HEAP_TYPE p_type);185186Error allocate(uint32_t p_descriptor_count, ID3D12Device *p_device, Allocation &r_allocation);187void free(const Allocation &p_allocation);188};189190DescriptorHeap resource_descriptor_heap;191DescriptorHeap sampler_descriptor_heap;192CPUDescriptorHeapPool resource_descriptor_heap_pool;193CPUDescriptorHeapPool rtv_descriptor_heap_pool;194CPUDescriptorHeapPool dsv_descriptor_heap_pool;195196CPUDescriptorHeapPool::Allocation null_rtv_alloc;197198struct {199Microsoft::WRL::ComPtr<ID3D12CommandSignature> draw;200Microsoft::WRL::ComPtr<ID3D12CommandSignature> draw_indexed;201Microsoft::WRL::ComPtr<ID3D12CommandSignature> dispatch;202} indirect_cmd_signatures;203204static 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);205void _set_object_name(ID3D12Object *p_object, String p_object_name);206Error _initialize_device();207Error _check_capabilities();208Error _get_device_limits();209Error _initialize_allocator();210Error _initialize_frames(uint32_t p_frame_count);211Error _initialize_command_signatures();212213public:214Error initialize(uint32_t p_device_index, uint32_t p_frame_count) override final;215216private:217/****************/218/**** MEMORY ****/219/****************/220221Microsoft::WRL::ComPtr<D3D12MA::Allocator> allocator;222223/******************/224/**** RESOURCE ****/225/******************/226227struct ResourceInfo {228struct States {229// As many subresources as mipmaps * layers; planes (for depth-stencil) are tracked together.230TightLocalVector<D3D12_RESOURCE_STATES> subresource_states; // Used only if not a view.231uint32_t last_batch_with_uav_barrier = 0;232};233234ID3D12Resource *resource = nullptr; // Non-null even if not owned.235struct {236Microsoft::WRL::ComPtr<ID3D12Resource> resource;237Microsoft::WRL::ComPtr<D3D12MA::Allocation> allocation;238States states;239} owner_info; // All empty if the resource is not owned.240States *states_ptr = nullptr; // Own or from another if it doesn't own the D3D12 resource.241};242243struct BarrierRequest {244static const uint32_t MAX_GROUPS = 4;245// Maybe this is too much data to have it locally. Benchmarking may reveal that246// cache would be used better by having a maximum of local subresource masks and beyond247// that have an allocated vector with the rest.248static const uint32_t MAX_SUBRESOURCES = 4096;249ID3D12Resource *dx_resource = nullptr;250uint8_t subres_mask_qwords = 0;251uint8_t planes = 0;252struct Group {253D3D12_RESOURCE_STATES states = {};254static_assert(MAX_SUBRESOURCES % 64 == 0);255uint64_t subres_mask[MAX_SUBRESOURCES / 64] = {};256} groups[MAX_GROUPS];257uint8_t groups_count = 0;258static const D3D12_RESOURCE_STATES DELETED_GROUP = D3D12_RESOURCE_STATES(0xFFFFFFFFU);259};260261struct CommandBufferInfo;262263void _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);264void _resource_transitions_flush(CommandBufferInfo *p_command_buffer);265266/*****************/267/**** BUFFERS ****/268/*****************/269270struct BufferInfo : public ResourceInfo {271D3D12_GPU_VIRTUAL_ADDRESS gpu_virtual_address = {};272DataFormat texel_format = DATA_FORMAT_MAX;273uint64_t size = 0;274struct {275bool is_dynamic : 1; // Only used for tracking (e.g. Vulkan needs these checks).276} flags = {};277278bool is_dynamic() const { return flags.is_dynamic; }279};280281struct BufferDynamicInfo : BufferInfo {282uint32_t frame_idx = UINT32_MAX;283uint8_t *persistent_ptr = nullptr;284#ifdef DEBUG_ENABLED285// For tracking that a persistent buffer isn't mapped twice in the same frame.286uint64_t last_frame_mapped = 0;287#endif288};289290public:291virtual BufferID buffer_create(uint64_t p_size, BitField<BufferUsageBits> p_usage, MemoryAllocationType p_allocation_type, uint64_t p_frames_drawn) override final;292virtual bool buffer_set_texel_format(BufferID p_buffer, DataFormat p_format) override final;293virtual void buffer_free(BufferID p_buffer) override final;294virtual uint64_t buffer_get_allocation_size(BufferID p_buffer) override final;295virtual uint8_t *buffer_map(BufferID p_buffer) override final;296virtual void buffer_unmap(BufferID p_buffer) override final;297virtual uint8_t *buffer_persistent_map_advance(BufferID p_buffer, uint64_t p_frames_drawn) override final;298virtual uint64_t buffer_get_dynamic_offsets(Span<BufferID> p_buffers) override final;299virtual uint64_t buffer_get_device_address(BufferID p_buffer) override final;300301/*****************/302/**** TEXTURE ****/303/*****************/304private:305struct TextureInfo : public ResourceInfo {306DataFormat format = DATA_FORMAT_MAX;307CD3DX12_RESOURCE_DESC desc = {};308uint32_t base_layer = 0;309uint32_t layers = 0;310uint32_t base_mip = 0;311uint32_t mipmaps = 0;312313struct {314D3D12_SHADER_RESOURCE_VIEW_DESC srv;315D3D12_UNORDERED_ACCESS_VIEW_DESC uav;316} view_descs = {};317318TextureInfo *main_texture = nullptr;319320#ifdef DEBUG_ENABLED321bool created_from_extension = false;322#endif323};324325HashMap<DXGI_FORMAT, uint32_t> format_sample_counts_mask_cache;326Mutex format_sample_counts_mask_cache_mutex;327328uint32_t _find_max_common_supported_sample_count(VectorView<DXGI_FORMAT> p_formats);329UINT _compute_component_mapping(const TextureView &p_view);330UINT _compute_plane_slice(DataFormat p_format, BitField<TextureAspectBits> p_aspect_bits);331UINT _compute_plane_slice(DataFormat p_format, TextureAspect p_aspect);332UINT _compute_subresource_from_layers(TextureInfo *p_texture, const TextureSubresourceLayers &p_layers, uint32_t p_layer_offset);333334void _discard_texture_subresources(const TextureInfo *p_tex_info, const CommandBufferInfo *p_cmd_buf_info);335336protected:337virtual bool _unordered_access_supported_by_format(DataFormat p_format);338339public:340virtual TextureID texture_create(const TextureFormat &p_format, const TextureView &p_view) override final;341virtual 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;342virtual TextureID texture_create_shared(TextureID p_original_texture, const TextureView &p_view) override final;343virtual 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;344virtual void texture_free(TextureID p_texture) override final;345virtual uint64_t texture_get_allocation_size(TextureID p_texture) override final;346virtual void texture_get_copyable_layout(TextureID p_texture, const TextureSubresource &p_subresource, TextureCopyableLayout *r_layout) override final;347virtual Vector<uint8_t> texture_get_data(TextureID p_texture, uint32_t p_layer) override final;348virtual BitField<TextureUsageBits> texture_get_usages_supported_by_format(DataFormat p_format, bool p_cpu_readable) override final;349virtual bool texture_can_make_shared_with_format(TextureID p_texture, DataFormat p_format, bool &r_raw_reinterpretation) override final;350351private:352TextureID _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);353354public:355/*****************/356/**** SAMPLER ****/357/*****************/358private:359LocalVector<D3D12_SAMPLER_DESC> samplers;360361struct SamplerDescriptorHeapAllocation : DescriptorHeap::Allocation {362uint32_t key = 0;363uint32_t use_count = 1;364};365366RBMap<uint32_t, SamplerDescriptorHeapAllocation> sampler_descriptor_heap_allocations;367368public:369virtual SamplerID sampler_create(const SamplerState &p_state) final override;370virtual void sampler_free(SamplerID p_sampler) final override;371virtual bool sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_filter) override final;372373/**********************/374/**** VERTEX ARRAY ****/375/**********************/376private:377struct VertexFormatInfo {378TightLocalVector<D3D12_INPUT_ELEMENT_DESC> input_elem_descs;379TightLocalVector<UINT> vertex_buffer_strides;380};381382public:383virtual VertexFormatID vertex_format_create(Span<VertexAttribute> p_vertex_attribs, const VertexAttributeBindingsMap &p_vertex_bindings) override final;384virtual void vertex_format_free(VertexFormatID p_vertex_format) override final;385386/******************/387/**** BARRIERS ****/388/******************/389390virtual void command_pipeline_barrier(391CommandBufferID p_cmd_buffer,392BitField<PipelineStageBits> p_src_stages,393BitField<PipelineStageBits> p_dst_stages,394VectorView<RDD::MemoryAccessBarrier> p_memory_barriers,395VectorView<RDD::BufferBarrier> p_buffer_barriers,396VectorView<RDD::TextureBarrier> p_texture_barriers,397VectorView<AccelerationStructureBarrier> p_acceleration_structure_barriers) override final;398399private:400/****************/401/**** FENCES ****/402/****************/403404struct FenceInfo {405Microsoft::WRL::ComPtr<ID3D12Fence> d3d_fence = nullptr;406HANDLE event_handle = nullptr;407UINT64 fence_value = 0;408};409410public:411virtual FenceID fence_create() override;412virtual Error fence_wait(FenceID p_fence) override;413virtual void fence_free(FenceID p_fence) override;414415private:416/********************/417/**** SEMAPHORES ****/418/********************/419420struct SemaphoreInfo {421Microsoft::WRL::ComPtr<ID3D12Fence> d3d_fence = nullptr;422UINT64 fence_value = 0;423};424425virtual SemaphoreID semaphore_create() override;426virtual void semaphore_free(SemaphoreID p_semaphore) override;427428/******************/429/**** COMMANDS ****/430/******************/431432// ----- QUEUE FAMILY -----433434virtual CommandQueueFamilyID command_queue_family_get(BitField<CommandQueueFamilyBits> p_cmd_queue_family_bits, RenderingContextDriver::SurfaceID p_surface = 0) override;435436private:437// ----- QUEUE -----438439struct CommandQueueInfo {440Microsoft::WRL::ComPtr<ID3D12CommandQueue> d3d_queue;441};442443public:444virtual CommandQueueID command_queue_create(CommandQueueFamilyID p_cmd_queue_family, bool p_identify_as_main_queue = false) override;445virtual 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;446virtual void command_queue_free(CommandQueueID p_cmd_queue) override;447448private:449// ----- POOL -----450struct CommandPoolInfo {451CommandQueueFamilyID queue_family;452CommandBufferType buffer_type = COMMAND_BUFFER_TYPE_PRIMARY;453// Since there are no command pools in D3D12, we need to track the command buffers created by this pool454// so that we can free them when the pool is freed.455SelfList<CommandBufferInfo>::List command_buffers;456};457458public:459virtual CommandPoolID command_pool_create(CommandQueueFamilyID p_cmd_queue_family, CommandBufferType p_cmd_buffer_type) override final;460virtual bool command_pool_reset(CommandPoolID p_cmd_pool) override final;461virtual void command_pool_free(CommandPoolID p_cmd_pool) override final;462463// ----- BUFFER -----464465private:466// Belongs to RENDERING-SUBPASS, but needed here.467struct FramebufferInfo;468struct RenderPassInfo;469struct RenderPassState {470struct AttachmentLayout {471struct AspectLayout {472TextureLayout cur_layout = TEXTURE_LAYOUT_UNDEFINED;473TextureLayout expected_layout = TEXTURE_LAYOUT_UNDEFINED;474};475476AspectLayout aspect_layouts[TEXTURE_ASPECT_MAX];477};478479uint32_t current_subpass = UINT32_MAX;480const FramebufferInfo *fb_info = nullptr;481const RenderPassInfo *pass_info = nullptr;482CD3DX12_RECT region_rect = {};483bool region_is_all = false;484LocalVector<AttachmentLayout> attachment_layouts;485486const VertexFormatInfo *vf_info = nullptr;487D3D12_VERTEX_BUFFER_VIEW vertex_buffer_views[8] = {};488uint32_t vertex_buffer_count = 0;489};490491struct DynParams {492D3D12_PRIMITIVE_TOPOLOGY primitive_topology = {};493Color blend_constant;494float depth_bounds_min = 0.0f;495float depth_bounds_max = 1.0f;496uint32_t stencil_reference = 0;497};498499// Leveraging knowledge of actual usage and D3D12 specifics (namely, command lists from the same allocator500// can't be freely begun and ended), an allocator per list works better.501struct CommandBufferInfo {502// Store a self list reference to be used by the command pool.503SelfList<CommandBufferInfo> command_buffer_info_elem{ this };504505Microsoft::WRL::ComPtr<ID3D12CommandAllocator> cmd_allocator;506Microsoft::WRL::ComPtr<ID3D12GraphicsCommandList> cmd_list;507Microsoft::WRL::ComPtr<ID3D12GraphicsCommandList1> cmd_list_1;508Microsoft::WRL::ComPtr<ID3D12GraphicsCommandList5> cmd_list_5;509Microsoft::WRL::ComPtr<ID3D12GraphicsCommandList7> cmd_list_7;510511ID3D12PipelineState *graphics_pso = nullptr;512ID3D12PipelineState *compute_pso = nullptr;513514DynParams dyn_params;515bool pending_dyn_params = true;516517uint32_t graphics_root_signature_crc = 0;518uint32_t compute_root_signature_crc = 0;519520RenderPassState render_pass_state;521bool descriptor_heaps_set = false;522523HashMap<ResourceInfo::States *, BarrierRequest> res_barriers_requests;524LocalVector<D3D12_RESOURCE_BARRIER> res_barriers;525uint32_t res_barriers_count = 0;526uint32_t res_barriers_batch = 0;527528CPUDescriptorHeapPool::Allocation uav_alloc;529CPUDescriptorHeapPool::Allocation rtv_alloc;530CPUDescriptorHeapPool::Allocation dsv_alloc;531};532533public:534virtual CommandBufferID command_buffer_create(CommandPoolID p_cmd_pool) override final;535virtual bool command_buffer_begin(CommandBufferID p_cmd_buffer) override final;536virtual bool command_buffer_begin_secondary(CommandBufferID p_cmd_buffer, RenderPassID p_render_pass, uint32_t p_subpass, FramebufferID p_framebuffer) override final;537virtual void command_buffer_end(CommandBufferID p_cmd_buffer) override final;538virtual void command_buffer_execute_secondary(CommandBufferID p_cmd_buffer, VectorView<CommandBufferID> p_secondary_cmd_buffers) override final;539540private:541/********************/542/**** SWAP CHAIN ****/543/********************/544545struct SwapChain {546Microsoft::WRL::ComPtr<IDXGISwapChain3> d3d_swap_chain;547RenderingContextDriver::SurfaceID surface = RenderingContextDriver::SurfaceID();548UINT present_flags = 0;549UINT sync_interval = 1;550UINT creation_flags = 0;551RenderPassID render_pass;552TightLocalVector<ID3D12Resource *> render_targets;553TightLocalVector<TextureInfo> render_targets_info;554TightLocalVector<FramebufferID> framebuffers;555RDD::DataFormat data_format = DATA_FORMAT_MAX;556};557558void _swap_chain_release(SwapChain *p_swap_chain);559void _swap_chain_release_buffers(SwapChain *p_swap_chain);560561public:562virtual SwapChainID swap_chain_create(RenderingContextDriver::SurfaceID p_surface) override;563virtual Error swap_chain_resize(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, uint32_t p_desired_framebuffer_count) override;564virtual FramebufferID swap_chain_acquire_framebuffer(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, bool &r_resize_required) override;565virtual RenderPassID swap_chain_get_render_pass(SwapChainID p_swap_chain) override;566virtual DataFormat swap_chain_get_format(SwapChainID p_swap_chain) override;567virtual void swap_chain_free(SwapChainID p_swap_chain) override;568569/*********************/570/**** FRAMEBUFFER ****/571/*********************/572private:573struct FramebufferInfo {574bool is_screen = false;575Size2i size;576577TightLocalVector<uint32_t> attachments_handle_inds; // RTV heap index for color; DSV heap index for DSV.578CPUDescriptorHeapPool::Allocation rtv_alloc;579CPUDescriptorHeapPool::Allocation dsv_alloc; // Used only for depth-stencil attachments.580581TightLocalVector<TextureID> attachments; // Color and depth-stencil. Used if not screen.582TextureID vrs_attachment;583};584585D3D12_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);586D3D12_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);587D3D12_DEPTH_STENCIL_VIEW_DESC _make_dsv_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);588589FramebufferID _framebuffer_create(RenderPassID p_render_pass, VectorView<TextureID> p_attachments, uint32_t p_width, uint32_t p_height, bool p_is_screen);590591public:592virtual FramebufferID framebuffer_create(RenderPassID p_render_pass, VectorView<TextureID> p_attachments, uint32_t p_width, uint32_t p_height) override final;593virtual void framebuffer_free(FramebufferID p_framebuffer) override final;594595/****************/596/**** SHADER ****/597/****************/598599private:600static const uint32_t ROOT_SIGNATURE_SIZE = 256;601static const uint32_t PUSH_CONSTANT_SIZE = 128; // Mimicking Vulkan.602603enum {604// We can only aim to set a maximum here, since depending on the shader605// there may be more or less root signature free for descriptor tables.606// Therefore, we'll have to rely on the final check at runtime, when building607// the root signature structure for a given shader.608// To be precise, these may be present or not, and their size vary statically:609// - Push constant (we'll assume this is always present to avoid reserving much610// more space for descriptor sets than needed for almost any imaginable case,611// given that most shader templates feature push constants).612// - NIR-DXIL runtime data.613MAX_UNIFORM_SETS = (ROOT_SIGNATURE_SIZE - PUSH_CONSTANT_SIZE) / sizeof(uint32_t),614};615616struct ShaderInfo {617uint32_t dxil_push_constant_size = 0;618uint32_t nir_runtime_data_root_param_idx = UINT32_MAX;619PipelineType pipeline_type = PIPELINE_TYPE_RASTERIZATION;620621struct UniformBindingInfo {622uint32_t stages = 0; // Actual shader stages using the uniform (0 if totally optimized out).623ResourceClass res_class = RES_CLASS_INVALID;624UniformType type = UNIFORM_TYPE_MAX;625uint32_t length = UINT32_MAX;626bool writable = false;627uint32_t resource_descriptor_offset = UINT32_MAX;628uint32_t sampler_descriptor_offset = UINT32_MAX;629uint32_t root_param_idx = UINT32_MAX;630};631632struct UniformSet {633TightLocalVector<UniformBindingInfo> bindings;634uint32_t resource_root_param_idx = UINT32_MAX;635uint32_t resource_descriptor_count = 0;636uint32_t sampler_root_param_idx = UINT32_MAX;637uint32_t sampler_descriptor_count = 0;638};639640TightLocalVector<UniformSet> sets;641642struct SpecializationConstant {643uint32_t constant_id = UINT32_MAX;644uint32_t int_value = UINT32_MAX;645uint64_t stages_bit_offsets[D3D12_BITCODE_OFFSETS_NUM_STAGES] = {};646};647648TightLocalVector<SpecializationConstant> specialization_constants;649uint32_t spirv_specialization_constants_ids_mask = 0;650651HashMap<ShaderStage, Vector<uint8_t>> stages_bytecode;652653Microsoft::WRL::ComPtr<ID3D12RootSignature> root_signature;654Microsoft::WRL::ComPtr<ID3D12RootSignatureDeserializer> root_signature_deserializer;655const D3D12_ROOT_SIGNATURE_DESC *root_signature_desc = nullptr; // Owned by the deserializer.656uint32_t root_signature_crc = 0;657};658659bool _shader_apply_specialization_constants(660const ShaderInfo *p_shader_info,661VectorView<PipelineSpecializationConstant> p_specialization_constants,662HashMap<ShaderStage, Vector<uint8_t>> &r_final_stages_bytecode);663664public:665virtual ShaderID shader_create_from_container(const Ref<RenderingShaderContainer> &p_shader_container, const Vector<ImmutableSampler> &p_immutable_samplers) override final;666virtual uint32_t shader_get_layout_hash(ShaderID p_shader) override final;667virtual void shader_free(ShaderID p_shader) override final;668virtual void shader_destroy_modules(ShaderID p_shader) override final;669670/*********************/671/**** UNIFORM SET ****/672/*********************/673674private:675struct UniformSetInfo {676DescriptorHeap::Allocation resource_descriptor_heap_alloc;677SamplerDescriptorHeapAllocation *sampler_descriptor_heap_alloc = nullptr;678679struct DynamicBuffer {680BufferDynamicInfo const *info = nullptr;681uint32_t binding = UINT_MAX;682};683684TightLocalVector<DynamicBuffer> dynamic_buffers;685686struct StateRequirement {687ResourceInfo *resource = nullptr;688bool is_buffer = false;689D3D12_RESOURCE_STATES states = {};690uint64_t shader_uniform_idx_mask = 0;691};692693TightLocalVector<StateRequirement> resource_states;694};695696public:697virtual UniformSetID uniform_set_create(VectorView<BoundUniform> p_uniforms, ShaderID p_shader, uint32_t p_set_index, int p_linear_pool_index) override final;698virtual void uniform_set_free(UniformSetID p_uniform_set) override final;699virtual uint32_t uniform_sets_get_dynamic_offsets(VectorView<UniformSetID> p_uniform_sets, ShaderID p_shader, uint32_t p_first_set_index, uint32_t p_set_count) const override final;700701// ----- COMMANDS -----702703virtual 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;704705private:706void _command_check_descriptor_sets(CommandBufferID p_cmd_buffer);707DescriptorHeap::Allocation _command_allocate_per_frame_descriptor();708709public:710/******************/711/**** TRANSFER ****/712/******************/713714virtual void command_clear_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, uint64_t p_offset, uint64_t p_size) override final;715virtual void command_copy_buffer(CommandBufferID p_cmd_buffer, BufferID p_src_buffer, BufferID p_dst_buffer, VectorView<BufferCopyRegion> p_regions) override final;716717virtual 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;718virtual 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;719virtual 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;720virtual void command_clear_depth_stencil_texture(CommandBufferID p_cmd_buffer, TextureID p_texture, TextureLayout p_texture_layout, float p_depth, uint8_t p_stencil, const TextureSubresourceRange &p_subresources) override final;721722public:723virtual 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;724virtual 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;725726/******************/727/**** PIPELINE ****/728/******************/729730struct RenderPipelineInfo {731const VertexFormatInfo *vf_info = nullptr;732DynParams dyn_params;733};734735struct PipelineInfo {736Microsoft::WRL::ComPtr<ID3D12PipelineState> pso;737const ShaderInfo *shader_info = nullptr;738RenderPipelineInfo render_info;739};740741virtual void pipeline_free(PipelineID p_pipeline) override final;742743public:744// ----- BINDING -----745746virtual 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;747748// ----- CACHE -----749750virtual bool pipeline_cache_create(const Vector<uint8_t> &p_data) override final;751virtual void pipeline_cache_free() override final;752virtual size_t pipeline_cache_query_size() override final;753virtual Vector<uint8_t> pipeline_cache_serialize() override final;754755/*******************/756/**** RENDERING ****/757/*******************/758759// ----- SUBPASS -----760761private:762struct RenderPassInfo {763TightLocalVector<Attachment> attachments;764TightLocalVector<Subpass> subpasses;765uint32_t view_count = 0;766uint32_t max_supported_sample_count = 0;767};768769public:770virtual 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;771virtual void render_pass_free(RenderPassID p_render_pass) override final;772773// ----- COMMANDS -----774775virtual 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;776777private:778void _render_pass_enhanced_barriers_flush(CommandBufferID p_cmd_buffer);779void _end_render_pass(CommandBufferID p_cmd_buffer);780781public:782virtual void command_end_render_pass(CommandBufferID p_cmd_buffer) override final;783virtual void command_next_render_subpass(CommandBufferID p_cmd_buffer, CommandBufferType p_cmd_buffer_type) override final;784virtual void command_render_set_viewport(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_viewports) override final;785virtual void command_render_set_scissor(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_scissors) override final;786787virtual void command_render_clear_attachments(CommandBufferID p_cmd_buffer, VectorView<AttachmentClear> p_attachment_clears, VectorView<Rect2i> p_rects) override final;788789// Binding.790virtual void command_bind_render_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) override final;791virtual 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, uint32_t p_dynamic_offsets) override final;792793// Drawing.794virtual 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;795virtual 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;796virtual 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;797virtual 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;798virtual 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;799virtual 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;800801// Buffer binding.802virtual void command_render_bind_vertex_buffers(CommandBufferID p_cmd_buffer, uint32_t p_binding_count, const BufferID *p_buffers, const uint64_t *p_offsets, uint64_t p_dynamic_offsets) override final;803virtual void command_render_bind_index_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, IndexBufferFormat p_format, uint64_t p_offset) override final;804805private:806void _bind_vertex_buffers(CommandBufferInfo *p_cmd_buf_info);807808public:809// Dynamic state.810virtual void command_render_set_blend_constants(CommandBufferID p_cmd_buffer, const Color &p_constants) override final;811virtual void command_render_set_line_width(CommandBufferID p_cmd_buffer, float p_width) override final;812813// ----- PIPELINE -----814815public:816virtual PipelineID render_pipeline_create(817ShaderID p_shader,818VertexFormatID p_vertex_format,819RenderPrimitive p_render_primitive,820PipelineRasterizationState p_rasterization_state,821PipelineMultisampleState p_multisample_state,822PipelineDepthStencilState p_depth_stencil_state,823PipelineColorBlendState p_blend_state,824VectorView<int32_t> p_color_attachments,825BitField<PipelineDynamicStateFlags> p_dynamic_state,826RenderPassID p_render_pass,827uint32_t p_render_subpass,828VectorView<PipelineSpecializationConstant> p_specialization_constants) override final;829830/*****************/831/**** COMPUTE ****/832/*****************/833834// ----- COMMANDS -----835836// Binding.837virtual void command_bind_compute_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) override final;838virtual 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, uint32_t p_dynamic_offsets) override final;839840// Dispatching.841virtual 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;842virtual void command_compute_dispatch_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset) override final;843844// ----- PIPELINE -----845846virtual PipelineID compute_pipeline_create(ShaderID p_shader, VectorView<PipelineSpecializationConstant> p_specialization_constants) override final;847848/********************/849/**** RAYTRACING ****/850/********************/851852// ---- ACCELERATION STRUCTURES ----853854virtual AccelerationStructureID blas_create(BufferID p_vertex_buffer, uint64_t p_vertex_offset, VertexFormatID p_vertex_format, uint32_t p_vertex_count, uint32_t p_position_attribute_location, BufferID p_index_buffer, IndexBufferFormat p_index_format, uint64_t p_index_offset, uint32_t p_index_count, BitField<AccelerationStructureGeometryBits> p_geometry_bits) override final;855virtual uint32_t tlas_instances_buffer_get_size_bytes(uint32_t p_instance_count) override final;856virtual void tlas_instances_buffer_fill(BufferID p_instances_buffer, VectorView<AccelerationStructureID> p_blases, VectorView<Transform3D> p_transforms) override final;857virtual AccelerationStructureID tlas_create(BufferID p_instances_buffer) override final;858virtual void acceleration_structure_free(AccelerationStructureID p_acceleration_structure) override final;859virtual uint32_t acceleration_structure_get_scratch_size_bytes(AccelerationStructureID p_acceleration_structure) override final;860861// ----- PIPELINE -----862863virtual RaytracingPipelineID raytracing_pipeline_create(ShaderID p_shader, VectorView<PipelineSpecializationConstant> p_specialization_constants) override final;864virtual void raytracing_pipeline_free(RaytracingPipelineID p_pipeline) override final;865866// ----- COMMANDS -----867868virtual void command_build_acceleration_structure(CommandBufferID p_cmd_buffer, AccelerationStructureID p_acceleration_structure, BufferID p_scratch_buffer) override final;869virtual void command_bind_raytracing_pipeline(CommandBufferID p_cmd_buffer, RaytracingPipelineID p_pipeline) override final;870virtual void command_bind_raytracing_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) override final;871virtual void command_trace_rays(CommandBufferID p_cmd_buffer, uint32_t p_width, uint32_t p_height) override final;872873/*****************/874/**** QUERIES ****/875/*****************/876877// ----- TIMESTAMP -----878879private:880struct TimestampQueryPoolInfo {881Microsoft::WRL::ComPtr<ID3D12QueryHeap> query_heap;882uint32_t query_count = 0;883Microsoft::WRL::ComPtr<D3D12MA::Allocation> results_buffer_allocation;884};885886public:887// Basic.888virtual QueryPoolID timestamp_query_pool_create(uint32_t p_query_count) override final;889virtual void timestamp_query_pool_free(QueryPoolID p_pool_id) override final;890virtual void timestamp_query_pool_get_results(QueryPoolID p_pool_id, uint32_t p_query_count, uint64_t *r_results) override final;891virtual uint64_t timestamp_query_result_to_time(uint64_t p_result) override final;892893// Commands.894virtual void command_timestamp_query_pool_reset(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_query_count) override final;895virtual void command_timestamp_write(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_index) override final;896897/****************/898/**** LABELS ****/899/****************/900901virtual void command_begin_label(CommandBufferID p_cmd_buffer, const char *p_label_name, const Color &p_color) override final;902virtual void command_end_label(CommandBufferID p_cmd_buffer) override final;903904/****************/905/**** DEBUG *****/906/****************/907virtual void command_insert_breadcrumb(CommandBufferID p_cmd_buffer, uint32_t p_data) override final;908909/********************/910/**** SUBMISSION ****/911/********************/912private:913struct FrameInfo {914LocalVector<DescriptorHeap::Allocation> descriptor_allocations;915uint32_t descriptor_allocation_count = 0;916};917TightLocalVector<FrameInfo> frames;918uint32_t frame_idx = 0;919uint32_t frames_drawn = 0;920bool segment_begun = false;921HashMap<uint64_t, bool> has_comp_alpha;922923public:924virtual void begin_segment(uint32_t p_frame_index, uint32_t p_frames_drawn) override final;925virtual void end_segment() override final;926927/**************/928/**** MISC ****/929/**************/930931virtual void set_object_name(ObjectType p_type, ID p_driver_id, const String &p_name) override final;932virtual uint64_t get_resource_native_handle(DriverResource p_type, ID p_driver_id) override final;933virtual uint64_t get_total_memory_used() override final;934virtual uint64_t get_lazily_memory_used() override final;935virtual uint64_t limit_get(Limit p_limit) override final;936virtual uint64_t api_trait_get(ApiTrait p_trait) override final;937virtual bool has_feature(Features p_feature) override final;938virtual const MultiviewCapabilities &get_multiview_capabilities() override final;939virtual const FragmentShadingRateCapabilities &get_fragment_shading_rate_capabilities() override final;940virtual const FragmentDensityMapCapabilities &get_fragment_density_map_capabilities() override final;941virtual String get_api_name() const override final;942virtual String get_api_version() const override final;943virtual String get_pipeline_cache_uuid() const override final;944virtual const Capabilities &get_capabilities() const override final;945virtual const RenderingShaderContainerFormat &get_shader_container_format() const override final;946947virtual bool is_composite_alpha_supported(CommandQueueID p_queue) const override final;948949static bool is_in_developer_mode();950951private:952/*********************/953/**** BOOKKEEPING ****/954/*********************/955956using VersatileResource = VersatileResourceTemplate<957BufferInfo,958TextureInfo,959TextureInfo,960TextureInfo,961VertexFormatInfo,962CommandBufferInfo,963FramebufferInfo,964ShaderInfo,965UniformSetInfo,966RenderPassInfo,967TimestampQueryPoolInfo>;968PagedAllocator<VersatileResource, true> resources_allocator;969970/******************/971972public:973RenderingDeviceDriverD3D12(RenderingContextDriverD3D12 *p_context_driver);974virtual ~RenderingDeviceDriverD3D12();975};976977978