Path: blob/master/servers/rendering/shader_compiler.cpp
20884 views
/**************************************************************************/1/* shader_compiler.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 "shader_compiler.h"3132#include "servers/rendering/rendering_server_globals.h"33#include "servers/rendering/shader_types.h"3435#define SL ShaderLanguage3637static String _mktab(int p_level) {38return String("\t").repeat(p_level);39}4041static String _typestr(SL::DataType p_type) {42String type = ShaderLanguage::get_datatype_name(p_type);43if (!RS::get_singleton()->is_low_end() && ShaderLanguage::is_sampler_type(p_type)) {44type = type.replace("sampler", "texture"); //we use textures instead of samplers in Vulkan GLSL45}46return type;47}4849static int _get_datatype_alignment(SL::DataType p_type) {50switch (p_type) {51case SL::TYPE_VOID:52return 0;53case SL::TYPE_BOOL:54return 4;55case SL::TYPE_BVEC2:56return 8;57case SL::TYPE_BVEC3:58return 16;59case SL::TYPE_BVEC4:60return 16;61case SL::TYPE_INT:62return 4;63case SL::TYPE_IVEC2:64return 8;65case SL::TYPE_IVEC3:66return 16;67case SL::TYPE_IVEC4:68return 16;69case SL::TYPE_UINT:70return 4;71case SL::TYPE_UVEC2:72return 8;73case SL::TYPE_UVEC3:74return 16;75case SL::TYPE_UVEC4:76return 16;77case SL::TYPE_FLOAT:78return 4;79case SL::TYPE_VEC2:80return 8;81case SL::TYPE_VEC3:82return 16;83case SL::TYPE_VEC4:84return 16;85case SL::TYPE_MAT2:86return 16;87case SL::TYPE_MAT3:88return 16;89case SL::TYPE_MAT4:90return 16;91case SL::TYPE_SAMPLER2D:92return 16;93case SL::TYPE_ISAMPLER2D:94return 16;95case SL::TYPE_USAMPLER2D:96return 16;97case SL::TYPE_SAMPLER2DARRAY:98return 16;99case SL::TYPE_ISAMPLER2DARRAY:100return 16;101case SL::TYPE_USAMPLER2DARRAY:102return 16;103case SL::TYPE_SAMPLER3D:104return 16;105case SL::TYPE_ISAMPLER3D:106return 16;107case SL::TYPE_USAMPLER3D:108return 16;109case SL::TYPE_SAMPLERCUBE:110return 16;111case SL::TYPE_SAMPLERCUBEARRAY:112return 16;113case SL::TYPE_SAMPLEREXT:114return 16;115case SL::TYPE_STRUCT:116return 0;117case SL::TYPE_MAX: {118ERR_FAIL_V(0);119}120}121122ERR_FAIL_V(0);123}124125static String _interpstr(SL::DataInterpolation p_interp) {126switch (p_interp) {127case SL::INTERPOLATION_FLAT:128return "flat ";129case SL::INTERPOLATION_SMOOTH:130return "";131case SL::INTERPOLATION_DEFAULT:132return "";133}134return "";135}136137static String _prestr(SL::DataPrecision p_pres, bool p_force_highp = false) {138switch (p_pres) {139case SL::PRECISION_LOWP:140return "lowp ";141case SL::PRECISION_MEDIUMP:142return "mediump ";143case SL::PRECISION_HIGHP:144return "highp ";145case SL::PRECISION_DEFAULT:146return p_force_highp ? "highp " : "";147}148return "";149}150151static String _constr(bool p_is_const) {152if (p_is_const) {153return "const ";154}155return "";156}157158static String _qualstr(SL::ArgumentQualifier p_qual) {159switch (p_qual) {160case SL::ARGUMENT_QUALIFIER_IN:161return "";162case SL::ARGUMENT_QUALIFIER_OUT:163return "out ";164case SL::ARGUMENT_QUALIFIER_INOUT:165return "inout ";166}167return "";168}169170static String _opstr(SL::Operator p_op) {171return SL::get_operator_text(p_op);172}173174static String _mkid(const String &p_id) {175String id = "m_" + p_id.replace("__", "_dus_");176return id.replace("__", "_dus_"); //doubleunderscore is reserved in glsl177}178179static String f2sp0(float p_float) {180String num = rtos(p_float);181if (!num.contains_char('.') && !num.contains_char('e')) {182num += ".0";183}184return num;185}186187static String get_constant_text(SL::DataType p_type, const Vector<SL::Scalar> &p_values) {188switch (p_type) {189case SL::TYPE_BOOL:190return p_values[0].boolean ? "true" : "false";191case SL::TYPE_BVEC2:192case SL::TYPE_BVEC3:193case SL::TYPE_BVEC4: {194String text = "bvec" + itos(p_type - SL::TYPE_BOOL + 1) + "(";195for (int i = 0; i < p_values.size(); i++) {196if (i > 0) {197text += ",";198}199200text += p_values[i].boolean ? "true" : "false";201}202text += ")";203return text;204}205206case SL::TYPE_INT:207return itos(p_values[0].sint);208case SL::TYPE_IVEC2:209case SL::TYPE_IVEC3:210case SL::TYPE_IVEC4: {211String text = "ivec" + itos(p_type - SL::TYPE_INT + 1) + "(";212for (int i = 0; i < p_values.size(); i++) {213if (i > 0) {214text += ",";215}216217text += itos(p_values[i].sint);218}219text += ")";220return text;221222} break;223case SL::TYPE_UINT:224return itos(p_values[0].uint) + "u";225case SL::TYPE_UVEC2:226case SL::TYPE_UVEC3:227case SL::TYPE_UVEC4: {228String text = "uvec" + itos(p_type - SL::TYPE_UINT + 1) + "(";229for (int i = 0; i < p_values.size(); i++) {230if (i > 0) {231text += ",";232}233234text += itos(p_values[i].uint) + "u";235}236text += ")";237return text;238} break;239case SL::TYPE_FLOAT:240return f2sp0(p_values[0].real);241case SL::TYPE_VEC2:242case SL::TYPE_VEC3:243case SL::TYPE_VEC4: {244String text = "vec" + itos(p_type - SL::TYPE_FLOAT + 1) + "(";245for (int i = 0; i < p_values.size(); i++) {246if (i > 0) {247text += ",";248}249250text += f2sp0(p_values[i].real);251}252text += ")";253return text;254255} break;256case SL::TYPE_MAT2:257case SL::TYPE_MAT3:258case SL::TYPE_MAT4: {259String text = "mat" + itos(p_type - SL::TYPE_MAT2 + 2) + "(";260for (int i = 0; i < p_values.size(); i++) {261if (i > 0) {262text += ",";263}264265text += f2sp0(p_values[i].real);266}267text += ")";268return text;269270} break;271default:272ERR_FAIL_V(String());273}274}275276String ShaderCompiler::_get_sampler_name(ShaderLanguage::TextureFilter p_filter, ShaderLanguage::TextureRepeat p_repeat) {277if (p_filter == ShaderLanguage::FILTER_DEFAULT) {278ERR_FAIL_COND_V(actions.default_filter == ShaderLanguage::FILTER_DEFAULT, String());279p_filter = actions.default_filter;280}281if (p_repeat == ShaderLanguage::REPEAT_DEFAULT) {282ERR_FAIL_COND_V(actions.default_repeat == ShaderLanguage::REPEAT_DEFAULT, String());283p_repeat = actions.default_repeat;284}285constexpr const char *name_mapping[] = {286"SAMPLER_NEAREST_CLAMP",287"SAMPLER_LINEAR_CLAMP",288"SAMPLER_NEAREST_WITH_MIPMAPS_CLAMP",289"SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP",290"SAMPLER_NEAREST_WITH_MIPMAPS_ANISOTROPIC_CLAMP",291"SAMPLER_LINEAR_WITH_MIPMAPS_ANISOTROPIC_CLAMP",292"SAMPLER_NEAREST_REPEAT",293"SAMPLER_LINEAR_REPEAT",294"SAMPLER_NEAREST_WITH_MIPMAPS_REPEAT",295"SAMPLER_LINEAR_WITH_MIPMAPS_REPEAT",296"SAMPLER_NEAREST_WITH_MIPMAPS_ANISOTROPIC_REPEAT",297"SAMPLER_LINEAR_WITH_MIPMAPS_ANISOTROPIC_REPEAT"298};299return String(name_mapping[p_filter + (p_repeat == ShaderLanguage::REPEAT_ENABLE ? ShaderLanguage::FILTER_DEFAULT : 0)]);300}301302void ShaderCompiler::_dump_function_deps(const SL::ShaderNode *p_node, const StringName &p_for_func, const HashMap<StringName, String> &p_func_code, String &r_to_add, HashSet<StringName> &added) {303int fidx = -1;304305for (int i = 0; i < p_node->vfunctions.size(); i++) {306if (p_node->vfunctions[i].name == p_for_func) {307fidx = i;308break;309}310}311312ERR_FAIL_COND(fidx == -1);313314Vector<StringName> uses_functions;315316for (const StringName &E : p_node->vfunctions[fidx].uses_function) {317uses_functions.push_back(E);318}319uses_functions.sort_custom<StringName::AlphCompare>(); //ensure order is deterministic so the same shader is always produced320321for (int k = 0; k < uses_functions.size(); k++) {322if (added.has(uses_functions[k])) {323continue; //was added already324}325326_dump_function_deps(p_node, uses_functions[k], p_func_code, r_to_add, added);327328SL::FunctionNode *fnode = nullptr;329330for (int i = 0; i < p_node->vfunctions.size(); i++) {331if (p_node->vfunctions[i].name == uses_functions[k]) {332fnode = p_node->vfunctions[i].function;333break;334}335}336337ERR_FAIL_NULL(fnode);338339r_to_add += "\n";340341String header;342if (fnode->return_type == SL::TYPE_STRUCT) {343header = _mkid(fnode->return_struct_name);344} else {345header = _typestr(fnode->return_type);346}347348if (fnode->return_array_size > 0) {349header += "[";350header += itos(fnode->return_array_size);351header += "]";352}353354header += " ";355header += _mkid(fnode->rname);356header += "(";357358for (int i = 0; i < fnode->arguments.size(); i++) {359if (i > 0) {360header += ", ";361}362header += _constr(fnode->arguments[i].is_const);363if (fnode->arguments[i].type == SL::TYPE_STRUCT) {364header += _qualstr(fnode->arguments[i].qualifier) + _mkid(fnode->arguments[i].struct_name) + " " + _mkid(fnode->arguments[i].name);365} else {366header += _qualstr(fnode->arguments[i].qualifier) + _prestr(fnode->arguments[i].precision) + _typestr(fnode->arguments[i].type) + " " + _mkid(fnode->arguments[i].name);367}368if (fnode->arguments[i].array_size > 0) {369header += "[";370header += itos(fnode->arguments[i].array_size);371header += "]";372}373}374375header += ")\n";376r_to_add += header;377r_to_add += p_func_code[uses_functions[k]];378379added.insert(uses_functions[k]);380}381}382383static String _get_global_shader_uniform_from_type_and_index(const String &p_buffer, const String &p_index, ShaderLanguage::DataType p_type) {384switch (p_type) {385case ShaderLanguage::TYPE_BOOL: {386return "bool(floatBitsToUint(" + p_buffer + "[" + p_index + "].x))";387}388case ShaderLanguage::TYPE_BVEC2: {389return "bvec2(floatBitsToUint(" + p_buffer + "[" + p_index + "].xy))";390}391case ShaderLanguage::TYPE_BVEC3: {392return "bvec3(floatBitsToUint(" + p_buffer + "[" + p_index + "].xyz))";393}394case ShaderLanguage::TYPE_BVEC4: {395return "bvec4(floatBitsToUint(" + p_buffer + "[" + p_index + "].xyzw))";396}397case ShaderLanguage::TYPE_INT: {398return "floatBitsToInt(" + p_buffer + "[" + p_index + "].x)";399}400case ShaderLanguage::TYPE_IVEC2: {401return "floatBitsToInt(" + p_buffer + "[" + p_index + "].xy)";402}403case ShaderLanguage::TYPE_IVEC3: {404return "floatBitsToInt(" + p_buffer + "[" + p_index + "].xyz)";405}406case ShaderLanguage::TYPE_IVEC4: {407return "floatBitsToInt(" + p_buffer + "[" + p_index + "].xyzw)";408}409case ShaderLanguage::TYPE_UINT: {410return "floatBitsToUint(" + p_buffer + "[" + p_index + "].x)";411}412case ShaderLanguage::TYPE_UVEC2: {413return "floatBitsToUint(" + p_buffer + "[" + p_index + "].xy)";414}415case ShaderLanguage::TYPE_UVEC3: {416return "floatBitsToUint(" + p_buffer + "[" + p_index + "].xyz)";417}418case ShaderLanguage::TYPE_UVEC4: {419return "floatBitsToUint(" + p_buffer + "[" + p_index + "].xyzw)";420}421case ShaderLanguage::TYPE_FLOAT: {422return "(" + p_buffer + "[" + p_index + "].x)";423}424case ShaderLanguage::TYPE_VEC2: {425return "(" + p_buffer + "[" + p_index + "].xy)";426}427case ShaderLanguage::TYPE_VEC3: {428return "(" + p_buffer + "[" + p_index + "].xyz)";429}430case ShaderLanguage::TYPE_VEC4: {431return "(" + p_buffer + "[" + p_index + "].xyzw)";432}433case ShaderLanguage::TYPE_MAT2: {434return "mat2(" + p_buffer + "[" + p_index + "].xy," + p_buffer + "[" + p_index + "+1u].xy)";435}436case ShaderLanguage::TYPE_MAT3: {437return "mat3(" + p_buffer + "[" + p_index + "].xyz," + p_buffer + "[" + p_index + "+1u].xyz," + p_buffer + "[" + p_index + "+2u].xyz)";438}439case ShaderLanguage::TYPE_MAT4: {440return "mat4(" + p_buffer + "[" + p_index + "].xyzw," + p_buffer + "[" + p_index + "+1u].xyzw," + p_buffer + "[" + p_index + "+2u].xyzw," + p_buffer + "[" + p_index + "+3u].xyzw)";441}442default: {443ERR_FAIL_V("void");444}445}446}447448String ShaderCompiler::_dump_node_code(const SL::Node *p_node, int p_level, GeneratedCode &r_gen_code, IdentifierActions &p_actions, const DefaultIdentifierActions &p_default_actions, bool p_assigning, bool p_use_scope) {449String code;450451switch (p_node->type) {452case SL::Node::NODE_TYPE_SHADER: {453SL::ShaderNode *pnode = (SL::ShaderNode *)p_node;454455// Render modes.456457for (int i = 0; i < pnode->render_modes.size(); i++) {458if (p_default_actions.render_mode_defines.has(pnode->render_modes[i]) && !used_rmode_defines.has(pnode->render_modes[i])) {459r_gen_code.defines.push_back(p_default_actions.render_mode_defines[pnode->render_modes[i]]);460used_rmode_defines.insert(pnode->render_modes[i]);461}462463if (p_actions.render_mode_flags.has(pnode->render_modes[i])) {464*p_actions.render_mode_flags[pnode->render_modes[i]] = true;465}466467if (p_actions.render_mode_values.has(pnode->render_modes[i])) {468Pair<int *, int> &p = p_actions.render_mode_values[pnode->render_modes[i]];469*p.first = p.second;470}471}472473// Stencil modes.474475for (int i = 0; i < pnode->stencil_modes.size(); i++) {476if (p_actions.stencil_mode_values.has(pnode->stencil_modes[i])) {477Pair<int *, int> &p = p_actions.stencil_mode_values[pnode->stencil_modes[i]];478*p.first = p.second;479}480}481482// Stencil reference value.483484if (p_actions.stencil_reference && pnode->stencil_reference != -1) {485*p_actions.stencil_reference = pnode->stencil_reference;486}487488// structs489490for (int i = 0; i < pnode->vstructs.size(); i++) {491SL::StructNode *st = pnode->vstructs[i].shader_struct;492String struct_code;493494struct_code += "struct ";495struct_code += _mkid(pnode->vstructs[i].name);496struct_code += " ";497struct_code += "{\n";498for (SL::MemberNode *m : st->members) {499if (m->datatype == SL::TYPE_STRUCT) {500struct_code += _mkid(m->struct_name);501} else {502struct_code += _prestr(m->precision);503struct_code += _typestr(m->datatype);504}505struct_code += " ";506struct_code += _mkid(m->name);507if (m->array_size > 0) {508struct_code += "[";509struct_code += itos(m->array_size);510struct_code += "]";511}512struct_code += ";\n";513}514struct_code += "}";515struct_code += ";\n";516517for (int j = 0; j < STAGE_MAX; j++) {518r_gen_code.stage_globals[j] += struct_code;519}520}521522int max_texture_uniforms = 0;523int max_uniforms = 0;524525for (const KeyValue<StringName, SL::ShaderNode::Uniform> &E : pnode->uniforms) {526if (SL::is_sampler_type(E.value.type)) {527if (E.value.hint == SL::ShaderNode::Uniform::HINT_SCREEN_TEXTURE ||528E.value.hint == SL::ShaderNode::Uniform::HINT_NORMAL_ROUGHNESS_TEXTURE ||529E.value.hint == SL::ShaderNode::Uniform::HINT_DEPTH_TEXTURE ||530E.value.hint == SL::ShaderNode::Uniform::HINT_BLIT_SOURCE0 ||531E.value.hint == SL::ShaderNode::Uniform::HINT_BLIT_SOURCE1 ||532E.value.hint == SL::ShaderNode::Uniform::HINT_BLIT_SOURCE2 ||533E.value.hint == SL::ShaderNode::Uniform::HINT_BLIT_SOURCE3) {534continue; // Don't create uniforms in the generated code for these.535}536max_texture_uniforms++;537} else {538if (E.value.scope == SL::ShaderNode::Uniform::SCOPE_INSTANCE) {539continue; // Instances are indexed directly, don't need index uniforms.540}541542max_uniforms++;543}544}545546r_gen_code.texture_uniforms.resize(max_texture_uniforms);547548Vector<int> uniform_sizes;549Vector<int> uniform_alignments;550Vector<StringName> uniform_defines;551uniform_sizes.resize(max_uniforms);552uniform_alignments.resize(max_uniforms);553uniform_defines.resize(max_uniforms);554bool uses_uniforms = false;555556Vector<StringName> uniform_names;557558for (const KeyValue<StringName, SL::ShaderNode::Uniform> &E : pnode->uniforms) {559uniform_names.push_back(E.key);560}561562uniform_names.sort_custom<StringName::AlphCompare>(); //ensure order is deterministic so the same shader is always produced563564for (int k = 0; k < uniform_names.size(); k++) {565const StringName &uniform_name = uniform_names[k];566const SL::ShaderNode::Uniform &uniform = pnode->uniforms[uniform_name];567568String ucode;569570if (uniform.scope == SL::ShaderNode::Uniform::SCOPE_INSTANCE) {571//insert, but don't generate any code.572p_actions.uniforms->insert(uniform_name, uniform);573continue; // Instances are indexed directly, don't need index uniforms.574}575576if (uniform.hint == SL::ShaderNode::Uniform::HINT_SCREEN_TEXTURE ||577uniform.hint == SL::ShaderNode::Uniform::HINT_NORMAL_ROUGHNESS_TEXTURE ||578uniform.hint == SL::ShaderNode::Uniform::HINT_DEPTH_TEXTURE ||579uniform.hint == SL::ShaderNode::Uniform::HINT_BLIT_SOURCE0 ||580uniform.hint == SL::ShaderNode::Uniform::HINT_BLIT_SOURCE1 ||581uniform.hint == SL::ShaderNode::Uniform::HINT_BLIT_SOURCE2 ||582uniform.hint == SL::ShaderNode::Uniform::HINT_BLIT_SOURCE3) {583continue; // Don't create uniforms in the generated code for these.584}585586if (SL::is_sampler_type(uniform.type)) {587// Texture layouts are different for OpenGL GLSL and Vulkan GLSL588if (!RS::get_singleton()->is_low_end()) {589ucode = "layout(set = " + itos(actions.texture_layout_set) + ", binding = " + itos(actions.base_texture_binding_index + uniform.texture_binding) + ") ";590}591ucode += "uniform ";592}593594bool is_buffer_global = !SL::is_sampler_type(uniform.type) && uniform.scope == SL::ShaderNode::Uniform::SCOPE_GLOBAL;595596if (is_buffer_global) {597//this is an integer to index the global table598ucode += _typestr(ShaderLanguage::TYPE_UINT);599} else {600ucode += _prestr(uniform.precision, ShaderLanguage::is_float_type(uniform.type));601ucode += _typestr(uniform.type);602}603604ucode += " " + _mkid(uniform_name);605if (uniform.array_size > 0) {606ucode += "[";607ucode += itos(uniform.array_size);608ucode += "]";609}610ucode += ";\n";611if (SL::is_sampler_type(uniform.type)) {612for (int j = 0; j < STAGE_MAX; j++) {613r_gen_code.stage_globals[j] += ucode;614}615616GeneratedCode::Texture texture;617texture.name = uniform_name;618texture.hint = uniform.hint;619texture.type = uniform.type;620texture.use_color = uniform.use_color;621texture.filter = uniform.filter;622texture.repeat = uniform.repeat;623texture.global = uniform.scope == ShaderLanguage::ShaderNode::Uniform::SCOPE_GLOBAL;624texture.array_size = uniform.array_size;625if (texture.global) {626r_gen_code.uses_global_textures = true;627}628629r_gen_code.texture_uniforms.write[uniform.texture_order] = texture;630} else {631if (!uses_uniforms) {632uses_uniforms = true;633}634uniform_defines.write[uniform.order] = ucode;635if (is_buffer_global) {636//globals are indices into the global table637uniform_sizes.write[uniform.order] = ShaderLanguage::get_datatype_size(ShaderLanguage::TYPE_UINT);638uniform_alignments.write[uniform.order] = _get_datatype_alignment(ShaderLanguage::TYPE_UINT);639} else {640// The following code enforces a 16-byte alignment of uniform arrays.641if (uniform.array_size > 0) {642int size = ShaderLanguage::get_datatype_size(uniform.type) * uniform.array_size;643int m = (16 * uniform.array_size);644if ((size % m) != 0) {645size += m - (size % m);646}647uniform_sizes.write[uniform.order] = size;648uniform_alignments.write[uniform.order] = 16;649} else {650uniform_sizes.write[uniform.order] = ShaderLanguage::get_datatype_size(uniform.type);651uniform_alignments.write[uniform.order] = _get_datatype_alignment(uniform.type);652}653}654}655656p_actions.uniforms->insert(uniform_name, uniform);657}658659for (int i = 0; i < max_uniforms; i++) {660r_gen_code.uniforms += uniform_defines[i];661}662663// add up664int offset = 0;665for (int i = 0; i < uniform_sizes.size(); i++) {666int align = offset % uniform_alignments[i];667668if (align != 0) {669offset += uniform_alignments[i] - align;670}671672r_gen_code.uniform_offsets.push_back(offset);673674offset += uniform_sizes[i];675}676677r_gen_code.uniform_total_size = offset;678679if (r_gen_code.uniform_total_size % 16 != 0) { //UBO sizes must be multiples of 16680r_gen_code.uniform_total_size += 16 - (r_gen_code.uniform_total_size % 16);681}682683uint32_t index = p_default_actions.base_varying_index;684685List<Pair<StringName, SL::ShaderNode::Varying>> var_frag_to_light;686687Vector<StringName> varying_names;688689for (const KeyValue<StringName, SL::ShaderNode::Varying> &E : pnode->varyings) {690varying_names.push_back(E.key);691}692693varying_names.sort_custom<StringName::AlphCompare>(); //ensure order is deterministic so the same shader is always produced694695for (int k = 0; k < varying_names.size(); k++) {696const StringName &varying_name = varying_names[k];697const SL::ShaderNode::Varying &varying = pnode->varyings[varying_name];698699if (varying.stage == SL::ShaderNode::Varying::STAGE_FRAGMENT) {700var_frag_to_light.push_back(Pair<StringName, SL::ShaderNode::Varying>(varying_name, varying));701fragment_varyings.insert(varying_name);702continue;703}704if (varying.type < SL::TYPE_INT) {705continue; // Ignore boolean types to prevent crashing (if varying is just declared).706}707708String vcode;709String interp_mode = _interpstr(varying.interpolation);710vcode += _prestr(varying.precision, ShaderLanguage::is_float_type(varying.type));711vcode += _typestr(varying.type);712vcode += " " + _mkid(varying_name);713uint32_t inc = varying.get_size();714715if (varying.array_size > 0) {716vcode += "[";717vcode += itos(varying.array_size);718vcode += "]";719}720721vcode += ";\n";722// GLSL ES 3.0 does not allow layout qualifiers for varyings723if (!RS::get_singleton()->is_low_end()) {724r_gen_code.stage_globals[STAGE_VERTEX] += "layout(location=" + itos(index) + ") ";725r_gen_code.stage_globals[STAGE_FRAGMENT] += "layout(location=" + itos(index) + ") ";726}727r_gen_code.stage_globals[STAGE_VERTEX] += interp_mode + "out " + vcode;728r_gen_code.stage_globals[STAGE_FRAGMENT] += interp_mode + "in " + vcode;729730index += inc;731}732733if (var_frag_to_light.size() > 0) {734String gcode = "\n\nstruct {\n";735for (const Pair<StringName, SL::ShaderNode::Varying> &E : var_frag_to_light) {736gcode += "\t" + _prestr(E.second.precision) + _typestr(E.second.type) + " " + _mkid(E.first);737if (E.second.array_size > 0) {738gcode += "[";739gcode += itos(E.second.array_size);740gcode += "]";741}742gcode += ";\n";743}744gcode += "} frag_to_light;\n";745r_gen_code.stage_globals[STAGE_FRAGMENT] += gcode;746}747748for (int i = 0; i < pnode->vconstants.size(); i++) {749const SL::ShaderNode::Constant &cnode = pnode->vconstants[i];750String gcode;751gcode += _constr(true);752gcode += _prestr(cnode.precision, ShaderLanguage::is_float_type(cnode.type));753if (cnode.type == SL::TYPE_STRUCT) {754gcode += _mkid(cnode.struct_name);755} else {756gcode += _typestr(cnode.type);757}758gcode += " " + _mkid(String(cnode.name));759if (cnode.array_size > 0) {760gcode += "[";761gcode += itos(cnode.array_size);762gcode += "]";763}764gcode += "=";765gcode += _dump_node_code(cnode.initializer, p_level, r_gen_code, p_actions, p_default_actions, p_assigning);766gcode += ";\n";767for (int j = 0; j < STAGE_MAX; j++) {768r_gen_code.stage_globals[j] += gcode;769}770}771772HashMap<StringName, String> function_code;773774//code for functions775for (int i = 0; i < pnode->vfunctions.size(); i++) {776SL::FunctionNode *fnode = pnode->vfunctions[i].function;777function = fnode;778current_func_name = fnode->name;779function_code[fnode->name] = _dump_node_code(fnode->body, p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning);780function = nullptr;781}782783//place functions in actual code784785HashSet<StringName> added_funcs_per_stage[STAGE_MAX];786787for (int i = 0; i < pnode->vfunctions.size(); i++) {788SL::FunctionNode *fnode = pnode->vfunctions[i].function;789790function = fnode;791792current_func_name = fnode->name;793794if (p_actions.entry_point_stages.has(fnode->name)) {795Stage stage = p_actions.entry_point_stages[fnode->name];796_dump_function_deps(pnode, fnode->name, function_code, r_gen_code.stage_globals[stage], added_funcs_per_stage[stage]);797r_gen_code.code[fnode->name] = function_code[fnode->name];798}799800function = nullptr;801}802803//code+=dump_node_code(pnode->body,p_level);804} break;805case SL::Node::NODE_TYPE_STRUCT: {806} break;807case SL::Node::NODE_TYPE_FUNCTION: {808} break;809case SL::Node::NODE_TYPE_BLOCK: {810SL::BlockNode *bnode = (SL::BlockNode *)p_node;811812//variables813if (!bnode->single_statement) {814code += _mktab(p_level - 1) + "{\n";815}816817int i = 0;818for (List<ShaderLanguage::Node *>::ConstIterator itr = bnode->statements.begin(); itr != bnode->statements.end(); ++itr, ++i) {819String scode = _dump_node_code(*itr, p_level, r_gen_code, p_actions, p_default_actions, p_assigning);820821if ((*itr)->type == SL::Node::NODE_TYPE_CONTROL_FLOW || bnode->single_statement) {822code += scode; //use directly823if (bnode->use_comma_between_statements && i + 1 < bnode->statements.size()) {824code += ",";825}826} else {827code += _mktab(p_level) + scode + ";\n";828}829}830if (!bnode->single_statement) {831code += _mktab(p_level - 1) + "}\n";832}833834} break;835case SL::Node::NODE_TYPE_VARIABLE_DECLARATION: {836SL::VariableDeclarationNode *vdnode = (SL::VariableDeclarationNode *)p_node;837838String declaration;839declaration += _constr(vdnode->is_const);840if (vdnode->datatype == SL::TYPE_STRUCT) {841declaration += _mkid(vdnode->struct_name);842} else {843declaration += _prestr(vdnode->precision) + _typestr(vdnode->datatype);844}845declaration += " ";846for (int i = 0; i < vdnode->declarations.size(); i++) {847bool is_array = vdnode->declarations[i].size > 0;848if (i > 0) {849declaration += ",";850}851declaration += _mkid(vdnode->declarations[i].name);852if (is_array) {853declaration += "[";854if (vdnode->declarations[i].size_expression != nullptr) {855declaration += _dump_node_code(vdnode->declarations[i].size_expression, p_level, r_gen_code, p_actions, p_default_actions, p_assigning);856} else {857declaration += itos(vdnode->declarations[i].size);858}859declaration += "]";860}861862if (!is_array || vdnode->declarations[i].single_expression) {863if (!vdnode->declarations[i].initializer.is_empty()) {864declaration += "=";865declaration += _dump_node_code(vdnode->declarations[i].initializer[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);866}867} else {868int size = vdnode->declarations[i].initializer.size();869if (size > 0) {870declaration += "=";871if (vdnode->datatype == SL::TYPE_STRUCT) {872declaration += _mkid(vdnode->struct_name);873} else {874declaration += _typestr(vdnode->datatype);875}876declaration += "[";877declaration += itos(size);878declaration += "]";879declaration += "(";880for (int j = 0; j < size; j++) {881if (j > 0) {882declaration += ",";883}884declaration += _dump_node_code(vdnode->declarations[i].initializer[j], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);885}886declaration += ")";887}888}889}890891code += declaration;892} break;893case SL::Node::NODE_TYPE_VARIABLE: {894SL::VariableNode *vnode = (SL::VariableNode *)p_node;895bool use_fragment_varying = false;896897if (!vnode->is_local && !(p_actions.entry_point_stages.has(current_func_name) && p_actions.entry_point_stages[current_func_name] == STAGE_VERTEX)) {898if (p_assigning) {899if (shader->varyings.has(vnode->name)) {900use_fragment_varying = true;901}902} else {903if (fragment_varyings.has(vnode->name)) {904use_fragment_varying = true;905}906}907}908909if (p_assigning && p_actions.write_flag_pointers.has(vnode->name)) {910*p_actions.write_flag_pointers[vnode->name] = true;911}912913if (p_default_actions.usage_defines.has(vnode->name) && !used_name_defines.has(vnode->name)) {914String define = p_default_actions.usage_defines[vnode->name];915if (define.begins_with("@")) {916define = p_default_actions.usage_defines[define.substr(1)];917}918r_gen_code.defines.push_back(define);919used_name_defines.insert(vnode->name);920}921922if (p_actions.usage_flag_pointers.has(vnode->name) && !used_flag_pointers.has(vnode->name)) {923*p_actions.usage_flag_pointers[vnode->name] = true;924used_flag_pointers.insert(vnode->name);925}926927if (p_default_actions.renames.has(vnode->name)) {928code = p_default_actions.renames[vnode->name];929} else {930if (shader->uniforms.has(vnode->name)) {931//its a uniform!932const ShaderLanguage::ShaderNode::Uniform &u = shader->uniforms[vnode->name];933if (u.is_texture()) {934StringName name;935if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_SCREEN_TEXTURE) {936name = "color_buffer";937if (u.filter >= ShaderLanguage::FILTER_NEAREST_MIPMAP) {938r_gen_code.uses_screen_texture_mipmaps = true;939}940r_gen_code.uses_screen_texture = true;941} else if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL_ROUGHNESS_TEXTURE) {942name = "normal_roughness_buffer";943r_gen_code.uses_normal_roughness_texture = true;944} else if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_DEPTH_TEXTURE) {945name = "depth_buffer";946r_gen_code.uses_depth_texture = true;947} else if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_BLIT_SOURCE0) {948name = "source0";949} else if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_BLIT_SOURCE1) {950name = "source1";951} else if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_BLIT_SOURCE2) {952name = "source2";953} else if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_BLIT_SOURCE3) {954name = "source3";955} else {956name = _mkid(vnode->name); //texture, use as is957}958959code = name;960} else {961//a scalar or vector962if (u.scope == ShaderLanguage::ShaderNode::Uniform::SCOPE_GLOBAL) {963code = actions.base_uniform_string + _mkid(vnode->name); //texture, use as is964//global variable, this means the code points to an index to the global table965code = _get_global_shader_uniform_from_type_and_index(p_default_actions.global_buffer_array_variable, code, u.type);966} else if (u.scope == ShaderLanguage::ShaderNode::Uniform::SCOPE_INSTANCE) {967//instance variable, index it as such968code = "(" + p_default_actions.instance_uniform_index_variable + "+" + itos(u.instance_index) + "u)";969code = _get_global_shader_uniform_from_type_and_index(p_default_actions.global_buffer_array_variable, code, u.type);970} else {971//regular uniform, index from UBO972code = actions.base_uniform_string + _mkid(vnode->name);973}974}975976} else {977if (use_fragment_varying) {978code = "frag_to_light.";979}980code += _mkid(vnode->name); //its something else (local var most likely) use as is981}982}983984if (vnode->name == time_name) {985if (p_actions.entry_point_stages.has(current_func_name) && p_actions.entry_point_stages[current_func_name] == STAGE_VERTEX) {986r_gen_code.uses_vertex_time = true;987}988if (p_actions.entry_point_stages.has(current_func_name) && p_actions.entry_point_stages[current_func_name] == STAGE_FRAGMENT) {989r_gen_code.uses_fragment_time = true;990}991}992993} break;994case SL::Node::NODE_TYPE_ARRAY_CONSTRUCT: {995SL::ArrayConstructNode *acnode = (SL::ArrayConstructNode *)p_node;996int sz = acnode->initializer.size();997if (acnode->datatype == SL::TYPE_STRUCT) {998code += _mkid(acnode->struct_name);999} else {1000code += _typestr(acnode->datatype);1001}1002code += "[";1003code += itos(acnode->initializer.size());1004code += "]";1005code += "(";1006for (int i = 0; i < sz; i++) {1007code += _dump_node_code(acnode->initializer[i], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);1008if (i != sz - 1) {1009code += ", ";1010}1011}1012code += ")";1013} break;1014case SL::Node::NODE_TYPE_ARRAY: {1015SL::ArrayNode *anode = (SL::ArrayNode *)p_node;1016bool use_fragment_varying = false;10171018if (!anode->is_local && !(p_actions.entry_point_stages.has(current_func_name) && p_actions.entry_point_stages[current_func_name] == STAGE_VERTEX)) {1019if (anode->assign_expression != nullptr && shader->varyings.has(anode->name)) {1020use_fragment_varying = true;1021} else {1022if (p_assigning) {1023if (shader->varyings.has(anode->name)) {1024use_fragment_varying = true;1025}1026} else {1027if (fragment_varyings.has(anode->name)) {1028use_fragment_varying = true;1029}1030}1031}1032}10331034if (p_assigning && p_actions.write_flag_pointers.has(anode->name)) {1035*p_actions.write_flag_pointers[anode->name] = true;1036}10371038if (p_default_actions.usage_defines.has(anode->name) && !used_name_defines.has(anode->name)) {1039String define = p_default_actions.usage_defines[anode->name];1040if (define.begins_with("@")) {1041define = p_default_actions.usage_defines[define.substr(1)];1042}1043r_gen_code.defines.push_back(define);1044used_name_defines.insert(anode->name);1045}10461047if (p_actions.usage_flag_pointers.has(anode->name) && !used_flag_pointers.has(anode->name)) {1048*p_actions.usage_flag_pointers[anode->name] = true;1049used_flag_pointers.insert(anode->name);1050}10511052if (p_default_actions.renames.has(anode->name)) {1053code = p_default_actions.renames[anode->name];1054} else {1055if (shader->uniforms.has(anode->name)) {1056//its a uniform!1057const ShaderLanguage::ShaderNode::Uniform &u = shader->uniforms[anode->name];1058if (u.is_texture()) {1059code = _mkid(anode->name); //texture, use as is1060} else {1061//a scalar or vector1062if (u.scope == ShaderLanguage::ShaderNode::Uniform::SCOPE_GLOBAL) {1063code = actions.base_uniform_string + _mkid(anode->name); //texture, use as is1064//global variable, this means the code points to an index to the global table1065code = _get_global_shader_uniform_from_type_and_index(p_default_actions.global_buffer_array_variable, code, u.type);1066} else if (u.scope == ShaderLanguage::ShaderNode::Uniform::SCOPE_INSTANCE) {1067//instance variable, index it as such1068code = "(" + p_default_actions.instance_uniform_index_variable + "+" + itos(u.instance_index) + "u)";1069code = _get_global_shader_uniform_from_type_and_index(p_default_actions.global_buffer_array_variable, code, u.type);1070} else {1071//regular uniform, index from UBO1072code = actions.base_uniform_string + _mkid(anode->name);1073}1074}1075} else {1076if (use_fragment_varying) {1077code = "frag_to_light.";1078}1079code += _mkid(anode->name);1080}1081}10821083if (anode->call_expression != nullptr) {1084code += ".";1085code += _dump_node_code(anode->call_expression, p_level, r_gen_code, p_actions, p_default_actions, p_assigning, false);1086} else if (anode->index_expression != nullptr) {1087code += "[";1088code += _dump_node_code(anode->index_expression, p_level, r_gen_code, p_actions, p_default_actions, p_assigning);1089code += "]";1090} else if (anode->assign_expression != nullptr) {1091code += "=";1092code += _dump_node_code(anode->assign_expression, p_level, r_gen_code, p_actions, p_default_actions, true, false);1093}10941095if (anode->name == time_name) {1096if (p_actions.entry_point_stages.has(current_func_name) && p_actions.entry_point_stages[current_func_name] == STAGE_VERTEX) {1097r_gen_code.uses_vertex_time = true;1098}1099if (p_actions.entry_point_stages.has(current_func_name) && p_actions.entry_point_stages[current_func_name] == STAGE_FRAGMENT) {1100r_gen_code.uses_fragment_time = true;1101}1102}11031104} break;1105case SL::Node::NODE_TYPE_CONSTANT: {1106SL::ConstantNode *cnode = (SL::ConstantNode *)p_node;11071108if (cnode->array_size == 0) {1109return get_constant_text(cnode->datatype, cnode->values);1110} else {1111if (cnode->get_datatype() == SL::TYPE_STRUCT) {1112code += _mkid(cnode->struct_name);1113} else {1114code += _typestr(cnode->datatype);1115}1116code += "[";1117code += itos(cnode->array_size);1118code += "]";1119code += "(";1120for (int i = 0; i < cnode->array_size; i++) {1121if (i > 0) {1122code += ",";1123} else {1124code += "";1125}1126code += _dump_node_code(cnode->array_declarations[0].initializer[i], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);1127}1128code += ")";1129}11301131} break;1132case SL::Node::NODE_TYPE_OPERATOR: {1133SL::OperatorNode *onode = (SL::OperatorNode *)p_node;11341135switch (onode->op) {1136case SL::OP_ASSIGN:1137case SL::OP_ASSIGN_ADD:1138case SL::OP_ASSIGN_SUB:1139case SL::OP_ASSIGN_MUL:1140case SL::OP_ASSIGN_DIV:1141case SL::OP_ASSIGN_SHIFT_LEFT:1142case SL::OP_ASSIGN_SHIFT_RIGHT:1143case SL::OP_ASSIGN_MOD:1144case SL::OP_ASSIGN_BIT_AND:1145case SL::OP_ASSIGN_BIT_OR:1146case SL::OP_ASSIGN_BIT_XOR:1147code = _dump_node_code(onode->arguments[0], p_level, r_gen_code, p_actions, p_default_actions, true) + _opstr(onode->op) + _dump_node_code(onode->arguments[1], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);1148break;1149case SL::OP_BIT_INVERT:1150case SL::OP_NEGATE:1151case SL::OP_NOT:1152case SL::OP_DECREMENT:1153case SL::OP_INCREMENT: {1154const String node_code = _dump_node_code(onode->arguments[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);11551156if (onode->op == SL::OP_NEGATE && node_code.begins_with("-")) { // To prevent writing unary minus twice.1157code = node_code;1158} else {1159code = _opstr(onode->op) + node_code;1160}11611162} break;1163case SL::OP_POST_DECREMENT:1164case SL::OP_POST_INCREMENT:1165code = _dump_node_code(onode->arguments[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning) + _opstr(onode->op);1166break;1167case SL::OP_CALL:1168case SL::OP_STRUCT:1169case SL::OP_CONSTRUCT: {1170ERR_FAIL_COND_V(onode->arguments[0]->type != SL::Node::NODE_TYPE_VARIABLE, String());1171const SL::VariableNode *vnode = static_cast<const SL::VariableNode *>(onode->arguments[0]);1172const SL::FunctionNode *func = nullptr;1173const bool is_internal_func = internal_functions.has(vnode->name);11741175if (!is_internal_func) {1176for (int i = 0; i < shader->vfunctions.size(); i++) {1177if (shader->vfunctions[i].name == vnode->name) {1178func = shader->vfunctions[i].function;1179break;1180}1181}1182}11831184bool is_texture_func = false;1185bool is_screen_texture = false;1186bool is_radiance_texture = false;1187bool texture_func_no_uv = false;1188bool texture_func_returns_data = false;11891190if (onode->op == SL::OP_STRUCT) {1191code += _mkid(vnode->name);1192} else if (onode->op == SL::OP_CONSTRUCT) {1193code += String(vnode->name);1194} else {1195if (p_actions.usage_flag_pointers.has(vnode->name) && !used_flag_pointers.has(vnode->name)) {1196*p_actions.usage_flag_pointers[vnode->name] = true;1197used_flag_pointers.insert(vnode->name);1198}11991200if (is_internal_func) {1201code += vnode->name;1202is_texture_func = texture_functions.has(vnode->name);1203texture_func_no_uv = (vnode->name == "textureSize" || vnode->name == "textureQueryLevels");1204texture_func_returns_data = texture_func_no_uv || vnode->name == "textureQueryLod";1205} else if (p_default_actions.renames.has(vnode->name)) {1206code += p_default_actions.renames[vnode->name];1207} else {1208code += _mkid(vnode->rname);1209}1210}12111212code += "(";12131214// if color backbuffer, depth backbuffer or normal roughness texture is used,1215// we will add logic to automatically switch between1216// sampler2D and sampler2D array and vec2 UV and vec3 UV.1217bool multiview_uv_needed = false;1218bool is_normal_roughness_texture = false;12191220for (int i = 1; i < onode->arguments.size(); i++) {1221if (i > 1) {1222code += ", ";1223}12241225bool is_out_qualifier = false;1226if (is_internal_func) {1227is_out_qualifier = SL::is_builtin_func_out_parameter(vnode->name, i - 1);1228} else if (func != nullptr) {1229const SL::ArgumentQualifier qualifier = func->arguments[i - 1].qualifier;1230is_out_qualifier = qualifier == SL::ARGUMENT_QUALIFIER_OUT || qualifier == SL::ARGUMENT_QUALIFIER_INOUT;1231}12321233if (is_out_qualifier) {1234StringName name;1235bool found = false;1236{1237const SL::Node *node = onode->arguments[i];12381239bool done = false;1240do {1241switch (node->type) {1242case SL::Node::NODE_TYPE_VARIABLE: {1243name = static_cast<const SL::VariableNode *>(node)->name;1244done = true;1245found = true;1246} break;1247case SL::Node::NODE_TYPE_MEMBER: {1248node = static_cast<const SL::MemberNode *>(node)->owner;1249} break;1250default: {1251done = true;1252} break;1253}1254} while (!done);1255}12561257if (found && p_actions.write_flag_pointers.has(name)) {1258*p_actions.write_flag_pointers[name] = true;1259}1260}12611262String node_code = _dump_node_code(onode->arguments[i], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);1263if (is_texture_func && i == 1) {1264// If we're doing a texture lookup we need to check our texture argument1265StringName texture_uniform;1266bool correct_texture_uniform = false;12671268switch (onode->arguments[i]->type) {1269case SL::Node::NODE_TYPE_VARIABLE: {1270const SL::VariableNode *varnode = static_cast<const SL::VariableNode *>(onode->arguments[i]);1271texture_uniform = varnode->name;1272correct_texture_uniform = true;1273} break;1274case SL::Node::NODE_TYPE_ARRAY: {1275const SL::ArrayNode *anode = static_cast<const SL::ArrayNode *>(onode->arguments[i]);1276texture_uniform = anode->name;1277correct_texture_uniform = true;1278} break;1279default:1280break;1281}12821283if (correct_texture_uniform && !RS::get_singleton()->is_low_end()) {1284// Need to map from texture to sampler in order to sample when using Vulkan GLSL.1285String sampler_name;1286bool is_depth_texture = false;12871288if (actions.custom_samplers.has(texture_uniform)) {1289sampler_name = actions.custom_samplers[texture_uniform];1290} else {1291if (shader->uniforms.has(texture_uniform)) {1292const ShaderLanguage::ShaderNode::Uniform &u = shader->uniforms[texture_uniform];1293if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_SCREEN_TEXTURE) {1294is_screen_texture = true;1295} else if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_DEPTH_TEXTURE) {1296is_depth_texture = true;1297} else if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL_ROUGHNESS_TEXTURE) {1298is_normal_roughness_texture = true;1299}1300sampler_name = _get_sampler_name(u.filter, u.repeat);1301} else {1302bool found = false;13031304for (int j = 0; j < function->arguments.size(); j++) {1305if (function->arguments[j].name == texture_uniform) {1306if (function->arguments[j].tex_builtin_check) {1307ERR_CONTINUE(!actions.custom_samplers.has(function->arguments[j].tex_builtin));1308sampler_name = actions.custom_samplers[function->arguments[j].tex_builtin];1309found = true;1310break;1311}1312if (function->arguments[j].tex_argument_check) {1313if (function->arguments[j].tex_hint == ShaderLanguage::ShaderNode::Uniform::HINT_SCREEN_TEXTURE) {1314is_screen_texture = true;1315} else if (function->arguments[j].tex_hint == ShaderLanguage::ShaderNode::Uniform::HINT_DEPTH_TEXTURE) {1316is_depth_texture = true;1317} else if (function->arguments[j].tex_hint == ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL_ROUGHNESS_TEXTURE) {1318is_normal_roughness_texture = true;1319}1320sampler_name = _get_sampler_name(function->arguments[j].tex_argument_filter, function->arguments[j].tex_argument_repeat);1321found = true;1322break;1323}1324}1325}1326if (!found) {1327//function was most likely unused, so use anything (compiler will remove it anyway)1328sampler_name = _get_sampler_name(ShaderLanguage::FILTER_DEFAULT, ShaderLanguage::REPEAT_DEFAULT);1329}1330}1331}13321333if (texture_uniform == SNAME("RADIANCE")) {1334is_radiance_texture = true;1335}13361337String data_type_name = "";1338if (actions.check_multiview_samplers && (is_screen_texture || is_depth_texture || is_normal_roughness_texture)) {1339data_type_name = "multiviewSampler";1340multiview_uv_needed = true;1341} else if (is_radiance_texture) {1342data_type_name = "sampler2D";1343} else {1344data_type_name = ShaderLanguage::get_datatype_name(onode->arguments[i]->get_datatype());1345}13461347code += data_type_name + "(" + node_code + ", " + sampler_name + ")";1348} else if (correct_texture_uniform && RS::get_singleton()->is_low_end()) {1349// Texture function on low end hardware (i.e. OpenGL).13501351if (shader->uniforms.has(texture_uniform)) {1352const ShaderLanguage::ShaderNode::Uniform &u = shader->uniforms[texture_uniform];1353if (actions.check_multiview_samplers) {1354if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_SCREEN_TEXTURE) {1355multiview_uv_needed = true;1356} else if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_DEPTH_TEXTURE) {1357multiview_uv_needed = true;1358} else if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL_ROUGHNESS_TEXTURE) {1359multiview_uv_needed = true;1360}1361}1362if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_SCREEN_TEXTURE) {1363is_screen_texture = true;1364}1365}13661367code += node_code;1368} else {1369code += node_code;1370}1371} else if (multiview_uv_needed && !texture_func_no_uv && i == 2) {1372// UV coordinate after using color, depth or normal roughness texture.1373node_code = "multiview_uv(" + node_code + ".xy)";13741375code += node_code;1376} else if (is_radiance_texture && !texture_func_no_uv && i == 2) {1377node_code = "vec3_to_oct_with_border(" + node_code + ", params.border_size)";13781379code += node_code;1380} else {1381code += node_code;1382}1383}1384code += ")";1385if (is_screen_texture && !texture_func_returns_data && actions.apply_luminance_multiplier) {1386if (RS::get_singleton()->is_low_end()) {1387code = "(" + code + " / vec4(vec3(scene_data_block.data.luminance_multiplier), 1.0))";1388} else {1389code = "(" + code + " * vec4(vec3(sc_luminance_multiplier()), 1.0))";1390}1391}1392if (is_normal_roughness_texture && !texture_func_returns_data) {1393code = "normal_roughness_compatibility(" + code + ")";1394}1395} break;1396case SL::OP_INDEX: {1397code += _dump_node_code(onode->arguments[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);1398code += "[";1399code += _dump_node_code(onode->arguments[1], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);1400code += "]";14011402} break;1403case SL::OP_SELECT_IF: {1404code += "(";1405code += _dump_node_code(onode->arguments[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);1406code += "?";1407code += _dump_node_code(onode->arguments[1], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);1408code += ":";1409code += _dump_node_code(onode->arguments[2], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);1410code += ")";14111412} break;1413case SL::OP_EMPTY: {1414// Semicolon (or empty statement) - ignored.1415} break;14161417default: {1418if (p_use_scope) {1419code += "(";1420}1421code += _dump_node_code(onode->arguments[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning) + " " + _opstr(onode->op) + " " + _dump_node_code(onode->arguments[1], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);1422if (p_use_scope) {1423code += ")";1424}1425break;1426}1427}14281429} break;1430case SL::Node::NODE_TYPE_CONTROL_FLOW: {1431SL::ControlFlowNode *cfnode = (SL::ControlFlowNode *)p_node;1432if (cfnode->flow_op == SL::FLOW_OP_IF) {1433code += _mktab(p_level) + "if (" + _dump_node_code(cfnode->expressions[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning) + ")\n";1434code += _dump_node_code(cfnode->blocks[0], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning);1435if (cfnode->blocks.size() == 2) {1436code += _mktab(p_level) + "else\n";1437code += _dump_node_code(cfnode->blocks[1], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning);1438}1439} else if (cfnode->flow_op == SL::FLOW_OP_SWITCH) {1440code += _mktab(p_level) + "switch (" + _dump_node_code(cfnode->expressions[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning) + ")\n";1441code += _dump_node_code(cfnode->blocks[0], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning);1442} else if (cfnode->flow_op == SL::FLOW_OP_CASE) {1443code += _mktab(p_level) + "case " + _dump_node_code(cfnode->expressions[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning) + ":\n";1444code += _dump_node_code(cfnode->blocks[0], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning);1445} else if (cfnode->flow_op == SL::FLOW_OP_DEFAULT) {1446code += _mktab(p_level) + "default:\n";1447code += _dump_node_code(cfnode->blocks[0], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning);1448} else if (cfnode->flow_op == SL::FLOW_OP_DO) {1449code += _mktab(p_level) + "do";1450code += _dump_node_code(cfnode->blocks[0], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning);1451code += _mktab(p_level) + "while (" + _dump_node_code(cfnode->expressions[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning) + ");";1452} else if (cfnode->flow_op == SL::FLOW_OP_WHILE) {1453code += _mktab(p_level) + "while (" + _dump_node_code(cfnode->expressions[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning) + ")\n";1454code += _dump_node_code(cfnode->blocks[0], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning);1455} else if (cfnode->flow_op == SL::FLOW_OP_FOR) {1456String left = _dump_node_code(cfnode->blocks[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);1457String middle = _dump_node_code(cfnode->blocks[1], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);1458String right = _dump_node_code(cfnode->blocks[2], p_level, r_gen_code, p_actions, p_default_actions, p_assigning);1459code += _mktab(p_level) + "for (" + left + ";" + middle + ";" + right + ")\n";1460code += _dump_node_code(cfnode->blocks[3], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning);14611462} else if (cfnode->flow_op == SL::FLOW_OP_RETURN) {1463if (cfnode->expressions.size()) {1464code = "return " + _dump_node_code(cfnode->expressions[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning) + ";";1465} else {1466code = "return;";1467}1468} else if (cfnode->flow_op == SL::FLOW_OP_DISCARD) {1469if (p_actions.usage_flag_pointers.has("DISCARD") && !used_flag_pointers.has("DISCARD")) {1470*p_actions.usage_flag_pointers["DISCARD"] = true;1471used_flag_pointers.insert("DISCARD");1472}14731474code = "discard;";1475} else if (cfnode->flow_op == SL::FLOW_OP_CONTINUE) {1476code = "continue;";1477} else if (cfnode->flow_op == SL::FLOW_OP_BREAK) {1478code = "break;";1479}14801481} break;1482case SL::Node::NODE_TYPE_MEMBER: {1483SL::MemberNode *mnode = (SL::MemberNode *)p_node;1484String name;1485if (mnode->basetype == SL::TYPE_STRUCT) {1486name = _mkid(mnode->name);1487} else {1488name = mnode->name;1489}1490code = _dump_node_code(mnode->owner, p_level, r_gen_code, p_actions, p_default_actions, p_assigning) + "." + name;1491if (mnode->index_expression != nullptr) {1492code += "[";1493code += _dump_node_code(mnode->index_expression, p_level, r_gen_code, p_actions, p_default_actions, p_assigning);1494code += "]";1495} else if (mnode->assign_expression != nullptr) {1496code += "=";1497code += _dump_node_code(mnode->assign_expression, p_level, r_gen_code, p_actions, p_default_actions, true, false);1498} else if (mnode->call_expression != nullptr) {1499code += ".";1500code += _dump_node_code(mnode->call_expression, p_level, r_gen_code, p_actions, p_default_actions, p_assigning, false);1501}1502} break;1503}15041505return code;1506}15071508ShaderLanguage::DataType ShaderCompiler::_get_global_shader_uniform_type(const StringName &p_name) {1509RS::GlobalShaderParameterType gvt = RSG::material_storage->global_shader_parameter_get_type(p_name);1510return (ShaderLanguage::DataType)RS::global_shader_uniform_type_get_shader_datatype(gvt);1511}15121513Error ShaderCompiler::compile(RS::ShaderMode p_mode, const String &p_code, IdentifierActions *p_actions, const String &p_path, GeneratedCode &r_gen_code) {1514SL::ShaderCompileInfo info;1515info.functions = ShaderTypes::get_singleton()->get_functions(p_mode);1516info.render_modes = ShaderTypes::get_singleton()->get_modes(p_mode);1517info.stencil_modes = ShaderTypes::get_singleton()->get_stencil_modes(p_mode);1518info.shader_types = ShaderTypes::get_singleton()->get_types();1519info.global_shader_uniform_type_func = _get_global_shader_uniform_type;1520info.base_varying_index = actions.base_varying_index;15211522Error err = parser.compile(p_code, info);15231524if (err != OK) {1525Vector<ShaderLanguage::FilePosition> include_positions = parser.get_include_positions();15261527String current;1528HashMap<String, Vector<String>> includes;1529includes[""] = Vector<String>();1530Vector<String> include_stack;1531Vector<String> shader_lines = p_code.split("\n");15321533// Reconstruct the files.1534for (int i = 0; i < shader_lines.size(); i++) {1535String l = shader_lines[i];1536if (l.begins_with("@@>")) {1537String inc_path = l.replace_first("@@>", "");15381539l = "#include \"" + inc_path + "\"";1540includes[current].append("#include \"" + inc_path + "\""); // Restore the include directive1541include_stack.push_back(current);1542current = inc_path;1543includes[inc_path] = Vector<String>();15441545} else if (l.begins_with("@@<")) {1546if (include_stack.size()) {1547current = include_stack[include_stack.size() - 1];1548include_stack.resize(include_stack.size() - 1);1549}1550} else {1551includes[current].push_back(l);1552}1553}15541555// Print the files.1556for (const KeyValue<String, Vector<String>> &E : includes) {1557int err_line = -1;1558for (const ShaderLanguage::FilePosition &include_position : include_positions) {1559if (include_position.file == E.key) {1560err_line = include_position.line;1561}1562}1563if (err_line < 0) {1564// Skip files that don't contain errors.1565continue;1566}15671568if (E.key.is_empty()) {1569if (p_path == "") {1570print_line("--Main Shader--");1571} else {1572print_line("--" + p_path + "--");1573}1574} else {1575print_line("--" + E.key + "--");1576}1577const Vector<String> &V = E.value;1578for (int i = 0; i < V.size(); i++) {1579if (i == err_line - 1) {1580// Mark the error line to be visible without having to look at1581// the trace at the end.1582print_line(vformat("E%4d-> %s", i + 1, V[i]));1583} else if ((i == err_line - 3) || (i == err_line - 2) || (i == err_line) || (i == err_line + 1)) {1584// Print 4 lines around the error line.1585print_line(vformat("%5d | %s", i + 1, V[i]));1586}1587}1588}15891590String file;1591int line;1592if (include_positions.size() > 1) {1593file = include_positions[include_positions.size() - 1].file;1594line = include_positions[include_positions.size() - 1].line;1595} else {1596file = p_path;1597line = parser.get_error_line();1598}15991600_err_print_error(nullptr, file.utf8().get_data(), line, parser.get_error_text().utf8().get_data(), false, ERR_HANDLER_SHADER);1601return err;1602}16031604r_gen_code.defines.clear();1605r_gen_code.code.clear();1606for (int i = 0; i < STAGE_MAX; i++) {1607r_gen_code.stage_globals[i] = String();1608}1609r_gen_code.uses_fragment_time = false;1610r_gen_code.uses_vertex_time = false;1611r_gen_code.uses_global_textures = false;1612r_gen_code.uses_screen_texture_mipmaps = false;1613r_gen_code.uses_screen_texture = false;1614r_gen_code.uses_depth_texture = false;1615r_gen_code.uses_normal_roughness_texture = false;16161617used_name_defines.clear();1618used_rmode_defines.clear();1619used_flag_pointers.clear();1620fragment_varyings.clear();16211622shader = parser.get_shader();1623function = nullptr;1624// Return value only relevant within nested calls.1625_ALLOW_DISCARD_ _dump_node_code(shader, 1, r_gen_code, *p_actions, actions, false);16261627return OK;1628}16291630void ShaderCompiler::initialize(DefaultIdentifierActions p_actions) {1631actions = p_actions;16321633time_name = "TIME";16341635List<String> func_list;16361637ShaderLanguage::get_builtin_funcs(&func_list);16381639for (const String &E : func_list) {1640internal_functions.insert(E);1641}1642texture_functions.insert("texture");1643texture_functions.insert("textureProj");1644texture_functions.insert("textureLod");1645texture_functions.insert("textureProjLod");1646texture_functions.insert("textureGrad");1647texture_functions.insert("textureProjGrad");1648texture_functions.insert("textureGather");1649texture_functions.insert("textureSize");1650texture_functions.insert("textureQueryLod");1651texture_functions.insert("textureQueryLevels");1652texture_functions.insert("texelFetch");1653}16541655ShaderCompiler::ShaderCompiler() {1656}165716581659