resource_importer_texture.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  1. /**************************************************************************/
  2. /* resource_importer_texture.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 "resource_importer_texture.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/io/config_file.h"
  33. #include "core/io/image_loader.h"
  34. #include "core/version.h"
  35. #include "editor/file_system/editor_file_system.h"
  36. #include "editor/gui/editor_toaster.h"
  37. #include "editor/import/resource_importer_texture_settings.h"
  38. #include "editor/settings/editor_settings.h"
  39. #include "editor/themes/editor_scale.h"
  40. #include "editor/themes/editor_theme_manager.h"
  41. #include "scene/resources/compressed_texture.h"
  42. void ResourceImporterTexture::_texture_reimport_roughness(const Ref<CompressedTexture2D> &p_tex, const String &p_normal_path, RS::TextureDetectRoughnessChannel p_channel) {
  43. ERR_FAIL_COND(p_tex.is_null());
  44. MutexLock lock(singleton->mutex);
  45. StringName path = p_tex->get_path();
  46. if (!singleton->make_flags.has(path)) {
  47. singleton->make_flags[path] = MakeInfo();
  48. }
  49. singleton->make_flags[path].flags |= MAKE_ROUGHNESS_FLAG;
  50. singleton->make_flags[path].channel_for_roughness = p_channel;
  51. singleton->make_flags[path].normal_path_for_roughness = p_normal_path;
  52. }
  53. void ResourceImporterTexture::_texture_reimport_3d(const Ref<CompressedTexture2D> &p_tex) {
  54. ERR_FAIL_COND(p_tex.is_null());
  55. MutexLock lock(singleton->mutex);
  56. StringName path = p_tex->get_path();
  57. if (!singleton->make_flags.has(path)) {
  58. singleton->make_flags[path] = MakeInfo();
  59. }
  60. singleton->make_flags[path].flags |= MAKE_3D_FLAG;
  61. }
  62. void ResourceImporterTexture::_texture_reimport_normal(const Ref<CompressedTexture2D> &p_tex) {
  63. ERR_FAIL_COND(p_tex.is_null());
  64. MutexLock lock(singleton->mutex);
  65. StringName path = p_tex->get_path();
  66. if (!singleton->make_flags.has(path)) {
  67. singleton->make_flags[path] = MakeInfo();
  68. }
  69. singleton->make_flags[path].flags |= MAKE_NORMAL_FLAG;
  70. }
  71. void ResourceImporterTexture::update_imports() {
  72. if (EditorFileSystem::get_singleton()->is_scanning() || EditorFileSystem::get_singleton()->is_importing()) {
  73. return; // Don't update when EditorFileSystem is doing something else.
  74. }
  75. MutexLock lock(mutex);
  76. Vector<String> to_reimport;
  77. if (make_flags.is_empty()) {
  78. return;
  79. }
  80. for (const KeyValue<StringName, MakeInfo> &E : make_flags) {
  81. Ref<ConfigFile> cf;
  82. cf.instantiate();
  83. String src_path = String(E.key) + ".import";
  84. Error err = cf->load(src_path);
  85. ERR_CONTINUE(err != OK);
  86. bool changed = false;
  87. if (E.value.flags & MAKE_NORMAL_FLAG && int(cf->get_value("params", "compress/normal_map")) == 0) {
  88. print_line(
  89. vformat(TTR("%s: Texture detected as used as a normal map in 3D. Enabling red-green texture compression to reduce memory usage (blue channel is discarded)."),
  90. String(E.key)));
  91. cf->set_value("params", "compress/normal_map", 1);
  92. changed = true;
  93. }
  94. if (E.value.flags & MAKE_ROUGHNESS_FLAG && int(cf->get_value("params", "roughness/mode")) == 0) {
  95. print_line(
  96. vformat(TTR("%s: Texture detected as used as a roughness map in 3D. Enabling roughness limiter based on the detected associated normal map at %s."),
  97. String(E.key), E.value.normal_path_for_roughness));
  98. cf->set_value("params", "roughness/mode", E.value.channel_for_roughness + 2);
  99. cf->set_value("params", "roughness/src_normal", E.value.normal_path_for_roughness);
  100. changed = true;
  101. }
  102. if (E.value.flags & MAKE_3D_FLAG && bool(cf->get_value("params", "detect_3d/compress_to"))) {
  103. const int compress_to = cf->get_value("params", "detect_3d/compress_to");
  104. // 3D detected, disable the callback.
  105. cf->set_value("params", "detect_3d/compress_to", 0);
  106. String compress_string;
  107. if (compress_to == 1) {
  108. cf->set_value("params", "compress/mode", COMPRESS_VRAM_COMPRESSED);
  109. compress_string = "VRAM Compressed (S3TC/ETC/BPTC)";
  110. } else if (compress_to == 2) {
  111. cf->set_value("params", "compress/mode", COMPRESS_BASIS_UNIVERSAL);
  112. compress_string = "Basis Universal";
  113. }
  114. print_line(
  115. vformat(TTR("%s: Texture detected as used in 3D. Enabling mipmap generation and setting the texture compression mode to %s."),
  116. String(E.key), compress_string));
  117. cf->set_value("params", "mipmaps/generate", true);
  118. changed = true;
  119. }
  120. if (changed) {
  121. cf->save(src_path);
  122. to_reimport.push_back(E.key);
  123. }
  124. }
  125. make_flags.clear();
  126. if (!to_reimport.is_empty()) {
  127. EditorFileSystem::get_singleton()->reimport_files(to_reimport);
  128. }
  129. }
  130. String ResourceImporterTexture::get_importer_name() const {
  131. return "texture";
  132. }
  133. String ResourceImporterTexture::get_visible_name() const {
  134. return "Texture2D";
  135. }
  136. void ResourceImporterTexture::get_recognized_extensions(List<String> *p_extensions) const {
  137. ImageLoader::get_recognized_extensions(p_extensions);
  138. }
  139. String ResourceImporterTexture::get_save_extension() const {
  140. return "ctex";
  141. }
  142. String ResourceImporterTexture::get_resource_type() const {
  143. return "CompressedTexture2D";
  144. }
  145. bool ResourceImporterTexture::get_option_visibility(const String &p_path, const String &p_option, const HashMap<StringName, Variant> &p_options) const {
  146. if (p_option == "compress/high_quality" || p_option == "compress/hdr_compression") {
  147. int compress_mode = int(p_options["compress/mode"]);
  148. if (compress_mode != COMPRESS_VRAM_COMPRESSED) {
  149. return false;
  150. }
  151. } else if (p_option == "compress/lossy_quality") {
  152. int compress_mode = int(p_options["compress/mode"]);
  153. if (compress_mode != COMPRESS_LOSSY) {
  154. return false;
  155. }
  156. } else if (p_option == "compress/hdr_mode") {
  157. int compress_mode = int(p_options["compress/mode"]);
  158. if (compress_mode < COMPRESS_VRAM_COMPRESSED) {
  159. return false;
  160. }
  161. } else if (p_option == "compress/normal_map") {
  162. int compress_mode = int(p_options["compress/mode"]);
  163. if (compress_mode == COMPRESS_LOSSLESS) {
  164. return false;
  165. }
  166. } else if (p_option == "mipmaps/limit") {
  167. return p_options["mipmaps/generate"];
  168. } else if (p_option == "compress/uastc_level" || p_option == "compress/rdo_quality_loss") {
  169. return int(p_options["compress/mode"]) == COMPRESS_BASIS_UNIVERSAL;
  170. }
  171. return true;
  172. }
  173. int ResourceImporterTexture::get_preset_count() const {
  174. return 3;
  175. }
  176. String ResourceImporterTexture::get_preset_name(int p_idx) const {
  177. static const char *preset_names[] = {
  178. TTRC("2D/3D (Auto-Detect)"),
  179. TTRC("2D"),
  180. TTRC("3D"),
  181. };
  182. return TTRGET(preset_names[p_idx]);
  183. }
  184. void ResourceImporterTexture::get_import_options(const String &p_path, List<ImportOption> *r_options, int p_preset) const {
  185. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "compress/mode", PROPERTY_HINT_ENUM, "Lossless,Lossy,VRAM Compressed,VRAM Uncompressed,Basis Universal", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), p_preset == PRESET_3D ? 2 : 0));
  186. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "compress/high_quality"), false));
  187. r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "compress/lossy_quality", PROPERTY_HINT_RANGE, "0,1,0.01"), 0.7));
  188. Image::BasisUniversalPackerParams basisu_params;
  189. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "compress/uastc_level", PROPERTY_HINT_ENUM, "Fastest,Faster,Medium,Slower,Slowest"), basisu_params.uastc_level));
  190. r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "compress/rdo_quality_loss", PROPERTY_HINT_RANGE, "0,10,0.001,or_greater"), basisu_params.rdo_quality_loss));
  191. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "compress/hdr_compression", PROPERTY_HINT_ENUM, "Disabled,Opaque Only,Always"), 1));
  192. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "compress/normal_map", PROPERTY_HINT_ENUM, "Detect,Enable,Disabled"), 0));
  193. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "compress/channel_pack", PROPERTY_HINT_ENUM, "sRGB Friendly,Optimized"), 0));
  194. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "mipmaps/generate", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), (p_preset == PRESET_3D ? true : false)));
  195. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "mipmaps/limit", PROPERTY_HINT_RANGE, "-1,256"), -1));
  196. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "roughness/mode", PROPERTY_HINT_ENUM, "Detect,Disabled,Red,Green,Blue,Alpha,Gray"), 0));
  197. r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "roughness/src_normal", PROPERTY_HINT_FILE, "*.bmp,*.dds,*.exr,*.jpeg,*.jpg,*.hdr,*.png,*.svg,*.tga,*.webp"), ""));
  198. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "process/channel_remap/red", PROPERTY_HINT_ENUM, "Red,Green,Blue,Alpha,Inverted Red,Inverted Green,Inverted Blue,Inverted Alpha,Unused,Zero,One"), 0));
  199. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "process/channel_remap/green", PROPERTY_HINT_ENUM, "Red,Green,Blue,Alpha,Inverted Red,Inverted Green,Inverted Blue,Inverted Alpha,Unused,Zero,One"), 1));
  200. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "process/channel_remap/blue", PROPERTY_HINT_ENUM, "Red,Green,Blue,Alpha,Inverted Red,Inverted Green,Inverted Blue,Inverted Alpha,Unused,Zero,One"), 2));
  201. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "process/channel_remap/alpha", PROPERTY_HINT_ENUM, "Red,Green,Blue,Alpha,Inverted Red,Inverted Green,Inverted Blue,Inverted Alpha,Unused,Zero,One"), 3));
  202. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "process/fix_alpha_border"), p_preset != PRESET_3D));
  203. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "process/premult_alpha"), false));
  204. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "process/normal_map_invert_y"), false));
  205. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "process/hdr_as_srgb"), false));
  206. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "process/hdr_clamp_exposure"), false));
  207. // Maximum bound is the highest allowed value for lossy compression (the lowest common denominator).
  208. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "process/size_limit", PROPERTY_HINT_RANGE, "0,16383,1"), 0));
  209. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "detect_3d/compress_to", PROPERTY_HINT_ENUM, "Disabled,VRAM Compressed,Basis Universal"), (p_preset == PRESET_DETECT) ? 1 : 0));
  210. // Do path based customization only if a path was passed.
  211. if (p_path.is_empty() || p_path.get_extension() == "svg") {
  212. r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "svg/scale", PROPERTY_HINT_RANGE, "0.001,100,0.001"), 1.0));
  213. // Editor use only, applies to SVG.
  214. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "editor/scale_with_editor_scale"), false));
  215. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "editor/convert_colors_with_editor_theme"), false));
  216. }
  217. }
  218. void ResourceImporterTexture::save_to_ctex_format(Ref<FileAccess> f, const Ref<Image> &p_image, CompressMode p_compress_mode, Image::UsedChannels p_channels, Image::CompressMode p_compress_format, float p_lossy_quality, const Image::BasisUniversalPackerParams &p_basisu_params) {
  219. switch (p_compress_mode) {
  220. case COMPRESS_LOSSLESS: {
  221. bool lossless_force_png = GLOBAL_GET("rendering/textures/lossless_compression/force_png") || !Image::_webp_mem_loader_func; // WebP module disabled or png is forced.
  222. bool use_webp = !lossless_force_png && p_image->get_width() <= 16383 && p_image->get_height() <= 16383; // WebP has a size limit.
  223. f->store_32(use_webp ? CompressedTexture2D::DATA_FORMAT_WEBP : CompressedTexture2D::DATA_FORMAT_PNG);
  224. f->store_16(p_image->get_width());
  225. f->store_16(p_image->get_height());
  226. f->store_32(p_image->get_mipmap_count());
  227. f->store_32(p_image->get_format());
  228. for (int i = 0; i < p_image->get_mipmap_count() + 1; i++) {
  229. Vector<uint8_t> data;
  230. if (use_webp) {
  231. data = Image::webp_lossless_packer(i ? p_image->get_image_from_mipmap(i) : p_image);
  232. } else {
  233. data = Image::png_packer(i ? p_image->get_image_from_mipmap(i) : p_image);
  234. }
  235. const uint64_t data_size = data.size();
  236. f->store_32(data_size);
  237. f->store_buffer(data.ptr(), data_size);
  238. }
  239. } break;
  240. case COMPRESS_LOSSY: {
  241. f->store_32(CompressedTexture2D::DATA_FORMAT_WEBP);
  242. f->store_16(p_image->get_width());
  243. f->store_16(p_image->get_height());
  244. f->store_32(p_image->get_mipmap_count());
  245. f->store_32(p_image->get_format());
  246. for (int i = 0; i < p_image->get_mipmap_count() + 1; i++) {
  247. Vector<uint8_t> data = Image::webp_lossy_packer(i ? p_image->get_image_from_mipmap(i) : p_image, p_lossy_quality);
  248. const uint64_t data_size = data.size();
  249. f->store_32(data_size);
  250. f->store_buffer(data.ptr(), data_size);
  251. }
  252. } break;
  253. case COMPRESS_VRAM_COMPRESSED: {
  254. Ref<Image> image = p_image->duplicate();
  255. image->compress_from_channels(p_compress_format, p_channels);
  256. f->store_32(CompressedTexture2D::DATA_FORMAT_IMAGE);
  257. f->store_16(image->get_width());
  258. f->store_16(image->get_height());
  259. f->store_32(image->get_mipmap_count());
  260. f->store_32(image->get_format());
  261. f->store_buffer(image->get_data());
  262. } break;
  263. case COMPRESS_VRAM_UNCOMPRESSED: {
  264. f->store_32(CompressedTexture2D::DATA_FORMAT_IMAGE);
  265. f->store_16(p_image->get_width());
  266. f->store_16(p_image->get_height());
  267. f->store_32(p_image->get_mipmap_count());
  268. f->store_32(p_image->get_format());
  269. f->store_buffer(p_image->get_data());
  270. } break;
  271. case COMPRESS_BASIS_UNIVERSAL: {
  272. f->store_32(CompressedTexture2D::DATA_FORMAT_BASIS_UNIVERSAL);
  273. f->store_16(p_image->get_width());
  274. f->store_16(p_image->get_height());
  275. f->store_32(p_image->get_mipmap_count());
  276. f->store_32(p_image->get_format());
  277. Vector<uint8_t> data = Image::basis_universal_packer(p_image, p_channels, p_basisu_params);
  278. const uint64_t data_size = data.size();
  279. f->store_32(data_size);
  280. f->store_buffer(data.ptr(), data_size);
  281. } break;
  282. }
  283. }
  284. void ResourceImporterTexture::_save_ctex(const Ref<Image> &p_image, const String &p_to_path, CompressMode p_compress_mode, float p_lossy_quality, const Image::BasisUniversalPackerParams &p_basisu_params, Image::CompressMode p_vram_compression, bool p_mipmaps, bool p_streamable, bool p_detect_3d, bool p_detect_roughness, bool p_detect_normal, bool p_force_normal, bool p_srgb_friendly, bool p_force_po2_for_compressed, uint32_t p_limit_mipmap, const Ref<Image> &p_normal, Image::RoughnessChannel p_roughness_channel) {
  285. Ref<FileAccess> f = FileAccess::open(p_to_path, FileAccess::WRITE);
  286. ERR_FAIL_COND(f.is_null());
  287. // Godot Streamable Texture 2D.
  288. f->store_8('G');
  289. f->store_8('S');
  290. f->store_8('T');
  291. f->store_8('2');
  292. // Current format version.
  293. f->store_32(CompressedTexture2D::FORMAT_VERSION);
  294. // Texture may be resized later, so original size must be saved first.
  295. f->store_32(p_image->get_width());
  296. f->store_32(p_image->get_height());
  297. uint32_t flags = 0;
  298. if (p_streamable) {
  299. flags |= CompressedTexture2D::FORMAT_BIT_STREAM;
  300. }
  301. if (p_mipmaps) {
  302. flags |= CompressedTexture2D::FORMAT_BIT_HAS_MIPMAPS;
  303. }
  304. if (p_detect_3d) {
  305. flags |= CompressedTexture2D::FORMAT_BIT_DETECT_3D;
  306. }
  307. if (p_detect_roughness) {
  308. flags |= CompressedTexture2D::FORMAT_BIT_DETECT_ROUGNESS;
  309. }
  310. if (p_detect_normal) {
  311. flags |= CompressedTexture2D::FORMAT_BIT_DETECT_NORMAL;
  312. }
  313. f->store_32(flags);
  314. f->store_32(p_limit_mipmap);
  315. // Reserved.
  316. f->store_32(0);
  317. f->store_32(0);
  318. f->store_32(0);
  319. if ((p_compress_mode == COMPRESS_LOSSLESS || p_compress_mode == COMPRESS_LOSSY) && p_image->get_format() >= Image::FORMAT_RF) {
  320. p_compress_mode = COMPRESS_VRAM_UNCOMPRESSED; //these can't go as lossy
  321. }
  322. Ref<Image> image = p_image->duplicate();
  323. if (p_mipmaps) {
  324. if (p_force_po2_for_compressed && (p_compress_mode == COMPRESS_BASIS_UNIVERSAL || p_compress_mode == COMPRESS_VRAM_COMPRESSED)) {
  325. image->resize_to_po2();
  326. }
  327. if (!image->has_mipmaps() || p_force_normal) {
  328. image->generate_mipmaps(p_force_normal);
  329. }
  330. } else {
  331. image->clear_mipmaps();
  332. }
  333. // Generate roughness mipmaps from normal texture.
  334. if (image->has_mipmaps() && p_normal.is_valid()) {
  335. image->generate_mipmap_roughness(p_roughness_channel, p_normal);
  336. }
  337. // Optimization: Only check for color channels when compressing as BasisU or VRAM.
  338. Image::UsedChannels used_channels = Image::USED_CHANNELS_RGBA;
  339. if (p_compress_mode == COMPRESS_BASIS_UNIVERSAL || p_compress_mode == COMPRESS_VRAM_COMPRESSED) {
  340. Image::CompressSource comp_source = Image::COMPRESS_SOURCE_GENERIC;
  341. if (p_force_normal) {
  342. comp_source = Image::COMPRESS_SOURCE_NORMAL;
  343. } else if (p_srgb_friendly) {
  344. comp_source = Image::COMPRESS_SOURCE_SRGB;
  345. }
  346. used_channels = image->detect_used_channels(comp_source);
  347. }
  348. save_to_ctex_format(f, image, p_compress_mode, used_channels, p_vram_compression, p_lossy_quality, p_basisu_params);
  349. }
  350. void ResourceImporterTexture::_save_editor_meta(const Dictionary &p_metadata, const String &p_to_path) {
  351. Ref<FileAccess> f = FileAccess::open(p_to_path, FileAccess::WRITE);
  352. ERR_FAIL_COND(f.is_null());
  353. f->store_var(p_metadata);
  354. }
  355. Dictionary ResourceImporterTexture::_load_editor_meta(const String &p_path) const {
  356. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
  357. ERR_FAIL_COND_V_MSG(f.is_null(), Dictionary(), vformat("Missing required editor-specific import metadata for a texture (please reimport it using the 'Import' tab): '%s'", p_path));
  358. return f->get_var();
  359. }
  360. void ResourceImporterTexture::_remap_channels(Ref<Image> &r_image, ChannelRemap p_options[4]) {
  361. ERR_FAIL_COND(r_image->is_compressed());
  362. // Currently HDR inverted remapping is not allowed.
  363. bool attempted_hdr_inverted = false;
  364. if (r_image->get_format() >= Image::FORMAT_RF && r_image->get_format() <= Image::FORMAT_RGBE9995) {
  365. // Formats which can hold HDR data cannot be inverted the same way as unsigned normalized ones (1.0 - channel).
  366. for (int i = 0; i < 4; i++) {
  367. switch (p_options[i]) {
  368. case REMAP_INV_R:
  369. attempted_hdr_inverted = true;
  370. p_options[i] = REMAP_R;
  371. break;
  372. case REMAP_INV_G:
  373. attempted_hdr_inverted = true;
  374. p_options[i] = REMAP_G;
  375. break;
  376. case REMAP_INV_B:
  377. attempted_hdr_inverted = true;
  378. p_options[i] = REMAP_B;
  379. break;
  380. case REMAP_INV_A:
  381. attempted_hdr_inverted = true;
  382. p_options[i] = REMAP_A;
  383. break;
  384. default:
  385. break;
  386. }
  387. }
  388. }
  389. if (attempted_hdr_inverted) {
  390. WARN_PRINT("Attempted to use an inverted channel remap on an HDR image. The remap has been changed to its uninverted equivalent.");
  391. }
  392. // Optimization: Set the remap from 'unused' to either 0 or 1 to avoid repeated checks in the conversion loop.
  393. for (int i = 0; i < 4; i++) {
  394. if (p_options[i] == REMAP_UNUSED) {
  395. p_options[i] = i == 3 ? REMAP_1 : REMAP_0;
  396. }
  397. }
  398. // Expand the image's channel count in the event that the current set of channels doesn't allow for the desired remap.
  399. const Image::Format original_format = r_image->get_format();
  400. const uint32_t channel_mask = Image::get_format_component_mask(original_format);
  401. // Whether a channel is supported by the format itself.
  402. const bool has_channel_r = channel_mask & 0x1;
  403. const bool has_channel_g = channel_mask & 0x2;
  404. const bool has_channel_b = channel_mask & 0x4;
  405. const bool has_channel_a = channel_mask & 0x8;
  406. // Whether a certain channel needs to be remapped.
  407. const bool remap_r = p_options[0] != REMAP_R ? !(!has_channel_r && p_options[0] == REMAP_0) : false;
  408. const bool remap_g = p_options[1] != REMAP_G ? !(!has_channel_g && p_options[1] == REMAP_0) : false;
  409. const bool remap_b = p_options[2] != REMAP_B ? !(!has_channel_b && p_options[2] == REMAP_0) : false;
  410. const bool remap_a = p_options[3] != REMAP_A ? !(!has_channel_a && p_options[3] == REMAP_1) : false;
  411. if (!(remap_r || remap_g || remap_b || remap_a)) {
  412. // Default color map, do nothing.
  413. return;
  414. }
  415. // Whether a certain channel set is needed, either from the source or the remap.
  416. const bool needs_rg = remap_g || has_channel_g;
  417. const bool needs_rgb = remap_b || has_channel_b;
  418. const bool needs_rgba = remap_a || has_channel_a;
  419. bool could_not_expand = false;
  420. switch (original_format) {
  421. case Image::FORMAT_R8:
  422. case Image::FORMAT_RG8:
  423. case Image::FORMAT_RGB8: {
  424. // Convert to either RGBA8, RGB8 or RG8.
  425. if (needs_rgba) {
  426. r_image->convert(Image::FORMAT_RGBA8);
  427. } else if (needs_rgb) {
  428. r_image->convert(Image::FORMAT_RGB8);
  429. } else if (needs_rg) {
  430. r_image->convert(Image::FORMAT_RG8);
  431. }
  432. } break;
  433. case Image::FORMAT_RH:
  434. case Image::FORMAT_RGH:
  435. case Image::FORMAT_RGBH: {
  436. // Convert to either RGBAH, RGBH or RGH.
  437. if (needs_rgba) {
  438. r_image->convert(Image::FORMAT_RGBAH);
  439. } else if (needs_rgb) {
  440. r_image->convert(Image::FORMAT_RGBH);
  441. } else if (needs_rg) {
  442. r_image->convert(Image::FORMAT_RGH);
  443. }
  444. } break;
  445. case Image::FORMAT_RF:
  446. case Image::FORMAT_RGF:
  447. case Image::FORMAT_RGBF: {
  448. // Convert to either RGBAF, RGBF or RGF.
  449. if (needs_rgba) {
  450. r_image->convert(Image::FORMAT_RGBAF);
  451. } else if (needs_rgb) {
  452. r_image->convert(Image::FORMAT_RGBF);
  453. } else if (needs_rg) {
  454. r_image->convert(Image::FORMAT_RGF);
  455. }
  456. } break;
  457. case Image::FORMAT_L8: {
  458. const bool uniform_rgb = (p_options[0] == p_options[1] && p_options[1] == p_options[2]) || !(remap_r || remap_g || remap_b);
  459. if (uniform_rgb) {
  460. // Uniform RGB.
  461. if (needs_rgba) {
  462. r_image->convert(Image::FORMAT_LA8);
  463. }
  464. } else {
  465. // Non-uniform RGB.
  466. if (needs_rgba) {
  467. r_image->convert(Image::FORMAT_RGBA8);
  468. } else {
  469. r_image->convert(Image::FORMAT_RGB8);
  470. }
  471. could_not_expand = true;
  472. }
  473. } break;
  474. case Image::FORMAT_LA8: {
  475. const bool uniform_rgb = (p_options[0] == p_options[1] && p_options[1] == p_options[2]) || !(remap_r || remap_g || remap_b);
  476. if (!uniform_rgb) {
  477. // Non-uniform RGB.
  478. r_image->convert(Image::FORMAT_RGBA8);
  479. could_not_expand = true;
  480. }
  481. } break;
  482. case Image::FORMAT_RGB565: {
  483. if (needs_rgba) {
  484. // RGB565 doesn't have an alpha expansion, convert to RGBA8.
  485. r_image->convert(Image::FORMAT_RGBA8);
  486. could_not_expand = true;
  487. }
  488. } break;
  489. case Image::FORMAT_RGBE9995: {
  490. if (needs_rgba) {
  491. // RGB9995 doesn't have an alpha expansion, convert to RGBAH.
  492. r_image->convert(Image::FORMAT_RGBAH);
  493. could_not_expand = true;
  494. }
  495. } break;
  496. default: {
  497. } break;
  498. }
  499. if (could_not_expand) {
  500. WARN_PRINT(vformat("Unable to expand image format %s's channels (the target format does not exist), converting to %s as a fallback.",
  501. Image::get_format_name(original_format), Image::get_format_name(r_image->get_format())));
  502. }
  503. // Remap the channels.
  504. for (int x = 0; x < r_image->get_width(); x++) {
  505. for (int y = 0; y < r_image->get_height(); y++) {
  506. Color src = r_image->get_pixel(x, y);
  507. Color dst;
  508. for (int i = 0; i < 4; i++) {
  509. switch (p_options[i]) {
  510. case REMAP_R:
  511. dst[i] = src.r;
  512. break;
  513. case REMAP_G:
  514. dst[i] = src.g;
  515. break;
  516. case REMAP_B:
  517. dst[i] = src.b;
  518. break;
  519. case REMAP_A:
  520. dst[i] = src.a;
  521. break;
  522. case REMAP_INV_R:
  523. dst[i] = 1.0f - src.r;
  524. break;
  525. case REMAP_INV_G:
  526. dst[i] = 1.0f - src.g;
  527. break;
  528. case REMAP_INV_B:
  529. dst[i] = 1.0f - src.b;
  530. break;
  531. case REMAP_INV_A:
  532. dst[i] = 1.0f - src.a;
  533. break;
  534. case REMAP_0:
  535. dst[i] = 0.0f;
  536. break;
  537. case REMAP_1:
  538. dst[i] = 1.0f;
  539. break;
  540. default:
  541. break;
  542. }
  543. }
  544. r_image->set_pixel(x, y, dst);
  545. }
  546. }
  547. }
  548. void ResourceImporterTexture::_invert_y_channel(Ref<Image> &r_image) {
  549. // Inverting the green channel can be used to flip a normal map's direction.
  550. // There's no standard when it comes to normal map Y direction, so this is
  551. // sometimes needed when using a normal map exported from another program.
  552. // See <http://wiki.polycount.com/wiki/Normal_Map_Technical_Details#Common_Swizzle_Coordinates>.
  553. const int height = r_image->get_height();
  554. const int width = r_image->get_width();
  555. for (int i = 0; i < width; i++) {
  556. for (int j = 0; j < height; j++) {
  557. const Color color = r_image->get_pixel(i, j);
  558. r_image->set_pixel(i, j, Color(color.r, 1 - color.g, color.b, color.a));
  559. }
  560. }
  561. }
  562. void ResourceImporterTexture::_clamp_hdr_exposure(Ref<Image> &r_image) {
  563. // Clamp HDR exposure following Filament's tonemapping formula.
  564. // This can be used to reduce fireflies in environment maps or reduce the influence
  565. // of the sun from an HDRI panorama on environment lighting (when a DirectionalLight3D is used instead).
  566. const int height = r_image->get_height();
  567. const int width = r_image->get_width();
  568. // These values are chosen arbitrarily and seem to produce good results with 4,096 samples.
  569. const float linear = 4096.0;
  570. const float compressed = 16384.0;
  571. for (int i = 0; i < width; i++) {
  572. for (int j = 0; j < height; j++) {
  573. const Color color = r_image->get_pixel(i, j);
  574. const float luma = color.get_luminance();
  575. Color clamped_color;
  576. if (luma <= linear) {
  577. clamped_color = color;
  578. } else {
  579. clamped_color = (color / luma) * ((linear * linear - compressed * luma) / (2 * linear - compressed - luma));
  580. }
  581. r_image->set_pixel(i, j, clamped_color);
  582. }
  583. }
  584. }
  585. Error ResourceImporterTexture::import(ResourceUID::ID p_source_id, const String &p_source_file, const String &p_save_path, const HashMap<StringName, Variant> &p_options, List<String> *r_platform_variants, List<String> *r_gen_files, Variant *r_metadata) {
  586. // Parse import options.
  587. int32_t loader_flags = ImageFormatLoader::FLAG_NONE;
  588. // Compression.
  589. CompressMode compress_mode = CompressMode(int(p_options["compress/mode"]));
  590. const float lossy = p_options["compress/lossy_quality"];
  591. const int pack_channels = p_options["compress/channel_pack"];
  592. const int normal = p_options["compress/normal_map"];
  593. const int hdr_compression = p_options["compress/hdr_compression"];
  594. const int high_quality = p_options["compress/high_quality"];
  595. // Mipmaps.
  596. const bool mipmaps = p_options["mipmaps/generate"];
  597. const uint32_t mipmap_limit = mipmaps ? uint32_t(p_options["mipmaps/limit"]) : uint32_t(-1);
  598. // Roughness.
  599. const int roughness = p_options["roughness/mode"];
  600. const String normal_map = p_options["roughness/src_normal"];
  601. // Processing.
  602. const int remap_r = p_options["process/channel_remap/red"];
  603. const int remap_g = p_options["process/channel_remap/green"];
  604. const int remap_b = p_options["process/channel_remap/blue"];
  605. const int remap_a = p_options["process/channel_remap/alpha"];
  606. const bool fix_alpha_border = p_options["process/fix_alpha_border"];
  607. const bool premult_alpha = p_options["process/premult_alpha"];
  608. const bool normal_map_invert_y = p_options["process/normal_map_invert_y"];
  609. const bool hdr_as_srgb = p_options["process/hdr_as_srgb"];
  610. const bool hdr_clamp_exposure = p_options["process/hdr_clamp_exposure"];
  611. int size_limit = p_options["process/size_limit"];
  612. const Image::BasisUniversalPackerParams basisu_params = {
  613. p_options["compress/uastc_level"],
  614. p_options["compress/rdo_quality_loss"],
  615. };
  616. bool using_fallback_size_limit = false;
  617. if (size_limit == 0) {
  618. using_fallback_size_limit = true;
  619. // If no size limit is defined, use a fallback size limit to prevent textures from looking incorrect or failing to import.
  620. switch (compress_mode) {
  621. case COMPRESS_LOSSY:
  622. // Maximum WebP size on either axis.
  623. size_limit = 16383;
  624. break;
  625. case COMPRESS_BASIS_UNIVERSAL:
  626. // Maximum Basis Universal size on either axis.
  627. size_limit = 16384;
  628. break;
  629. default:
  630. // As of June 2024, no GPU can correctly display a texture larger than 32768 pixels on either axis.
  631. size_limit = 32768;
  632. break;
  633. }
  634. }
  635. // Support for texture streaming is not implemented yet.
  636. const bool stream = false;
  637. // SVG-specific options.
  638. float scale = p_options.has("svg/scale") ? float(p_options["svg/scale"]) : 1.0f;
  639. // Editor-specific options.
  640. bool use_editor_scale = p_options.has("editor/scale_with_editor_scale") && p_options["editor/scale_with_editor_scale"];
  641. bool convert_editor_colors = p_options.has("editor/convert_colors_with_editor_theme") && p_options["editor/convert_colors_with_editor_theme"];
  642. if (hdr_as_srgb) {
  643. loader_flags |= ImageFormatLoader::FLAG_FORCE_LINEAR;
  644. }
  645. // Start importing images.
  646. LocalVector<Ref<Image>> images_imported;
  647. // Load the normal image.
  648. Ref<Image> normal_image;
  649. Image::RoughnessChannel roughness_channel = Image::ROUGHNESS_CHANNEL_R;
  650. if (mipmaps && roughness > 1 && FileAccess::exists(normal_map)) {
  651. normal_image.instantiate();
  652. if (ImageLoader::load_image(normal_map, normal_image) == OK) {
  653. roughness_channel = Image::RoughnessChannel(roughness - 2);
  654. }
  655. }
  656. // Load the main image.
  657. Ref<Image> image;
  658. image.instantiate();
  659. Error err = ImageLoader::load_image(p_source_file, image, nullptr, loader_flags, scale);
  660. if (err != OK) {
  661. return err;
  662. }
  663. images_imported.push_back(image);
  664. // Load the editor-only image.
  665. Ref<Image> editor_image;
  666. if (use_editor_scale || convert_editor_colors) {
  667. float editor_scale = use_editor_scale ? scale * EDSCALE : scale;
  668. int32_t editor_loader_flags = loader_flags;
  669. if (convert_editor_colors) {
  670. editor_loader_flags |= ImageFormatLoader::FLAG_CONVERT_COLORS;
  671. }
  672. editor_image.instantiate();
  673. err = ImageLoader::load_image(p_source_file, editor_image, nullptr, editor_loader_flags, editor_scale);
  674. if (err != OK) {
  675. WARN_PRINT(vformat("Failed to import an image resource for editor use from '%s'.", p_source_file));
  676. } else {
  677. if (convert_editor_colors) {
  678. float image_saturation = EDITOR_GET("interface/theme/icon_saturation");
  679. editor_image->adjust_bcs(1.0, 1.0, image_saturation);
  680. }
  681. images_imported.push_back(editor_image);
  682. }
  683. }
  684. for (Ref<Image> &target_image : images_imported) {
  685. // Apply the size limit.
  686. if (size_limit > 0 && (target_image->get_width() > size_limit || target_image->get_height() > size_limit)) {
  687. if (target_image->get_width() >= target_image->get_height()) {
  688. int new_width = size_limit;
  689. int new_height = target_image->get_height() * new_width / target_image->get_width();
  690. if (using_fallback_size_limit) {
  691. // Only warn if downsizing occurred when the user did not explicitly request it.
  692. WARN_PRINT(vformat("%s: Texture was downsized on import as its width (%d pixels) exceeded the importable size limit (%d pixels).", p_source_file, target_image->get_width(), size_limit));
  693. }
  694. target_image->resize(new_width, new_height, Image::INTERPOLATE_CUBIC);
  695. } else {
  696. int new_height = size_limit;
  697. int new_width = target_image->get_width() * new_height / target_image->get_height();
  698. if (using_fallback_size_limit) {
  699. // Only warn if downsizing occurred when the user did not explicitly request it.
  700. WARN_PRINT(vformat("%s: Texture was downsized on import as its height (%d pixels) exceeded the importable size limit (%d pixels).", p_source_file, target_image->get_height(), size_limit));
  701. }
  702. target_image->resize(new_width, new_height, Image::INTERPOLATE_CUBIC);
  703. }
  704. if (normal == 1) {
  705. target_image->normalize();
  706. }
  707. }
  708. {
  709. ChannelRemap remaps[4] = {
  710. (ChannelRemap)remap_r,
  711. (ChannelRemap)remap_g,
  712. (ChannelRemap)remap_b,
  713. (ChannelRemap)remap_a,
  714. };
  715. _remap_channels(target_image, remaps);
  716. }
  717. // Fix alpha border.
  718. if (fix_alpha_border) {
  719. target_image->fix_alpha_edges();
  720. }
  721. // Premultiply the alpha.
  722. if (premult_alpha) {
  723. target_image->premultiply_alpha();
  724. }
  725. // Invert the green channel of the image to flip the normal map it contains.
  726. if (normal_map_invert_y) {
  727. _invert_y_channel(target_image);
  728. }
  729. // Clamp HDR exposure.
  730. if (hdr_clamp_exposure) {
  731. _clamp_hdr_exposure(target_image);
  732. }
  733. }
  734. bool detect_3d = int(p_options["detect_3d/compress_to"]) > 0;
  735. bool detect_roughness = roughness == 0;
  736. bool detect_normal = normal == 0;
  737. bool force_normal = normal == 1;
  738. bool srgb_friendly_pack = pack_channels == 0;
  739. Array formats_imported;
  740. if (compress_mode == COMPRESS_VRAM_COMPRESSED) {
  741. // Must import in desktop and mobile formats in order of priority, so platform chooses the best supported one (e.g. s3tc over etc2 on desktop).
  742. const bool is_hdr = (image->get_format() >= Image::FORMAT_RF && image->get_format() <= Image::FORMAT_RGBE9995);
  743. const bool can_s3tc_bptc = ResourceImporterTextureSettings::should_import_s3tc_bptc();
  744. const bool can_etc2_astc = ResourceImporterTextureSettings::should_import_etc2_astc();
  745. // Add list of formats imported.
  746. if (can_s3tc_bptc) {
  747. formats_imported.push_back("s3tc_bptc");
  748. }
  749. if (can_etc2_astc) {
  750. formats_imported.push_back("etc2_astc");
  751. }
  752. bool can_compress_hdr = hdr_compression > 0;
  753. bool has_alpha = image->detect_alpha() != Image::ALPHA_NONE;
  754. bool force_uncompressed = false;
  755. if (is_hdr) {
  756. if (has_alpha) {
  757. // Can compress HDR, but HDR with alpha is not compressible.
  758. if (hdr_compression == 2) {
  759. // But user selected to compress HDR anyway, so force an alpha-less format.
  760. if (image->get_format() == Image::FORMAT_RGBAF) {
  761. image->convert(Image::FORMAT_RGBF);
  762. } else if (image->get_format() == Image::FORMAT_RGBAH) {
  763. image->convert(Image::FORMAT_RGBH);
  764. }
  765. } else {
  766. can_compress_hdr = false;
  767. }
  768. }
  769. // Fall back to RGBE99995.
  770. if (!can_compress_hdr && image->get_format() != Image::FORMAT_RGBE9995) {
  771. image->convert(Image::FORMAT_RGBE9995);
  772. force_uncompressed = true;
  773. }
  774. }
  775. if (force_uncompressed) {
  776. _save_ctex(image, p_save_path + ".ctex", COMPRESS_VRAM_UNCOMPRESSED, lossy, basisu_params, Image::COMPRESS_S3TC /* This is ignored. */,
  777. mipmaps, stream, detect_3d, detect_roughness, detect_normal, force_normal, srgb_friendly_pack, false, mipmap_limit, normal_image, roughness_channel);
  778. } else {
  779. if (can_s3tc_bptc) {
  780. Image::CompressMode image_compress_mode;
  781. String image_compress_format;
  782. if (high_quality || is_hdr) {
  783. image_compress_mode = Image::COMPRESS_BPTC;
  784. image_compress_format = "bptc";
  785. } else {
  786. image_compress_mode = Image::COMPRESS_S3TC;
  787. image_compress_format = "s3tc";
  788. }
  789. _save_ctex(image, p_save_path + "." + image_compress_format + ".ctex", compress_mode, lossy, basisu_params, image_compress_mode, mipmaps,
  790. stream, detect_3d, detect_roughness, detect_normal, force_normal, srgb_friendly_pack, false, mipmap_limit, normal_image, roughness_channel);
  791. r_platform_variants->push_back(image_compress_format);
  792. }
  793. if (can_etc2_astc) {
  794. Image::CompressMode image_compress_mode;
  795. String image_compress_format;
  796. if (high_quality || is_hdr) {
  797. image_compress_mode = Image::COMPRESS_ASTC;
  798. image_compress_format = "astc";
  799. } else {
  800. image_compress_mode = Image::COMPRESS_ETC2;
  801. image_compress_format = "etc2";
  802. }
  803. _save_ctex(image, p_save_path + "." + image_compress_format + ".ctex", compress_mode, lossy, basisu_params, image_compress_mode, mipmaps, stream, detect_3d,
  804. detect_roughness, detect_normal, force_normal, srgb_friendly_pack, false, mipmap_limit, normal_image, roughness_channel);
  805. r_platform_variants->push_back(image_compress_format);
  806. }
  807. }
  808. } else {
  809. // Import normally.
  810. _save_ctex(image, p_save_path + ".ctex", compress_mode, lossy, basisu_params, Image::COMPRESS_S3TC /* This is ignored. */,
  811. mipmaps, stream, detect_3d, detect_roughness, detect_normal, force_normal, srgb_friendly_pack, false, mipmap_limit, normal_image, roughness_channel);
  812. }
  813. if (editor_image.is_valid()) {
  814. _save_ctex(editor_image, p_save_path + ".editor.ctex", compress_mode, lossy, basisu_params, Image::COMPRESS_S3TC /* This is ignored. */,
  815. mipmaps, stream, detect_3d, detect_roughness, detect_normal, force_normal, srgb_friendly_pack, false, mipmap_limit, normal_image, roughness_channel);
  816. // Generate and save editor-specific metadata, which we cannot save to the .import file.
  817. Dictionary editor_meta;
  818. if (use_editor_scale) {
  819. editor_meta["editor_scale"] = EDSCALE;
  820. }
  821. if (convert_editor_colors) {
  822. editor_meta["editor_dark_theme"] = EditorThemeManager::is_dark_theme();
  823. }
  824. _save_editor_meta(editor_meta, p_save_path + ".editor.meta");
  825. }
  826. if (r_metadata) {
  827. Dictionary meta;
  828. meta["vram_texture"] = compress_mode == COMPRESS_VRAM_COMPRESSED;
  829. if (formats_imported.size()) {
  830. meta["imported_formats"] = formats_imported;
  831. }
  832. if (editor_image.is_valid()) {
  833. meta["has_editor_variant"] = true;
  834. }
  835. *r_metadata = meta;
  836. }
  837. return OK;
  838. }
  839. const char *ResourceImporterTexture::compression_formats[] = {
  840. "s3tc_bptc",
  841. "etc2_astc",
  842. nullptr
  843. };
  844. String ResourceImporterTexture::get_import_settings_string() const {
  845. String s;
  846. int index = 0;
  847. while (compression_formats[index]) {
  848. const String setting_path = "rendering/textures/vram_compression/import_" + String(compression_formats[index]);
  849. if (bool(GLOBAL_GET(setting_path))) {
  850. s += String(compression_formats[index]);
  851. }
  852. index++;
  853. }
  854. return s;
  855. }
  856. bool ResourceImporterTexture::are_import_settings_valid(const String &p_path, const Dictionary &p_meta) const {
  857. if (p_meta.has("has_editor_variant")) {
  858. String imported_path = ResourceFormatImporter::get_singleton()->get_internal_resource_path(p_path);
  859. if (!FileAccess::exists(imported_path)) {
  860. return false;
  861. }
  862. String editor_meta_path = imported_path.replace(".editor.ctex", ".editor.meta");
  863. Dictionary editor_meta = _load_editor_meta(editor_meta_path);
  864. if (editor_meta.has("editor_scale") && (float)editor_meta["editor_scale"] != EDSCALE) {
  865. return false;
  866. }
  867. if (editor_meta.has("editor_dark_theme") && (bool)editor_meta["editor_dark_theme"] != EditorThemeManager::is_dark_theme()) {
  868. return false;
  869. }
  870. }
  871. if (!p_meta.has("vram_texture")) {
  872. return false;
  873. }
  874. if (!bool(p_meta["vram_texture"])) {
  875. return true; // Do not care about non-VRAM.
  876. }
  877. // Will become invalid if formats are missing to import.
  878. Vector<String> formats_imported;
  879. if (p_meta.has("imported_formats")) {
  880. formats_imported = p_meta["imported_formats"];
  881. }
  882. int index = 0;
  883. bool valid = true;
  884. while (compression_formats[index]) {
  885. const String setting_path = "rendering/textures/vram_compression/import_" + String(compression_formats[index]);
  886. if (ProjectSettings::get_singleton()->has_setting(setting_path)) {
  887. if (bool(GLOBAL_GET(setting_path)) && !formats_imported.has(compression_formats[index])) {
  888. valid = false;
  889. break;
  890. }
  891. } else {
  892. WARN_PRINT("Setting for imported format not found: " + setting_path);
  893. }
  894. index++;
  895. }
  896. return valid;
  897. }
  898. ResourceImporterTexture *ResourceImporterTexture::singleton = nullptr;
  899. ResourceImporterTexture::ResourceImporterTexture(bool p_singleton) {
  900. // This should only be set through the EditorNode.
  901. if (p_singleton) {
  902. singleton = this;
  903. }
  904. CompressedTexture2D::request_3d_callback = _texture_reimport_3d;
  905. CompressedTexture2D::request_roughness_callback = _texture_reimport_roughness;
  906. CompressedTexture2D::request_normal_callback = _texture_reimport_normal;
  907. }
  908. ResourceImporterTexture::~ResourceImporterTexture() {
  909. if (singleton == this) {
  910. singleton = nullptr;
  911. }
  912. }