Path: blob/master/servers/rendering/renderer_rd/shader_rd.cpp
20878 views
/**************************************************************************/1/* shader_rd.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_rd.h"3132#include "core/io/dir_access.h"33#include "core/io/file_access.h"34#include "core/object/worker_thread_pool.h"35#include "core/version.h"36#include "servers/rendering/rendering_device.h"37#include "servers/rendering/shader_include_db.h"3839#define ENABLE_SHADER_CACHE 14041void ShaderRD::_add_stage(const char *p_code, StageType p_stage_type) {42Vector<String> lines = String(p_code).split("\n");4344String text;4546int line_count = lines.size();47for (int i = 0; i < line_count; i++) {48const String &l = lines[i];49bool push_chunk = false;5051StageTemplate::Chunk chunk;5253if (l.begins_with("#VERSION_DEFINES")) {54chunk.type = StageTemplate::Chunk::TYPE_VERSION_DEFINES;55push_chunk = true;56} else if (l.begins_with("#GLOBALS")) {57switch (p_stage_type) {58case STAGE_TYPE_VERTEX:59chunk.type = StageTemplate::Chunk::TYPE_VERTEX_GLOBALS;60break;61case STAGE_TYPE_FRAGMENT:62chunk.type = StageTemplate::Chunk::TYPE_FRAGMENT_GLOBALS;63break;64case STAGE_TYPE_COMPUTE:65chunk.type = StageTemplate::Chunk::TYPE_COMPUTE_GLOBALS;66break;67case STAGE_TYPE_RAYGEN:68chunk.type = StageTemplate::Chunk::TYPE_RAYGEN_GLOBALS;69break;70case STAGE_TYPE_ANY_HIT:71chunk.type = StageTemplate::Chunk::TYPE_ANY_HIT_GLOBALS;72break;73case STAGE_TYPE_CLOSEST_HIT:74chunk.type = StageTemplate::Chunk::TYPE_CLOSEST_HIT_GLOBALS;75break;76case STAGE_TYPE_MISS:77chunk.type = StageTemplate::Chunk::TYPE_MISS_GLOBALS;78break;79case STAGE_TYPE_INTERSECTION:80chunk.type = StageTemplate::Chunk::TYPE_INTERSECTION_GLOBALS;81break;82default: {83}84}8586push_chunk = true;87} else if (l.begins_with("#MATERIAL_UNIFORMS")) {88chunk.type = StageTemplate::Chunk::TYPE_MATERIAL_UNIFORMS;89push_chunk = true;90} else if (l.begins_with("#CODE")) {91chunk.type = StageTemplate::Chunk::TYPE_CODE;92push_chunk = true;93chunk.code = l.replace_first("#CODE", String()).remove_char(':').strip_edges().to_upper();94} else if (l.begins_with("#include ")) {95String include_file = l.replace("#include ", "").strip_edges();96if (include_file[0] == '"') {97int end_pos = include_file.find_char('"', 1);98if (end_pos >= 0) {99include_file = include_file.substr(1, end_pos - 1);100101String include_code = ShaderIncludeDB::get_built_in_include_file(include_file);102if (!include_code.is_empty()) {103// Add these lines into our parse list so we parse them as well.104Vector<String> include_lines = include_code.split("\n");105106for (int j = include_lines.size() - 1; j >= 0; j--) {107lines.insert(i + 1, include_lines[j]);108}109110line_count = lines.size();111} else {112// Add it in as is.113text += l + "\n";114}115} else {116// Add it in as is.117text += l + "\n";118}119} else {120// Add it in as is.121text += l + "\n";122}123} else {124text += l + "\n";125}126127if (push_chunk) {128if (!text.is_empty()) {129StageTemplate::Chunk text_chunk;130text_chunk.type = StageTemplate::Chunk::TYPE_TEXT;131text_chunk.text = text.utf8();132stage_templates[p_stage_type].chunks.push_back(text_chunk);133text = String();134}135stage_templates[p_stage_type].chunks.push_back(chunk);136}137}138139if (!text.is_empty()) {140StageTemplate::Chunk text_chunk;141text_chunk.type = StageTemplate::Chunk::TYPE_TEXT;142text_chunk.text = text.utf8();143stage_templates[p_stage_type].chunks.push_back(text_chunk);144text = String();145}146}147148void ShaderRD::setup(const char *p_vertex_code, const char *p_fragment_code, const char *p_compute_code, const char *p_name) {149name = p_name;150151if (p_compute_code) {152_add_stage(p_compute_code, STAGE_TYPE_COMPUTE);153pipeline_type = RD::PIPELINE_TYPE_COMPUTE;154} else {155pipeline_type = RD::PIPELINE_TYPE_RASTERIZATION;156if (p_vertex_code) {157_add_stage(p_vertex_code, STAGE_TYPE_VERTEX);158}159if (p_fragment_code) {160_add_stage(p_fragment_code, STAGE_TYPE_FRAGMENT);161}162}163164StringBuilder tohash;165tohash.append("[GodotVersionNumber]");166tohash.append(GODOT_VERSION_NUMBER);167tohash.append("[GodotVersionHash]");168tohash.append(GODOT_VERSION_HASH);169tohash.append("[Vertex]");170tohash.append(p_vertex_code ? p_vertex_code : "");171tohash.append("[Fragment]");172tohash.append(p_fragment_code ? p_fragment_code : "");173tohash.append("[Compute]");174tohash.append(p_compute_code ? p_compute_code : "");175tohash.append("[DebugInfo]");176tohash.append(Engine::get_singleton()->is_generate_spirv_debug_info_enabled() ? "1" : "0");177178base_sha256 = tohash.as_string().sha256_text();179}180181void ShaderRD::setup_raytracing(const char *p_raygen_code, const char *p_any_hit_code, const char *p_closest_hit_code, const char *p_miss_code, const char *p_intersection_code, const char *p_name) {182name = p_name;183184pipeline_type = RD::PIPELINE_TYPE_RAYTRACING;185if (p_raygen_code) {186_add_stage(p_raygen_code, STAGE_TYPE_RAYGEN);187}188if (p_any_hit_code) {189_add_stage(p_any_hit_code, STAGE_TYPE_ANY_HIT);190}191if (p_closest_hit_code) {192_add_stage(p_closest_hit_code, STAGE_TYPE_CLOSEST_HIT);193}194if (p_miss_code) {195_add_stage(p_miss_code, STAGE_TYPE_MISS);196}197if (p_intersection_code) {198_add_stage(p_intersection_code, STAGE_TYPE_INTERSECTION);199}200201StringBuilder tohash;202tohash.append("[GodotVersionNumber]");203tohash.append(GODOT_VERSION_NUMBER);204tohash.append("[GodotVersionHash]");205tohash.append(GODOT_VERSION_HASH);206tohash.append("[Raygen]");207tohash.append(p_raygen_code ? p_raygen_code : "");208tohash.append("[AnyHit]");209tohash.append(p_any_hit_code ? p_any_hit_code : "");210tohash.append("[ClosestHit]");211tohash.append(p_closest_hit_code ? p_closest_hit_code : "");212tohash.append("[Miss]");213tohash.append(p_miss_code ? p_miss_code : "");214tohash.append("[Intersection]");215tohash.append(p_intersection_code ? p_intersection_code : "");216tohash.append("[DebugInfo]");217tohash.append(Engine::get_singleton()->is_generate_spirv_debug_info_enabled() ? "1" : "0");218219base_sha256 = tohash.as_string().sha256_text();220}221222RID ShaderRD::version_create(bool p_embedded) {223//initialize() was never called224ERR_FAIL_COND_V(group_to_variant_map.is_empty(), RID());225226Version version;227version.dirty = true;228version.valid = false;229version.initialize_needed = true;230version.embedded = p_embedded;231version.variants.clear();232version.variant_data.clear();233234version.mutex = memnew(Mutex);235RID rid = version_owner.make_rid(version);236{237MutexLock lock(versions_mutex);238version_mutexes.insert(rid, version.mutex);239}240241if (p_embedded) {242MutexLock lock(shader_versions_embedded_set_mutex);243shader_versions_embedded_set.insert({ this, rid });244}245246return rid;247}248249void ShaderRD::_initialize_version(Version *p_version) {250_clear_version(p_version);251252p_version->valid = false;253p_version->dirty = false;254255p_version->variants.resize_initialized(variant_defines.size());256p_version->variant_data.resize(variant_defines.size());257p_version->group_compilation_tasks.resize_initialized(group_enabled.size());258}259260void ShaderRD::_clear_version(Version *p_version) {261_compile_ensure_finished(p_version);262263// Clear versions if they exist.264if (!p_version->variants.is_empty()) {265for (int i = 0; i < variant_defines.size(); i++) {266if (p_version->variants[i].is_valid()) {267RD::get_singleton()->free_rid(p_version->variants[i]);268}269}270271p_version->variants.clear();272p_version->variant_data.clear();273}274}275276void ShaderRD::_build_variant_code(StringBuilder &builder, uint32_t p_variant, const Version *p_version, const StageTemplate &p_template) {277for (const StageTemplate::Chunk &chunk : p_template.chunks) {278switch (chunk.type) {279case StageTemplate::Chunk::TYPE_VERSION_DEFINES: {280builder.append("\n"); //make sure defines begin at newline281builder.append(general_defines.get_data());282builder.append(variant_defines[p_variant].text.get_data());283for (int j = 0; j < p_version->custom_defines.size(); j++) {284builder.append(p_version->custom_defines[j].get_data());285}286builder.append("\n"); //make sure defines begin at newline287if (p_version->uniforms.size()) {288builder.append("#define MATERIAL_UNIFORMS_USED\n");289}290for (const KeyValue<StringName, CharString> &E : p_version->code_sections) {291builder.append(String("#define ") + String(E.key) + "_CODE_USED\n");292}293builder.append(String("#define RENDER_DRIVER_") + OS::get_singleton()->get_current_rendering_driver_name().to_upper() + "\n");294builder.append("#define samplerExternalOES sampler2D\n");295builder.append("#define textureExternalOES texture2D\n");296} break;297case StageTemplate::Chunk::TYPE_MATERIAL_UNIFORMS: {298builder.append(p_version->uniforms.get_data()); //uniforms (same for vertex and fragment)299} break;300case StageTemplate::Chunk::TYPE_VERTEX_GLOBALS: {301builder.append(p_version->vertex_globals.get_data()); // vertex globals302} break;303case StageTemplate::Chunk::TYPE_FRAGMENT_GLOBALS: {304builder.append(p_version->fragment_globals.get_data()); // fragment globals305} break;306case StageTemplate::Chunk::TYPE_COMPUTE_GLOBALS: {307builder.append(p_version->compute_globals.get_data()); // compute globals308} break;309case StageTemplate::Chunk::TYPE_RAYGEN_GLOBALS: {310builder.append(p_version->raygen_globals.get_data()); // raygen globals311} break;312case StageTemplate::Chunk::TYPE_ANY_HIT_GLOBALS: {313builder.append(p_version->any_hit_globals.get_data()); // any_hit globals314} break;315case StageTemplate::Chunk::TYPE_CLOSEST_HIT_GLOBALS: {316builder.append(p_version->closest_hit_globals.get_data()); // closest_hit globals317} break;318case StageTemplate::Chunk::TYPE_MISS_GLOBALS: {319builder.append(p_version->miss_globals.get_data()); // miss globals320} break;321case StageTemplate::Chunk::TYPE_INTERSECTION_GLOBALS: {322builder.append(p_version->intersection_globals.get_data()); // intersection globals323} break;324case StageTemplate::Chunk::TYPE_CODE: {325if (p_version->code_sections.has(chunk.code)) {326builder.append(p_version->code_sections[chunk.code].get_data());327}328} break;329case StageTemplate::Chunk::TYPE_TEXT: {330builder.append(chunk.text.get_data());331} break;332}333}334}335336Vector<String> ShaderRD::_build_variant_stage_sources(uint32_t p_variant, CompileData p_data) {337if (!variants_enabled[p_variant]) {338return Vector<String>(); // Variant is disabled, return.339}340341Vector<String> stage_sources;342stage_sources.resize(RD::SHADER_STAGE_MAX);343344if (pipeline_type == RD::PIPELINE_TYPE_COMPUTE) {345// Compute stage.346StringBuilder builder;347_build_variant_code(builder, p_variant, p_data.version, stage_templates[STAGE_TYPE_COMPUTE]);348stage_sources.write[RD::SHADER_STAGE_COMPUTE] = builder.as_string();349} else if (pipeline_type == RD::PIPELINE_TYPE_RAYTRACING) {350{351// Raygen stage.352StringBuilder builder;353_build_variant_code(builder, p_variant, p_data.version, stage_templates[STAGE_TYPE_RAYGEN]);354stage_sources.write[RD::SHADER_STAGE_RAYGEN] = builder.as_string();355}356357{358// Any hit stage.359StringBuilder builder;360_build_variant_code(builder, p_variant, p_data.version, stage_templates[STAGE_TYPE_ANY_HIT]);361stage_sources.write[RD::SHADER_STAGE_ANY_HIT] = builder.as_string();362}363364{365// Closest hit stage.366StringBuilder builder;367_build_variant_code(builder, p_variant, p_data.version, stage_templates[STAGE_TYPE_CLOSEST_HIT]);368stage_sources.write[RD::SHADER_STAGE_CLOSEST_HIT] = builder.as_string();369}370371{372// Miss stage.373StringBuilder builder;374_build_variant_code(builder, p_variant, p_data.version, stage_templates[STAGE_TYPE_MISS]);375stage_sources.write[RD::SHADER_STAGE_MISS] = builder.as_string();376}377378{379// Intersection stage.380StringBuilder builder;381_build_variant_code(builder, p_variant, p_data.version, stage_templates[STAGE_TYPE_INTERSECTION]);382stage_sources.write[RD::SHADER_STAGE_INTERSECTION] = builder.as_string();383}384} else {385{386// Vertex stage.387StringBuilder builder;388_build_variant_code(builder, p_variant, p_data.version, stage_templates[STAGE_TYPE_VERTEX]);389stage_sources.write[RD::SHADER_STAGE_VERTEX] = builder.as_string();390}391392{393// Fragment stage.394StringBuilder builder;395_build_variant_code(builder, p_variant, p_data.version, stage_templates[STAGE_TYPE_FRAGMENT]);396stage_sources.write[RD::SHADER_STAGE_FRAGMENT] = builder.as_string();397}398}399400return stage_sources;401}402403void ShaderRD::_compile_variant(uint32_t p_variant, CompileData p_data) {404uint32_t variant = group_to_variant_map[p_data.group][p_variant];405if (!variants_enabled[variant]) {406return; // Variant is disabled, return.407}408409Vector<String> variant_stage_sources = _build_variant_stage_sources(variant, p_data);410Vector<RD::ShaderStageSPIRVData> variant_stages = compile_stages(variant_stage_sources, dynamic_buffers);411ERR_FAIL_COND(variant_stages.is_empty());412413Vector<uint8_t> shader_data = RD::get_singleton()->shader_compile_binary_from_spirv(variant_stages, name + ":" + itos(variant));414ERR_FAIL_COND(shader_data.is_empty());415416{417p_data.version->variants.write[variant] = RD::get_singleton()->shader_create_from_bytecode_with_samplers(shader_data, p_data.version->variants[variant], immutable_samplers);418p_data.version->variant_data.write[variant] = shader_data;419}420}421422Vector<String> ShaderRD::version_build_variant_stage_sources(RID p_version, int p_variant) {423Version *version = version_owner.get_or_null(p_version);424ERR_FAIL_NULL_V(version, Vector<String>());425426if (version->dirty) {427_initialize_version(version);428}429430CompileData compile_data;431compile_data.version = version;432compile_data.group = variant_to_group[p_variant];433return _build_variant_stage_sources(p_variant, compile_data);434}435436RS::ShaderNativeSourceCode ShaderRD::version_get_native_source_code(RID p_version) {437Version *version = version_owner.get_or_null(p_version);438RS::ShaderNativeSourceCode source_code;439ERR_FAIL_NULL_V(version, source_code);440441MutexLock lock(*version->mutex);442443source_code.versions.resize(variant_defines.size());444445for (int i = 0; i < source_code.versions.size(); i++) {446if (pipeline_type == RD::PIPELINE_TYPE_RASTERIZATION) {447// Vertex stage.448449StringBuilder builder;450_build_variant_code(builder, i, version, stage_templates[STAGE_TYPE_VERTEX]);451452RS::ShaderNativeSourceCode::Version::Stage stage;453stage.name = "vertex";454stage.code = builder.as_string();455456source_code.versions.write[i].stages.push_back(stage);457}458459if (pipeline_type == RD::PIPELINE_TYPE_RASTERIZATION) {460// Fragment stage.461462StringBuilder builder;463_build_variant_code(builder, i, version, stage_templates[STAGE_TYPE_FRAGMENT]);464465RS::ShaderNativeSourceCode::Version::Stage stage;466stage.name = "fragment";467stage.code = builder.as_string();468469source_code.versions.write[i].stages.push_back(stage);470}471472if (pipeline_type == RD::PIPELINE_TYPE_COMPUTE) {473// Compute stage.474475StringBuilder builder;476_build_variant_code(builder, i, version, stage_templates[STAGE_TYPE_COMPUTE]);477478RS::ShaderNativeSourceCode::Version::Stage stage;479stage.name = "compute";480stage.code = builder.as_string();481482source_code.versions.write[i].stages.push_back(stage);483}484485if (pipeline_type == RD::PIPELINE_TYPE_RAYTRACING) {486// Raygen stage.487488StringBuilder builder;489_build_variant_code(builder, i, version, stage_templates[STAGE_TYPE_RAYGEN]);490491RS::ShaderNativeSourceCode::Version::Stage stage;492stage.name = "raygen";493stage.code = builder.as_string();494495source_code.versions.write[i].stages.push_back(stage);496}497if (pipeline_type == RD::PIPELINE_TYPE_RAYTRACING) {498// Any hit stage.499500StringBuilder builder;501_build_variant_code(builder, i, version, stage_templates[STAGE_TYPE_ANY_HIT]);502503RS::ShaderNativeSourceCode::Version::Stage stage;504stage.name = "any_hit";505stage.code = builder.as_string();506507source_code.versions.write[i].stages.push_back(stage);508}509if (pipeline_type == RD::PIPELINE_TYPE_RAYTRACING) {510// Closest hit stage.511512StringBuilder builder;513_build_variant_code(builder, i, version, stage_templates[STAGE_TYPE_CLOSEST_HIT]);514515RS::ShaderNativeSourceCode::Version::Stage stage;516stage.name = "closest_hit";517stage.code = builder.as_string();518519source_code.versions.write[i].stages.push_back(stage);520}521if (pipeline_type == RD::PIPELINE_TYPE_RAYTRACING) {522// Miss stage.523524StringBuilder builder;525_build_variant_code(builder, i, version, stage_templates[STAGE_TYPE_MISS]);526527RS::ShaderNativeSourceCode::Version::Stage stage;528stage.name = "miss";529stage.code = builder.as_string();530531source_code.versions.write[i].stages.push_back(stage);532}533if (pipeline_type == RD::PIPELINE_TYPE_RAYTRACING) {534// Intersection stage.535536StringBuilder builder;537_build_variant_code(builder, i, version, stage_templates[STAGE_TYPE_INTERSECTION]);538539RS::ShaderNativeSourceCode::Version::Stage stage;540stage.name = "intersection";541stage.code = builder.as_string();542543source_code.versions.write[i].stages.push_back(stage);544}545}546547return source_code;548}549550String ShaderRD::version_get_cache_file_relative_path(RID p_version, int p_group, const String &p_api_name) {551Version *version = version_owner.get_or_null(p_version);552ERR_FAIL_NULL_V(version, String());553554return _get_cache_file_relative_path(version, p_group, p_api_name);555}556557String ShaderRD::_version_get_sha1(Version *p_version) const {558StringBuilder hash_build;559560hash_build.append("[uniforms]");561hash_build.append(p_version->uniforms.get_data());562hash_build.append("[vertex_globals]");563hash_build.append(p_version->vertex_globals.get_data());564hash_build.append("[fragment_globals]");565hash_build.append(p_version->fragment_globals.get_data());566hash_build.append("[compute_globals]");567hash_build.append(p_version->compute_globals.get_data());568hash_build.append("[raygen_globals]");569hash_build.append(p_version->raygen_globals.get_data());570hash_build.append("[any_hit_globals]");571hash_build.append(p_version->any_hit_globals.get_data());572hash_build.append("[closest_hit_globals]");573hash_build.append(p_version->closest_hit_globals.get_data());574hash_build.append("[miss_globals]");575hash_build.append(p_version->miss_globals.get_data());576hash_build.append("[intersection_globals]");577hash_build.append(p_version->intersection_globals.get_data());578579Vector<StringName> code_sections;580for (const KeyValue<StringName, CharString> &E : p_version->code_sections) {581code_sections.push_back(E.key);582}583code_sections.sort_custom<StringName::AlphCompare>();584585for (int i = 0; i < code_sections.size(); i++) {586hash_build.append(String("[code:") + String(code_sections[i]) + "]");587hash_build.append(p_version->code_sections[code_sections[i]].get_data());588}589for (int i = 0; i < p_version->custom_defines.size(); i++) {590hash_build.append("[custom_defines:" + itos(i) + "]");591hash_build.append(p_version->custom_defines[i].get_data());592}593594return hash_build.as_string().sha1_text();595}596597static const char *shader_file_header = "GDSC";598static const uint32_t cache_file_version = 4;599600String ShaderRD::_get_cache_file_relative_path(Version *p_version, int p_group, const String &p_api_name) {601String sha1 = _version_get_sha1(p_version);602return name.path_join(group_sha256[p_group]).path_join(sha1) + "." + p_api_name + ".cache";603}604605String ShaderRD::_get_cache_file_path(Version *p_version, int p_group, const String &p_api_name, bool p_user_dir) {606const String &shader_cache_dir = p_user_dir ? shader_cache_user_dir : shader_cache_res_dir;607String relative_path = _get_cache_file_relative_path(p_version, p_group, p_api_name);608return shader_cache_dir.path_join(relative_path);609}610611bool ShaderRD::_load_from_cache(Version *p_version, int p_group) {612String api_safe_name = String(RD::get_singleton()->get_device_api_name()).validate_filename().to_lower();613Ref<FileAccess> f;614if (shader_cache_user_dir_valid) {615f = FileAccess::open(_get_cache_file_path(p_version, p_group, api_safe_name, true), FileAccess::READ);616}617618if (f.is_null() && shader_cache_res_dir_valid) {619f = FileAccess::open(_get_cache_file_path(p_version, p_group, api_safe_name, false), FileAccess::READ);620}621622if (f.is_null()) {623const String &sha1 = _version_get_sha1(p_version);624print_verbose(vformat("Shader cache miss for %s", name.path_join(group_sha256[p_group]).path_join(sha1)));625return false;626}627628char header[5] = { 0, 0, 0, 0, 0 };629f->get_buffer((uint8_t *)header, 4);630ERR_FAIL_COND_V(header != String(shader_file_header), false);631632uint32_t file_version = f->get_32();633if (file_version != cache_file_version) {634return false; // wrong version635}636637uint32_t variant_count = f->get_32();638639ERR_FAIL_COND_V(variant_count != (uint32_t)group_to_variant_map[p_group].size(), false); //should not happen but check640641for (uint32_t i = 0; i < variant_count; i++) {642int variant_id = group_to_variant_map[p_group][i];643uint32_t variant_size = f->get_32();644if (!variants_enabled[variant_id]) {645continue;646}647if (variant_size == 0) {648// A new variant has been requested, failing the entire load will generate it649print_verbose(vformat("Shader cache miss for %s due to missing variant %d", name.path_join(group_sha256[p_group]).path_join(_version_get_sha1(p_version)), variant_id));650return false;651}652Vector<uint8_t> variant_bytes;653variant_bytes.resize(variant_size);654655uint32_t br = f->get_buffer(variant_bytes.ptrw(), variant_size);656657ERR_FAIL_COND_V(br != variant_size, false);658659p_version->variant_data.write[variant_id] = variant_bytes;660}661662for (uint32_t i = 0; i < variant_count; i++) {663int variant_id = group_to_variant_map[p_group][i];664if (!variants_enabled[variant_id]) {665p_version->variants.write[variant_id] = RID();666continue;667}668print_verbose(vformat("Loading cache for shader %s, variant %d", name, i));669{670RID shader = RD::get_singleton()->shader_create_from_bytecode_with_samplers(p_version->variant_data[variant_id], p_version->variants[variant_id], immutable_samplers);671if (shader.is_null()) {672for (uint32_t j = 0; j < i; j++) {673int variant_free_id = group_to_variant_map[p_group][j];674RD::get_singleton()->free_rid(p_version->variants[variant_free_id]);675}676ERR_FAIL_COND_V(shader.is_null(), false);677}678679p_version->variants.write[variant_id] = shader;680}681}682683p_version->valid = true;684return true;685}686687void ShaderRD::_save_to_cache(Version *p_version, int p_group) {688ERR_FAIL_COND(!shader_cache_user_dir_valid);689String api_safe_name = String(RD::get_singleton()->get_device_api_name()).validate_filename().to_lower();690const String &path = _get_cache_file_path(p_version, p_group, api_safe_name, true);691Ref<FileAccess> f = FileAccess::open(path, FileAccess::WRITE);692ERR_FAIL_COND(f.is_null());693694PackedByteArray shader_cache_bytes = ShaderRD::save_shader_cache_bytes(group_to_variant_map[p_group], p_version->variant_data);695f->store_buffer(shader_cache_bytes);696}697698void ShaderRD::_allocate_placeholders(Version *p_version, int p_group) {699ERR_FAIL_COND(p_version->variants.is_empty());700701for (uint32_t i = 0; i < group_to_variant_map[p_group].size(); i++) {702int variant_id = group_to_variant_map[p_group][i];703RID shader = RD::get_singleton()->shader_create_placeholder();704{705p_version->variants.write[variant_id] = shader;706}707}708}709710// Try to compile all variants for a given group.711// Will skip variants that are disabled.712void ShaderRD::_compile_version_start(Version *p_version, int p_group) {713if (!group_enabled[p_group]) {714return;715}716717p_version->dirty = false;718719#if ENABLE_SHADER_CACHE720if (shader_cache_user_dir_valid || shader_cache_res_dir_valid) {721if (_load_from_cache(p_version, p_group)) {722return;723}724}725#endif726727CompileData compile_data;728compile_data.version = p_version;729compile_data.group = p_group;730731WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_template_group_task(this, &ShaderRD::_compile_variant, compile_data, group_to_variant_map[p_group].size(), -1, true, SNAME("ShaderCompilation"));732p_version->group_compilation_tasks.write[p_group] = group_task;733}734735void ShaderRD::_compile_version_end(Version *p_version, int p_group) {736if (p_version->group_compilation_tasks.size() <= p_group || p_version->group_compilation_tasks[p_group] == 0) {737return;738}739WorkerThreadPool::GroupID group_task = p_version->group_compilation_tasks[p_group];740WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);741p_version->group_compilation_tasks.write[p_group] = 0;742743bool all_valid = true;744745for (uint32_t i = 0; i < group_to_variant_map[p_group].size(); i++) {746int variant_id = group_to_variant_map[p_group][i];747if (!variants_enabled[variant_id]) {748continue; // Disabled.749}750if (p_version->variants[variant_id].is_null()) {751all_valid = false;752break;753}754}755756if (!all_valid) {757// Clear versions if they exist.758for (int i = 0; i < variant_defines.size(); i++) {759if (!variants_enabled[i] || !group_enabled[variant_defines[i].group]) {760continue; // Disabled.761}762if (!p_version->variants[i].is_null()) {763RD::get_singleton()->free_rid(p_version->variants[i]);764}765}766767p_version->variants.clear();768p_version->variant_data.clear();769return;770}771#if ENABLE_SHADER_CACHE772else if (shader_cache_user_dir_valid) {773_save_to_cache(p_version, p_group);774}775#endif776777p_version->valid = true;778}779780void ShaderRD::_compile_ensure_finished(Version *p_version) {781// Wait for compilation of existing groups if necessary.782for (int i = 0; i < group_enabled.size(); i++) {783_compile_version_end(p_version, i);784}785}786787void ShaderRD::_version_set(Version *p_version, const HashMap<String, String> &p_code, const Vector<String> &p_custom_defines) {788p_version->code_sections.clear();789for (const KeyValue<String, String> &E : p_code) {790p_version->code_sections[StringName(E.key.to_upper())] = E.value.utf8();791}792793p_version->custom_defines.clear();794for (const String &custom_define : p_custom_defines) {795p_version->custom_defines.push_back(custom_define.utf8());796}797798p_version->dirty = true;799if (p_version->initialize_needed) {800_initialize_version(p_version);801for (int i = 0; i < group_enabled.size(); i++) {802if (!group_enabled[i]) {803_allocate_placeholders(p_version, i);804continue;805}806_compile_version_start(p_version, i);807}808p_version->initialize_needed = false;809}810}811812void ShaderRD::version_set_code(RID p_version, const HashMap<String, String> &p_code, const String &p_uniforms, const String &p_vertex_globals, const String &p_fragment_globals, const Vector<String> &p_custom_defines) {813ERR_FAIL_COND(pipeline_type != RD::PIPELINE_TYPE_RASTERIZATION);814815Version *version = version_owner.get_or_null(p_version);816ERR_FAIL_NULL(version);817818MutexLock lock(*version->mutex);819820_compile_ensure_finished(version);821822version->vertex_globals = p_vertex_globals.utf8();823version->fragment_globals = p_fragment_globals.utf8();824version->uniforms = p_uniforms.utf8();825826_version_set(version, p_code, p_custom_defines);827}828829void ShaderRD::version_set_compute_code(RID p_version, const HashMap<String, String> &p_code, const String &p_uniforms, const String &p_compute_globals, const Vector<String> &p_custom_defines) {830ERR_FAIL_COND(pipeline_type != RD::PIPELINE_TYPE_COMPUTE);831832Version *version = version_owner.get_or_null(p_version);833ERR_FAIL_NULL(version);834835MutexLock lock(*version->mutex);836837_compile_ensure_finished(version);838839version->compute_globals = p_compute_globals.utf8();840version->uniforms = p_uniforms.utf8();841842_version_set(version, p_code, p_custom_defines);843}844845void ShaderRD::version_set_raytracing_code(RID p_version, const HashMap<String, String> &p_code, const String &p_uniforms, const String &p_raygen_globals, const String &p_any_hit_globals, const String &p_closest_hit_globals, const String &p_miss_globals, const String &p_intersection_globals, const Vector<String> &p_custom_defines) {846ERR_FAIL_COND(pipeline_type != RD::PIPELINE_TYPE_RAYTRACING);847848Version *version = version_owner.get_or_null(p_version);849ERR_FAIL_NULL(version);850851version->raygen_globals = p_raygen_globals.utf8();852version->any_hit_globals = p_any_hit_globals.utf8();853version->closest_hit_globals = p_closest_hit_globals.utf8();854version->miss_globals = p_miss_globals.utf8();855version->intersection_globals = p_intersection_globals.utf8();856version->uniforms = p_uniforms.utf8();857858_version_set(version, p_code, p_custom_defines);859}860861bool ShaderRD::version_is_valid(RID p_version) {862Version *version = version_owner.get_or_null(p_version);863ERR_FAIL_NULL_V(version, false);864865MutexLock lock(*version->mutex);866867if (version->dirty) {868_initialize_version(version);869for (int i = 0; i < group_enabled.size(); i++) {870if (!group_enabled[i]) {871_allocate_placeholders(version, i);872continue;873}874_compile_version_start(version, i);875}876}877878_compile_ensure_finished(version);879880return version->valid;881}882883bool ShaderRD::version_free(RID p_version) {884if (version_owner.owns(p_version)) {885{886MutexLock lock(versions_mutex);887version_mutexes.erase(p_version);888}889890Version *version = version_owner.get_or_null(p_version);891if (version->embedded) {892MutexLock lock(shader_versions_embedded_set_mutex);893shader_versions_embedded_set.erase({ this, p_version });894}895896version->mutex->lock();897_clear_version(version);898version_owner.free(p_version);899version->mutex->unlock();900memdelete(version->mutex);901} else {902return false;903}904905return true;906}907908void ShaderRD::set_variant_enabled(int p_variant, bool p_enabled) {909ERR_FAIL_COND(version_owner.get_rid_count() > 0); //versions exist910ERR_FAIL_INDEX(p_variant, variants_enabled.size());911variants_enabled.write[p_variant] = p_enabled;912}913914bool ShaderRD::is_variant_enabled(int p_variant) const {915ERR_FAIL_INDEX_V(p_variant, variants_enabled.size(), false);916return variants_enabled[p_variant];917}918919int64_t ShaderRD::get_variant_count() const {920return variants_enabled.size();921}922923int ShaderRD::get_variant_to_group(int p_variant) const {924return variant_to_group[p_variant];925}926927void ShaderRD::enable_group(int p_group) {928ERR_FAIL_INDEX(p_group, group_enabled.size());929930if (group_enabled[p_group]) {931// Group already enabled, do nothing.932return;933}934935group_enabled.write[p_group] = true;936937// Compile all versions again to include the new group.938for (const RID &version_rid : version_owner.get_owned_list()) {939Version *version = version_owner.get_or_null(version_rid);940version->mutex->lock();941_compile_version_start(version, p_group);942version->mutex->unlock();943}944}945946bool ShaderRD::is_group_enabled(int p_group) const {947return group_enabled[p_group];948}949950int64_t ShaderRD::get_group_count() const {951return group_enabled.size();952}953954const LocalVector<int> &ShaderRD::get_group_to_variants(int p_group) const {955return group_to_variant_map[p_group];956}957958const String &ShaderRD::get_name() const {959return name;960}961962const Vector<uint64_t> &ShaderRD::get_dynamic_buffers() const {963return dynamic_buffers;964}965966bool ShaderRD::shader_cache_cleanup_on_start = false;967968ShaderRD::ShaderRD() {969// Do not feel forced to use this, in most cases it makes little to no difference.970bool use_32_threads = false;971if (RD::get_singleton()->get_device_vendor_name() == "NVIDIA") {972use_32_threads = true;973}974String base_compute_define_text;975if (use_32_threads) {976base_compute_define_text = "\n#define NATIVE_LOCAL_GROUP_SIZE 32\n#define NATIVE_LOCAL_SIZE_2D_X 8\n#define NATIVE_LOCAL_SIZE_2D_Y 4\n";977} else {978base_compute_define_text = "\n#define NATIVE_LOCAL_GROUP_SIZE 64\n#define NATIVE_LOCAL_SIZE_2D_X 8\n#define NATIVE_LOCAL_SIZE_2D_Y 8\n";979}980981base_compute_defines = base_compute_define_text.ascii();982}983984void ShaderRD::initialize(const Vector<String> &p_variant_defines, const String &p_general_defines, const Vector<RD::PipelineImmutableSampler> &p_immutable_samplers, const Vector<uint64_t> &p_dynamic_buffers) {985ERR_FAIL_COND(variant_defines.size());986ERR_FAIL_COND(p_variant_defines.is_empty());987988general_defines = p_general_defines.utf8();989immutable_samplers = p_immutable_samplers;990dynamic_buffers = p_dynamic_buffers;991992// When initialized this way, there is just one group and its always enabled.993group_to_variant_map.insert(0, LocalVector<int>{});994group_enabled.push_back(true);995996for (int i = 0; i < p_variant_defines.size(); i++) {997variant_defines.push_back(VariantDefine(0, p_variant_defines[i], true));998variants_enabled.push_back(true);999variant_to_group.push_back(0);1000group_to_variant_map[0].push_back(i);1001}10021003if (!shader_cache_user_dir.is_empty() || !shader_cache_res_dir.is_empty()) {1004group_sha256.resize(1);1005_initialize_cache();1006}1007}10081009void ShaderRD::_initialize_cache() {1010shader_cache_user_dir_valid = !shader_cache_user_dir.is_empty();1011shader_cache_res_dir_valid = !shader_cache_res_dir.is_empty();1012if (!shader_cache_user_dir_valid) {1013return;1014}10151016for (const KeyValue<int, LocalVector<int>> &E : group_to_variant_map) {1017StringBuilder hash_build;10181019hash_build.append("[base_hash]");1020hash_build.append(base_sha256);1021hash_build.append("[general_defines]");1022hash_build.append(general_defines.get_data());1023hash_build.append("[group_id]");1024hash_build.append(itos(E.key));1025for (uint32_t i = 0; i < E.value.size(); i++) {1026hash_build.append("[variant_defines:" + itos(E.value[i]) + "]");1027hash_build.append(variant_defines[E.value[i]].text.get_data());1028}10291030for (const uint64_t dyn_buffer : dynamic_buffers) {1031hash_build.append("[dynamic_buffer]");1032hash_build.append(uitos(dyn_buffer));1033}10341035group_sha256[E.key] = hash_build.as_string().sha256_text();10361037if (!shader_cache_user_dir.is_empty()) {1038// Validate if it's possible to write to all the directories required by in the user directory.1039Ref<DirAccess> d = DirAccess::open(shader_cache_user_dir);1040if (d.is_null()) {1041shader_cache_user_dir_valid = false;1042ERR_FAIL_MSG(vformat("Unable to open shader cache directory at %s.", shader_cache_user_dir));1043}10441045if (d->change_dir(name) != OK) {1046Error err = d->make_dir(name);1047if (err != OK) {1048shader_cache_user_dir_valid = false;1049ERR_FAIL_MSG(vformat("Unable to create shader cache directory %s at %s.", name, shader_cache_user_dir));1050}10511052d->change_dir(name);1053}10541055if (d->change_dir(group_sha256[E.key]) != OK) {1056Error err = d->make_dir(group_sha256[E.key]);1057if (err != OK) {1058shader_cache_user_dir_valid = false;1059ERR_FAIL_MSG(vformat("Unable to create shader cache directory %s/%s at %s.", name, group_sha256[E.key], shader_cache_user_dir));1060}1061}1062}10631064print_verbose("Shader '" + name + "' (group " + itos(E.key) + ") SHA256: " + group_sha256[E.key]);1065}1066}10671068// Same as above, but allows specifying shader compilation groups.1069void ShaderRD::initialize(const Vector<VariantDefine> &p_variant_defines, const String &p_general_defines, const Vector<RD::PipelineImmutableSampler> &p_immutable_samplers, const Vector<uint64_t> &p_dynamic_buffers) {1070ERR_FAIL_COND(variant_defines.size());1071ERR_FAIL_COND(p_variant_defines.is_empty());10721073general_defines = p_general_defines.utf8();1074immutable_samplers = p_immutable_samplers;1075dynamic_buffers = p_dynamic_buffers;10761077int max_group_id = 0;10781079for (int i = 0; i < p_variant_defines.size(); i++) {1080// Fill variant array.1081variant_defines.push_back(p_variant_defines[i]);1082variants_enabled.push_back(true);1083variant_to_group.push_back(p_variant_defines[i].group);10841085// Map variant array index to group id, so we can iterate over groups later.1086if (!group_to_variant_map.has(p_variant_defines[i].group)) {1087group_to_variant_map.insert(p_variant_defines[i].group, LocalVector<int>{});1088}1089group_to_variant_map[p_variant_defines[i].group].push_back(i);10901091// Track max size.1092if (p_variant_defines[i].group > max_group_id) {1093max_group_id = p_variant_defines[i].group;1094}1095}10961097// Set all to groups to false, then enable those that should be default.1098group_enabled.resize_initialized(max_group_id + 1);1099bool *enabled_ptr = group_enabled.ptrw();1100for (int i = 0; i < p_variant_defines.size(); i++) {1101if (p_variant_defines[i].default_enabled) {1102enabled_ptr[p_variant_defines[i].group] = true;1103}1104}11051106if (!shader_cache_user_dir.is_empty()) {1107group_sha256.resize(max_group_id + 1);1108_initialize_cache();1109}1110}11111112void ShaderRD::shaders_embedded_set_lock() {1113shader_versions_embedded_set_mutex.lock();1114}11151116const ShaderRD::ShaderVersionPairSet &ShaderRD::shaders_embedded_set_get() {1117return shader_versions_embedded_set;1118}11191120void ShaderRD::shaders_embedded_set_unlock() {1121shader_versions_embedded_set_mutex.unlock();1122}11231124void ShaderRD::set_shader_cache_user_dir(const String &p_dir) {1125shader_cache_user_dir = p_dir;1126}11271128const String &ShaderRD::get_shader_cache_user_dir() {1129return shader_cache_user_dir;1130}11311132void ShaderRD::set_shader_cache_res_dir(const String &p_dir) {1133shader_cache_res_dir = p_dir;1134}11351136const String &ShaderRD::get_shader_cache_res_dir() {1137return shader_cache_res_dir;1138}11391140void ShaderRD::set_shader_cache_save_compressed(bool p_enable) {1141shader_cache_save_compressed = p_enable;1142}11431144void ShaderRD::set_shader_cache_save_compressed_zstd(bool p_enable) {1145shader_cache_save_compressed_zstd = p_enable;1146}11471148void ShaderRD::set_shader_cache_save_debug(bool p_enable) {1149shader_cache_save_debug = p_enable;1150}11511152Vector<RD::ShaderStageSPIRVData> ShaderRD::compile_stages(const Vector<String> &p_stage_sources, const Vector<uint64_t> &p_dynamic_buffers) {1153RD::ShaderStageSPIRVData stage;1154Vector<RD::ShaderStageSPIRVData> stages;1155String error;1156RD::ShaderStage compilation_failed_stage = RD::SHADER_STAGE_MAX;1157bool compilation_failed = false;1158for (int64_t i = 0; i < p_stage_sources.size() && !compilation_failed; i++) {1159if (p_stage_sources[i].is_empty()) {1160continue;1161}11621163stage.spirv = RD::get_singleton()->shader_compile_spirv_from_source(RD::ShaderStage(i), p_stage_sources[i], RD::SHADER_LANGUAGE_GLSL, &error);1164stage.dynamic_buffers = p_dynamic_buffers;1165stage.shader_stage = RD::ShaderStage(i);1166if (!stage.spirv.is_empty()) {1167stages.push_back(stage);11681169} else {1170compilation_failed_stage = RD::ShaderStage(i);1171compilation_failed = true;1172}1173}11741175if (compilation_failed) {1176ERR_PRINT("Error compiling " + String(compilation_failed_stage == RD::SHADER_STAGE_COMPUTE ? "Compute " : (compilation_failed_stage == RD::SHADER_STAGE_VERTEX ? "Vertex" : "Fragment")) + " shader.");1177ERR_PRINT(error);11781179#ifdef DEBUG_ENABLED1180ERR_PRINT("code:\n" + p_stage_sources[compilation_failed_stage].get_with_code_lines());1181#endif11821183return Vector<RD::ShaderStageSPIRVData>();1184} else {1185return stages;1186}1187}11881189PackedByteArray ShaderRD::save_shader_cache_bytes(const LocalVector<int> &p_variants, const Vector<Vector<uint8_t>> &p_variant_data) {1190uint32_t variant_count = p_variants.size();1191PackedByteArray bytes;1192int64_t total_size = 0;1193total_size += 4 + sizeof(uint32_t) * 2;1194for (uint32_t i = 0; i < variant_count; i++) {1195total_size += sizeof(uint32_t) + p_variant_data[p_variants[i]].size();1196}11971198bytes.resize(total_size);11991200uint8_t *bytes_ptr = bytes.ptrw();1201memcpy(bytes_ptr, shader_file_header, 4);1202bytes_ptr += 4;12031204*(uint32_t *)(bytes_ptr) = cache_file_version;1205bytes_ptr += sizeof(uint32_t);12061207*(uint32_t *)(bytes_ptr) = variant_count;1208bytes_ptr += sizeof(uint32_t);12091210for (uint32_t i = 0; i < variant_count; i++) {1211int variant_id = p_variants[i];1212*(uint32_t *)(bytes_ptr) = uint32_t(p_variant_data[variant_id].size());1213bytes_ptr += sizeof(uint32_t);12141215memcpy(bytes_ptr, p_variant_data[variant_id].ptr(), p_variant_data[variant_id].size());1216bytes_ptr += p_variant_data[variant_id].size();1217}12181219DEV_ASSERT((bytes.ptrw() + bytes.size()) == bytes_ptr);1220return bytes;1221}12221223String ShaderRD::shader_cache_user_dir;1224String ShaderRD::shader_cache_res_dir;1225bool ShaderRD::shader_cache_save_compressed = true;1226bool ShaderRD::shader_cache_save_compressed_zstd = true;1227bool ShaderRD::shader_cache_save_debug = true;12281229ShaderRD::~ShaderRD() {1230LocalVector<RID> remaining = version_owner.get_owned_list();1231if (remaining.size()) {1232ERR_PRINT(itos(remaining.size()) + " shaders of type " + name + " were never freed");1233for (const RID &version_rid : remaining) {1234version_free(version_rid);1235}1236}1237}123812391240