shader_baker_export_plugin.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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) {
  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);
  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)) {
  88. return false;
  89. }
  90. shader_cache_platform_name = p_platform->get_os_name();
  91. shader_cache_renderer_name = RendererSceneRenderRD::get_singleton()->get_name();
  92. tasks_processed = 0;
  93. tasks_total = 0;
  94. tasks_cancelled = false;
  95. StringBuilder to_hash;
  96. to_hash.append("[GodotVersionNumber]");
  97. to_hash.append(GODOT_VERSION_NUMBER);
  98. to_hash.append("[GodotVersionHash]");
  99. to_hash.append(GODOT_VERSION_HASH);
  100. to_hash.append("[Renderer]");
  101. to_hash.append(shader_cache_renderer_name);
  102. customization_configuration_hash = to_hash.as_string().hash64();
  103. BitField<RenderingShaderLibrary::FeatureBits> renderer_features = {};
  104. bool xr_enabled = GLOBAL_GET("xr/shaders/enabled");
  105. renderer_features.set_flag(RenderingShaderLibrary::FEATURE_ADVANCED_BIT);
  106. if (xr_enabled) {
  107. renderer_features.set_flag(RenderingShaderLibrary::FEATURE_MULTIVIEW_BIT);
  108. }
  109. int vrs_mode = GLOBAL_GET("rendering/vrs/mode");
  110. if (vrs_mode != 0) {
  111. renderer_features.set_flag(RenderingShaderLibrary::FEATURE_VRS_BIT);
  112. }
  113. // Both FP16 and FP32 variants should be included.
  114. renderer_features.set_flag(RenderingShaderLibrary::FEATURE_FP16_BIT);
  115. renderer_features.set_flag(RenderingShaderLibrary::FEATURE_FP32_BIT);
  116. RendererSceneRenderRD::get_singleton()->enable_features(renderer_features);
  117. // Included all shaders created by renderers and effects.
  118. ShaderRD::shaders_embedded_set_lock();
  119. const ShaderRD::ShaderVersionPairSet &pair_set = ShaderRD::shaders_embedded_set_get();
  120. for (Pair<ShaderRD *, RID> pair : pair_set) {
  121. _customize_shader_version(pair.first, pair.second);
  122. }
  123. ShaderRD::shaders_embedded_set_unlock();
  124. // Include all shaders created by embedded materials.
  125. RendererRD::MaterialStorage *material_storage = RendererRD::MaterialStorage::get_singleton();
  126. material_storage->shader_embedded_set_lock();
  127. const HashSet<RID> &rid_set = material_storage->shader_embedded_set_get();
  128. for (RID rid : rid_set) {
  129. RendererRD::MaterialStorage::ShaderData *shader_data = material_storage->shader_get_data(rid);
  130. if (shader_data != nullptr) {
  131. Pair<ShaderRD *, RID> shader_version_pair = shader_data->get_native_shader_and_version();
  132. if (shader_version_pair.first != nullptr) {
  133. _customize_shader_version(shader_version_pair.first, shader_version_pair.second);
  134. }
  135. }
  136. }
  137. material_storage->shader_embedded_set_unlock();
  138. return true;
  139. }
  140. bool ShaderBakerExportPlugin::_begin_customize_scenes(const Ref<EditorExportPlatform> &p_platform, const Vector<String> &p_features) {
  141. if (!_is_active(p_features)) {
  142. return false;
  143. }
  144. if (shader_container_format == nullptr) {
  145. // Resource customization failed to initialize.
  146. return false;
  147. }
  148. return true;
  149. }
  150. void ShaderBakerExportPlugin::_end_customize_resources() {
  151. if (!_initialize_cache_directory()) {
  152. return;
  153. }
  154. // Run a progress bar that waits for all shader baking tasks to finish.
  155. bool progress_active = true;
  156. EditorProgress editor_progress("baking_shaders", TTR("Baking shaders"), tasks_total);
  157. editor_progress.step("Baking...", 0);
  158. while (progress_active) {
  159. uint32_t tasks_for_progress = 0;
  160. {
  161. MutexLock lock(tasks_mutex);
  162. if (tasks_processed >= tasks_total) {
  163. progress_active = false;
  164. } else {
  165. tasks_condition.wait(lock);
  166. tasks_for_progress = tasks_processed;
  167. }
  168. }
  169. if (progress_active && editor_progress.step("Baking...", tasks_for_progress)) {
  170. // User skipped the shader baker, we just don't pack the shaders in the project.
  171. tasks_cancelled = true;
  172. progress_active = false;
  173. }
  174. }
  175. String shader_cache_user_dir = ShaderRD::get_shader_cache_user_dir();
  176. for (const ShaderGroupItem &group_item : shader_group_items) {
  177. // Wait for all shader compilation tasks of the group to be finished.
  178. for (WorkerThreadPool::TaskID task_id : group_item.variant_tasks) {
  179. WorkerThreadPool::get_singleton()->wait_for_task_completion(task_id);
  180. }
  181. if (!tasks_cancelled) {
  182. WorkResult work_result;
  183. {
  184. MutexLock lock(shader_work_results_mutex);
  185. work_result = shader_work_results[group_item.cache_path];
  186. }
  187. PackedByteArray cache_file_bytes = ShaderRD::save_shader_cache_bytes(group_item.variants, work_result.variant_data);
  188. add_file(shader_cache_user_dir.path_join(group_item.cache_path), cache_file_bytes, false);
  189. String cache_file_path = shader_cache_export_path.path_join(group_item.cache_path);
  190. if (!DirAccess::exists(cache_file_path)) {
  191. DirAccess::make_dir_recursive_absolute(cache_file_path.get_base_dir());
  192. }
  193. Ref<FileAccess> cache_file_access = FileAccess::open(cache_file_path, FileAccess::WRITE);
  194. if (cache_file_access.is_valid()) {
  195. cache_file_access->store_buffer(cache_file_bytes);
  196. }
  197. }
  198. }
  199. if (!tasks_cancelled) {
  200. String file_cache_path = shader_cache_export_path.path_join("file_cache");
  201. Ref<FileAccess> cache_list_access = FileAccess::open(file_cache_path, FileAccess::READ_WRITE);
  202. if (cache_list_access.is_null()) {
  203. cache_list_access = FileAccess::open(file_cache_path, FileAccess::WRITE);
  204. }
  205. if (cache_list_access.is_valid()) {
  206. String cache_list_line;
  207. while (cache_list_line = cache_list_access->get_line(), !cache_list_line.is_empty()) {
  208. // Only add if it wasn't already added.
  209. if (!shader_paths_processed.has(cache_list_line)) {
  210. PackedByteArray cache_file_bytes = FileAccess::get_file_as_bytes(shader_cache_export_path.path_join(cache_list_line));
  211. if (!cache_file_bytes.is_empty()) {
  212. add_file(shader_cache_user_dir.path_join(cache_list_line), cache_file_bytes, false);
  213. }
  214. }
  215. shader_paths_processed.erase(cache_list_line);
  216. }
  217. for (const String &shader_path : shader_paths_processed) {
  218. cache_list_access->store_line(shader_path);
  219. }
  220. cache_list_access->close();
  221. }
  222. }
  223. shader_paths_processed.clear();
  224. shader_work_results.clear();
  225. shader_group_items.clear();
  226. _cleanup_container_format();
  227. }
  228. Ref<Resource> ShaderBakerExportPlugin::_customize_resource(const Ref<Resource> &p_resource, const String &p_path) {
  229. RendererRD::MaterialStorage *singleton = RendererRD::MaterialStorage::get_singleton();
  230. DEV_ASSERT(singleton != nullptr);
  231. Ref<Material> material = p_resource;
  232. if (material.is_valid()) {
  233. RID material_rid = material->get_rid();
  234. if (material_rid.is_valid()) {
  235. RendererRD::MaterialStorage::ShaderData *shader_data = singleton->material_get_shader_data(material_rid);
  236. if (shader_data != nullptr) {
  237. Pair<ShaderRD *, RID> shader_version_pair = shader_data->get_native_shader_and_version();
  238. if (shader_version_pair.first != nullptr) {
  239. _customize_shader_version(shader_version_pair.first, shader_version_pair.second);
  240. }
  241. }
  242. }
  243. }
  244. return Ref<Resource>();
  245. }
  246. Node *ShaderBakerExportPlugin::_customize_scene(Node *p_root, const String &p_path) {
  247. LocalVector<Node *> nodes_to_visit;
  248. nodes_to_visit.push_back(p_root);
  249. while (!nodes_to_visit.is_empty()) {
  250. // Visit all nodes recursively in the scene to find the Label3Ds and Sprite3Ds.
  251. Node *node = nodes_to_visit[nodes_to_visit.size() - 1];
  252. nodes_to_visit.remove_at(nodes_to_visit.size() - 1);
  253. Label3D *label_3d = Object::cast_to<Label3D>(node);
  254. Sprite3D *sprite_3d = Object::cast_to<Sprite3D>(node);
  255. if (label_3d != nullptr || sprite_3d != nullptr) {
  256. // Create materials for Label3D and Sprite3D, which are normally generated at runtime on demand.
  257. HashMap<StringName, Variant> properties;
  258. // These must match the defaults set by Sprite3D/Label3D.
  259. properties["transparent"] = true; // Label3D doesn't have this property, but it is always true anyway.
  260. properties["shaded"] = false;
  261. properties["double_sided"] = true;
  262. properties["no_depth_test"] = false;
  263. properties["fixed_size"] = false;
  264. properties["billboard"] = StandardMaterial3D::BILLBOARD_DISABLED;
  265. properties["texture_filter"] = StandardMaterial3D::TEXTURE_FILTER_LINEAR_WITH_MIPMAPS;
  266. properties["alpha_antialiasing_mode"] = StandardMaterial3D::ALPHA_ANTIALIASING_OFF;
  267. properties["alpha_cut"] = SpriteBase3D::ALPHA_CUT_DISABLED;
  268. List<PropertyInfo> property_list;
  269. node->get_property_list(&property_list);
  270. for (const PropertyInfo &info : property_list) {
  271. bool valid = false;
  272. Variant property = node->get(info.name, &valid);
  273. if (valid) {
  274. properties[info.name] = property;
  275. }
  276. }
  277. // This must follow the logic in Sprite3D::draw_texture_rect().
  278. BaseMaterial3D::Transparency mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_DISABLED;
  279. if (properties["transparent"]) {
  280. SpriteBase3D::AlphaCutMode acm = SpriteBase3D::AlphaCutMode(int(properties["alpha_cut"]));
  281. if (acm == SpriteBase3D::ALPHA_CUT_DISCARD) {
  282. mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA_SCISSOR;
  283. } else if (acm == SpriteBase3D::ALPHA_CUT_OPAQUE_PREPASS) {
  284. mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA_DEPTH_PRE_PASS;
  285. } else if (acm == SpriteBase3D::ALPHA_CUT_HASH) {
  286. mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA_HASH;
  287. } else {
  288. mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA;
  289. }
  290. }
  291. StandardMaterial3D::BillboardMode billboard_mode = StandardMaterial3D::BillboardMode(int(properties["billboard"]));
  292. 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"])));
  293. _customize_resource(sprite_3d_material, String());
  294. if (label_3d != nullptr) {
  295. // Generate variants with and without MSDF support since we don't have access to the font here.
  296. 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"])));
  297. _customize_resource(label_3d_material, String());
  298. }
  299. }
  300. // Visit children.
  301. int child_count = node->get_child_count();
  302. for (int i = 0; i < child_count; i++) {
  303. nodes_to_visit.push_back(node->get_child(i));
  304. }
  305. }
  306. return nullptr;
  307. }
  308. uint64_t ShaderBakerExportPlugin::_get_customization_configuration_hash() const {
  309. return customization_configuration_hash;
  310. }
  311. void ShaderBakerExportPlugin::_customize_shader_version(ShaderRD *p_shader, RID p_version) {
  312. const int64_t variant_count = p_shader->get_variant_count();
  313. const int64_t group_count = p_shader->get_group_count();
  314. LocalVector<ShaderGroupItem> group_items;
  315. group_items.resize(group_count);
  316. RBSet<uint32_t> groups_to_compile;
  317. for (int64_t i = 0; i < group_count; i++) {
  318. if (!p_shader->is_group_enabled(i)) {
  319. continue;
  320. }
  321. String cache_path = p_shader->version_get_cache_file_relative_path(p_version, i, shader_container_driver);
  322. if (shader_paths_processed.has(cache_path)) {
  323. continue;
  324. }
  325. shader_paths_processed.insert(cache_path);
  326. groups_to_compile.insert(i);
  327. group_items[i].cache_path = cache_path;
  328. group_items[i].variants = p_shader->get_group_to_variants(i);
  329. {
  330. MutexLock lock(shader_work_results_mutex);
  331. shader_work_results[cache_path].variant_data.resize(variant_count);
  332. }
  333. }
  334. for (int64_t i = 0; i < variant_count; i++) {
  335. int group = p_shader->get_variant_to_group(i);
  336. if (!p_shader->is_variant_enabled(i) || !groups_to_compile.has(group)) {
  337. continue;
  338. }
  339. WorkItem work_item;
  340. work_item.cache_path = group_items[group].cache_path;
  341. work_item.shader_name = p_shader->get_name();
  342. work_item.stage_sources = p_shader->version_build_variant_stage_sources(p_version, i);
  343. work_item.variant = i;
  344. WorkerThreadPool::TaskID task_id = WorkerThreadPool::get_singleton()->add_template_task(this, &ShaderBakerExportPlugin::_process_work_item, work_item);
  345. group_items[group].variant_tasks.push_back(task_id);
  346. tasks_total++;
  347. }
  348. for (uint32_t i : groups_to_compile) {
  349. shader_group_items.push_back(group_items[i]);
  350. }
  351. }
  352. void ShaderBakerExportPlugin::_process_work_item(WorkItem p_work_item) {
  353. if (!tasks_cancelled) {
  354. // Only process the item if the tasks haven't been cancelled by the user yet.
  355. Vector<RD::ShaderStageSPIRVData> spirv_data = ShaderRD::compile_stages(p_work_item.stage_sources);
  356. ERR_FAIL_COND_MSG(spirv_data.is_empty(), "Unable to retrieve SPIR-V data for shader");
  357. RD::ShaderReflection shader_refl;
  358. Error err = RenderingDeviceCommons::reflect_spirv(spirv_data, shader_refl);
  359. ERR_FAIL_COND_MSG(err != OK, "Unable to reflect SPIR-V data that was compiled");
  360. Ref<RenderingShaderContainer> shader_container = shader_container_format->create_container();
  361. shader_container->set_from_shader_reflection(p_work_item.shader_name, shader_refl);
  362. // Compile shader binary from SPIR-V.
  363. bool code_compiled = shader_container->set_code_from_spirv(spirv_data);
  364. ERR_FAIL_COND_MSG(!code_compiled, vformat("Failed to compile code to native for SPIR-V."));
  365. PackedByteArray shader_bytes = shader_container->to_bytes();
  366. {
  367. MutexLock lock(shader_work_results_mutex);
  368. shader_work_results[p_work_item.cache_path].variant_data.ptrw()[p_work_item.variant] = shader_bytes;
  369. }
  370. }
  371. {
  372. MutexLock lock(tasks_mutex);
  373. tasks_processed++;
  374. }
  375. tasks_condition.notify_one();
  376. }
  377. ShaderBakerExportPlugin::ShaderBakerExportPlugin() {
  378. // Do nothing.
  379. }
  380. ShaderBakerExportPlugin::~ShaderBakerExportPlugin() {
  381. // Do nothing.
  382. }
  383. void ShaderBakerExportPlugin::add_platform(Ref<ShaderBakerExportPluginPlatform> p_platform) {
  384. platforms.push_back(p_platform);
  385. }
  386. void ShaderBakerExportPlugin::remove_platform(Ref<ShaderBakerExportPluginPlatform> p_platform) {
  387. platforms.erase(p_platform);
  388. }