Path: blob/master/drivers/d3d12/rendering_device_driver_d3d12.h
9973 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/hash_map.h"33#include "core/templates/paged_allocator.h"34#include "core/templates/self_list.h"35#include "rendering_shader_container_d3d12.h"36#include "servers/rendering/rendering_device_driver.h"3738#ifndef _MSC_VER39// Match current version used by MinGW, MSVC and Direct3D 12 headers use 500.40#define __REQUIRED_RPCNDR_H_VERSION__ 47541#endif4243#include <d3dx12.h>44#include <dxgi1_6.h>45#define D3D12MA_D3D12_HEADERS_ALREADY_INCLUDED46#include <D3D12MemAlloc.h>4748#include <wrl/client.h>4950#if defined(_MSC_VER) && defined(MemoryBarrier)51// Annoying define from winnt.h. Reintroduced by some of the headers above.52#undef MemoryBarrier53#endif5455using Microsoft::WRL::ComPtr;5657#ifdef DEV_ENABLED58#define CUSTOM_INFO_QUEUE_ENABLED 059#endif6061class RenderingContextDriverD3D12;6263// Design principles:64// - D3D12 structs are zero-initialized and fields not requiring a non-zero value are omitted (except in cases where expresivity reasons apply).65class RenderingDeviceDriverD3D12 : public RenderingDeviceDriver {66/*****************/67/**** GENERIC ****/68/*****************/6970struct D3D12Format {71DXGI_FORMAT family = DXGI_FORMAT_UNKNOWN;72DXGI_FORMAT general_format = DXGI_FORMAT_UNKNOWN;73UINT swizzle = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;74DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN;75};7677static const D3D12Format RD_TO_D3D12_FORMAT[RDD::DATA_FORMAT_MAX];7879struct DeviceLimits {80uint64_t max_srvs_per_shader_stage = 0;81uint64_t max_cbvs_per_shader_stage = 0;82uint64_t max_samplers_across_all_stages = 0;83uint64_t max_uavs_across_all_stages = 0;84uint64_t timestamp_frequency = 0;85};8687struct SubgroupCapabilities {88uint32_t size = 0;89bool wave_ops_supported = false;90uint32_t supported_stages_flags_rd() const;91uint32_t supported_operations_flags_rd() const;92};9394struct ShaderCapabilities {95D3D_SHADER_MODEL shader_model = (D3D_SHADER_MODEL)0;96bool native_16bit_ops = false;97};9899struct StorageBufferCapabilities {100bool storage_buffer_16_bit_access_is_supported = false;101};102103struct FormatCapabilities {104bool relaxed_casting_supported = false;105};106107struct BarrierCapabilities {108bool enhanced_barriers_supported = false;109};110111struct MiscFeaturesSupport {112bool depth_bounds_supported = false;113};114115RenderingContextDriverD3D12 *context_driver = nullptr;116RenderingContextDriver::Device context_device;117ComPtr<IDXGIAdapter> adapter;118DXGI_ADAPTER_DESC adapter_desc;119ComPtr<ID3D12Device> device;120DeviceLimits device_limits;121RDD::Capabilities device_capabilities;122uint32_t feature_level = 0; // Major * 10 + minor.123SubgroupCapabilities subgroup_capabilities;124RDD::MultiviewCapabilities multiview_capabilities;125FragmentShadingRateCapabilities fsr_capabilities;126FragmentDensityMapCapabilities fdm_capabilities;127ShaderCapabilities shader_capabilities;128StorageBufferCapabilities storage_buffer_capabilities;129FormatCapabilities format_capabilities;130BarrierCapabilities barrier_capabilities;131MiscFeaturesSupport misc_features_support;132RenderingShaderContainerFormatD3D12 shader_container_format;133String pipeline_cache_id;134135class DescriptorsHeap {136D3D12_DESCRIPTOR_HEAP_DESC desc = {};137ComPtr<ID3D12DescriptorHeap> heap;138uint32_t handle_size = 0;139140public:141class Walker { // Texas Ranger.142friend class DescriptorsHeap;143144uint32_t handle_size = 0;145uint32_t handle_count = 0;146D3D12_CPU_DESCRIPTOR_HANDLE first_cpu_handle = {};147D3D12_GPU_DESCRIPTOR_HANDLE first_gpu_handle = {};148uint32_t handle_index = 0;149150public:151D3D12_CPU_DESCRIPTOR_HANDLE get_curr_cpu_handle();152D3D12_GPU_DESCRIPTOR_HANDLE get_curr_gpu_handle();153_FORCE_INLINE_ void rewind() { handle_index = 0; }154void advance(uint32_t p_count = 1);155uint32_t get_current_handle_index() const { return handle_index; }156uint32_t get_free_handles() { return handle_count - handle_index; }157bool is_at_eof() { return handle_index == handle_count; }158};159160Error allocate(ID3D12Device *m_device, D3D12_DESCRIPTOR_HEAP_TYPE m_type, uint32_t m_descriptor_count, bool p_for_gpu);161uint32_t get_descriptor_count() const { return desc.NumDescriptors; }162ID3D12DescriptorHeap *get_heap() const { return heap.Get(); }163164Walker make_walker() const;165};166167struct {168ComPtr<ID3D12CommandSignature> draw;169ComPtr<ID3D12CommandSignature> draw_indexed;170ComPtr<ID3D12CommandSignature> dispatch;171} indirect_cmd_signatures;172173static 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);174void _set_object_name(ID3D12Object *p_object, String p_object_name);175Error _initialize_device();176Error _check_capabilities();177Error _get_device_limits();178Error _initialize_allocator();179Error _initialize_frames(uint32_t p_frame_count);180Error _initialize_command_signatures();181182public:183Error initialize(uint32_t p_device_index, uint32_t p_frame_count) override final;184185private:186/****************/187/**** MEMORY ****/188/****************/189190ComPtr<D3D12MA::Allocator> allocator;191192/******************/193/**** RESOURCE ****/194/******************/195196struct ResourceInfo {197struct States {198// As many subresources as mipmaps * layers; planes (for depth-stencil) are tracked together.199TightLocalVector<D3D12_RESOURCE_STATES> subresource_states; // Used only if not a view.200uint32_t last_batch_with_uav_barrier = 0;201};202203ID3D12Resource *resource = nullptr; // Non-null even if not owned.204struct {205ComPtr<ID3D12Resource> resource;206ComPtr<D3D12MA::Allocation> allocation;207States states;208} owner_info; // All empty if the resource is not owned.209States *states_ptr = nullptr; // Own or from another if it doesn't own the D3D12 resource.210};211212struct BarrierRequest {213static const uint32_t MAX_GROUPS = 4;214// Maybe this is too much data to have it locally. Benchmarking may reveal that215// cache would be used better by having a maximum of local subresource masks and beyond216// that have an allocated vector with the rest.217static const uint32_t MAX_SUBRESOURCES = 4096;218ID3D12Resource *dx_resource = nullptr;219uint8_t subres_mask_qwords = 0;220uint8_t planes = 0;221struct Group {222D3D12_RESOURCE_STATES states = {};223static_assert(MAX_SUBRESOURCES % 64 == 0);224uint64_t subres_mask[MAX_SUBRESOURCES / 64] = {};225} groups[MAX_GROUPS];226uint8_t groups_count = 0;227static const D3D12_RESOURCE_STATES DELETED_GROUP = D3D12_RESOURCE_STATES(0xFFFFFFFFU);228};229230struct CommandBufferInfo;231232void _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);233void _resource_transitions_flush(CommandBufferInfo *p_command_buffer);234235/*****************/236/**** BUFFERS ****/237/*****************/238239struct BufferInfo : public ResourceInfo {240DataFormat texel_format = DATA_FORMAT_MAX;241uint64_t size = 0;242struct {243bool usable_as_uav : 1;244} flags = {};245};246247public:248virtual BufferID buffer_create(uint64_t p_size, BitField<BufferUsageBits> p_usage, MemoryAllocationType p_allocation_type) override final;249virtual bool buffer_set_texel_format(BufferID p_buffer, DataFormat p_format) override final;250virtual void buffer_free(BufferID p_buffer) override final;251virtual uint64_t buffer_get_allocation_size(BufferID p_buffer) override final;252virtual uint8_t *buffer_map(BufferID p_buffer) override final;253virtual void buffer_unmap(BufferID p_buffer) override final;254virtual uint64_t buffer_get_device_address(BufferID p_buffer) override final;255256/*****************/257/**** TEXTURE ****/258/*****************/259private:260struct TextureInfo : public ResourceInfo {261DataFormat format = DATA_FORMAT_MAX;262CD3DX12_RESOURCE_DESC desc = {};263uint32_t base_layer = 0;264uint32_t layers = 0;265uint32_t base_mip = 0;266uint32_t mipmaps = 0;267268struct {269D3D12_SHADER_RESOURCE_VIEW_DESC srv;270D3D12_UNORDERED_ACCESS_VIEW_DESC uav;271} view_descs = {};272273TextureInfo *main_texture = nullptr;274275UINT mapped_subresource = UINT_MAX;276SelfList<TextureInfo> pending_clear{ this };277#ifdef DEBUG_ENABLED278bool created_from_extension = false;279#endif280};281SelfList<TextureInfo>::List textures_pending_clear;282283HashMap<DXGI_FORMAT, uint32_t> format_sample_counts_mask_cache;284Mutex format_sample_counts_mask_cache_mutex;285286uint32_t _find_max_common_supported_sample_count(VectorView<DXGI_FORMAT> p_formats);287UINT _compute_component_mapping(const TextureView &p_view);288UINT _compute_plane_slice(DataFormat p_format, BitField<TextureAspectBits> p_aspect_bits);289UINT _compute_plane_slice(DataFormat p_format, TextureAspect p_aspect);290UINT _compute_subresource_from_layers(TextureInfo *p_texture, const TextureSubresourceLayers &p_layers, uint32_t p_layer_offset);291292void _discard_texture_subresources(const TextureInfo *p_tex_info, const CommandBufferInfo *p_cmd_buf_info);293294protected:295virtual bool _unordered_access_supported_by_format(DataFormat p_format);296297public:298virtual TextureID texture_create(const TextureFormat &p_format, const TextureView &p_view) override final;299virtual 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;300virtual TextureID texture_create_shared(TextureID p_original_texture, const TextureView &p_view) override final;301virtual 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;302virtual void texture_free(TextureID p_texture) override final;303virtual uint64_t texture_get_allocation_size(TextureID p_texture) override final;304virtual void texture_get_copyable_layout(TextureID p_texture, const TextureSubresource &p_subresource, TextureCopyableLayout *r_layout) override final;305virtual uint8_t *texture_map(TextureID p_texture, const TextureSubresource &p_subresource) override final;306virtual void texture_unmap(TextureID p_texture) override final;307virtual BitField<TextureUsageBits> texture_get_usages_supported_by_format(DataFormat p_format, bool p_cpu_readable) override final;308virtual bool texture_can_make_shared_with_format(TextureID p_texture, DataFormat p_format, bool &r_raw_reinterpretation) override final;309310private:311TextureID _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);312313public:314/*****************/315/**** SAMPLER ****/316/*****************/317private:318LocalVector<D3D12_SAMPLER_DESC> samplers;319320public:321virtual SamplerID sampler_create(const SamplerState &p_state) final override;322virtual void sampler_free(SamplerID p_sampler) final override;323virtual bool sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_filter) override final;324325/**********************/326/**** VERTEX ARRAY ****/327/**********************/328private:329struct VertexFormatInfo {330TightLocalVector<D3D12_INPUT_ELEMENT_DESC> input_elem_descs;331TightLocalVector<UINT> vertex_buffer_strides;332};333334public:335virtual VertexFormatID vertex_format_create(VectorView<VertexAttribute> p_vertex_attribs) override final;336virtual void vertex_format_free(VertexFormatID p_vertex_format) override final;337338/******************/339/**** BARRIERS ****/340/******************/341342virtual void command_pipeline_barrier(343CommandBufferID p_cmd_buffer,344BitField<PipelineStageBits> p_src_stages,345BitField<PipelineStageBits> p_dst_stages,346VectorView<RDD::MemoryBarrier> p_memory_barriers,347VectorView<RDD::BufferBarrier> p_buffer_barriers,348VectorView<RDD::TextureBarrier> p_texture_barriers) override final;349350private:351/****************/352/**** FENCES ****/353/****************/354355struct FenceInfo {356ComPtr<ID3D12Fence> d3d_fence = nullptr;357HANDLE event_handle = nullptr;358UINT64 fence_value = 0;359};360361public:362virtual FenceID fence_create() override;363virtual Error fence_wait(FenceID p_fence) override;364virtual void fence_free(FenceID p_fence) override;365366private:367/********************/368/**** SEMAPHORES ****/369/********************/370371struct SemaphoreInfo {372ComPtr<ID3D12Fence> d3d_fence = nullptr;373UINT64 fence_value = 0;374};375376virtual SemaphoreID semaphore_create() override;377virtual void semaphore_free(SemaphoreID p_semaphore) override;378379/******************/380/**** COMMANDS ****/381/******************/382383// ----- QUEUE FAMILY -----384385virtual CommandQueueFamilyID command_queue_family_get(BitField<CommandQueueFamilyBits> p_cmd_queue_family_bits, RenderingContextDriver::SurfaceID p_surface = 0) override;386387private:388// ----- QUEUE -----389390struct CommandQueueInfo {391ComPtr<ID3D12CommandQueue> d3d_queue;392};393394public:395virtual CommandQueueID command_queue_create(CommandQueueFamilyID p_cmd_queue_family, bool p_identify_as_main_queue = false) override;396virtual 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;397virtual void command_queue_free(CommandQueueID p_cmd_queue) override;398399private:400// ----- POOL -----401struct CommandPoolInfo {402CommandQueueFamilyID queue_family;403CommandBufferType buffer_type = COMMAND_BUFFER_TYPE_PRIMARY;404// Since there are no command pools in D3D12, we need to track the command buffers created by this pool405// so that we can free them when the pool is freed.406SelfList<CommandBufferInfo>::List command_buffers;407};408409public:410virtual CommandPoolID command_pool_create(CommandQueueFamilyID p_cmd_queue_family, CommandBufferType p_cmd_buffer_type) override final;411virtual bool command_pool_reset(CommandPoolID p_cmd_pool) override final;412virtual void command_pool_free(CommandPoolID p_cmd_pool) override final;413414// ----- BUFFER -----415416private:417// Belongs to RENDERING-SUBPASS, but needed here.418struct FramebufferInfo;419struct RenderPassInfo;420struct RenderPassState {421uint32_t current_subpass = UINT32_MAX;422const FramebufferInfo *fb_info = nullptr;423const RenderPassInfo *pass_info = nullptr;424CD3DX12_RECT region_rect = {};425bool region_is_all = false;426427const VertexFormatInfo *vf_info = nullptr;428D3D12_VERTEX_BUFFER_VIEW vertex_buffer_views[8] = {};429uint32_t vertex_buffer_count = 0;430};431432// Leveraging knowledge of actual usage and D3D12 specifics (namely, command lists from the same allocator433// can't be freely begun and ended), an allocator per list works better.434struct CommandBufferInfo {435// Store a self list reference to be used by the command pool.436SelfList<CommandBufferInfo> command_buffer_info_elem{ this };437438ComPtr<ID3D12CommandAllocator> cmd_allocator;439ComPtr<ID3D12GraphicsCommandList> cmd_list;440441ID3D12PipelineState *graphics_pso = nullptr;442ID3D12PipelineState *compute_pso = nullptr;443444uint32_t graphics_root_signature_crc = 0;445uint32_t compute_root_signature_crc = 0;446447RenderPassState render_pass_state;448bool descriptor_heaps_set = false;449450HashMap<ResourceInfo::States *, BarrierRequest> res_barriers_requests;451LocalVector<D3D12_RESOURCE_BARRIER> res_barriers;452uint32_t res_barriers_count = 0;453uint32_t res_barriers_batch = 0;454};455456public:457virtual CommandBufferID command_buffer_create(CommandPoolID p_cmd_pool) override final;458virtual bool command_buffer_begin(CommandBufferID p_cmd_buffer) override final;459virtual bool command_buffer_begin_secondary(CommandBufferID p_cmd_buffer, RenderPassID p_render_pass, uint32_t p_subpass, FramebufferID p_framebuffer) override final;460virtual void command_buffer_end(CommandBufferID p_cmd_buffer) override final;461virtual void command_buffer_execute_secondary(CommandBufferID p_cmd_buffer, VectorView<CommandBufferID> p_secondary_cmd_buffers) override final;462463private:464/********************/465/**** SWAP CHAIN ****/466/********************/467468struct SwapChain {469ComPtr<IDXGISwapChain3> d3d_swap_chain;470RenderingContextDriver::SurfaceID surface = RenderingContextDriver::SurfaceID();471UINT present_flags = 0;472UINT sync_interval = 1;473UINT creation_flags = 0;474RenderPassID render_pass;475TightLocalVector<ID3D12Resource *> render_targets;476TightLocalVector<TextureInfo> render_targets_info;477TightLocalVector<FramebufferID> framebuffers;478RDD::DataFormat data_format = DATA_FORMAT_MAX;479};480481void _swap_chain_release(SwapChain *p_swap_chain);482void _swap_chain_release_buffers(SwapChain *p_swap_chain);483484public:485virtual SwapChainID swap_chain_create(RenderingContextDriver::SurfaceID p_surface) override;486virtual Error swap_chain_resize(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, uint32_t p_desired_framebuffer_count) override;487virtual FramebufferID swap_chain_acquire_framebuffer(CommandQueueID p_cmd_queue, SwapChainID p_swap_chain, bool &r_resize_required) override;488virtual RenderPassID swap_chain_get_render_pass(SwapChainID p_swap_chain) override;489virtual DataFormat swap_chain_get_format(SwapChainID p_swap_chain) override;490virtual void swap_chain_free(SwapChainID p_swap_chain) override;491492/*********************/493/**** FRAMEBUFFER ****/494/*********************/495private:496struct FramebufferInfo {497bool is_screen = false;498Size2i size;499TightLocalVector<uint32_t> attachments_handle_inds; // RTV heap index for color; DSV heap index for DSV.500DescriptorsHeap rtv_heap;501DescriptorsHeap dsv_heap; // Used only if not for screen and some depth-stencil attachments.502503TightLocalVector<TextureID> attachments; // Color and depth-stencil. Used if not screen.504TextureID vrs_attachment;505};506507D3D12_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);508D3D12_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);509D3D12_DEPTH_STENCIL_VIEW_DESC _make_dsv_for_texture(const TextureInfo *p_texture_info);510511FramebufferID _framebuffer_create(RenderPassID p_render_pass, VectorView<TextureID> p_attachments, uint32_t p_width, uint32_t p_height, bool p_is_screen);512513public:514virtual FramebufferID framebuffer_create(RenderPassID p_render_pass, VectorView<TextureID> p_attachments, uint32_t p_width, uint32_t p_height) override final;515virtual void framebuffer_free(FramebufferID p_framebuffer) override final;516517/****************/518/**** SHADER ****/519/****************/520521private:522static const uint32_t ROOT_SIGNATURE_SIZE = 256;523static const uint32_t PUSH_CONSTANT_SIZE = 128; // Mimicking Vulkan.524525enum {526// We can only aim to set a maximum here, since depending on the shader527// there may be more or less root signature free for descriptor tables.528// Therefore, we'll have to rely on the final check at runtime, when building529// the root signature structure for a given shader.530// To be precise, these may be present or not, and their size vary statically:531// - Push constant (we'll assume this is always present to avoid reserving much532// more space for descriptor sets than needed for almost any imaginable case,533// given that most shader templates feature push constants).534// - NIR-DXIL runtime data.535MAX_UNIFORM_SETS = (ROOT_SIGNATURE_SIZE - PUSH_CONSTANT_SIZE) / sizeof(uint32_t),536};537538struct ShaderInfo {539uint32_t dxil_push_constant_size = 0;540uint32_t nir_runtime_data_root_param_idx = UINT32_MAX;541bool is_compute = false;542543struct UniformBindingInfo {544uint32_t stages = 0; // Actual shader stages using the uniform (0 if totally optimized out).545ResourceClass res_class = RES_CLASS_INVALID;546UniformType type = UNIFORM_TYPE_MAX;547uint32_t length = UINT32_MAX;548#ifdef DEV_ENABLED549bool writable = false;550#endif551struct RootSignatureLocation {552uint32_t root_param_idx = UINT32_MAX;553uint32_t range_idx = UINT32_MAX;554};555struct {556RootSignatureLocation resource;557RootSignatureLocation sampler;558} root_sig_locations;559};560561struct UniformSet {562TightLocalVector<UniformBindingInfo> bindings;563struct {564uint32_t resources = 0;565uint32_t samplers = 0;566} num_root_params;567};568569TightLocalVector<UniformSet> sets;570571struct SpecializationConstant {572uint32_t constant_id = UINT32_MAX;573uint32_t int_value = UINT32_MAX;574uint64_t stages_bit_offsets[D3D12_BITCODE_OFFSETS_NUM_STAGES] = {};575};576577TightLocalVector<SpecializationConstant> specialization_constants;578uint32_t spirv_specialization_constants_ids_mask = 0;579580HashMap<ShaderStage, Vector<uint8_t>> stages_bytecode;581582ComPtr<ID3D12RootSignature> root_signature;583ComPtr<ID3D12RootSignatureDeserializer> root_signature_deserializer;584const D3D12_ROOT_SIGNATURE_DESC *root_signature_desc = nullptr; // Owned by the deserializer.585uint32_t root_signature_crc = 0;586};587588bool _shader_apply_specialization_constants(589const ShaderInfo *p_shader_info,590VectorView<PipelineSpecializationConstant> p_specialization_constants,591HashMap<ShaderStage, Vector<uint8_t>> &r_final_stages_bytecode);592593public:594virtual ShaderID shader_create_from_container(const Ref<RenderingShaderContainer> &p_shader_container, const Vector<ImmutableSampler> &p_immutable_samplers) override final;595virtual uint32_t shader_get_layout_hash(ShaderID p_shader) override final;596virtual void shader_free(ShaderID p_shader) override final;597virtual void shader_destroy_modules(ShaderID p_shader) override final;598599/*********************/600/**** UNIFORM SET ****/601/*********************/602603private:604struct RootDescriptorTable {605uint32_t root_param_idx = UINT32_MAX;606D3D12_GPU_DESCRIPTOR_HANDLE start_gpu_handle = {};607};608609struct UniformSetInfo {610struct {611DescriptorsHeap resources;612DescriptorsHeap samplers;613} desc_heaps;614615struct StateRequirement {616ResourceInfo *resource = nullptr;617bool is_buffer = false;618D3D12_RESOURCE_STATES states = {};619uint64_t shader_uniform_idx_mask = 0;620};621TightLocalVector<StateRequirement> resource_states;622623struct RecentBind {624uint64_t segment_serial = 0;625uint32_t root_signature_crc = 0;626struct {627TightLocalVector<RootDescriptorTable> resources;628TightLocalVector<RootDescriptorTable> samplers;629} root_tables;630int uses = 0;631} recent_binds[4]; // A better amount may be empirically found.632633#ifdef DEV_ENABLED634// Filthy, but useful for dev.635struct ResourceDescInfo {636D3D12_DESCRIPTOR_RANGE_TYPE type;637D3D12_SRV_DIMENSION srv_dimension;638};639TightLocalVector<ResourceDescInfo> resources_desc_info;640#endif641};642643public:644virtual UniformSetID uniform_set_create(VectorView<BoundUniform> p_uniforms, ShaderID p_shader, uint32_t p_set_index, int p_linear_pool_index) override final;645virtual void uniform_set_free(UniformSetID p_uniform_set) override final;646647// ----- COMMANDS -----648649virtual 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;650651private:652void _command_check_descriptor_sets(CommandBufferID p_cmd_buffer);653void _command_bind_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index, bool p_for_compute);654void _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);655656public:657/******************/658/**** TRANSFER ****/659/******************/660661virtual void command_clear_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, uint64_t p_offset, uint64_t p_size) override final;662virtual void command_copy_buffer(CommandBufferID p_cmd_buffer, BufferID p_src_buffer, BufferID p_dst_buffer, VectorView<BufferCopyRegion> p_regions) override final;663664virtual 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;665virtual 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;666virtual 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;667668public:669virtual 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;670virtual 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;671672/******************/673/**** PIPELINE ****/674/******************/675676struct RenderPipelineInfo {677const VertexFormatInfo *vf_info = nullptr;678679struct {680D3D12_PRIMITIVE_TOPOLOGY primitive_topology = {};681Color blend_constant;682float depth_bounds_min = 0.0f;683float depth_bounds_max = 0.0f;684uint32_t stencil_reference = 0;685} dyn_params;686};687688struct PipelineInfo {689ID3D12PipelineState *pso = nullptr;690const ShaderInfo *shader_info = nullptr;691RenderPipelineInfo render_info;692};693694virtual void pipeline_free(PipelineID p_pipeline) override final;695696public:697// ----- BINDING -----698699virtual 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;700701// ----- CACHE -----702703virtual bool pipeline_cache_create(const Vector<uint8_t> &p_data) override final;704virtual void pipeline_cache_free() override final;705virtual size_t pipeline_cache_query_size() override final;706virtual Vector<uint8_t> pipeline_cache_serialize() override final;707708/*******************/709/**** RENDERING ****/710/*******************/711712// ----- SUBPASS -----713714private:715struct RenderPassInfo {716TightLocalVector<Attachment> attachments;717TightLocalVector<Subpass> subpasses;718uint32_t view_count = 0;719uint32_t max_supported_sample_count = 0;720};721722public:723virtual 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;724virtual void render_pass_free(RenderPassID p_render_pass) override final;725726// ----- COMMANDS -----727728virtual 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;729730private:731void _end_render_pass(CommandBufferID p_cmd_buffer);732733public:734virtual void command_end_render_pass(CommandBufferID p_cmd_buffer) override final;735virtual void command_next_render_subpass(CommandBufferID p_cmd_buffer, CommandBufferType p_cmd_buffer_type) override final;736virtual void command_render_set_viewport(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_viewports) override final;737virtual void command_render_set_scissor(CommandBufferID p_cmd_buffer, VectorView<Rect2i> p_scissors) override final;738739virtual void command_render_clear_attachments(CommandBufferID p_cmd_buffer, VectorView<AttachmentClear> p_attachment_clears, VectorView<Rect2i> p_rects) override final;740741// Binding.742virtual void command_bind_render_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) override final;743virtual void command_bind_render_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) override final;744virtual 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;745746// Drawing.747virtual 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;748virtual 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;749virtual 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;750virtual 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;751virtual 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;752virtual 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;753754// Buffer binding.755virtual 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;756virtual void command_render_bind_index_buffer(CommandBufferID p_cmd_buffer, BufferID p_buffer, IndexBufferFormat p_format, uint64_t p_offset) override final;757758private:759void _bind_vertex_buffers(CommandBufferInfo *p_cmd_buf_info);760761public:762// Dynamic state.763virtual void command_render_set_blend_constants(CommandBufferID p_cmd_buffer, const Color &p_constants) override final;764virtual void command_render_set_line_width(CommandBufferID p_cmd_buffer, float p_width) override final;765766// ----- PIPELINE -----767768public:769virtual PipelineID render_pipeline_create(770ShaderID p_shader,771VertexFormatID p_vertex_format,772RenderPrimitive p_render_primitive,773PipelineRasterizationState p_rasterization_state,774PipelineMultisampleState p_multisample_state,775PipelineDepthStencilState p_depth_stencil_state,776PipelineColorBlendState p_blend_state,777VectorView<int32_t> p_color_attachments,778BitField<PipelineDynamicStateFlags> p_dynamic_state,779RenderPassID p_render_pass,780uint32_t p_render_subpass,781VectorView<PipelineSpecializationConstant> p_specialization_constants) override final;782783/*****************/784/**** COMPUTE ****/785/*****************/786787// ----- COMMANDS -----788789// Binding.790virtual void command_bind_compute_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) override final;791virtual void command_bind_compute_uniform_set(CommandBufferID p_cmd_buffer, UniformSetID p_uniform_set, ShaderID p_shader, uint32_t p_set_index) override final;792virtual 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;793794// Dispatching.795virtual 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;796virtual void command_compute_dispatch_indirect(CommandBufferID p_cmd_buffer, BufferID p_indirect_buffer, uint64_t p_offset) override final;797798// ----- PIPELINE -----799800virtual PipelineID compute_pipeline_create(ShaderID p_shader, VectorView<PipelineSpecializationConstant> p_specialization_constants) override final;801802/*****************/803/**** QUERIES ****/804/*****************/805806// ----- TIMESTAMP -----807808private:809struct TimestampQueryPoolInfo {810ComPtr<ID3D12QueryHeap> query_heap;811uint32_t query_count = 0;812ComPtr<D3D12MA::Allocation> results_buffer_allocation;813};814815public:816// Basic.817virtual QueryPoolID timestamp_query_pool_create(uint32_t p_query_count) override final;818virtual void timestamp_query_pool_free(QueryPoolID p_pool_id) override final;819virtual void timestamp_query_pool_get_results(QueryPoolID p_pool_id, uint32_t p_query_count, uint64_t *r_results) override final;820virtual uint64_t timestamp_query_result_to_time(uint64_t p_result) override final;821822// Commands.823virtual void command_timestamp_query_pool_reset(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_query_count) override final;824virtual void command_timestamp_write(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_index) override final;825826/****************/827/**** LABELS ****/828/****************/829830virtual void command_begin_label(CommandBufferID p_cmd_buffer, const char *p_label_name, const Color &p_color) override final;831virtual void command_end_label(CommandBufferID p_cmd_buffer) override final;832833/****************/834/**** DEBUG *****/835/****************/836virtual void command_insert_breadcrumb(CommandBufferID p_cmd_buffer, uint32_t p_data) override final;837838/********************/839/**** SUBMISSION ****/840/********************/841private:842struct FrameInfo {843struct {844DescriptorsHeap resources;845DescriptorsHeap samplers;846DescriptorsHeap aux;847DescriptorsHeap rtv;848} desc_heaps;849struct {850DescriptorsHeap::Walker resources;851DescriptorsHeap::Walker samplers;852DescriptorsHeap::Walker aux;853DescriptorsHeap::Walker rtv;854} desc_heap_walkers;855struct {856bool resources = false;857bool samplers = false;858bool aux = false;859bool rtv = false;860} desc_heaps_exhausted_reported;861CD3DX12_CPU_DESCRIPTOR_HANDLE null_rtv_handle = {}; // For [[MANUAL_SUBPASSES]].862uint32_t segment_serial = 0;863864#ifdef DEV_ENABLED865uint32_t uniform_set_reused = 0;866#endif867};868TightLocalVector<FrameInfo> frames;869uint32_t frame_idx = 0;870uint32_t frames_drawn = 0;871uint32_t segment_serial = 0;872bool segment_begun = false;873HashMap<uint64_t, bool> has_comp_alpha;874875public:876virtual void begin_segment(uint32_t p_frame_index, uint32_t p_frames_drawn) override final;877virtual void end_segment() override final;878879/**************/880/**** MISC ****/881/**************/882883virtual void set_object_name(ObjectType p_type, ID p_driver_id, const String &p_name) override final;884virtual uint64_t get_resource_native_handle(DriverResource p_type, ID p_driver_id) override final;885virtual uint64_t get_total_memory_used() override final;886virtual uint64_t get_lazily_memory_used() override final;887virtual uint64_t limit_get(Limit p_limit) override final;888virtual uint64_t api_trait_get(ApiTrait p_trait) override final;889virtual bool has_feature(Features p_feature) override final;890virtual const MultiviewCapabilities &get_multiview_capabilities() override final;891virtual const FragmentShadingRateCapabilities &get_fragment_shading_rate_capabilities() override final;892virtual const FragmentDensityMapCapabilities &get_fragment_density_map_capabilities() override final;893virtual String get_api_name() const override final;894virtual String get_api_version() const override final;895virtual String get_pipeline_cache_uuid() const override final;896virtual const Capabilities &get_capabilities() const override final;897virtual const RenderingShaderContainerFormat &get_shader_container_format() const override final;898899virtual bool is_composite_alpha_supported(CommandQueueID p_queue) const override final;900901static bool is_in_developer_mode();902903private:904/*********************/905/**** BOOKKEEPING ****/906/*********************/907908using VersatileResource = VersatileResourceTemplate<909BufferInfo,910TextureInfo,911TextureInfo,912TextureInfo,913VertexFormatInfo,914CommandBufferInfo,915FramebufferInfo,916ShaderInfo,917UniformSetInfo,918RenderPassInfo,919TimestampQueryPoolInfo>;920PagedAllocator<VersatileResource, true> resources_allocator;921922/******************/923924public:925RenderingDeviceDriverD3D12(RenderingContextDriverD3D12 *p_context_driver);926virtual ~RenderingDeviceDriverD3D12();927};928929930