Path: blob/master/editor/export/shader_baker_export_plugin.cpp
20959 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/io/dir_access.h"34#include "core/version.h"35#include "editor/editor_node.h"36#include "scene/3d/label_3d.h"37#include "scene/3d/sprite_3d.h"38#include "servers/rendering/renderer_rd/renderer_scene_render_rd.h"39#include "servers/rendering/renderer_rd/storage_rd/material_storage.h"40#include "servers/rendering/rendering_shader_container.h"4142// Ensure that AlphaCut is the same between the two classes so we can share the code to detect transparency.43static_assert(ENUM_MEMBERS_EQUAL(SpriteBase3D::ALPHA_CUT_DISABLED, Label3D::ALPHA_CUT_DISABLED));44static_assert(ENUM_MEMBERS_EQUAL(SpriteBase3D::ALPHA_CUT_DISCARD, Label3D::ALPHA_CUT_DISCARD));45static_assert(ENUM_MEMBERS_EQUAL(SpriteBase3D::ALPHA_CUT_OPAQUE_PREPASS, Label3D::ALPHA_CUT_OPAQUE_PREPASS));46static_assert(ENUM_MEMBERS_EQUAL(SpriteBase3D::ALPHA_CUT_HASH, Label3D::ALPHA_CUT_HASH));47static_assert(ENUM_MEMBERS_EQUAL(SpriteBase3D::ALPHA_CUT_MAX, Label3D::ALPHA_CUT_MAX));4849String ShaderBakerExportPlugin::get_name() const {50return "ShaderBaker";51}5253bool ShaderBakerExportPlugin::_is_active(const Vector<String> &p_features) const {54// Shader baker should only work when a RendererRD driver is active, as the embedded shaders won't be found otherwise.55return RendererSceneRenderRD::get_singleton() != nullptr && RendererRD::MaterialStorage::get_singleton() != nullptr && p_features.has("shader_baker");56}5758bool ShaderBakerExportPlugin::_initialize_container_format(const Ref<EditorExportPlatform> &p_platform, const Ref<EditorExportPreset> &p_preset) {59shader_container_driver = p_preset->get_project_setting("rendering/rendering_device/driver");60ERR_FAIL_COND_V_MSG(shader_container_driver.is_empty(), false, "Invalid `rendering/rendering_device/driver` setting, disabling shader baking.");6162for (Ref<ShaderBakerExportPluginPlatform> platform : platforms) {63if (platform->matches_driver(shader_container_driver)) {64shader_container_format = platform->create_shader_container_format(p_platform, p_preset);65ERR_FAIL_NULL_V_MSG(shader_container_format, false, "Unable to create shader container format for the export platform.");66return true;67}68}6970return false;71}7273void ShaderBakerExportPlugin::_cleanup_container_format() {74if (shader_container_format != nullptr) {75memdelete(shader_container_format);76shader_container_format = nullptr;77}78}7980bool ShaderBakerExportPlugin::_initialize_cache_directory() {81shader_cache_export_path = get_export_base_path().path_join("shader_baker").path_join(shader_cache_platform_name).path_join(shader_container_driver);8283if (!DirAccess::dir_exists_absolute(shader_cache_export_path)) {84Error err = DirAccess::make_dir_recursive_absolute(shader_cache_export_path);85ERR_FAIL_COND_V_MSG(err != OK, false, "Can't create shader cache folder for exporting.");86}8788return true;89}9091bool ShaderBakerExportPlugin::_begin_customize_resources(const Ref<EditorExportPlatform> &p_platform, const Vector<String> &p_features) {92if (!_is_active(p_features)) {93return false;94}9596if (!_initialize_container_format(p_platform, get_export_preset())) {97return false;98}99100if (Engine::get_singleton()->is_generate_spirv_debug_info_enabled()) {101WARN_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.");102return false;103}104105shader_cache_platform_name = p_platform->get_os_name();106shader_cache_renderer_name = RendererSceneRenderRD::get_singleton()->get_name();107tasks_processed = 0;108tasks_total = 0;109tasks_cancelled = false;110111StringBuilder to_hash;112to_hash.append("[GodotVersionNumber]");113to_hash.append(GODOT_VERSION_NUMBER);114to_hash.append("[GodotVersionHash]");115to_hash.append(GODOT_VERSION_HASH);116to_hash.append("[Renderer]");117to_hash.append(shader_cache_renderer_name);118customization_configuration_hash = to_hash.as_string().hash64();119120BitField<RenderingShaderLibrary::FeatureBits> renderer_features = {};121#ifndef XR_DISABLED122bool xr_enabled = GLOBAL_GET("xr/shaders/enabled");123renderer_features.set_flag(RenderingShaderLibrary::FEATURE_ADVANCED_BIT);124if (xr_enabled) {125renderer_features.set_flag(RenderingShaderLibrary::FEATURE_MULTIVIEW_BIT);126}127#endif // XR_DISABLED128129int vrs_mode = GLOBAL_GET("rendering/vrs/mode");130if (vrs_mode != 0) {131renderer_features.set_flag(RenderingShaderLibrary::FEATURE_VRS_BIT);132}133134// Both FP16 and FP32 variants should be included.135renderer_features.set_flag(RenderingShaderLibrary::FEATURE_FP16_BIT);136renderer_features.set_flag(RenderingShaderLibrary::FEATURE_FP32_BIT);137138RendererSceneRenderRD::get_singleton()->enable_features(renderer_features);139140// Included all shaders created by renderers and effects.141ShaderRD::shaders_embedded_set_lock();142const ShaderRD::ShaderVersionPairSet &pair_set = ShaderRD::shaders_embedded_set_get();143for (Pair<ShaderRD *, RID> pair : pair_set) {144_customize_shader_version(pair.first, pair.second);145}146147ShaderRD::shaders_embedded_set_unlock();148149// Include all shaders created by embedded materials.150RendererRD::MaterialStorage *material_storage = RendererRD::MaterialStorage::get_singleton();151material_storage->shader_embedded_set_lock();152const HashSet<RID> &rid_set = material_storage->shader_embedded_set_get();153for (RID rid : rid_set) {154RendererRD::MaterialStorage::ShaderData *shader_data = material_storage->shader_get_data(rid);155if (shader_data != nullptr) {156Pair<ShaderRD *, RID> shader_version_pair = shader_data->get_native_shader_and_version();157if (shader_version_pair.first != nullptr) {158_customize_shader_version(shader_version_pair.first, shader_version_pair.second);159}160}161}162163material_storage->shader_embedded_set_unlock();164165return true;166}167168bool ShaderBakerExportPlugin::_begin_customize_scenes(const Ref<EditorExportPlatform> &p_platform, const Vector<String> &p_features) {169if (!_is_active(p_features)) {170return false;171}172173if (shader_container_format == nullptr) {174// Resource customization failed to initialize.175return false;176}177178return true;179}180181void ShaderBakerExportPlugin::_end_customize_resources() {182if (!_initialize_cache_directory()) {183return;184}185186// Run a progress bar that waits for all shader baking tasks to finish.187bool progress_active = true;188EditorProgress editor_progress("baking_shaders", TTR("Baking shaders"), tasks_total);189editor_progress.step("Baking...", 0);190while (progress_active) {191uint32_t tasks_for_progress = 0;192{193MutexLock lock(tasks_mutex);194if (tasks_processed >= tasks_total) {195progress_active = false;196} else {197tasks_condition.wait(lock);198tasks_for_progress = tasks_processed;199}200}201202if (progress_active && editor_progress.step("Baking...", tasks_for_progress)) {203// User skipped the shader baker, we just don't pack the shaders in the project.204tasks_cancelled = true;205progress_active = false;206}207}208209String shader_cache_user_dir = ShaderRD::get_shader_cache_user_dir();210for (const ShaderGroupItem &group_item : shader_group_items) {211// Wait for all shader compilation tasks of the group to be finished.212for (WorkerThreadPool::TaskID task_id : group_item.variant_tasks) {213WorkerThreadPool::get_singleton()->wait_for_task_completion(task_id);214}215216if (!tasks_cancelled) {217WorkResult work_result;218{219MutexLock lock(shader_work_results_mutex);220work_result = shader_work_results[group_item.cache_path];221}222223PackedByteArray cache_file_bytes = ShaderRD::save_shader_cache_bytes(group_item.variants, work_result.variant_data);224add_file(shader_cache_user_dir.path_join(group_item.cache_path), cache_file_bytes, false);225226String cache_file_path = shader_cache_export_path.path_join(group_item.cache_path);227if (!DirAccess::exists(cache_file_path)) {228DirAccess::make_dir_recursive_absolute(cache_file_path.get_base_dir());229}230231Ref<FileAccess> cache_file_access = FileAccess::open(cache_file_path, FileAccess::WRITE);232if (cache_file_access.is_valid()) {233cache_file_access->store_buffer(cache_file_bytes);234}235}236}237238if (!tasks_cancelled) {239String file_cache_path = shader_cache_export_path.path_join("file_cache");240Ref<FileAccess> cache_list_access = FileAccess::open(file_cache_path, FileAccess::READ_WRITE);241if (cache_list_access.is_null()) {242cache_list_access = FileAccess::open(file_cache_path, FileAccess::WRITE);243}244245if (cache_list_access.is_valid()) {246String cache_list_line;247while (cache_list_line = cache_list_access->get_line(), !cache_list_line.is_empty()) {248// Only add if it wasn't already added.249if (!shader_paths_processed.has(cache_list_line)) {250PackedByteArray cache_file_bytes = FileAccess::get_file_as_bytes(shader_cache_export_path.path_join(cache_list_line));251if (!cache_file_bytes.is_empty()) {252add_file(shader_cache_user_dir.path_join(cache_list_line), cache_file_bytes, false);253}254}255256shader_paths_processed.erase(cache_list_line);257}258259for (const String &shader_path : shader_paths_processed) {260cache_list_access->store_line(shader_path);261}262263cache_list_access->close();264}265}266267shader_paths_processed.clear();268shader_work_results.clear();269shader_group_items.clear();270271_cleanup_container_format();272}273274Ref<Resource> ShaderBakerExportPlugin::_customize_resource(const Ref<Resource> &p_resource, const String &p_path) {275RendererRD::MaterialStorage *singleton = RendererRD::MaterialStorage::get_singleton();276DEV_ASSERT(singleton != nullptr);277278Ref<Material> material = p_resource;279if (material.is_valid()) {280RID material_rid = material->get_rid();281if (material_rid.is_valid()) {282RendererRD::MaterialStorage::ShaderData *shader_data = singleton->material_get_shader_data(material_rid);283if (shader_data != nullptr) {284Pair<ShaderRD *, RID> shader_version_pair = shader_data->get_native_shader_and_version();285if (shader_version_pair.first != nullptr) {286_customize_shader_version(shader_version_pair.first, shader_version_pair.second);287}288}289}290}291292return Ref<Resource>();293}294295Node *ShaderBakerExportPlugin::_customize_scene(Node *p_root, const String &p_path) {296LocalVector<Node *> nodes_to_visit;297nodes_to_visit.push_back(p_root);298while (!nodes_to_visit.is_empty()) {299// Visit all nodes recursively in the scene to find the Label3Ds and Sprite3Ds.300Node *node = nodes_to_visit[nodes_to_visit.size() - 1];301nodes_to_visit.remove_at(nodes_to_visit.size() - 1);302303Label3D *label_3d = Object::cast_to<Label3D>(node);304Sprite3D *sprite_3d = Object::cast_to<Sprite3D>(node);305if (label_3d != nullptr || sprite_3d != nullptr) {306// Create materials for Label3D and Sprite3D, which are normally generated at runtime on demand.307HashMap<StringName, Variant> properties;308309// These must match the defaults set by Sprite3D/Label3D.310properties["transparent"] = true; // Label3D doesn't have this property, but it is always true anyway.311properties["shaded"] = false;312properties["double_sided"] = true;313properties["no_depth_test"] = false;314properties["fixed_size"] = false;315properties["billboard"] = StandardMaterial3D::BILLBOARD_DISABLED;316properties["texture_filter"] = StandardMaterial3D::TEXTURE_FILTER_LINEAR_WITH_MIPMAPS;317properties["alpha_antialiasing_mode"] = StandardMaterial3D::ALPHA_ANTIALIASING_OFF;318properties["alpha_cut"] = SpriteBase3D::ALPHA_CUT_DISABLED;319320List<PropertyInfo> property_list;321node->get_property_list(&property_list);322for (const PropertyInfo &info : property_list) {323bool valid = false;324Variant property = node->get(info.name, &valid);325if (valid) {326properties[info.name] = property;327}328}329330// This must follow the logic in Sprite3D::draw_texture_rect().331BaseMaterial3D::Transparency mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_DISABLED;332if (properties["transparent"]) {333SpriteBase3D::AlphaCutMode acm = SpriteBase3D::AlphaCutMode(int(properties["alpha_cut"]));334if (acm == SpriteBase3D::ALPHA_CUT_DISCARD) {335mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA_SCISSOR;336} else if (acm == SpriteBase3D::ALPHA_CUT_OPAQUE_PREPASS) {337mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA_DEPTH_PRE_PASS;338} else if (acm == SpriteBase3D::ALPHA_CUT_HASH) {339mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA_HASH;340} else {341mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA;342}343}344345StandardMaterial3D::BillboardMode billboard_mode = StandardMaterial3D::BillboardMode(int(properties["billboard"]));346Ref<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"])));347_customize_resource(sprite_3d_material, String());348349if (label_3d != nullptr) {350// Generate variants with and without MSDF support since we don't have access to the font here.351Ref<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"])));352_customize_resource(label_3d_material, String());353}354}355356// Visit children.357int child_count = node->get_child_count();358for (int i = 0; i < child_count; i++) {359nodes_to_visit.push_back(node->get_child(i));360}361}362363return nullptr;364}365366uint64_t ShaderBakerExportPlugin::_get_customization_configuration_hash() const {367return customization_configuration_hash;368}369370void ShaderBakerExportPlugin::_customize_shader_version(ShaderRD *p_shader, RID p_version) {371const int64_t variant_count = p_shader->get_variant_count();372const int64_t group_count = p_shader->get_group_count();373LocalVector<ShaderGroupItem> group_items;374group_items.resize(group_count);375376RBSet<uint32_t> groups_to_compile;377for (int64_t i = 0; i < group_count; i++) {378if (!p_shader->is_group_enabled(i)) {379continue;380}381382String cache_path = p_shader->version_get_cache_file_relative_path(p_version, i, shader_container_driver);383if (shader_paths_processed.has(cache_path)) {384continue;385}386387shader_paths_processed.insert(cache_path);388groups_to_compile.insert(i);389390group_items[i].cache_path = cache_path;391group_items[i].variants = p_shader->get_group_to_variants(i);392393{394MutexLock lock(shader_work_results_mutex);395shader_work_results[cache_path].variant_data.resize(variant_count);396}397}398399for (int64_t i = 0; i < variant_count; i++) {400int group = p_shader->get_variant_to_group(i);401if (!p_shader->is_variant_enabled(i) || !groups_to_compile.has(group)) {402continue;403}404405WorkItem work_item;406work_item.cache_path = group_items[group].cache_path;407work_item.shader_name = p_shader->get_name();408work_item.stage_sources = p_shader->version_build_variant_stage_sources(p_version, i);409work_item.dynamic_buffers = p_shader->get_dynamic_buffers();410work_item.variant = i;411412WorkerThreadPool::TaskID task_id = WorkerThreadPool::get_singleton()->add_template_task(this, &ShaderBakerExportPlugin::_process_work_item, work_item);413group_items[group].variant_tasks.push_back(task_id);414tasks_total++;415}416417for (uint32_t i : groups_to_compile) {418shader_group_items.push_back(group_items[i]);419}420}421422void ShaderBakerExportPlugin::_process_work_item(WorkItem p_work_item) {423if (!tasks_cancelled) {424// Only process the item if the tasks haven't been cancelled by the user yet.425Vector<RD::ShaderStageSPIRVData> spirv_data = ShaderRD::compile_stages(p_work_item.stage_sources, p_work_item.dynamic_buffers);426if (unlikely(spirv_data.is_empty())) {427ERR_PRINT("Unable to retrieve SPIR-V data for shader.");428} else {429Ref<RenderingShaderContainer> shader_container = shader_container_format->create_container();430431// Compile shader binary from SPIR-V.432bool code_compiled = shader_container->set_code_from_spirv(p_work_item.shader_name, spirv_data);433if (unlikely(!code_compiled)) {434ERR_PRINT("Failed to compile code to native for SPIR-V.");435} else {436PackedByteArray shader_bytes = shader_container->to_bytes();437{438MutexLock lock(shader_work_results_mutex);439shader_work_results[p_work_item.cache_path].variant_data.ptrw()[p_work_item.variant] = shader_bytes;440}441}442}443}444445{446MutexLock lock(tasks_mutex);447tasks_processed++;448}449450tasks_condition.notify_one();451}452453ShaderBakerExportPlugin::ShaderBakerExportPlugin() {454// Do nothing.455}456457ShaderBakerExportPlugin::~ShaderBakerExportPlugin() {458// Do nothing.459}460461void ShaderBakerExportPlugin::add_platform(Ref<ShaderBakerExportPluginPlatform> p_platform) {462platforms.push_back(p_platform);463}464465void ShaderBakerExportPlugin::remove_platform(Ref<ShaderBakerExportPluginPlatform> p_platform) {466platforms.erase(p_platform);467}468469470