shader_baker_export_plugin.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. /**************************************************************************/
  2. /* shader_baker_export_plugin.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "shader_baker_export_plugin.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/version.h"
  33. #include "editor/editor_node.h"
  34. #include "scene/3d/label_3d.h"
  35. #include "scene/3d/sprite_3d.h"
  36. #include "servers/rendering/renderer_rd/renderer_scene_render_rd.h"
  37. #include "servers/rendering/renderer_rd/storage_rd/material_storage.h"
  38. // Ensure that AlphaCut is the same between the two classes so we can share the code to detect transparency.
  39. static_assert(ENUM_MEMBERS_EQUAL(SpriteBase3D::ALPHA_CUT_DISABLED, Label3D::ALPHA_CUT_DISABLED));
  40. static_assert(ENUM_MEMBERS_EQUAL(SpriteBase3D::ALPHA_CUT_DISCARD, Label3D::ALPHA_CUT_DISCARD));
  41. static_assert(ENUM_MEMBERS_EQUAL(SpriteBase3D::ALPHA_CUT_OPAQUE_PREPASS, Label3D::ALPHA_CUT_OPAQUE_PREPASS));
  42. static_assert(ENUM_MEMBERS_EQUAL(SpriteBase3D::ALPHA_CUT_HASH, Label3D::ALPHA_CUT_HASH));
  43. static_assert(ENUM_MEMBERS_EQUAL(SpriteBase3D::ALPHA_CUT_MAX, Label3D::ALPHA_CUT_MAX));
  44. String ShaderBakerExportPlugin::get_name() const {
  45. return "ShaderBaker";
  46. }
  47. bool ShaderBakerExportPlugin::_is_active(const Vector<String> &p_features) const {
  48. // Shader baker should only work when a RendererRD driver is active, as the embedded shaders won't be found otherwise.
  49. return RendererSceneRenderRD::get_singleton() != nullptr && RendererRD::MaterialStorage::get_singleton() != nullptr && p_features.has("shader_baker");
  50. }
  51. bool ShaderBakerExportPlugin::_initialize_container_format(const Ref<EditorExportPlatform> &p_platform, const Vector<String> &p_features, const Ref<EditorExportPreset> &p_preset) {
  52. Variant driver_variant = GLOBAL_GET("rendering/rendering_device/driver." + p_platform->get_os_name().to_lower());
  53. if (!driver_variant.is_string()) {
  54. driver_variant = GLOBAL_GET("rendering/rendering_device/driver");
  55. if (!driver_variant.is_string()) {
  56. return false;
  57. }
  58. }
  59. shader_container_driver = driver_variant;
  60. for (Ref<ShaderBakerExportPluginPlatform> platform : platforms) {
  61. if (platform->matches_driver(shader_container_driver)) {
  62. shader_container_format = platform->create_shader_container_format(p_platform, get_export_preset());
  63. ERR_FAIL_NULL_V_MSG(shader_container_format, false, "Unable to create shader container format for the export platform.");
  64. return true;
  65. }
  66. }
  67. return false;
  68. }
  69. void ShaderBakerExportPlugin::_cleanup_container_format() {
  70. if (shader_container_format != nullptr) {
  71. memdelete(shader_container_format);
  72. shader_container_format = nullptr;
  73. }
  74. }
  75. bool ShaderBakerExportPlugin::_initialize_cache_directory() {
  76. shader_cache_export_path = get_export_base_path().path_join("shader_baker").path_join(shader_cache_platform_name).path_join(shader_container_driver);
  77. if (!DirAccess::dir_exists_absolute(shader_cache_export_path)) {
  78. Error err = DirAccess::make_dir_recursive_absolute(shader_cache_export_path);
  79. ERR_FAIL_COND_V_MSG(err != OK, false, "Can't create shader cache folder for exporting.");
  80. }
  81. return true;
  82. }
  83. bool ShaderBakerExportPlugin::_begin_customize_resources(const Ref<EditorExportPlatform> &p_platform, const Vector<String> &p_features) {
  84. if (!_is_active(p_features)) {
  85. return false;
  86. }
  87. if (!_initialize_container_format(p_platform, p_features, get_export_preset())) {
  88. return false;
  89. }
  90. if (Engine::get_singleton()->is_generate_spirv_debug_info_enabled()) {
  91. WARN_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.");
  92. return false;
  93. }
  94. shader_cache_platform_name = p_platform->get_os_name();
  95. shader_cache_renderer_name = RendererSceneRenderRD::get_singleton()->get_name();
  96. tasks_processed = 0;
  97. tasks_total = 0;
  98. tasks_cancelled = false;
  99. StringBuilder to_hash;
  100. to_hash.append("[GodotVersionNumber]");
  101. to_hash.append(GODOT_VERSION_NUMBER);
  102. to_hash.append("[GodotVersionHash]");
  103. to_hash.append(GODOT_VERSION_HASH);
  104. to_hash.append("[Renderer]");
  105. to_hash.append(shader_cache_renderer_name);
  106. customization_configuration_hash = to_hash.as_string().hash64();
  107. BitField<RenderingShaderLibrary::FeatureBits> renderer_features = {};
  108. bool xr_enabled = GLOBAL_GET("xr/shaders/enabled");
  109. renderer_features.set_flag(RenderingShaderLibrary::FEATURE_ADVANCED_BIT);
  110. if (xr_enabled) {
  111. renderer_features.set_flag(RenderingShaderLibrary::FEATURE_MULTIVIEW_BIT);
  112. }
  113. int vrs_mode = GLOBAL_GET("rendering/vrs/mode");
  114. if (vrs_mode != 0) {
  115. renderer_features.set_flag(RenderingShaderLibrary::FEATURE_VRS_BIT);
  116. }
  117. // Both FP16 and FP32 variants should be included.
  118. renderer_features.set_flag(RenderingShaderLibrary::FEATURE_FP16_BIT);
  119. renderer_features.set_flag(RenderingShaderLibrary::FEATURE_FP32_BIT);
  120. RendererSceneRenderRD::get_singleton()->enable_features(renderer_features);
  121. // Included all shaders created by renderers and effects.
  122. ShaderRD::shaders_embedded_set_lock();
  123. const ShaderRD::ShaderVersionPairSet &pair_set = ShaderRD::shaders_embedded_set_get();
  124. for (Pair<ShaderRD *, RID> pair : pair_set) {
  125. _customize_shader_version(pair.first, pair.second);
  126. }
  127. ShaderRD::shaders_embedded_set_unlock();
  128. // Include all shaders created by embedded materials.
  129. RendererRD::MaterialStorage *material_storage = RendererRD::MaterialStorage::get_singleton();
  130. material_storage->shader_embedded_set_lock();
  131. const HashSet<RID> &rid_set = material_storage->shader_embedded_set_get();
  132. for (RID rid : rid_set) {
  133. RendererRD::MaterialStorage::ShaderData *shader_data = material_storage->shader_get_data(rid);
  134. if (shader_data != nullptr) {
  135. Pair<ShaderRD *, RID> shader_version_pair = shader_data->get_native_shader_and_version();
  136. if (shader_version_pair.first != nullptr) {
  137. _customize_shader_version(shader_version_pair.first, shader_version_pair.second);
  138. }
  139. }
  140. }
  141. material_storage->shader_embedded_set_unlock();
  142. return true;
  143. }
  144. bool ShaderBakerExportPlugin::_begin_customize_scenes(const Ref<EditorExportPlatform> &p_platform, const Vector<String> &p_features) {
  145. if (!_is_active(p_features)) {
  146. return false;
  147. }
  148. if (shader_container_format == nullptr) {
  149. // Resource customization failed to initialize.
  150. return false;
  151. }
  152. return true;
  153. }
  154. void ShaderBakerExportPlugin::_end_customize_resources() {
  155. if (!_initialize_cache_directory()) {
  156. return;
  157. }
  158. // Run a progress bar that waits for all shader baking tasks to finish.
  159. bool progress_active = true;
  160. EditorProgress editor_progress("baking_shaders", TTR("Baking shaders"), tasks_total);
  161. editor_progress.step("Baking...", 0);
  162. while (progress_active) {
  163. uint32_t tasks_for_progress = 0;
  164. {
  165. MutexLock lock(tasks_mutex);
  166. if (tasks_processed >= tasks_total) {
  167. progress_active = false;
  168. } else {
  169. tasks_condition.wait(lock);
  170. tasks_for_progress = tasks_processed;
  171. }
  172. }
  173. if (progress_active && editor_progress.step("Baking...", tasks_for_progress)) {
  174. // User skipped the shader baker, we just don't pack the shaders in the project.
  175. tasks_cancelled = true;
  176. progress_active = false;
  177. }
  178. }
  179. String shader_cache_user_dir = ShaderRD::get_shader_cache_user_dir();
  180. for (const ShaderGroupItem &group_item : shader_group_items) {
  181. // Wait for all shader compilation tasks of the group to be finished.
  182. for (WorkerThreadPool::TaskID task_id : group_item.variant_tasks) {
  183. WorkerThreadPool::get_singleton()->wait_for_task_completion(task_id);
  184. }
  185. if (!tasks_cancelled) {
  186. WorkResult work_result;
  187. {
  188. MutexLock lock(shader_work_results_mutex);
  189. work_result = shader_work_results[group_item.cache_path];
  190. }
  191. PackedByteArray cache_file_bytes = ShaderRD::save_shader_cache_bytes(group_item.variants, work_result.variant_data);
  192. add_file(shader_cache_user_dir.path_join(group_item.cache_path), cache_file_bytes, false);
  193. String cache_file_path = shader_cache_export_path.path_join(group_item.cache_path);
  194. if (!DirAccess::exists(cache_file_path)) {
  195. DirAccess::make_dir_recursive_absolute(cache_file_path.get_base_dir());
  196. }
  197. Ref<FileAccess> cache_file_access = FileAccess::open(cache_file_path, FileAccess::WRITE);
  198. if (cache_file_access.is_valid()) {
  199. cache_file_access->store_buffer(cache_file_bytes);
  200. }
  201. }
  202. }
  203. if (!tasks_cancelled) {
  204. String file_cache_path = shader_cache_export_path.path_join("file_cache");
  205. Ref<FileAccess> cache_list_access = FileAccess::open(file_cache_path, FileAccess::READ_WRITE);
  206. if (cache_list_access.is_null()) {
  207. cache_list_access = FileAccess::open(file_cache_path, FileAccess::WRITE);
  208. }
  209. if (cache_list_access.is_valid()) {
  210. String cache_list_line;
  211. while (cache_list_line = cache_list_access->get_line(), !cache_list_line.is_empty()) {
  212. // Only add if it wasn't already added.
  213. if (!shader_paths_processed.has(cache_list_line)) {
  214. PackedByteArray cache_file_bytes = FileAccess::get_file_as_bytes(shader_cache_export_path.path_join(cache_list_line));
  215. if (!cache_file_bytes.is_empty()) {
  216. add_file(shader_cache_user_dir.path_join(cache_list_line), cache_file_bytes, false);
  217. }
  218. }
  219. shader_paths_processed.erase(cache_list_line);
  220. }
  221. for (const String &shader_path : shader_paths_processed) {
  222. cache_list_access->store_line(shader_path);
  223. }
  224. cache_list_access->close();
  225. }
  226. }
  227. shader_paths_processed.clear();
  228. shader_work_results.clear();
  229. shader_group_items.clear();
  230. _cleanup_container_format();
  231. }
  232. Ref<Resource> ShaderBakerExportPlugin::_customize_resource(const Ref<Resource> &p_resource, const String &p_path) {
  233. RendererRD::MaterialStorage *singleton = RendererRD::MaterialStorage::get_singleton();
  234. DEV_ASSERT(singleton != nullptr);
  235. Ref<Material> material = p_resource;
  236. if (material.is_valid()) {
  237. RID material_rid = material->get_rid();
  238. if (material_rid.is_valid()) {
  239. RendererRD::MaterialStorage::ShaderData *shader_data = singleton->material_get_shader_data(material_rid);
  240. if (shader_data != nullptr) {
  241. Pair<ShaderRD *, RID> shader_version_pair = shader_data->get_native_shader_and_version();
  242. if (shader_version_pair.first != nullptr) {
  243. _customize_shader_version(shader_version_pair.first, shader_version_pair.second);
  244. }
  245. }
  246. }
  247. }
  248. return Ref<Resource>();
  249. }
  250. Node *ShaderBakerExportPlugin::_customize_scene(Node *p_root, const String &p_path) {
  251. LocalVector<Node *> nodes_to_visit;
  252. nodes_to_visit.push_back(p_root);
  253. while (!nodes_to_visit.is_empty()) {
  254. // Visit all nodes recursively in the scene to find the Label3Ds and Sprite3Ds.
  255. Node *node = nodes_to_visit[nodes_to_visit.size() - 1];
  256. nodes_to_visit.remove_at(nodes_to_visit.size() - 1);
  257. Label3D *label_3d = Object::cast_to<Label3D>(node);
  258. Sprite3D *sprite_3d = Object::cast_to<Sprite3D>(node);
  259. if (label_3d != nullptr || sprite_3d != nullptr) {
  260. // Create materials for Label3D and Sprite3D, which are normally generated at runtime on demand.
  261. HashMap<StringName, Variant> properties;
  262. // These must match the defaults set by Sprite3D/Label3D.
  263. properties["transparent"] = true; // Label3D doesn't have this property, but it is always true anyway.
  264. properties["shaded"] = false;
  265. properties["double_sided"] = true;
  266. properties["no_depth_test"] = false;
  267. properties["fixed_size"] = false;
  268. properties["billboard"] = StandardMaterial3D::BILLBOARD_DISABLED;
  269. properties["texture_filter"] = StandardMaterial3D::TEXTURE_FILTER_LINEAR_WITH_MIPMAPS;
  270. properties["alpha_antialiasing_mode"] = StandardMaterial3D::ALPHA_ANTIALIASING_OFF;
  271. properties["alpha_cut"] = SpriteBase3D::ALPHA_CUT_DISABLED;
  272. List<PropertyInfo> property_list;
  273. node->get_property_list(&property_list);
  274. for (const PropertyInfo &info : property_list) {
  275. bool valid = false;
  276. Variant property = node->get(info.name, &valid);
  277. if (valid) {
  278. properties[info.name] = property;
  279. }
  280. }
  281. // This must follow the logic in Sprite3D::draw_texture_rect().
  282. BaseMaterial3D::Transparency mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_DISABLED;
  283. if (properties["transparent"]) {
  284. SpriteBase3D::AlphaCutMode acm = SpriteBase3D::AlphaCutMode(int(properties["alpha_cut"]));
  285. if (acm == SpriteBase3D::ALPHA_CUT_DISCARD) {
  286. mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA_SCISSOR;
  287. } else if (acm == SpriteBase3D::ALPHA_CUT_OPAQUE_PREPASS) {
  288. mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA_DEPTH_PRE_PASS;
  289. } else if (acm == SpriteBase3D::ALPHA_CUT_HASH) {
  290. mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA_HASH;
  291. } else {
  292. mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA;
  293. }
  294. }
  295. StandardMaterial3D::BillboardMode billboard_mode = StandardMaterial3D::BillboardMode(int(properties["billboard"]));
  296. Ref<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"])));
  297. _customize_resource(sprite_3d_material, String());
  298. if (label_3d != nullptr) {
  299. // Generate variants with and without MSDF support since we don't have access to the font here.
  300. Ref<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"])));
  301. _customize_resource(label_3d_material, String());
  302. }
  303. }
  304. // Visit children.
  305. int child_count = node->get_child_count();
  306. for (int i = 0; i < child_count; i++) {
  307. nodes_to_visit.push_back(node->get_child(i));
  308. }
  309. }
  310. return nullptr;
  311. }
  312. uint64_t ShaderBakerExportPlugin::_get_customization_configuration_hash() const {
  313. return customization_configuration_hash;
  314. }
  315. void ShaderBakerExportPlugin::_customize_shader_version(ShaderRD *p_shader, RID p_version) {
  316. const int64_t variant_count = p_shader->get_variant_count();
  317. const int64_t group_count = p_shader->get_group_count();
  318. LocalVector<ShaderGroupItem> group_items;
  319. group_items.resize(group_count);
  320. RBSet<uint32_t> groups_to_compile;
  321. for (int64_t i = 0; i < group_count; i++) {
  322. if (!p_shader->is_group_enabled(i)) {
  323. continue;
  324. }
  325. String cache_path = p_shader->version_get_cache_file_relative_path(p_version, i, shader_container_driver);
  326. if (shader_paths_processed.has(cache_path)) {
  327. continue;
  328. }
  329. shader_paths_processed.insert(cache_path);
  330. groups_to_compile.insert(i);
  331. group_items[i].cache_path = cache_path;
  332. group_items[i].variants = p_shader->get_group_to_variants(i);
  333. {
  334. MutexLock lock(shader_work_results_mutex);
  335. shader_work_results[cache_path].variant_data.resize(variant_count);
  336. }
  337. }
  338. for (int64_t i = 0; i < variant_count; i++) {
  339. int group = p_shader->get_variant_to_group(i);
  340. if (!p_shader->is_variant_enabled(i) || !groups_to_compile.has(group)) {
  341. continue;
  342. }
  343. WorkItem work_item;
  344. work_item.cache_path = group_items[group].cache_path;
  345. work_item.shader_name = p_shader->get_name();
  346. work_item.stage_sources = p_shader->version_build_variant_stage_sources(p_version, i);
  347. work_item.variant = i;
  348. WorkerThreadPool::TaskID task_id = WorkerThreadPool::get_singleton()->add_template_task(this, &ShaderBakerExportPlugin::_process_work_item, work_item);
  349. group_items[group].variant_tasks.push_back(task_id);
  350. tasks_total++;
  351. }
  352. for (uint32_t i : groups_to_compile) {
  353. shader_group_items.push_back(group_items[i]);
  354. }
  355. }
  356. void ShaderBakerExportPlugin::_process_work_item(WorkItem p_work_item) {
  357. if (!tasks_cancelled) {
  358. // Only process the item if the tasks haven't been cancelled by the user yet.
  359. Vector<RD::ShaderStageSPIRVData> spirv_data = ShaderRD::compile_stages(p_work_item.stage_sources);
  360. ERR_FAIL_COND_MSG(spirv_data.is_empty(), "Unable to retrieve SPIR-V data for shader");
  361. RD::ShaderReflection shader_refl;
  362. Error err = RenderingDeviceCommons::reflect_spirv(spirv_data, shader_refl);
  363. ERR_FAIL_COND_MSG(err != OK, "Unable to reflect SPIR-V data that was compiled");
  364. Ref<RenderingShaderContainer> shader_container = shader_container_format->create_container();
  365. shader_container->set_from_shader_reflection(p_work_item.shader_name, shader_refl);
  366. // Compile shader binary from SPIR-V.
  367. bool code_compiled = shader_container->set_code_from_spirv(spirv_data);
  368. ERR_FAIL_COND_MSG(!code_compiled, vformat("Failed to compile code to native for SPIR-V."));
  369. PackedByteArray shader_bytes = shader_container->to_bytes();
  370. {
  371. MutexLock lock(shader_work_results_mutex);
  372. shader_work_results[p_work_item.cache_path].variant_data.ptrw()[p_work_item.variant] = shader_bytes;
  373. }
  374. }
  375. {
  376. MutexLock lock(tasks_mutex);
  377. tasks_processed++;
  378. }
  379. tasks_condition.notify_one();
  380. }
  381. ShaderBakerExportPlugin::ShaderBakerExportPlugin() {
  382. // Do nothing.
  383. }
  384. ShaderBakerExportPlugin::~ShaderBakerExportPlugin() {
  385. // Do nothing.
  386. }
  387. void ShaderBakerExportPlugin::add_platform(Ref<ShaderBakerExportPluginPlatform> p_platform) {
  388. platforms.push_back(p_platform);
  389. }
  390. void ShaderBakerExportPlugin::remove_platform(Ref<ShaderBakerExportPluginPlatform> p_platform) {
  391. platforms.erase(p_platform);
  392. }