Path: blob/master/editor/export/shader_baker_export_plugin.cpp
9896 views
/**************************************************************************/1/* shader_baker_export_plugin.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_baker_export_plugin.h"3132#include "core/config/project_settings.h"33#include "core/version.h"34#include "editor/editor_node.h"35#include "scene/3d/label_3d.h"36#include "scene/3d/sprite_3d.h"37#include "servers/rendering/renderer_rd/renderer_scene_render_rd.h"38#include "servers/rendering/renderer_rd/storage_rd/material_storage.h"3940// Ensure that AlphaCut is the same between the two classes so we can share the code to detect transparency.41static_assert(ENUM_MEMBERS_EQUAL(SpriteBase3D::ALPHA_CUT_DISABLED, Label3D::ALPHA_CUT_DISABLED));42static_assert(ENUM_MEMBERS_EQUAL(SpriteBase3D::ALPHA_CUT_DISCARD, Label3D::ALPHA_CUT_DISCARD));43static_assert(ENUM_MEMBERS_EQUAL(SpriteBase3D::ALPHA_CUT_OPAQUE_PREPASS, Label3D::ALPHA_CUT_OPAQUE_PREPASS));44static_assert(ENUM_MEMBERS_EQUAL(SpriteBase3D::ALPHA_CUT_HASH, Label3D::ALPHA_CUT_HASH));45static_assert(ENUM_MEMBERS_EQUAL(SpriteBase3D::ALPHA_CUT_MAX, Label3D::ALPHA_CUT_MAX));4647String ShaderBakerExportPlugin::get_name() const {48return "ShaderBaker";49}5051bool ShaderBakerExportPlugin::_is_active(const Vector<String> &p_features) const {52// Shader baker should only work when a RendererRD driver is active, as the embedded shaders won't be found otherwise.53return RendererSceneRenderRD::get_singleton() != nullptr && RendererRD::MaterialStorage::get_singleton() != nullptr && p_features.has("shader_baker");54}5556bool ShaderBakerExportPlugin::_initialize_container_format(const Ref<EditorExportPlatform> &p_platform, const Vector<String> &p_features) {57Variant driver_variant = GLOBAL_GET("rendering/rendering_device/driver." + p_platform->get_os_name().to_lower());58if (!driver_variant.is_string()) {59driver_variant = GLOBAL_GET("rendering/rendering_device/driver");60if (!driver_variant.is_string()) {61return false;62}63}6465shader_container_driver = driver_variant;6667for (Ref<ShaderBakerExportPluginPlatform> platform : platforms) {68if (platform->matches_driver(shader_container_driver)) {69shader_container_format = platform->create_shader_container_format(p_platform);70ERR_FAIL_NULL_V_MSG(shader_container_format, false, "Unable to create shader container format for the export platform.");71return true;72}73}7475return false;76}7778void ShaderBakerExportPlugin::_cleanup_container_format() {79if (shader_container_format != nullptr) {80memdelete(shader_container_format);81shader_container_format = nullptr;82}83}8485bool ShaderBakerExportPlugin::_initialize_cache_directory() {86shader_cache_export_path = get_export_base_path().path_join("shader_baker").path_join(shader_cache_platform_name).path_join(shader_container_driver);8788if (!DirAccess::dir_exists_absolute(shader_cache_export_path)) {89Error err = DirAccess::make_dir_recursive_absolute(shader_cache_export_path);90ERR_FAIL_COND_V_MSG(err != OK, false, "Can't create shader cache folder for exporting.");91}9293return true;94}9596bool ShaderBakerExportPlugin::_begin_customize_resources(const Ref<EditorExportPlatform> &p_platform, const Vector<String> &p_features) {97if (!_is_active(p_features)) {98return false;99}100101if (!_initialize_container_format(p_platform, p_features)) {102return false;103}104105if (Engine::get_singleton()->is_generate_spirv_debug_info_enabled()) {106WARN_PRINT("Shader baker can't generate a compatible shader when run with --generate-spirv-debug-info. Restart the editor without this argument if you want to bake shaders.");107return false;108}109110shader_cache_platform_name = p_platform->get_os_name();111shader_cache_renderer_name = RendererSceneRenderRD::get_singleton()->get_name();112tasks_processed = 0;113tasks_total = 0;114tasks_cancelled = false;115116StringBuilder to_hash;117to_hash.append("[GodotVersionNumber]");118to_hash.append(GODOT_VERSION_NUMBER);119to_hash.append("[GodotVersionHash]");120to_hash.append(GODOT_VERSION_HASH);121to_hash.append("[Renderer]");122to_hash.append(shader_cache_renderer_name);123customization_configuration_hash = to_hash.as_string().hash64();124125BitField<RenderingShaderLibrary::FeatureBits> renderer_features = {};126bool xr_enabled = GLOBAL_GET("xr/shaders/enabled");127renderer_features.set_flag(RenderingShaderLibrary::FEATURE_ADVANCED_BIT);128if (xr_enabled) {129renderer_features.set_flag(RenderingShaderLibrary::FEATURE_MULTIVIEW_BIT);130}131132int vrs_mode = GLOBAL_GET("rendering/vrs/mode");133if (vrs_mode != 0) {134renderer_features.set_flag(RenderingShaderLibrary::FEATURE_VRS_BIT);135}136137// Both FP16 and FP32 variants should be included.138renderer_features.set_flag(RenderingShaderLibrary::FEATURE_FP16_BIT);139renderer_features.set_flag(RenderingShaderLibrary::FEATURE_FP32_BIT);140141RendererSceneRenderRD::get_singleton()->enable_features(renderer_features);142143// Included all shaders created by renderers and effects.144ShaderRD::shaders_embedded_set_lock();145const ShaderRD::ShaderVersionPairSet &pair_set = ShaderRD::shaders_embedded_set_get();146for (Pair<ShaderRD *, RID> pair : pair_set) {147_customize_shader_version(pair.first, pair.second);148}149150ShaderRD::shaders_embedded_set_unlock();151152// Include all shaders created by embedded materials.153RendererRD::MaterialStorage *material_storage = RendererRD::MaterialStorage::get_singleton();154material_storage->shader_embedded_set_lock();155const HashSet<RID> &rid_set = material_storage->shader_embedded_set_get();156for (RID rid : rid_set) {157RendererRD::MaterialStorage::ShaderData *shader_data = material_storage->shader_get_data(rid);158if (shader_data != nullptr) {159Pair<ShaderRD *, RID> shader_version_pair = shader_data->get_native_shader_and_version();160if (shader_version_pair.first != nullptr) {161_customize_shader_version(shader_version_pair.first, shader_version_pair.second);162}163}164}165166material_storage->shader_embedded_set_unlock();167168return true;169}170171bool ShaderBakerExportPlugin::_begin_customize_scenes(const Ref<EditorExportPlatform> &p_platform, const Vector<String> &p_features) {172if (!_is_active(p_features)) {173return false;174}175176if (shader_container_format == nullptr) {177// Resource customization failed to initialize.178return false;179}180181return true;182}183184void ShaderBakerExportPlugin::_end_customize_resources() {185if (!_initialize_cache_directory()) {186return;187}188189// Run a progress bar that waits for all shader baking tasks to finish.190bool progress_active = true;191EditorProgress editor_progress("baking_shaders", TTR("Baking shaders"), tasks_total);192editor_progress.step("Baking...", 0);193while (progress_active) {194uint32_t tasks_for_progress = 0;195{196MutexLock lock(tasks_mutex);197if (tasks_processed >= tasks_total) {198progress_active = false;199} else {200tasks_condition.wait(lock);201tasks_for_progress = tasks_processed;202}203}204205if (progress_active && editor_progress.step("Baking...", tasks_for_progress)) {206// User skipped the shader baker, we just don't pack the shaders in the project.207tasks_cancelled = true;208progress_active = false;209}210}211212String shader_cache_user_dir = ShaderRD::get_shader_cache_user_dir();213for (const ShaderGroupItem &group_item : shader_group_items) {214// Wait for all shader compilation tasks of the group to be finished.215for (WorkerThreadPool::TaskID task_id : group_item.variant_tasks) {216WorkerThreadPool::get_singleton()->wait_for_task_completion(task_id);217}218219if (!tasks_cancelled) {220WorkResult work_result;221{222MutexLock lock(shader_work_results_mutex);223work_result = shader_work_results[group_item.cache_path];224}225226PackedByteArray cache_file_bytes = ShaderRD::save_shader_cache_bytes(group_item.variants, work_result.variant_data);227add_file(shader_cache_user_dir.path_join(group_item.cache_path), cache_file_bytes, false);228229String cache_file_path = shader_cache_export_path.path_join(group_item.cache_path);230if (!DirAccess::exists(cache_file_path)) {231DirAccess::make_dir_recursive_absolute(cache_file_path.get_base_dir());232}233234Ref<FileAccess> cache_file_access = FileAccess::open(cache_file_path, FileAccess::WRITE);235if (cache_file_access.is_valid()) {236cache_file_access->store_buffer(cache_file_bytes);237}238}239}240241if (!tasks_cancelled) {242String file_cache_path = shader_cache_export_path.path_join("file_cache");243Ref<FileAccess> cache_list_access = FileAccess::open(file_cache_path, FileAccess::READ_WRITE);244if (cache_list_access.is_null()) {245cache_list_access = FileAccess::open(file_cache_path, FileAccess::WRITE);246}247248if (cache_list_access.is_valid()) {249String cache_list_line;250while (cache_list_line = cache_list_access->get_line(), !cache_list_line.is_empty()) {251// Only add if it wasn't already added.252if (!shader_paths_processed.has(cache_list_line)) {253PackedByteArray cache_file_bytes = FileAccess::get_file_as_bytes(shader_cache_export_path.path_join(cache_list_line));254if (!cache_file_bytes.is_empty()) {255add_file(shader_cache_user_dir.path_join(cache_list_line), cache_file_bytes, false);256}257}258259shader_paths_processed.erase(cache_list_line);260}261262for (const String &shader_path : shader_paths_processed) {263cache_list_access->store_line(shader_path);264}265266cache_list_access->close();267}268}269270shader_paths_processed.clear();271shader_work_results.clear();272shader_group_items.clear();273274_cleanup_container_format();275}276277Ref<Resource> ShaderBakerExportPlugin::_customize_resource(const Ref<Resource> &p_resource, const String &p_path) {278RendererRD::MaterialStorage *singleton = RendererRD::MaterialStorage::get_singleton();279DEV_ASSERT(singleton != nullptr);280281Ref<Material> material = p_resource;282if (material.is_valid()) {283RID material_rid = material->get_rid();284if (material_rid.is_valid()) {285RendererRD::MaterialStorage::ShaderData *shader_data = singleton->material_get_shader_data(material_rid);286if (shader_data != nullptr) {287Pair<ShaderRD *, RID> shader_version_pair = shader_data->get_native_shader_and_version();288if (shader_version_pair.first != nullptr) {289_customize_shader_version(shader_version_pair.first, shader_version_pair.second);290}291}292}293}294295return Ref<Resource>();296}297298Node *ShaderBakerExportPlugin::_customize_scene(Node *p_root, const String &p_path) {299LocalVector<Node *> nodes_to_visit;300nodes_to_visit.push_back(p_root);301while (!nodes_to_visit.is_empty()) {302// Visit all nodes recursively in the scene to find the Label3Ds and Sprite3Ds.303Node *node = nodes_to_visit[nodes_to_visit.size() - 1];304nodes_to_visit.remove_at(nodes_to_visit.size() - 1);305306Label3D *label_3d = Object::cast_to<Label3D>(node);307Sprite3D *sprite_3d = Object::cast_to<Sprite3D>(node);308if (label_3d != nullptr || sprite_3d != nullptr) {309// Create materials for Label3D and Sprite3D, which are normally generated at runtime on demand.310HashMap<StringName, Variant> properties;311312// These must match the defaults set by Sprite3D/Label3D.313properties["transparent"] = true; // Label3D doesn't have this property, but it is always true anyway.314properties["shaded"] = false;315properties["double_sided"] = true;316properties["no_depth_test"] = false;317properties["fixed_size"] = false;318properties["billboard"] = StandardMaterial3D::BILLBOARD_DISABLED;319properties["texture_filter"] = StandardMaterial3D::TEXTURE_FILTER_LINEAR_WITH_MIPMAPS;320properties["alpha_antialiasing_mode"] = StandardMaterial3D::ALPHA_ANTIALIASING_OFF;321properties["alpha_cut"] = SpriteBase3D::ALPHA_CUT_DISABLED;322323List<PropertyInfo> property_list;324node->get_property_list(&property_list);325for (const PropertyInfo &info : property_list) {326bool valid = false;327Variant property = node->get(info.name, &valid);328if (valid) {329properties[info.name] = property;330}331}332333// This must follow the logic in Sprite3D::draw_texture_rect().334BaseMaterial3D::Transparency mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_DISABLED;335if (properties["transparent"]) {336SpriteBase3D::AlphaCutMode acm = SpriteBase3D::AlphaCutMode(int(properties["alpha_cut"]));337if (acm == SpriteBase3D::ALPHA_CUT_DISCARD) {338mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA_SCISSOR;339} else if (acm == SpriteBase3D::ALPHA_CUT_OPAQUE_PREPASS) {340mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA_DEPTH_PRE_PASS;341} else if (acm == SpriteBase3D::ALPHA_CUT_HASH) {342mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA_HASH;343} else {344mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA;345}346}347348StandardMaterial3D::BillboardMode billboard_mode = StandardMaterial3D::BillboardMode(int(properties["billboard"]));349Ref<Material> sprite_3d_material = StandardMaterial3D::get_material_for_2d(bool(properties["shaded"]), mat_transparency, bool(properties["double_sided"]), billboard_mode == StandardMaterial3D::BILLBOARD_ENABLED, billboard_mode == StandardMaterial3D::BILLBOARD_FIXED_Y, false, bool(properties["no_depth_test"]), bool(properties["fixed_size"]), BaseMaterial3D::TextureFilter(int(properties["texture_filter"])), BaseMaterial3D::AlphaAntiAliasing(int(properties["alpha_antialiasing_mode"])));350_customize_resource(sprite_3d_material, String());351352if (label_3d != nullptr) {353// Generate variants with and without MSDF support since we don't have access to the font here.354Ref<Material> label_3d_material = StandardMaterial3D::get_material_for_2d(bool(properties["shaded"]), mat_transparency, bool(properties["double_sided"]), billboard_mode == StandardMaterial3D::BILLBOARD_ENABLED, billboard_mode == StandardMaterial3D::BILLBOARD_FIXED_Y, true, bool(properties["no_depth_test"]), bool(properties["fixed_size"]), BaseMaterial3D::TextureFilter(int(properties["texture_filter"])), BaseMaterial3D::AlphaAntiAliasing(int(properties["alpha_antialiasing_mode"])));355_customize_resource(label_3d_material, String());356}357}358359// Visit children.360int child_count = node->get_child_count();361for (int i = 0; i < child_count; i++) {362nodes_to_visit.push_back(node->get_child(i));363}364}365366return nullptr;367}368369uint64_t ShaderBakerExportPlugin::_get_customization_configuration_hash() const {370return customization_configuration_hash;371}372373void ShaderBakerExportPlugin::_customize_shader_version(ShaderRD *p_shader, RID p_version) {374const int64_t variant_count = p_shader->get_variant_count();375const int64_t group_count = p_shader->get_group_count();376LocalVector<ShaderGroupItem> group_items;377group_items.resize(group_count);378379RBSet<uint32_t> groups_to_compile;380for (int64_t i = 0; i < group_count; i++) {381if (!p_shader->is_group_enabled(i)) {382continue;383}384385String cache_path = p_shader->version_get_cache_file_relative_path(p_version, i, shader_container_driver);386if (shader_paths_processed.has(cache_path)) {387continue;388}389390shader_paths_processed.insert(cache_path);391groups_to_compile.insert(i);392393group_items[i].cache_path = cache_path;394group_items[i].variants = p_shader->get_group_to_variants(i);395396{397MutexLock lock(shader_work_results_mutex);398shader_work_results[cache_path].variant_data.resize(variant_count);399}400}401402for (int64_t i = 0; i < variant_count; i++) {403int group = p_shader->get_variant_to_group(i);404if (!p_shader->is_variant_enabled(i) || !groups_to_compile.has(group)) {405continue;406}407408WorkItem work_item;409work_item.cache_path = group_items[group].cache_path;410work_item.shader_name = p_shader->get_name();411work_item.stage_sources = p_shader->version_build_variant_stage_sources(p_version, i);412work_item.variant = i;413414WorkerThreadPool::TaskID task_id = WorkerThreadPool::get_singleton()->add_template_task(this, &ShaderBakerExportPlugin::_process_work_item, work_item);415group_items[group].variant_tasks.push_back(task_id);416tasks_total++;417}418419for (uint32_t i : groups_to_compile) {420shader_group_items.push_back(group_items[i]);421}422}423424void ShaderBakerExportPlugin::_process_work_item(WorkItem p_work_item) {425if (!tasks_cancelled) {426// Only process the item if the tasks haven't been cancelled by the user yet.427Vector<RD::ShaderStageSPIRVData> spirv_data = ShaderRD::compile_stages(p_work_item.stage_sources);428ERR_FAIL_COND_MSG(spirv_data.is_empty(), "Unable to retrieve SPIR-V data for shader");429430RD::ShaderReflection shader_refl;431Error err = RenderingDeviceCommons::reflect_spirv(spirv_data, shader_refl);432ERR_FAIL_COND_MSG(err != OK, "Unable to reflect SPIR-V data that was compiled");433434Ref<RenderingShaderContainer> shader_container = shader_container_format->create_container();435shader_container->set_from_shader_reflection(p_work_item.shader_name, shader_refl);436437// Compile shader binary from SPIR-V.438bool code_compiled = shader_container->set_code_from_spirv(spirv_data);439ERR_FAIL_COND_MSG(!code_compiled, vformat("Failed to compile code to native for SPIR-V."));440441PackedByteArray shader_bytes = shader_container->to_bytes();442{443MutexLock lock(shader_work_results_mutex);444shader_work_results[p_work_item.cache_path].variant_data.ptrw()[p_work_item.variant] = shader_bytes;445}446}447448{449MutexLock lock(tasks_mutex);450tasks_processed++;451}452453tasks_condition.notify_one();454}455456ShaderBakerExportPlugin::ShaderBakerExportPlugin() {457// Do nothing.458}459460ShaderBakerExportPlugin::~ShaderBakerExportPlugin() {461// Do nothing.462}463464void ShaderBakerExportPlugin::add_platform(Ref<ShaderBakerExportPluginPlatform> p_platform) {465platforms.push_back(p_platform);466}467468void ShaderBakerExportPlugin::remove_platform(Ref<ShaderBakerExportPluginPlatform> p_platform) {469platforms.erase(p_platform);470}471472473