Path: blob/master/servers/rendering/rendering_shader_container.cpp
11351 views
/**************************************************************************/1/* rendering_shader_container.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.h"3132#include "core/io/compression.h"3334#include "thirdparty/spirv-reflect/spirv_reflect.h"3536static inline uint32_t aligned_to(uint32_t p_size, uint32_t p_alignment) {37if (p_size % p_alignment) {38return p_size + (p_alignment - (p_size % p_alignment));39} else {40return p_size;41}42}4344RenderingShaderContainer::ReflectedShaderStage::ReflectedShaderStage() :45_module(memnew(SpvReflectShaderModule)) {46}4748RenderingShaderContainer::ReflectedShaderStage::~ReflectedShaderStage() {49spvReflectDestroyShaderModule(_module);50memdelete(_module);51}5253const SpvReflectShaderModule &RenderingShaderContainer::ReflectedShaderStage::module() const {54return *_module;55}5657const Span<uint32_t> RenderingShaderContainer::ReflectedShaderStage::spirv() const {58return _spirv_data.span().reinterpret<uint32_t>();59}6061uint32_t RenderingShaderContainer::_from_bytes_header_extra_data(const uint8_t *p_bytes) {62return 0;63}6465uint32_t RenderingShaderContainer::_from_bytes_reflection_extra_data(const uint8_t *p_bytes) {66return 0;67}6869uint32_t RenderingShaderContainer::_from_bytes_reflection_binding_uniform_extra_data_start(const uint8_t *p_bytes) {70return 0;71}7273uint32_t RenderingShaderContainer::_from_bytes_reflection_binding_uniform_extra_data(const uint8_t *p_bytes, uint32_t p_index) {74return 0;75}7677uint32_t RenderingShaderContainer::_from_bytes_reflection_specialization_extra_data_start(const uint8_t *p_bytes) {78return 0;79}8081uint32_t RenderingShaderContainer::_from_bytes_reflection_specialization_extra_data(const uint8_t *p_bytes, uint32_t p_index) {82return 0;83}8485uint32_t RenderingShaderContainer::_from_bytes_shader_extra_data_start(const uint8_t *p_bytes) {86return 0;87}8889uint32_t RenderingShaderContainer::_from_bytes_shader_extra_data(const uint8_t *p_bytes, uint32_t p_index) {90return 0;91}9293uint32_t RenderingShaderContainer::_from_bytes_footer_extra_data(const uint8_t *p_bytes) {94return 0;95}9697uint32_t RenderingShaderContainer::_to_bytes_header_extra_data(uint8_t *) const {98return 0;99}100101uint32_t RenderingShaderContainer::_to_bytes_reflection_extra_data(uint8_t *) const {102return 0;103}104105uint32_t RenderingShaderContainer::_to_bytes_reflection_binding_uniform_extra_data(uint8_t *, uint32_t) const {106return 0;107}108109uint32_t RenderingShaderContainer::_to_bytes_reflection_specialization_extra_data(uint8_t *, uint32_t) const {110return 0;111}112113uint32_t RenderingShaderContainer::_to_bytes_shader_extra_data(uint8_t *, uint32_t) const {114return 0;115}116117uint32_t RenderingShaderContainer::_to_bytes_footer_extra_data(uint8_t *) const {118return 0;119}120121void RenderingShaderContainer::_set_from_shader_reflection_post(const RenderingDeviceCommons::ShaderReflection &p_reflection) {122// Do nothing.123}124125Error RenderingShaderContainer::reflect_spirv(const String &p_shader_name, Span<RenderingDeviceCommons::ShaderStageSPIRVData> p_spirv, LocalVector<ReflectedShaderStage> &r_refl) {126using RDC = RenderingDeviceCommons;127RDC::ShaderReflection reflection;128129shader_name = p_shader_name.utf8();130131const uint32_t spirv_size = p_spirv.size() + 0;132r_refl.resize(spirv_size);133134for (uint32_t i = 0; i < spirv_size; i++) {135RDC::ShaderStage stage = p_spirv[i].shader_stage;136RDC::ShaderStage stage_flag = (RDC::ShaderStage)(1 << p_spirv[i].shader_stage);137r_refl[i].shader_stage = p_spirv[i].shader_stage;138r_refl[i]._spirv_data = p_spirv[i].spirv;139140if (p_spirv[i].shader_stage == RDC::SHADER_STAGE_COMPUTE) {141reflection.is_compute = true;142ERR_FAIL_COND_V_MSG(spirv_size != 1, FAILED,143"Compute shaders can only receive one stage, dedicated to compute.");144}145ERR_FAIL_COND_V_MSG(reflection.stages_bits.has_flag(stage_flag), FAILED,146"Stage " + String(RDC::SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + " submitted more than once.");147148{149SpvReflectShaderModule &module = *r_refl.ptr()[i]._module;150const uint8_t *spirv = p_spirv[i].spirv.ptr();151SpvReflectResult result = spvReflectCreateShaderModule2(SPV_REFLECT_MODULE_FLAG_NO_COPY, p_spirv[i].spirv.size(), spirv, &module);152ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED,153"Reflection of SPIR-V shader stage '" + String(RDC::SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + "' failed parsing shader.");154155for (uint32_t j = 0; j < module.capability_count; j++) {156if (module.capabilities[j].value == SpvCapabilityMultiView) {157reflection.has_multiview = true;158break;159}160}161162if (reflection.is_compute) {163reflection.compute_local_size[0] = module.entry_points->local_size.x;164reflection.compute_local_size[1] = module.entry_points->local_size.y;165reflection.compute_local_size[2] = module.entry_points->local_size.z;166}167uint32_t binding_count = 0;168result = spvReflectEnumerateDescriptorBindings(&module, &binding_count, nullptr);169ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED,170"Reflection of SPIR-V shader stage '" + String(RDC::SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + "' failed enumerating descriptor bindings.");171172if (binding_count > 0) {173// Parse bindings.174175Vector<SpvReflectDescriptorBinding *> bindings;176bindings.resize(binding_count);177result = spvReflectEnumerateDescriptorBindings(&module, &binding_count, bindings.ptrw());178179ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED,180"Reflection of SPIR-V shader stage '" + String(RDC::SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + "' failed getting descriptor bindings.");181182for (uint32_t j = 0; j < binding_count; j++) {183const SpvReflectDescriptorBinding &binding = *bindings[j];184185RDC::ShaderUniform uniform;186187bool need_array_dimensions = false;188bool need_block_size = false;189bool may_be_writable = false;190191switch (binding.descriptor_type) {192case SPV_REFLECT_DESCRIPTOR_TYPE_SAMPLER: {193uniform.type = RDC::UNIFORM_TYPE_SAMPLER;194need_array_dimensions = true;195} break;196case SPV_REFLECT_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: {197uniform.type = RDC::UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;198need_array_dimensions = true;199} break;200case SPV_REFLECT_DESCRIPTOR_TYPE_SAMPLED_IMAGE: {201uniform.type = RDC::UNIFORM_TYPE_TEXTURE;202need_array_dimensions = true;203} break;204case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_IMAGE: {205uniform.type = RDC::UNIFORM_TYPE_IMAGE;206need_array_dimensions = true;207may_be_writable = true;208} break;209case SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER: {210uniform.type = RDC::UNIFORM_TYPE_TEXTURE_BUFFER;211need_array_dimensions = true;212} break;213case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER: {214uniform.type = RDC::UNIFORM_TYPE_IMAGE_BUFFER;215need_array_dimensions = true;216may_be_writable = true;217} break;218case SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_BUFFER: {219uniform.type = RDC::UNIFORM_TYPE_UNIFORM_BUFFER;220need_block_size = true;221} break;222case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER: {223uniform.type = RDC::UNIFORM_TYPE_STORAGE_BUFFER;224need_block_size = true;225may_be_writable = true;226} break;227case SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC: {228ERR_PRINT("Dynamic uniform buffer not supported.");229continue;230} break;231case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: {232ERR_PRINT("Dynamic storage buffer not supported.");233continue;234} break;235case SPV_REFLECT_DESCRIPTOR_TYPE_INPUT_ATTACHMENT: {236uniform.type = RDC::UNIFORM_TYPE_INPUT_ATTACHMENT;237need_array_dimensions = true;238} break;239case SPV_REFLECT_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR: {240ERR_PRINT("Acceleration structure not supported.");241continue;242} break;243}244245if (need_array_dimensions) {246if (binding.array.dims_count == 0) {247uniform.length = 1;248} else {249for (uint32_t k = 0; k < binding.array.dims_count; k++) {250if (k == 0) {251uniform.length = binding.array.dims[0];252} else {253uniform.length *= binding.array.dims[k];254}255}256}257258} else if (need_block_size) {259uniform.length = binding.block.size;260} else {261uniform.length = 0;262}263264if (may_be_writable) {265if (binding.descriptor_type == SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_IMAGE) {266uniform.writable = !(binding.decoration_flags & SPV_REFLECT_DECORATION_NON_WRITABLE);267} else {268uniform.writable = !(binding.decoration_flags & SPV_REFLECT_DECORATION_NON_WRITABLE) && !(binding.block.decoration_flags & SPV_REFLECT_DECORATION_NON_WRITABLE);269}270} else {271uniform.writable = false;272}273274uniform.binding = binding.binding;275uint32_t set = binding.set;276277ERR_FAIL_COND_V_MSG(set >= RDC::MAX_UNIFORM_SETS, FAILED,278"On shader stage '" + String(RDC::SHADER_STAGE_NAMES[stage]) + "', uniform '" + binding.name + "' uses a set (" + itos(set) + ") index larger than what is supported (" + itos(RDC::MAX_UNIFORM_SETS) + ").");279280if (set < (uint32_t)reflection.uniform_sets.size()) {281// Check if this already exists.282bool exists = false;283for (int k = 0; k < reflection.uniform_sets[set].size(); k++) {284if (reflection.uniform_sets[set][k].binding == uniform.binding) {285// Already exists, verify that it's the same type.286ERR_FAIL_COND_V_MSG(reflection.uniform_sets[set][k].type != uniform.type, FAILED,287"On shader stage '" + String(RDC::SHADER_STAGE_NAMES[stage]) + "', uniform '" + binding.name + "' trying to reuse location for set=" + itos(set) + ", binding=" + itos(uniform.binding) + " with different uniform type.");288289// Also, verify that it's the same size.290ERR_FAIL_COND_V_MSG(reflection.uniform_sets[set][k].length != uniform.length, FAILED,291"On shader stage '" + String(RDC::SHADER_STAGE_NAMES[stage]) + "', uniform '" + binding.name + "' trying to reuse location for set=" + itos(set) + ", binding=" + itos(uniform.binding) + " with different uniform size.");292293// Also, verify that it has the same writability.294ERR_FAIL_COND_V_MSG(reflection.uniform_sets[set][k].writable != uniform.writable, FAILED,295"On shader stage '" + String(RDC::SHADER_STAGE_NAMES[stage]) + "', uniform '" + binding.name + "' trying to reuse location for set=" + itos(set) + ", binding=" + itos(uniform.binding) + " with different writability.");296297// Just append stage mask and return.298reflection.uniform_sets.write[set].write[k].stages.set_flag(stage_flag);299exists = true;300break;301}302}303304if (exists) {305continue; // Merged.306}307}308309uniform.stages.set_flag(stage_flag);310311if (set >= (uint32_t)reflection.uniform_sets.size()) {312reflection.uniform_sets.resize(set + 1);313}314315reflection.uniform_sets.write[set].push_back(uniform);316}317}318319{320// Specialization constants.321322uint32_t sc_count = 0;323result = spvReflectEnumerateSpecializationConstants(&module, &sc_count, nullptr);324ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED,325"Reflection of SPIR-V shader stage '" + String(RDC::SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + "' failed enumerating specialization constants.");326327if (sc_count) {328Vector<SpvReflectSpecializationConstant *> spec_constants;329spec_constants.resize(sc_count);330331result = spvReflectEnumerateSpecializationConstants(&module, &sc_count, spec_constants.ptrw());332ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED,333"Reflection of SPIR-V shader stage '" + String(RDC::SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + "' failed obtaining specialization constants.");334335for (uint32_t j = 0; j < sc_count; j++) {336int32_t existing = -1;337RDC::ShaderSpecializationConstant sconst;338SpvReflectSpecializationConstant *spc = spec_constants[j];339340sconst.constant_id = spc->constant_id;341sconst.int_value = 0; // Clear previous value JIC.342switch (spc->constant_type) {343case SPV_REFLECT_SPECIALIZATION_CONSTANT_BOOL: {344sconst.type = RDC::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL;345sconst.bool_value = spc->default_value.int_bool_value != 0;346} break;347case SPV_REFLECT_SPECIALIZATION_CONSTANT_INT: {348sconst.type = RDC::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_INT;349sconst.int_value = spc->default_value.int_bool_value;350} break;351case SPV_REFLECT_SPECIALIZATION_CONSTANT_FLOAT: {352sconst.type = RDC::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_FLOAT;353sconst.float_value = spc->default_value.float_value;354} break;355}356sconst.stages.set_flag(stage_flag);357358for (int k = 0; k < reflection.specialization_constants.size(); k++) {359if (reflection.specialization_constants[k].constant_id == sconst.constant_id) {360ERR_FAIL_COND_V_MSG(reflection.specialization_constants[k].type != sconst.type, FAILED, "More than one specialization constant used for id (" + itos(sconst.constant_id) + "), but their types differ.");361ERR_FAIL_COND_V_MSG(reflection.specialization_constants[k].int_value != sconst.int_value, FAILED, "More than one specialization constant used for id (" + itos(sconst.constant_id) + "), but their default values differ.");362existing = k;363break;364}365}366367if (existing >= 0) {368reflection.specialization_constants.write[existing].stages.set_flag(stage_flag);369} else {370reflection.specialization_constants.push_back(sconst);371}372}373374reflection.specialization_constants.sort();375}376}377378if (stage == RDC::SHADER_STAGE_VERTEX || stage == RDC::SHADER_STAGE_FRAGMENT) {379uint32_t iv_count = 0;380result = spvReflectEnumerateInputVariables(&module, &iv_count, nullptr);381ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED,382"Reflection of SPIR-V shader stage '" + String(RDC::SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + "' failed enumerating input variables.");383384if (iv_count) {385Vector<SpvReflectInterfaceVariable *> input_vars;386input_vars.resize(iv_count);387388result = spvReflectEnumerateInputVariables(&module, &iv_count, input_vars.ptrw());389ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED,390"Reflection of SPIR-V shader stage '" + String(RDC::SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + "' failed obtaining input variables.");391392for (const SpvReflectInterfaceVariable *v : input_vars) {393if (!v) {394continue;395}396if (stage == RDC::SHADER_STAGE_VERTEX) {397if (v->decoration_flags == 0) { // Regular input.398reflection.vertex_input_mask |= (((uint64_t)1) << v->location);399}400}401if (v->built_in == SpvBuiltInViewIndex) {402reflection.has_multiview = true;403}404}405}406}407408if (stage == RDC::SHADER_STAGE_FRAGMENT) {409uint32_t ov_count = 0;410result = spvReflectEnumerateOutputVariables(&module, &ov_count, nullptr);411ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED,412"Reflection of SPIR-V shader stage '" + String(RDC::SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + "' failed enumerating output variables.");413414if (ov_count) {415Vector<SpvReflectInterfaceVariable *> output_vars;416output_vars.resize(ov_count);417418result = spvReflectEnumerateOutputVariables(&module, &ov_count, output_vars.ptrw());419ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED,420"Reflection of SPIR-V shader stage '" + String(RDC::SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + "' failed obtaining output variables.");421422for (const SpvReflectInterfaceVariable *refvar : output_vars) {423if (!refvar) {424continue;425}426if (refvar->built_in != SpvBuiltInFragDepth) {427reflection.fragment_output_mask |= 1 << refvar->location;428}429}430}431}432433uint32_t pc_count = 0;434result = spvReflectEnumeratePushConstantBlocks(&module, &pc_count, nullptr);435ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED,436"Reflection of SPIR-V shader stage '" + String(RDC::SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + "' failed enumerating push constants.");437438if (pc_count) {439ERR_FAIL_COND_V_MSG(pc_count > 1, FAILED,440"Reflection of SPIR-V shader stage '" + String(RDC::SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + "': Only one push constant is supported, which should be the same across shader stages.");441442Vector<SpvReflectBlockVariable *> pconstants;443pconstants.resize(pc_count);444result = spvReflectEnumeratePushConstantBlocks(&module, &pc_count, pconstants.ptrw());445ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, FAILED,446"Reflection of SPIR-V shader stage '" + String(RDC::SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + "' failed obtaining push constants.");447#if 0448if (pconstants[0] == nullptr) {449Ref<FileAccess> f = FileAccess::open("res://popo.spv", FileAccess::WRITE);450f->store_buffer((const uint8_t *)&SpirV[0], SpirV.size() * sizeof(uint32_t));451}452#endif453454ERR_FAIL_COND_V_MSG(reflection.push_constant_size && reflection.push_constant_size != pconstants[0]->size, FAILED,455"Reflection of SPIR-V shader stage '" + String(RDC::SHADER_STAGE_NAMES[p_spirv[i].shader_stage]) + "': Push constant block must be the same across shader stages.");456457reflection.push_constant_size = pconstants[0]->size;458reflection.push_constant_stages.set_flag(stage_flag);459460//print_line("Stage: " + String(RDC::SHADER_STAGE_NAMES[stage]) + " push constant of size=" + itos(push_constant.push_constant_size));461}462}463464reflection.stages_bits.set_flag(stage_flag);465}466467// Sort all uniform_sets by binding.468for (uint32_t i = 0; i < reflection.uniform_sets.size(); i++) {469reflection.uniform_sets.write[i].sort();470}471472set_from_shader_reflection(reflection);473474return OK;475}476477void RenderingShaderContainer::set_from_shader_reflection(const RenderingDeviceCommons::ShaderReflection &p_reflection) {478reflection_binding_set_uniforms_count.clear();479reflection_binding_set_uniforms_data.clear();480reflection_specialization_data.clear();481reflection_shader_stages.clear();482483reflection_data.vertex_input_mask = p_reflection.vertex_input_mask;484reflection_data.fragment_output_mask = p_reflection.fragment_output_mask;485reflection_data.specialization_constants_count = p_reflection.specialization_constants.size();486reflection_data.is_compute = p_reflection.is_compute;487reflection_data.has_multiview = p_reflection.has_multiview;488reflection_data.compute_local_size[0] = p_reflection.compute_local_size[0];489reflection_data.compute_local_size[1] = p_reflection.compute_local_size[1];490reflection_data.compute_local_size[2] = p_reflection.compute_local_size[2];491reflection_data.set_count = p_reflection.uniform_sets.size();492reflection_data.push_constant_size = p_reflection.push_constant_size;493reflection_data.push_constant_stages_mask = uint32_t(p_reflection.push_constant_stages);494reflection_data.shader_name_len = shader_name.length();495496ReflectionBindingData binding_data;497for (const Vector<RenderingDeviceCommons::ShaderUniform> &uniform_set : p_reflection.uniform_sets) {498for (const RenderingDeviceCommons::ShaderUniform &uniform : uniform_set) {499binding_data.type = uint32_t(uniform.type);500binding_data.binding = uniform.binding;501binding_data.stages = uint32_t(uniform.stages);502binding_data.length = uniform.length;503binding_data.writable = uint32_t(uniform.writable);504reflection_binding_set_uniforms_data.push_back(binding_data);505}506507reflection_binding_set_uniforms_count.push_back(uniform_set.size());508}509510ReflectionSpecializationData specialization_data;511for (const RenderingDeviceCommons::ShaderSpecializationConstant &spec : p_reflection.specialization_constants) {512specialization_data.type = uint32_t(spec.type);513specialization_data.constant_id = spec.constant_id;514specialization_data.int_value = spec.int_value;515specialization_data.stage_flags = uint32_t(spec.stages);516reflection_specialization_data.push_back(specialization_data);517}518519for (uint32_t i = 0; i < RenderingDeviceCommons::SHADER_STAGE_MAX; i++) {520if (p_reflection.stages_bits.has_flag(RenderingDeviceCommons::ShaderStage(1U << i))) {521reflection_shader_stages.push_back(RenderingDeviceCommons::ShaderStage(i));522}523}524525reflection_data.stage_count = reflection_shader_stages.size();526527_set_from_shader_reflection_post(p_reflection);528}529530bool RenderingShaderContainer::set_code_from_spirv(const String &p_shader_name, Span<RenderingDeviceCommons::ShaderStageSPIRVData> p_spirv) {531LocalVector<ReflectedShaderStage> spirv;532ERR_FAIL_COND_V(reflect_spirv(p_shader_name, p_spirv, spirv) != OK, false);533return _set_code_from_spirv(spirv.span());534}535536RenderingDeviceCommons::ShaderReflection RenderingShaderContainer::get_shader_reflection() const {537RenderingDeviceCommons::ShaderReflection shader_refl;538shader_refl.push_constant_size = reflection_data.push_constant_size;539shader_refl.push_constant_stages = reflection_data.push_constant_stages_mask;540shader_refl.vertex_input_mask = reflection_data.vertex_input_mask;541shader_refl.fragment_output_mask = reflection_data.fragment_output_mask;542shader_refl.is_compute = reflection_data.is_compute;543shader_refl.has_multiview = reflection_data.has_multiview;544shader_refl.compute_local_size[0] = reflection_data.compute_local_size[0];545shader_refl.compute_local_size[1] = reflection_data.compute_local_size[1];546shader_refl.compute_local_size[2] = reflection_data.compute_local_size[2];547shader_refl.uniform_sets.resize(reflection_data.set_count);548shader_refl.specialization_constants.resize(reflection_data.specialization_constants_count);549shader_refl.stages_vector.resize(reflection_data.stage_count);550551DEV_ASSERT(reflection_binding_set_uniforms_count.size() == reflection_data.set_count && "The amount of elements in the reflection and the shader container can't be different.");552uint32_t uniform_index = 0;553for (uint32_t i = 0; i < reflection_data.set_count; i++) {554Vector<RenderingDeviceCommons::ShaderUniform> &uniform_set = shader_refl.uniform_sets.ptrw()[i];555uint32_t uniforms_count = reflection_binding_set_uniforms_count[i];556uniform_set.resize(uniforms_count);557for (uint32_t j = 0; j < uniforms_count; j++) {558const ReflectionBindingData &binding = reflection_binding_set_uniforms_data[uniform_index++];559RenderingDeviceCommons::ShaderUniform &uniform = uniform_set.ptrw()[j];560uniform.type = RenderingDeviceCommons::UniformType(binding.type);561uniform.writable = binding.writable;562uniform.length = binding.length;563uniform.binding = binding.binding;564uniform.stages = binding.stages;565}566}567568shader_refl.specialization_constants.resize(reflection_data.specialization_constants_count);569for (uint32_t i = 0; i < reflection_data.specialization_constants_count; i++) {570const ReflectionSpecializationData &spec = reflection_specialization_data[i];571RenderingDeviceCommons::ShaderSpecializationConstant &sc = shader_refl.specialization_constants.ptrw()[i];572sc.type = RenderingDeviceCommons::PipelineSpecializationConstantType(spec.type);573sc.constant_id = spec.constant_id;574sc.int_value = spec.int_value;575sc.stages = spec.stage_flags;576}577578shader_refl.stages_vector.resize(reflection_data.stage_count);579for (uint32_t i = 0; i < reflection_data.stage_count; i++) {580shader_refl.stages_vector.set(i, reflection_shader_stages[i]);581shader_refl.stages_bits.set_flag(RenderingDeviceCommons::ShaderStage(1U << reflection_shader_stages[i]));582}583584return shader_refl;585}586587bool RenderingShaderContainer::from_bytes(const PackedByteArray &p_bytes) {588const uint64_t alignment = sizeof(uint32_t);589const uint8_t *bytes_ptr = p_bytes.ptr();590uint64_t bytes_offset = 0;591592// Read container header.593ERR_FAIL_COND_V_MSG(int64_t(bytes_offset + sizeof(ContainerHeader)) > p_bytes.size(), false, "Not enough bytes for a container header in shader container.");594const ContainerHeader &container_header = *(const ContainerHeader *)(&bytes_ptr[bytes_offset]);595bytes_offset += sizeof(ContainerHeader);596bytes_offset += _from_bytes_header_extra_data(&bytes_ptr[bytes_offset]);597598ERR_FAIL_COND_V_MSG(container_header.magic_number != CONTAINER_MAGIC_NUMBER, false, "Incorrect magic number in shader container.");599ERR_FAIL_COND_V_MSG(container_header.version > CONTAINER_VERSION, false, "Unsupported version in shader container.");600ERR_FAIL_COND_V_MSG(container_header.format != _format(), false, "Incorrect format in shader container.");601ERR_FAIL_COND_V_MSG(container_header.format_version > _format_version(), false, "Unsupported format version in shader container.");602603// Adjust shaders to the size indicated by the container header.604shaders.resize(container_header.shader_count);605606// Read reflection data.607ERR_FAIL_COND_V_MSG(int64_t(bytes_offset + sizeof(ReflectionData)) > p_bytes.size(), false, "Not enough bytes for reflection data in shader container.");608reflection_data = *(const ReflectionData *)(&bytes_ptr[bytes_offset]);609bytes_offset += sizeof(ReflectionData);610bytes_offset += _from_bytes_reflection_extra_data(&bytes_ptr[bytes_offset]);611612// Read shader name.613ERR_FAIL_COND_V_MSG(int64_t(bytes_offset + reflection_data.shader_name_len) > p_bytes.size(), false, "Not enough bytes for shader name in shader container.");614if (reflection_data.shader_name_len > 0) {615String shader_name_str;616shader_name_str.append_utf8((const char *)(&bytes_ptr[bytes_offset]), reflection_data.shader_name_len);617shader_name = shader_name_str.utf8();618bytes_offset = aligned_to(bytes_offset + reflection_data.shader_name_len, alignment);619} else {620shader_name = CharString();621}622623reflection_binding_set_uniforms_count.resize(reflection_data.set_count);624reflection_binding_set_uniforms_data.clear();625626uint32_t uniform_index = 0;627for (uint32_t i = 0; i < reflection_data.set_count; i++) {628ERR_FAIL_COND_V_MSG(int64_t(bytes_offset + sizeof(uint32_t)) > p_bytes.size(), false, "Not enough bytes for uniform set count in shader container.");629uint32_t uniforms_count = *(uint32_t *)(&bytes_ptr[bytes_offset]);630reflection_binding_set_uniforms_count.ptrw()[i] = uniforms_count;631bytes_offset += sizeof(uint32_t);632633reflection_binding_set_uniforms_data.resize(reflection_binding_set_uniforms_data.size() + uniforms_count);634bytes_offset += _from_bytes_reflection_binding_uniform_extra_data_start(&bytes_ptr[bytes_offset]);635636for (uint32_t j = 0; j < uniforms_count; j++) {637ERR_FAIL_COND_V_MSG(int64_t(bytes_offset + sizeof(ReflectionBindingData)) > p_bytes.size(), false, "Not enough bytes for uniform in shader container.");638memcpy(&reflection_binding_set_uniforms_data.ptrw()[uniform_index], &bytes_ptr[bytes_offset], sizeof(ReflectionBindingData));639bytes_offset += sizeof(ReflectionBindingData);640bytes_offset += _from_bytes_reflection_binding_uniform_extra_data(&bytes_ptr[bytes_offset], uniform_index);641uniform_index++;642}643}644645reflection_specialization_data.resize(reflection_data.specialization_constants_count);646bytes_offset += _from_bytes_reflection_specialization_extra_data_start(&bytes_ptr[bytes_offset]);647648for (uint32_t i = 0; i < reflection_data.specialization_constants_count; i++) {649ERR_FAIL_COND_V_MSG(int64_t(bytes_offset + sizeof(ReflectionSpecializationData)) > p_bytes.size(), false, "Not enough bytes for specialization in shader container.");650memcpy(&reflection_specialization_data.ptrw()[i], &bytes_ptr[bytes_offset], sizeof(ReflectionSpecializationData));651bytes_offset += sizeof(ReflectionSpecializationData);652bytes_offset += _from_bytes_reflection_specialization_extra_data(&bytes_ptr[bytes_offset], i);653}654655const uint32_t stage_count = reflection_data.stage_count;656if (stage_count > 0) {657ERR_FAIL_COND_V_MSG(int64_t(bytes_offset + stage_count * sizeof(RenderingDeviceCommons::ShaderStage)) > p_bytes.size(), false, "Not enough bytes for stages in shader container.");658reflection_shader_stages.resize(stage_count);659bytes_offset += _from_bytes_shader_extra_data_start(&bytes_ptr[bytes_offset]);660memcpy(reflection_shader_stages.ptrw(), &bytes_ptr[bytes_offset], stage_count * sizeof(RenderingDeviceCommons::ShaderStage));661bytes_offset += stage_count * sizeof(RenderingDeviceCommons::ShaderStage);662}663664// Read shaders.665for (int64_t i = 0; i < shaders.size(); i++) {666ERR_FAIL_COND_V_MSG(int64_t(bytes_offset + sizeof(ShaderHeader)) > p_bytes.size(), false, "Not enough bytes for shader header in shader container.");667const ShaderHeader &header = *(const ShaderHeader *)(&bytes_ptr[bytes_offset]);668bytes_offset += sizeof(ShaderHeader);669670ERR_FAIL_COND_V_MSG(int64_t(bytes_offset + header.code_compressed_size) > p_bytes.size(), false, "Not enough bytes for a shader in shader container.");671Shader &shader = shaders.ptrw()[i];672shader.shader_stage = RenderingDeviceCommons::ShaderStage(header.shader_stage);673shader.code_compression_flags = header.code_compression_flags;674shader.code_decompressed_size = header.code_decompressed_size;675shader.code_compressed_bytes.resize(header.code_compressed_size);676memcpy(shader.code_compressed_bytes.ptrw(), &bytes_ptr[bytes_offset], header.code_compressed_size);677bytes_offset = aligned_to(bytes_offset + header.code_compressed_size, alignment);678bytes_offset += _from_bytes_shader_extra_data(&bytes_ptr[bytes_offset], i);679}680681bytes_offset += _from_bytes_footer_extra_data(&bytes_ptr[bytes_offset]);682683ERR_FAIL_COND_V_MSG(bytes_offset != (uint64_t)p_bytes.size(), false, "Amount of bytes in the container does not match the amount of bytes read.");684return true;685}686687PackedByteArray RenderingShaderContainer::to_bytes() const {688// Compute the exact size the container will require for writing everything out.689const uint64_t alignment = sizeof(uint32_t);690uint64_t total_size = 0;691total_size += sizeof(ContainerHeader) + _to_bytes_header_extra_data(nullptr);692total_size += sizeof(ReflectionData) + _to_bytes_reflection_extra_data(nullptr);693total_size += aligned_to(reflection_data.shader_name_len, alignment);694total_size += reflection_binding_set_uniforms_count.size() * sizeof(uint32_t);695total_size += reflection_binding_set_uniforms_data.size() * sizeof(ReflectionBindingData);696total_size += reflection_specialization_data.size() * sizeof(ReflectionSpecializationData);697total_size += reflection_shader_stages.size() * sizeof(RenderingDeviceCommons::ShaderStage);698699for (uint32_t i = 0; i < reflection_binding_set_uniforms_data.size(); i++) {700total_size += _to_bytes_reflection_binding_uniform_extra_data(nullptr, i);701}702703for (uint32_t i = 0; i < reflection_specialization_data.size(); i++) {704total_size += _to_bytes_reflection_specialization_extra_data(nullptr, i);705}706707for (uint32_t i = 0; i < shaders.size(); i++) {708total_size += sizeof(ShaderHeader);709total_size += shaders[i].code_compressed_bytes.size();710total_size = aligned_to(total_size, alignment);711total_size += _to_bytes_shader_extra_data(nullptr, i);712}713714total_size += _to_bytes_footer_extra_data(nullptr);715716// Create the array that will hold all of the data.717PackedByteArray bytes;718bytes.resize_initialized(total_size);719720// Write out the data to the array.721uint64_t bytes_offset = 0;722uint8_t *bytes_ptr = bytes.ptrw();723ContainerHeader &container_header = *(ContainerHeader *)(&bytes_ptr[bytes_offset]);724container_header.magic_number = CONTAINER_MAGIC_NUMBER;725container_header.version = CONTAINER_VERSION;726container_header.format = _format();727container_header.format_version = _format_version();728container_header.shader_count = shaders.size();729bytes_offset += sizeof(ContainerHeader);730bytes_offset += _to_bytes_header_extra_data(&bytes_ptr[bytes_offset]);731732memcpy(&bytes_ptr[bytes_offset], &reflection_data, sizeof(ReflectionData));733bytes_offset += sizeof(ReflectionData);734bytes_offset += _to_bytes_reflection_extra_data(&bytes_ptr[bytes_offset]);735736if (shader_name.size() > 0) {737memcpy(&bytes_ptr[bytes_offset], shader_name.ptr(), reflection_data.shader_name_len);738bytes_offset = aligned_to(bytes_offset + reflection_data.shader_name_len, alignment);739}740741uint32_t uniform_index = 0;742for (uint32_t uniform_count : reflection_binding_set_uniforms_count) {743memcpy(&bytes_ptr[bytes_offset], &uniform_count, sizeof(uniform_count));744bytes_offset += sizeof(uint32_t);745746for (uint32_t i = 0; i < uniform_count; i++) {747memcpy(&bytes_ptr[bytes_offset], &reflection_binding_set_uniforms_data[uniform_index], sizeof(ReflectionBindingData));748bytes_offset += sizeof(ReflectionBindingData);749bytes_offset += _to_bytes_reflection_binding_uniform_extra_data(&bytes_ptr[bytes_offset], uniform_index);750uniform_index++;751}752}753754for (uint32_t i = 0; i < reflection_specialization_data.size(); i++) {755memcpy(&bytes_ptr[bytes_offset], &reflection_specialization_data.ptr()[i], sizeof(ReflectionSpecializationData));756bytes_offset += sizeof(ReflectionSpecializationData);757bytes_offset += _to_bytes_reflection_specialization_extra_data(&bytes_ptr[bytes_offset], i);758}759760if (!reflection_shader_stages.is_empty()) {761uint32_t stage_count = reflection_shader_stages.size();762memcpy(&bytes_ptr[bytes_offset], reflection_shader_stages.ptr(), stage_count * sizeof(RenderingDeviceCommons::ShaderStage));763bytes_offset += stage_count * sizeof(RenderingDeviceCommons::ShaderStage);764}765766for (uint32_t i = 0; i < shaders.size(); i++) {767const Shader &shader = shaders[i];768ShaderHeader &header = *(ShaderHeader *)(&bytes.ptr()[bytes_offset]);769header.shader_stage = shader.shader_stage;770header.code_compressed_size = uint32_t(shader.code_compressed_bytes.size());771header.code_compression_flags = shader.code_compression_flags;772header.code_decompressed_size = shader.code_decompressed_size;773bytes_offset += sizeof(ShaderHeader);774memcpy(&bytes.ptrw()[bytes_offset], shader.code_compressed_bytes.ptr(), shader.code_compressed_bytes.size());775bytes_offset = aligned_to(bytes_offset + shader.code_compressed_bytes.size(), alignment);776bytes_offset += _to_bytes_shader_extra_data(&bytes_ptr[bytes_offset], i);777}778779bytes_offset += _to_bytes_footer_extra_data(&bytes_ptr[bytes_offset]);780781ERR_FAIL_COND_V_MSG(bytes_offset != total_size, PackedByteArray(), "Amount of bytes written does not match the amount of bytes reserved for the container.");782return bytes;783}784785bool RenderingShaderContainer::compress_code(const uint8_t *p_decompressed_bytes, uint32_t p_decompressed_size, uint8_t *p_compressed_bytes, uint32_t *r_compressed_size, uint32_t *r_compressed_flags) const {786DEV_ASSERT(p_decompressed_bytes != nullptr);787DEV_ASSERT(p_decompressed_size > 0);788DEV_ASSERT(p_compressed_bytes != nullptr);789DEV_ASSERT(r_compressed_size != nullptr);790DEV_ASSERT(r_compressed_flags != nullptr);791792*r_compressed_flags = 0;793794PackedByteArray zstd_bytes;795const int64_t zstd_max_bytes = Compression::get_max_compressed_buffer_size(p_decompressed_size, Compression::MODE_ZSTD);796zstd_bytes.resize(zstd_max_bytes);797798const int64_t zstd_size = Compression::compress(zstd_bytes.ptrw(), p_decompressed_bytes, p_decompressed_size, Compression::MODE_ZSTD);799if (zstd_size > 0 && (uint32_t)(zstd_size) < p_decompressed_size) {800// Only choose Zstd if it results in actual compression.801memcpy(p_compressed_bytes, zstd_bytes.ptr(), zstd_size);802*r_compressed_size = zstd_size;803*r_compressed_flags |= COMPRESSION_FLAG_ZSTD;804} else {805// Just copy the input to the output directly.806memcpy(p_compressed_bytes, p_decompressed_bytes, p_decompressed_size);807*r_compressed_size = p_decompressed_size;808}809810return true;811}812813bool RenderingShaderContainer::decompress_code(const uint8_t *p_compressed_bytes, uint32_t p_compressed_size, uint32_t p_compressed_flags, uint8_t *p_decompressed_bytes, uint32_t p_decompressed_size) const {814DEV_ASSERT(p_compressed_bytes != nullptr);815DEV_ASSERT(p_compressed_size > 0);816DEV_ASSERT(p_decompressed_bytes != nullptr);817DEV_ASSERT(p_decompressed_size > 0);818819bool uses_zstd = p_compressed_flags & COMPRESSION_FLAG_ZSTD;820if (uses_zstd) {821if (!Compression::decompress(p_decompressed_bytes, p_decompressed_size, p_compressed_bytes, p_compressed_size, Compression::MODE_ZSTD)) {822ERR_FAIL_V_MSG(false, "Malformed zstd input for decompressing shader code.");823}824} else {825memcpy(p_decompressed_bytes, p_compressed_bytes, MIN(p_compressed_size, p_decompressed_size));826}827828return true;829}830831RenderingShaderContainer::RenderingShaderContainer() {}832833RenderingShaderContainer::~RenderingShaderContainer() {}834835836