Path: blob/master/drivers/d3d12/rendering_shader_container_d3d12.cpp
21076 views
/**************************************************************************/1/* rendering_shader_container_d3d12.cpp */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#include "rendering_shader_container_d3d12.h"3132#include "core/templates/sort_array.h"3334#include "dxil_hash.h"3536#include <zlib.h>3738GODOT_GCC_WARNING_PUSH39GODOT_GCC_WARNING_IGNORE("-Wimplicit-fallthrough")40GODOT_GCC_WARNING_IGNORE("-Wlogical-not-parentheses")41GODOT_GCC_WARNING_IGNORE("-Wmissing-field-initializers")42GODOT_GCC_WARNING_IGNORE("-Wnon-virtual-dtor")43GODOT_GCC_WARNING_IGNORE("-Wshadow")44GODOT_GCC_WARNING_IGNORE("-Wswitch")45GODOT_CLANG_WARNING_PUSH46GODOT_CLANG_WARNING_IGNORE("-Wimplicit-fallthrough")47GODOT_CLANG_WARNING_IGNORE("-Wlogical-not-parentheses")48GODOT_CLANG_WARNING_IGNORE("-Wmissing-field-initializers")49GODOT_CLANG_WARNING_IGNORE("-Wnon-virtual-dtor")50GODOT_CLANG_WARNING_IGNORE("-Wstring-plus-int")51GODOT_CLANG_WARNING_IGNORE("-Wswitch")52GODOT_MSVC_WARNING_PUSH53GODOT_MSVC_WARNING_IGNORE(4200) // "nonstandard extension used: zero-sized array in struct/union".54GODOT_MSVC_WARNING_IGNORE(4806) // "'&': unsafe operation: no value of type 'bool' promoted to type 'uint32_t' can equal the given constant".5556#include <dxgi1_6.h>57#include <thirdparty/directx_headers/include/directx/d3dx12.h>58#define D3D12MA_D3D12_HEADERS_ALREADY_INCLUDED59#include <thirdparty/d3d12ma/D3D12MemAlloc.h>6061#include <wrl/client.h>6263#include <nir_spirv.h>64#include <nir_to_dxil.h>65#include <spirv_to_dxil.h>66extern "C" {67#include <dxil_spirv_nir.h>6869void dxil_reassign_driver_locations(nir_shader *s, nir_variable_mode modes,70uint64_t other_stage_mask, const BITSET_WORD *other_stage_frac_mask);71}7273GODOT_GCC_WARNING_POP74GODOT_CLANG_WARNING_POP75GODOT_MSVC_WARNING_POP7677// SPIR-V to DXIL does way too many allocations, which causes worker threads78// to bottleneck each other due to sharing the same global process heap.79// This can be solved by making each thread allocate from its own heap.80#define SPIRV_TO_DXIL_ENABLE_HEAP_PER_THREAD8182#ifdef SPIRV_TO_DXIL_ENABLE_HEAP_PER_THREAD8384namespace {85struct Win32Heap {86HANDLE handle;87SafeRefCount ref_count;8889Win32Heap() {90handle = HeapCreate(0, 0, 0);91ref_count.init();92}9394~Win32Heap() {95HeapDestroy(handle);96}97};9899constexpr size_t ALLOC_HEADER_SIZE = sizeof(Win32Heap *) * 2;100} //namespace101102extern "C" {103void *godot_nir_malloc(size_t p_size) {104// This RAII helper is for allowing the heap to be destroyed when the thread quits.105struct Win32HeapHolder {106Win32Heap *win32_heap = nullptr;107108Win32HeapHolder() {109win32_heap = memnew(Win32Heap);110}111112~Win32HeapHolder() {113if (win32_heap->ref_count.unref()) {114memdelete(win32_heap);115}116}117};118119thread_local Win32HeapHolder holder;120121void *block = HeapAlloc(holder.win32_heap->handle, 0, p_size + ALLOC_HEADER_SIZE);122123// Store the heap in the allocation for the realloc/free operations.124*(Win32Heap **)block = holder.win32_heap;125holder.win32_heap->ref_count.ref();126127return (uint8_t *)block + ALLOC_HEADER_SIZE;128}129130void *godot_nir_realloc(void *p_block, size_t p_size) {131uint8_t *actual_block = (uint8_t *)p_block - ALLOC_HEADER_SIZE;132Win32Heap *win32_heap = *(Win32Heap **)actual_block;133return (uint8_t *)HeapReAlloc(win32_heap->handle, 0, actual_block, p_size + ALLOC_HEADER_SIZE) + ALLOC_HEADER_SIZE;134}135136void godot_nir_free(void *p_block) {137if (p_block != nullptr) {138uint8_t *actual_block = (uint8_t *)p_block - ALLOC_HEADER_SIZE;139Win32Heap *win32_heap = *(Win32Heap **)actual_block;140HeapFree(win32_heap->handle, 0, actual_block);141142// Allocations can outlive the threads they were created in if they were stored globally.143if (win32_heap->ref_count.unref()) {144memdelete(win32_heap);145}146}147}148}149150#else151152extern "C" {153void *godot_nir_malloc(size_t p_size) {154return malloc(p_size);155}156157void *godot_nir_realloc(void *p_block, size_t p_size) {158return realloc(p_block, p_size);159}160161void godot_nir_free(void *p_block) {162return free(p_block);163}164}165166#endif167168static D3D12_SHADER_VISIBILITY stages_to_d3d12_visibility(uint32_t p_stages_mask) {169switch (p_stages_mask) {170case RenderingDeviceCommons::SHADER_STAGE_VERTEX_BIT:171return D3D12_SHADER_VISIBILITY_VERTEX;172case RenderingDeviceCommons::SHADER_STAGE_FRAGMENT_BIT:173return D3D12_SHADER_VISIBILITY_PIXEL;174default:175return D3D12_SHADER_VISIBILITY_ALL;176}177}178179uint32_t RenderingDXIL::patch_specialization_constant(180RenderingDeviceCommons::PipelineSpecializationConstantType p_type,181const void *p_value,182const uint64_t (&p_stages_bit_offsets)[D3D12_BITCODE_OFFSETS_NUM_STAGES],183HashMap<RenderingDeviceCommons::ShaderStage, Vector<uint8_t>> &r_stages_bytecodes,184bool p_is_first_patch) {185int64_t patch_val = 0;186switch (p_type) {187case RenderingDeviceCommons::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_INT: {188patch_val = *((const int32_t *)p_value);189} break;190case RenderingDeviceCommons::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL: {191bool bool_value = *((const bool *)p_value);192patch_val = (int32_t)bool_value;193} break;194case RenderingDeviceCommons::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_FLOAT: {195patch_val = *((const int32_t *)p_value);196} break;197}198199// Encode to signed VBR.200if (patch_val >= 0) {201patch_val <<= 1;202} else {203patch_val = ((-patch_val) << 1) | 1;204}205206auto tamper_bits = [](uint8_t *p_start, uint64_t p_bit_offset, uint64_t p_tb_value) -> uint64_t {207uint64_t original = 0;208uint32_t curr_input_byte = p_bit_offset / 8;209uint8_t curr_input_bit = p_bit_offset % 8;210auto get_curr_input_bit = [&]() -> bool {211return ((p_start[curr_input_byte] >> curr_input_bit) & 1);212};213auto move_to_next_input_bit = [&]() {214if (curr_input_bit == 7) {215curr_input_bit = 0;216curr_input_byte++;217} else {218curr_input_bit++;219}220};221auto tamper_input_bit = [&](bool p_new_bit) {222p_start[curr_input_byte] &= ~((uint8_t)1 << curr_input_bit);223if (p_new_bit) {224p_start[curr_input_byte] |= (uint8_t)1 << curr_input_bit;225}226};227uint8_t value_bit_idx = 0;228for (uint32_t i = 0; i < 5; i++) { // 32 bits take 5 full bytes in VBR.229for (uint32_t j = 0; j < 7; j++) {230bool input_bit = get_curr_input_bit();231original |= (uint64_t)(input_bit ? 1 : 0) << value_bit_idx;232tamper_input_bit((p_tb_value >> value_bit_idx) & 1);233move_to_next_input_bit();234value_bit_idx++;235}236#ifdef DEV_ENABLED237bool input_bit = get_curr_input_bit();238DEV_ASSERT((i < 4 && input_bit) || (i == 4 && !input_bit));239#endif240move_to_next_input_bit();241}242return original;243};244uint32_t stages_patched_mask = 0;245for (int stage = 0; stage < RenderingDeviceCommons::SHADER_STAGE_MAX; stage++) {246if (!r_stages_bytecodes.has((RenderingDeviceCommons::ShaderStage)stage)) {247continue;248}249250uint64_t offset = p_stages_bit_offsets[RenderingShaderContainerD3D12::SHADER_STAGES_BIT_OFFSET_INDICES[stage]];251if (offset == 0) {252// This constant does not appear at this stage.253continue;254}255256Vector<uint8_t> &bytecode = r_stages_bytecodes[(RenderingDeviceCommons::ShaderStage)stage];257#ifdef DEV_ENABLED258uint64_t orig_patch_val = tamper_bits(bytecode.ptrw(), offset, (uint64_t)patch_val);259// Checking against the value the NIR patch should have set.260DEV_ASSERT(!p_is_first_patch || ((orig_patch_val >> 1) & GODOT_NIR_SC_SENTINEL_MAGIC_MASK) == GODOT_NIR_SC_SENTINEL_MAGIC);261uint64_t readback_patch_val = tamper_bits(bytecode.ptrw(), offset, (uint64_t)patch_val);262DEV_ASSERT(readback_patch_val == (uint64_t)patch_val);263#else264tamper_bits(bytecode.ptrw(), offset, (uint64_t)patch_val);265#endif266267stages_patched_mask |= (1 << stage);268}269270return stages_patched_mask;271}272273void RenderingDXIL::sign_bytecode(RenderingDeviceCommons::ShaderStage p_stage, Vector<uint8_t> &r_dxil_blob) {274uint8_t *w = r_dxil_blob.ptrw();275compute_dxil_hash(w + 20, r_dxil_blob.size() - 20, w + 4);276}277278// RenderingShaderContainerD3D12279280uint32_t RenderingShaderContainerD3D12::_format() const {281return 0x43443344;282}283284uint32_t RenderingShaderContainerD3D12::_format_version() const {285return FORMAT_VERSION;286}287288uint32_t RenderingShaderContainerD3D12::_from_bytes_reflection_extra_data(const uint8_t *p_bytes) {289reflection_data_d3d12 = *(const ReflectionDataD3D12 *)(p_bytes);290reflection_binding_set_data_d3d12.resize(reflection_data.set_count);291for (uint32_t i = 0; i < reflection_binding_set_data_d3d12.size(); i++) {292reflection_binding_set_data_d3d12.ptrw()[i] = *(const ReflectionBindingSetDataD3D12 *)(p_bytes + sizeof(ReflectionDataD3D12) + (i * sizeof(ReflectionBindingSetDataD3D12)));293}294return sizeof(ReflectionDataD3D12) + (reflection_binding_set_data_d3d12.size() * sizeof(ReflectionBindingSetDataD3D12));295}296297uint32_t RenderingShaderContainerD3D12::_from_bytes_reflection_binding_uniform_extra_data_start(const uint8_t *p_bytes) {298reflection_binding_set_uniforms_data_d3d12.resize(reflection_binding_set_uniforms_data.size());299return 0;300}301302uint32_t RenderingShaderContainerD3D12::_from_bytes_reflection_binding_uniform_extra_data(const uint8_t *p_bytes, uint32_t p_index) {303reflection_binding_set_uniforms_data_d3d12.ptrw()[p_index] = *(const ReflectionBindingDataD3D12 *)(p_bytes);304return sizeof(ReflectionBindingDataD3D12);305}306307uint32_t RenderingShaderContainerD3D12::_from_bytes_reflection_specialization_extra_data_start(const uint8_t *p_bytes) {308reflection_specialization_data_d3d12.resize(reflection_specialization_data.size());309return 0;310}311312uint32_t RenderingShaderContainerD3D12::_from_bytes_reflection_specialization_extra_data(const uint8_t *p_bytes, uint32_t p_index) {313reflection_specialization_data_d3d12.ptrw()[p_index] = *(const ReflectionSpecializationDataD3D12 *)(p_bytes);314return sizeof(ReflectionSpecializationDataD3D12);315}316317uint32_t RenderingShaderContainerD3D12::_from_bytes_footer_extra_data(const uint8_t *p_bytes) {318ContainerFooterD3D12 footer = *(const ContainerFooterD3D12 *)(p_bytes);319root_signature_crc = footer.root_signature_crc;320root_signature_bytes.resize(footer.root_signature_length);321memcpy(root_signature_bytes.ptrw(), p_bytes + sizeof(ContainerFooterD3D12), root_signature_bytes.size());322return sizeof(ContainerFooterD3D12) + footer.root_signature_length;323}324325uint32_t RenderingShaderContainerD3D12::_to_bytes_reflection_extra_data(uint8_t *p_bytes) const {326if (p_bytes != nullptr) {327*(ReflectionDataD3D12 *)(p_bytes) = reflection_data_d3d12;328for (uint32_t i = 0; i < reflection_binding_set_data_d3d12.size(); i++) {329*(ReflectionBindingSetDataD3D12 *)(p_bytes + sizeof(ReflectionDataD3D12) + (i * sizeof(ReflectionBindingSetDataD3D12))) = reflection_binding_set_data_d3d12[i];330}331}332333return sizeof(ReflectionDataD3D12) + (reflection_binding_set_data_d3d12.size() * sizeof(ReflectionBindingSetDataD3D12));334}335336uint32_t RenderingShaderContainerD3D12::_to_bytes_reflection_binding_uniform_extra_data(uint8_t *p_bytes, uint32_t p_index) const {337if (p_bytes != nullptr) {338*(ReflectionBindingDataD3D12 *)(p_bytes) = reflection_binding_set_uniforms_data_d3d12[p_index];339}340341return sizeof(ReflectionBindingDataD3D12);342}343344uint32_t RenderingShaderContainerD3D12::_to_bytes_reflection_specialization_extra_data(uint8_t *p_bytes, uint32_t p_index) const {345if (p_bytes != nullptr) {346*(ReflectionSpecializationDataD3D12 *)(p_bytes) = reflection_specialization_data_d3d12[p_index];347}348349return sizeof(ReflectionSpecializationDataD3D12);350}351352uint32_t RenderingShaderContainerD3D12::_to_bytes_footer_extra_data(uint8_t *p_bytes) const {353if (p_bytes != nullptr) {354ContainerFooterD3D12 &footer = *(ContainerFooterD3D12 *)(p_bytes);355footer.root_signature_length = root_signature_bytes.size();356footer.root_signature_crc = root_signature_crc;357memcpy(p_bytes + sizeof(ContainerFooterD3D12), root_signature_bytes.ptr(), root_signature_bytes.size());358}359360return sizeof(ContainerFooterD3D12) + root_signature_bytes.size();361}362363#if NIR_ENABLED364bool RenderingShaderContainerD3D12::_convert_spirv_to_nir(Span<ReflectShaderStage> p_spirv, const nir_shader_compiler_options *p_compiler_options, HashMap<int, nir_shader *> &r_stages_nir_shaders, Vector<RenderingDeviceCommons::ShaderStage> &r_stages, BitField<RenderingDeviceCommons::ShaderStage> &r_stages_processed) {365r_stages_processed.clear();366367dxil_spirv_runtime_conf dxil_runtime_conf = {};368dxil_runtime_conf.runtime_data_cbv.base_shader_register = RUNTIME_DATA_REGISTER;369dxil_runtime_conf.push_constant_cbv.base_shader_register = ROOT_CONSTANT_REGISTER;370dxil_runtime_conf.first_vertex_and_base_instance_mode = DXIL_SPIRV_SYSVAL_TYPE_ZERO;371dxil_runtime_conf.workgroup_id_mode = DXIL_SPIRV_SYSVAL_TYPE_ZERO;372373// Explicitly keeping these false because converting UAV descriptors to SRVs do not seem to have real performance benefits on desktop GPUs.374// It also makes it easier to implement descriptor heaps and enhanced barriers.375dxil_runtime_conf.declared_read_only_images_as_srvs = false;376dxil_runtime_conf.inferred_read_only_images_as_srvs = false;377378// Translate SPIR-V to NIR.379for (uint64_t i = 0; i < p_spirv.size(); i++) {380RenderingDeviceCommons::ShaderStage stage = p_spirv[i].shader_stage;381RenderingDeviceCommons::ShaderStage stage_flag = (RenderingDeviceCommons::ShaderStage)(1 << stage);382r_stages.push_back(stage);383r_stages_processed.set_flag(stage_flag);384385const char *entry_point = "main";386static const mesa_shader_stage SPIRV_TO_MESA_STAGES[RenderingDeviceCommons::SHADER_STAGE_MAX] = {387MESA_SHADER_VERTEX, // SHADER_STAGE_VERTEX388MESA_SHADER_FRAGMENT, // SHADER_STAGE_FRAGMENT389MESA_SHADER_TESS_CTRL, // SHADER_STAGE_TESSELATION_CONTROL390MESA_SHADER_TESS_EVAL, // SHADER_STAGE_TESSELATION_EVALUATION391MESA_SHADER_COMPUTE, // SHADER_STAGE_COMPUTE392};393394Span<uint32_t> code = p_spirv[i].spirv();395nir_shader *shader = spirv_to_nir(396code.ptr(),397code.size(),398nullptr,3990,400SPIRV_TO_MESA_STAGES[stage],401entry_point,402dxil_spirv_nir_get_spirv_options(),403p_compiler_options);404405ERR_FAIL_NULL_V_MSG(shader, false, "Shader translation (step 1) at stage " + String(RenderingDeviceCommons::SHADER_STAGE_NAMES[stage]) + " failed.");406407if (stage == RenderingDeviceCommons::SHADER_STAGE_VERTEX) {408dxil_runtime_conf.yz_flip.y_mask = 0xffff;409dxil_runtime_conf.yz_flip.mode = DXIL_SPIRV_Y_FLIP_UNCONDITIONAL;410} else {411dxil_runtime_conf.yz_flip.y_mask = 0;412dxil_runtime_conf.yz_flip.mode = DXIL_SPIRV_YZ_FLIP_NONE;413}414415dxil_spirv_nir_prep(shader);416dxil_spirv_metadata dxil_metadata = {};417dxil_spirv_nir_passes(shader, &dxil_runtime_conf, &dxil_metadata);418419r_stages_nir_shaders[stage] = shader;420}421422// Link NIR shaders.423for (int i = RenderingDeviceCommons::SHADER_STAGE_MAX - 1; i >= 0; i--) {424if (!r_stages_nir_shaders.has(i)) {425continue;426}427nir_shader *shader = r_stages_nir_shaders[i];428nir_shader *prev_shader = nullptr;429for (int j = i - 1; j >= 0; j--) {430if (r_stages_nir_shaders.has(j)) {431prev_shader = r_stages_nir_shaders[j];432break;433}434}435if (prev_shader) {436dxil_spirv_metadata dxil_metadata = {};437dxil_spirv_nir_link(shader, prev_shader, &dxil_runtime_conf, &dxil_metadata);438}439// There is a bug in the Direct3D runtime during creation of a PSO with view instancing. If a fragment440// shader uses front/back face detection (SV_IsFrontFace), its signature must include the pixel position441// builtin variable (SV_Position), otherwise an Internal Runtime error will occur.442if (i == RenderingDeviceCommons::SHADER_STAGE_FRAGMENT) {443const bool use_front_face =444nir_find_variable_with_location(shader, nir_var_shader_in, VARYING_SLOT_FACE) ||445(shader->info.inputs_read & VARYING_BIT_FACE) ||446nir_find_variable_with_location(shader, nir_var_system_value, SYSTEM_VALUE_FRONT_FACE) ||447BITSET_TEST(shader->info.system_values_read, SYSTEM_VALUE_FRONT_FACE);448const bool use_position =449nir_find_variable_with_location(shader, nir_var_shader_in, VARYING_SLOT_POS) ||450(shader->info.inputs_read & VARYING_BIT_POS) ||451nir_find_variable_with_location(shader, nir_var_system_value, SYSTEM_VALUE_FRAG_COORD) ||452BITSET_TEST(shader->info.system_values_read, SYSTEM_VALUE_FRAG_COORD);453if (use_front_face && !use_position) {454nir_variable *const pos = nir_variable_create(shader, nir_var_shader_in, glsl_vec4_type(), "gl_FragCoord");455pos->data.location = VARYING_SLOT_POS;456shader->info.inputs_read |= VARYING_BIT_POS;457458if (prev_shader) {459dxil_reassign_driver_locations(shader, nir_var_shader_in, prev_shader->info.outputs_written, NULL);460dxil_reassign_driver_locations(prev_shader, nir_var_shader_out, shader->info.inputs_read, NULL);461}462}463}464}465466return true;467}468469struct GodotNirCallbackUserData {470RenderingShaderContainerD3D12 *container;471RenderingDeviceCommons::ShaderStage stage;472};473474static dxil_shader_model shader_model_d3d_to_dxil(D3D_SHADER_MODEL p_d3d_shader_model) {475static_assert(SHADER_MODEL_6_0 == 0x60000);476static_assert(SHADER_MODEL_6_3 == 0x60003);477static_assert(D3D_SHADER_MODEL_6_0 == 0x60);478static_assert(D3D_SHADER_MODEL_6_3 == 0x63);479return (dxil_shader_model)((p_d3d_shader_model >> 4) * 0x10000 + (p_d3d_shader_model & 0xf));480}481482bool RenderingShaderContainerD3D12::_convert_nir_to_dxil(const HashMap<int, nir_shader *> &p_stages_nir_shaders, BitField<RenderingDeviceCommons::ShaderStage> p_stages_processed, HashMap<RenderingDeviceCommons::ShaderStage, Vector<uint8_t>> &r_dxil_blobs) {483// Translate NIR to DXIL.484for (KeyValue<int, nir_shader *> it : p_stages_nir_shaders) {485RenderingDeviceCommons::ShaderStage stage = (RenderingDeviceCommons::ShaderStage)(it.key);486GodotNirCallbackUserData godot_nir_callback_user_data;487godot_nir_callback_user_data.container = this;488godot_nir_callback_user_data.stage = stage;489490GodotNirCallbacks godot_nir_callbacks = {};491godot_nir_callbacks.data = &godot_nir_callback_user_data;492godot_nir_callbacks.report_resource = _nir_report_resource;493godot_nir_callbacks.report_sc_bit_offset_fn = _nir_report_sc_bit_offset;494godot_nir_callbacks.report_bitcode_bit_offset_fn = _nir_report_bitcode_bit_offset;495496nir_to_dxil_options nir_to_dxil_options = {};497nir_to_dxil_options.environment = DXIL_ENVIRONMENT_VULKAN;498nir_to_dxil_options.shader_model_max = shader_model_d3d_to_dxil(D3D_SHADER_MODEL(REQUIRED_SHADER_MODEL));499nir_to_dxil_options.validator_version_max = NO_DXIL_VALIDATION;500nir_to_dxil_options.godot_nir_callbacks = &godot_nir_callbacks;501502dxil_logger logger = {};503logger.log = [](void *p_priv, const char *p_msg) {504#ifdef DEBUG_ENABLED505print_verbose(p_msg);506#endif507};508509blob dxil_blob = {};510bool ok = nir_to_dxil(it.value, &nir_to_dxil_options, &logger, &dxil_blob);511ERR_FAIL_COND_V_MSG(!ok, false, "Shader translation at stage " + String(RenderingDeviceCommons::SHADER_STAGE_NAMES[stage]) + " failed.");512513Vector<uint8_t> blob_copy;514blob_copy.resize(dxil_blob.size);515memcpy(blob_copy.ptrw(), dxil_blob.data, dxil_blob.size);516blob_finish(&dxil_blob);517r_dxil_blobs.insert(stage, blob_copy);518}519520return true;521}522523bool RenderingShaderContainerD3D12::_convert_spirv_to_dxil(Span<ReflectShaderStage> p_spirv, HashMap<RenderingDeviceCommons::ShaderStage, Vector<uint8_t>> &r_dxil_blobs, Vector<RenderingDeviceCommons::ShaderStage> &r_stages, BitField<RenderingDeviceCommons::ShaderStage> &r_stages_processed) {524r_dxil_blobs.clear();525526HashMap<int, nir_shader *> stages_nir_shaders;527auto free_nir_shaders = [&]() {528for (KeyValue<int, nir_shader *> &E : stages_nir_shaders) {529ralloc_free(E.value);530}531stages_nir_shaders.clear();532};533534// This structure must live as long as the shaders are alive.535nir_shader_compiler_options compiler_options = {};536const unsigned supported_bit_sizes = 16 | 32 | 64;537dxil_get_nir_compiler_options(&compiler_options, shader_model_d3d_to_dxil(D3D_SHADER_MODEL(REQUIRED_SHADER_MODEL)), supported_bit_sizes, supported_bit_sizes);538compiler_options.lower_base_vertex = false;539540// This is based on spirv2dxil.c. May need updates when it changes.541// Also, this has to stay around until after linking.542if (!_convert_spirv_to_nir(p_spirv, &compiler_options, stages_nir_shaders, r_stages, r_stages_processed)) {543free_nir_shaders();544return false;545}546547if (!_convert_nir_to_dxil(stages_nir_shaders, r_stages_processed, r_dxil_blobs)) {548free_nir_shaders();549return false;550}551552free_nir_shaders();553return true;554}555556bool RenderingShaderContainerD3D12::_generate_root_signature(BitField<RenderingDeviceCommons::ShaderStage> p_stages_processed) {557// Root (push) constants.558LocalVector<D3D12_ROOT_PARAMETER1> root_params;559if (reflection_data_d3d12.dxil_push_constant_stages) {560CD3DX12_ROOT_PARAMETER1 push_constant;561push_constant.InitAsConstants(562reflection_data.push_constant_size / sizeof(uint32_t),563ROOT_CONSTANT_REGISTER,5640,565stages_to_d3d12_visibility(reflection_data_d3d12.dxil_push_constant_stages));566567root_params.push_back(push_constant);568}569570// NIR-DXIL runtime data.571if (reflection_data_d3d12.nir_runtime_data_root_param_idx == 1) { // Set above to 1 when discovering runtime data is needed.572DEV_ASSERT(reflection_data.pipeline_type != RDC::PIPELINE_TYPE_COMPUTE); // Could be supported if needed, but it's pointless as of now.573reflection_data_d3d12.nir_runtime_data_root_param_idx = root_params.size();574CD3DX12_ROOT_PARAMETER1 nir_runtime_data;575nir_runtime_data.InitAsConstants(576sizeof(dxil_spirv_vertex_runtime_data) / sizeof(uint32_t),577RUNTIME_DATA_REGISTER,5780,579D3D12_SHADER_VISIBILITY_VERTEX);580root_params.push_back(nir_runtime_data);581}582583// Descriptor tables (up to two per uniform set, for resources and/or samplers).584// These have to stay around until serialization!585struct TraceableDescriptorTable {586uint32_t stages_mask = {};587Vector<D3D12_DESCRIPTOR_RANGE1> ranges;588uint32_t set = UINT_MAX;589};590591uint32_t binding_start = 0;592Vector<TraceableDescriptorTable> resource_tables_maps;593Vector<TraceableDescriptorTable> sampler_tables_maps;594for (uint32_t i = 0; i < reflection_binding_set_uniforms_count.size(); i++) {595bool first_resource_in_set = true;596bool first_sampler_in_set = true;597uint32_t uniform_count = reflection_binding_set_uniforms_count[i];598for (uint32_t j = 0; j < uniform_count; j++) {599const ReflectionBindingData &uniform = reflection_binding_set_uniforms_data[binding_start + j];600ReflectionBindingDataD3D12 &uniform_d3d12 = reflection_binding_set_uniforms_data_d3d12.ptrw()[binding_start + j];601#ifdef DEV_ENABLED602bool really_used = uniform_d3d12.dxil_stages != 0;603bool anybody_home = (ResourceClass)(uniform_d3d12.resource_class) != RES_CLASS_INVALID || uniform_d3d12.has_sampler;604DEV_ASSERT(anybody_home == really_used);605#endif606607auto insert_range = [i](D3D12_DESCRIPTOR_RANGE_TYPE p_range_type,608uint32_t p_num_descriptors,609uint32_t p_dxil_register,610uint32_t p_dxil_stages_mask,611uint32_t &r_descriptor_offset,612uint32_t &r_descriptor_count,613bool &r_first_in_set,614Vector<TraceableDescriptorTable> &r_tables) {615r_descriptor_offset = r_descriptor_count;616617if (r_first_in_set) {618r_tables.resize(r_tables.size() + 1);619r_first_in_set = false;620}621622TraceableDescriptorTable &table = r_tables.write[r_tables.size() - 1];623DEV_ASSERT(table.set == UINT_MAX || table.set == i);624625table.stages_mask |= p_dxil_stages_mask;626table.set = i;627628CD3DX12_DESCRIPTOR_RANGE1 range;629630// Due to the aliasing hack for SRV-UAV of different families,631// we can be causing an unintended change of data (sometimes the validation layers catch it).632D3D12_DESCRIPTOR_RANGE_FLAGS flags = D3D12_DESCRIPTOR_RANGE_FLAG_NONE;633if (p_range_type == D3D12_DESCRIPTOR_RANGE_TYPE_SRV || p_range_type == D3D12_DESCRIPTOR_RANGE_TYPE_UAV) {634flags = D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE;635} else if (p_range_type == D3D12_DESCRIPTOR_RANGE_TYPE_CBV) {636flags = D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC_WHILE_SET_AT_EXECUTE;637}638639range.Init(p_range_type, p_num_descriptors, p_dxil_register, 0, flags, r_descriptor_offset);640r_descriptor_count += p_num_descriptors;641table.ranges.push_back(range);642};643644D3D12_DESCRIPTOR_RANGE_TYPE range_type = (D3D12_DESCRIPTOR_RANGE_TYPE)UINT_MAX;645bool has_sampler = false;646uint32_t num_descriptors = 1;647648switch (uniform.type) {649case RDC::UNIFORM_TYPE_SAMPLER: {650has_sampler = true;651num_descriptors = uniform.length;652} break;653case RDC::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE: {654range_type = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;655has_sampler = true;656num_descriptors = MAX(1u, uniform.length);657} break;658case RDC::UNIFORM_TYPE_TEXTURE: {659range_type = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;660num_descriptors = MAX(1u, uniform.length);661} break;662case RDC::UNIFORM_TYPE_IMAGE: {663range_type = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;664num_descriptors = MAX(1u, uniform.length);665} break;666case RDC::UNIFORM_TYPE_TEXTURE_BUFFER: {667CRASH_NOW_MSG("Unimplemented!");668} break;669case RDC::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER: {670CRASH_NOW_MSG("Unimplemented!");671} break;672case RDC::UNIFORM_TYPE_IMAGE_BUFFER: {673CRASH_NOW_MSG("Unimplemented!");674} break;675case RDC::UNIFORM_TYPE_UNIFORM_BUFFER: {676range_type = D3D12_DESCRIPTOR_RANGE_TYPE_CBV;677} break;678case RDC::UNIFORM_TYPE_UNIFORM_BUFFER_DYNAMIC: {679range_type = D3D12_DESCRIPTOR_RANGE_TYPE_CBV;680} break;681case RDC::UNIFORM_TYPE_STORAGE_BUFFER: {682range_type = uniform.writable ? D3D12_DESCRIPTOR_RANGE_TYPE_UAV : D3D12_DESCRIPTOR_RANGE_TYPE_SRV;683} break;684case RDC::UNIFORM_TYPE_STORAGE_BUFFER_DYNAMIC: {685range_type = uniform.writable ? D3D12_DESCRIPTOR_RANGE_TYPE_UAV : D3D12_DESCRIPTOR_RANGE_TYPE_SRV;686} break;687case RDC::UNIFORM_TYPE_INPUT_ATTACHMENT: {688range_type = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;689} break;690default: {691DEV_ASSERT(false);692}693}694695uint32_t dxil_register = i * GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER + uniform.binding * GODOT_NIR_BINDING_MULTIPLIER;696if (range_type != (D3D12_DESCRIPTOR_RANGE_TYPE)UINT_MAX) {697// Dynamic buffers are converted to root descriptors to prevent copying descriptors during command recording.698// Out of bounds accesses are not a concern because that's already undefined behavior on Vulkan.699if (uniform.type == RDC::UNIFORM_TYPE_UNIFORM_BUFFER_DYNAMIC || uniform.type == RDC::UNIFORM_TYPE_STORAGE_BUFFER_DYNAMIC) {700CD3DX12_ROOT_PARAMETER1 root_param = {};701D3D12_SHADER_VISIBILITY visibility = stages_to_d3d12_visibility(uniform.stages);702703switch (range_type) {704case D3D12_DESCRIPTOR_RANGE_TYPE_CBV: {705root_param.InitAsConstantBufferView(dxil_register, 0, D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC_WHILE_SET_AT_EXECUTE, visibility);706} break;707case D3D12_DESCRIPTOR_RANGE_TYPE_SRV: {708root_param.InitAsShaderResourceView(dxil_register, 0, D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, visibility);709} break;710case D3D12_DESCRIPTOR_RANGE_TYPE_UAV: {711root_param.InitAsUnorderedAccessView(dxil_register, 0, D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, visibility);712} break;713default: {714DEV_ASSERT(false && "Unrecognized range type.");715} break;716}717718uniform_d3d12.root_param_idx = root_params.size();719root_params.push_back(root_param);720} else {721insert_range(722range_type,723num_descriptors,724dxil_register,725uniform.stages,726uniform_d3d12.resource_descriptor_offset,727reflection_binding_set_data_d3d12.ptrw()[i].resource_descriptor_count,728first_resource_in_set,729resource_tables_maps);730}731}732733if (has_sampler) {734insert_range(735D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER,736num_descriptors,737dxil_register,738uniform.stages,739uniform_d3d12.sampler_descriptor_offset,740reflection_binding_set_data_d3d12.ptrw()[i].sampler_descriptor_count,741first_sampler_in_set,742sampler_tables_maps);743}744}745746binding_start += uniform_count;747}748749for (const TraceableDescriptorTable &table : resource_tables_maps) {750CD3DX12_ROOT_PARAMETER1 root_table = {};751root_table.InitAsDescriptorTable(table.ranges.size(), table.ranges.ptr(), stages_to_d3d12_visibility(table.stages_mask));752reflection_binding_set_data_d3d12.ptrw()[table.set].resource_root_param_idx = root_params.size();753root_params.push_back(root_table);754}755756for (const TraceableDescriptorTable &table : sampler_tables_maps) {757CD3DX12_ROOT_PARAMETER1 root_table = {};758root_table.InitAsDescriptorTable(table.ranges.size(), table.ranges.ptr(), stages_to_d3d12_visibility(table.stages_mask));759reflection_binding_set_data_d3d12.ptrw()[table.set].sampler_root_param_idx = root_params.size();760root_params.push_back(root_table);761}762763CD3DX12_VERSIONED_ROOT_SIGNATURE_DESC root_sig_desc = {};764D3D12_ROOT_SIGNATURE_FLAGS root_sig_flags =765D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |766D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |767D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS;768769if (!p_stages_processed.has_flag(RenderingDeviceCommons::SHADER_STAGE_VERTEX_BIT)) {770root_sig_flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS;771}772773if (!p_stages_processed.has_flag(RenderingDeviceCommons::SHADER_STAGE_FRAGMENT_BIT)) {774root_sig_flags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS;775}776777if (reflection_data.vertex_input_mask) {778root_sig_flags |= D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;779}780781root_sig_desc.Init_1_1(root_params.size(), root_params.ptr(), 0, nullptr, root_sig_flags);782783// Create and store the root signature and its CRC32.784ID3DBlob *error_blob = nullptr;785ID3DBlob *root_sig_blob = nullptr;786HRESULT res = D3DX12SerializeVersionedRootSignature(HMODULE(lib_d3d12), &root_sig_desc, D3D_ROOT_SIGNATURE_VERSION_1_1, &root_sig_blob, &error_blob);787if (SUCCEEDED(res)) {788root_signature_bytes.resize(root_sig_blob->GetBufferSize());789memcpy(root_signature_bytes.ptrw(), root_sig_blob->GetBufferPointer(), root_sig_blob->GetBufferSize());790791root_signature_crc = crc32(0, nullptr, 0);792root_signature_crc = crc32(root_signature_crc, (const Bytef *)root_sig_blob->GetBufferPointer(), root_sig_blob->GetBufferSize());793794return true;795} else {796if (root_sig_blob != nullptr) {797root_sig_blob->Release();798}799800String error_string;801if (error_blob != nullptr) {802error_string = vformat("Serialization of root signature failed with error 0x%08ux and the following message:\n%s", uint32_t(res), String::ascii(Span((char *)error_blob->GetBufferPointer(), error_blob->GetBufferSize())));803error_blob->Release();804} else {805error_string = vformat("Serialization of root signature failed with error 0x%08ux", uint32_t(res));806}807808ERR_FAIL_V_MSG(false, error_string);809}810}811812void RenderingShaderContainerD3D12::_nir_report_resource(uint32_t p_register, uint32_t p_space, uint32_t p_dxil_type, void *p_data) {813const GodotNirCallbackUserData &user_data = *(GodotNirCallbackUserData *)p_data;814815// Types based on Mesa's dxil_container.h.816static const uint32_t DXIL_RES_SAMPLER = 1;817static const ResourceClass DXIL_TYPE_TO_CLASS[] = {818RES_CLASS_INVALID, // DXIL_RES_INVALID819RES_CLASS_INVALID, // DXIL_RES_SAMPLER820RES_CLASS_CBV, // DXIL_RES_CBV821RES_CLASS_SRV, // DXIL_RES_SRV_TYPED822RES_CLASS_SRV, // DXIL_RES_SRV_RAW823RES_CLASS_SRV, // DXIL_RES_SRV_STRUCTURED824RES_CLASS_UAV, // DXIL_RES_UAV_TYPED825RES_CLASS_UAV, // DXIL_RES_UAV_RAW826RES_CLASS_UAV, // DXIL_RES_UAV_STRUCTURED827RES_CLASS_INVALID, // DXIL_RES_UAV_STRUCTURED_WITH_COUNTER828};829830DEV_ASSERT(p_dxil_type < ARRAY_SIZE(DXIL_TYPE_TO_CLASS));831ResourceClass resource_class = DXIL_TYPE_TO_CLASS[p_dxil_type];832833if (p_register == ROOT_CONSTANT_REGISTER && p_space == 0) {834DEV_ASSERT(resource_class == RES_CLASS_CBV);835user_data.container->reflection_data_d3d12.dxil_push_constant_stages |= (1 << user_data.stage);836} else if (p_register == RUNTIME_DATA_REGISTER && p_space == 0) {837DEV_ASSERT(resource_class == RES_CLASS_CBV);838user_data.container->reflection_data_d3d12.nir_runtime_data_root_param_idx = 1; // Temporary, to be determined later.839} else {840DEV_ASSERT(p_space == 0);841842uint32_t set = p_register / GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER;843uint32_t binding = (p_register % GODOT_NIR_DESCRIPTOR_SET_MULTIPLIER) / GODOT_NIR_BINDING_MULTIPLIER;844845DEV_ASSERT(set < (uint32_t)user_data.container->reflection_binding_set_uniforms_count.size());846847uint32_t binding_start = 0;848for (uint32_t i = 0; i < set; i++) {849binding_start += user_data.container->reflection_binding_set_uniforms_count[i];850}851852[[maybe_unused]] bool found = false;853for (uint32_t i = 0; i < user_data.container->reflection_binding_set_uniforms_count[set]; i++) {854const ReflectionBindingData &uniform = user_data.container->reflection_binding_set_uniforms_data[binding_start + i];855ReflectionBindingDataD3D12 &uniform_d3d12 = user_data.container->reflection_binding_set_uniforms_data_d3d12.ptrw()[binding_start + i];856if (uniform.binding != binding) {857continue;858}859860uniform_d3d12.dxil_stages |= (1 << user_data.stage);861if (resource_class != RES_CLASS_INVALID) {862DEV_ASSERT(uniform_d3d12.resource_class == (uint32_t)RES_CLASS_INVALID || uniform_d3d12.resource_class == (uint32_t)resource_class);863uniform_d3d12.resource_class = resource_class;864} else if (p_dxil_type == DXIL_RES_SAMPLER) {865uniform_d3d12.has_sampler = (uint32_t)true;866} else {867DEV_ASSERT(false && "Unknown resource class.");868}869found = true;870}871872DEV_ASSERT(found);873}874}875876void RenderingShaderContainerD3D12::_nir_report_sc_bit_offset(uint32_t p_sc_id, uint64_t p_bit_offset, void *p_data) {877const GodotNirCallbackUserData &user_data = *(GodotNirCallbackUserData *)p_data;878[[maybe_unused]] bool found = false;879for (int64_t i = 0; i < user_data.container->reflection_specialization_data.size(); i++) {880const ReflectionSpecializationData &sc = user_data.container->reflection_specialization_data[i];881ReflectionSpecializationDataD3D12 &sc_d3d12 = user_data.container->reflection_specialization_data_d3d12.ptrw()[i];882if (sc.constant_id != p_sc_id) {883continue;884}885886uint32_t offset_idx = SHADER_STAGES_BIT_OFFSET_INDICES[user_data.stage];887DEV_ASSERT(sc_d3d12.stages_bit_offsets[offset_idx] == 0);888sc_d3d12.stages_bit_offsets[offset_idx] = p_bit_offset;889found = true;890break;891}892893DEV_ASSERT(found);894}895896void RenderingShaderContainerD3D12::_nir_report_bitcode_bit_offset(uint64_t p_bit_offset, void *p_data) {897DEV_ASSERT(p_bit_offset % 8 == 0);898899const GodotNirCallbackUserData &user_data = *(GodotNirCallbackUserData *)p_data;900uint32_t offset_idx = SHADER_STAGES_BIT_OFFSET_INDICES[user_data.stage];901for (int64_t i = 0; i < user_data.container->reflection_specialization_data.size(); i++) {902ReflectionSpecializationDataD3D12 &sc_d3d12 = user_data.container->reflection_specialization_data_d3d12.ptrw()[i];903if (sc_d3d12.stages_bit_offsets[offset_idx] == 0) {904// This SC has been optimized out from this stage.905continue;906}907908sc_d3d12.stages_bit_offsets[offset_idx] += p_bit_offset;909}910}911#endif912913void RenderingShaderContainerD3D12::_set_from_shader_reflection_post(const ReflectShader &p_shader) {914reflection_binding_set_data_d3d12.resize(reflection_binding_set_uniforms_count.size());915reflection_binding_set_uniforms_data_d3d12.resize(reflection_binding_set_uniforms_data.size());916reflection_specialization_data_d3d12.resize(reflection_specialization_data.size());917918// Sort bindings inside each uniform set. This guarantees the root signature will be generated in the correct order.919SortArray<ReflectionBindingData> sorter;920uint32_t binding_start = 0;921for (uint32_t i = 0; i < reflection_binding_set_uniforms_count.size(); i++) {922uint32_t uniform_count = reflection_binding_set_uniforms_count[i];923if (uniform_count > 0) {924sorter.sort(&reflection_binding_set_uniforms_data.ptrw()[binding_start], uniform_count);925binding_start += uniform_count;926}927}928}929930bool RenderingShaderContainerD3D12::_set_code_from_spirv(const ReflectShader &p_shader) {931#if NIR_ENABLED932const LocalVector<ReflectShaderStage> &p_spirv = p_shader.shader_stages;933reflection_data_d3d12.nir_runtime_data_root_param_idx = UINT32_MAX;934935for (int64_t i = 0; i < reflection_specialization_data.size(); i++) {936DEV_ASSERT(reflection_specialization_data[i].constant_id < (sizeof(reflection_data_d3d12.spirv_specialization_constants_ids_mask) * 8) && "Constant IDs with values above 31 are not supported.");937reflection_data_d3d12.spirv_specialization_constants_ids_mask |= (1 << reflection_specialization_data[i].constant_id);938}939940// Translate SPIR-V shaders to DXIL, and collect shader info from the new representation.941HashMap<RenderingDeviceCommons::ShaderStage, Vector<uint8_t>> dxil_blobs;942Vector<RenderingDeviceCommons::ShaderStage> stages;943BitField<RenderingDeviceCommons::ShaderStage> stages_processed = {};944if (!_convert_spirv_to_dxil(p_spirv, dxil_blobs, stages, stages_processed)) {945return false;946}947948// Patch with default values of specialization constants.949DEV_ASSERT(reflection_specialization_data.size() == reflection_specialization_data_d3d12.size());950for (int32_t i = 0; i < reflection_specialization_data.size(); i++) {951const ReflectionSpecializationData &sc = reflection_specialization_data[i];952const ReflectionSpecializationDataD3D12 &sc_d3d12 = reflection_specialization_data_d3d12[i];953RenderingDXIL::patch_specialization_constant((RenderingDeviceCommons::PipelineSpecializationConstantType)(sc.type), &sc.int_value, sc_d3d12.stages_bit_offsets, dxil_blobs, true);954}955956// Sign.957uint32_t shader_index = 0;958for (KeyValue<RenderingDeviceCommons::ShaderStage, Vector<uint8_t>> &E : dxil_blobs) {959RenderingDXIL::sign_bytecode(E.key, E.value);960}961962// Store compressed DXIL blobs as the shaders.963shaders.resize(p_spirv.size());964for (int64_t i = 0; i < shaders.size(); i++) {965const PackedByteArray &dxil_bytes = dxil_blobs[stages[i]];966RenderingShaderContainer::Shader &shader = shaders.ptrw()[i];967uint32_t compressed_size = 0;968shader.shader_stage = stages[i];969shader.code_decompressed_size = dxil_bytes.size();970shader.code_compressed_bytes.resize(dxil_bytes.size());971972bool compressed = compress_code(dxil_bytes.ptr(), dxil_bytes.size(), shader.code_compressed_bytes.ptrw(), &compressed_size, &shader.code_compression_flags);973ERR_FAIL_COND_V_MSG(!compressed, false, vformat("Failed to compress native code to native for SPIR-V #%d.", shader_index));974975shader.code_compressed_bytes.resize(compressed_size);976}977978if (!_generate_root_signature(stages_processed)) {979return false;980}981982return true;983#else984ERR_FAIL_V_MSG(false, "Shader compilation is not supported at runtime without NIR.");985#endif986}987988RenderingShaderContainerD3D12::RenderingShaderContainerD3D12() {989// Default empty constructor.990}991992RenderingShaderContainerD3D12::RenderingShaderContainerD3D12(void *p_lib_d3d12) {993lib_d3d12 = p_lib_d3d12;994}995996RenderingShaderContainerD3D12::ShaderReflectionD3D12 RenderingShaderContainerD3D12::get_shader_reflection_d3d12() const {997ShaderReflectionD3D12 reflection;998reflection.spirv_specialization_constants_ids_mask = reflection_data_d3d12.spirv_specialization_constants_ids_mask;999reflection.dxil_push_constant_stages = reflection_data_d3d12.dxil_push_constant_stages;1000reflection.nir_runtime_data_root_param_idx = reflection_data_d3d12.nir_runtime_data_root_param_idx;1001reflection.reflection_binding_sets_d3d12 = reflection_binding_set_data_d3d12;1002reflection.reflection_specialization_data_d3d12 = reflection_specialization_data_d3d12;1003reflection.root_signature_bytes = root_signature_bytes;1004reflection.root_signature_crc = root_signature_crc;10051006// Transform data vector into a vector of vectors that's easier to user.1007uint32_t uniform_index = 0;1008reflection.reflection_binding_set_uniforms_d3d12.resize(reflection_binding_set_uniforms_count.size());1009for (int64_t i = 0; i < reflection.reflection_binding_set_uniforms_d3d12.size(); i++) {1010Vector<ReflectionBindingDataD3D12> &uniforms = reflection.reflection_binding_set_uniforms_d3d12.ptrw()[i];1011uniforms.resize(reflection_binding_set_uniforms_count[i]);1012for (int64_t j = 0; j < uniforms.size(); j++) {1013uniforms.ptrw()[j] = reflection_binding_set_uniforms_data_d3d12[uniform_index];1014uniform_index++;1015}1016}10171018return reflection;1019}10201021// RenderingShaderContainerFormatD3D1210221023void RenderingShaderContainerFormatD3D12::set_lib_d3d12(void *p_lib_d3d12) {1024lib_d3d12 = p_lib_d3d12;1025}10261027Ref<RenderingShaderContainer> RenderingShaderContainerFormatD3D12::create_container() const {1028return memnew(RenderingShaderContainerD3D12(lib_d3d12));1029}10301031RenderingDeviceCommons::ShaderLanguageVersion RenderingShaderContainerFormatD3D12::get_shader_language_version() const {1032// NIR-DXIL is Vulkan 1.1-conformant.1033return SHADER_LANGUAGE_VULKAN_VERSION_1_1;1034}10351036RenderingDeviceCommons::ShaderSpirvVersion RenderingShaderContainerFormatD3D12::get_shader_spirv_version() const {1037// The SPIR-V part of Mesa supports 1.6, but:1038// - SPIRV-Reflect won't be able to parse the compute workgroup size.1039// - We want to play it safe with NIR-DXIL.1040return SHADER_SPIRV_VERSION_1_5;1041}10421043RenderingShaderContainerFormatD3D12::RenderingShaderContainerFormatD3D12() {}10441045RenderingShaderContainerFormatD3D12::~RenderingShaderContainerFormatD3D12() {}104610471048