resource_importer_texture.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  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/editor_file_system.h"
  36. #include "editor/editor_node.h"
  37. #include "editor/editor_scale.h"
  38. #include "editor/editor_settings.h"
  39. void ResourceImporterTexture::_texture_reimport_roughness(const Ref<CompressedTexture2D> &p_tex, const String &p_normal_path, RS::TextureDetectRoughnessChannel p_channel) {
  40. ERR_FAIL_COND(p_tex.is_null());
  41. MutexLock lock(singleton->mutex);
  42. StringName path = p_tex->get_path();
  43. if (!singleton->make_flags.has(path)) {
  44. singleton->make_flags[path] = MakeInfo();
  45. }
  46. singleton->make_flags[path].flags |= MAKE_ROUGHNESS_FLAG;
  47. singleton->make_flags[path].channel_for_roughness = p_channel;
  48. singleton->make_flags[path].normal_path_for_roughness = p_normal_path;
  49. }
  50. void ResourceImporterTexture::_texture_reimport_3d(const Ref<CompressedTexture2D> &p_tex) {
  51. ERR_FAIL_COND(p_tex.is_null());
  52. MutexLock lock(singleton->mutex);
  53. StringName path = p_tex->get_path();
  54. if (!singleton->make_flags.has(path)) {
  55. singleton->make_flags[path] = MakeInfo();
  56. }
  57. singleton->make_flags[path].flags |= MAKE_3D_FLAG;
  58. }
  59. void ResourceImporterTexture::_texture_reimport_normal(const Ref<CompressedTexture2D> &p_tex) {
  60. ERR_FAIL_COND(p_tex.is_null());
  61. MutexLock lock(singleton->mutex);
  62. StringName path = p_tex->get_path();
  63. if (!singleton->make_flags.has(path)) {
  64. singleton->make_flags[path] = MakeInfo();
  65. }
  66. singleton->make_flags[path].flags |= MAKE_NORMAL_FLAG;
  67. }
  68. void ResourceImporterTexture::update_imports() {
  69. if (EditorFileSystem::get_singleton()->is_scanning() || EditorFileSystem::get_singleton()->is_importing()) {
  70. return; // do nothing for now
  71. }
  72. MutexLock lock(mutex);
  73. Vector<String> to_reimport;
  74. {
  75. if (make_flags.is_empty()) {
  76. return;
  77. }
  78. for (const KeyValue<StringName, MakeInfo> &E : make_flags) {
  79. Ref<ConfigFile> cf;
  80. cf.instantiate();
  81. String src_path = String(E.key) + ".import";
  82. Error err = cf->load(src_path);
  83. ERR_CONTINUE(err != OK);
  84. bool changed = false;
  85. if (E.value.flags & MAKE_NORMAL_FLAG && int(cf->get_value("params", "compress/normal_map")) == 0) {
  86. print_line(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)."), String(E.key)));
  87. cf->set_value("params", "compress/normal_map", 1);
  88. changed = true;
  89. }
  90. if (E.value.flags & MAKE_ROUGHNESS_FLAG && int(cf->get_value("params", "roughness/mode")) == 0) {
  91. print_line(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."), String(E.key), E.value.normal_path_for_roughness));
  92. cf->set_value("params", "roughness/mode", E.value.channel_for_roughness + 2);
  93. cf->set_value("params", "roughness/src_normal", E.value.normal_path_for_roughness);
  94. changed = true;
  95. }
  96. if (E.value.flags & MAKE_3D_FLAG && bool(cf->get_value("params", "detect_3d/compress_to"))) {
  97. const int compress_to = cf->get_value("params", "detect_3d/compress_to");
  98. String compress_string;
  99. cf->set_value("params", "detect_3d/compress_to", 0);
  100. if (compress_to == 1) {
  101. cf->set_value("params", "compress/mode", COMPRESS_VRAM_COMPRESSED);
  102. compress_string = "VRAM Compressed (S3TC/ETC/BPTC)";
  103. } else if (compress_to == 2) {
  104. cf->set_value("params", "compress/mode", COMPRESS_BASIS_UNIVERSAL);
  105. compress_string = "Basis Universal";
  106. }
  107. print_line(vformat(TTR("%s: Texture detected as used in 3D. Enabling mipmap generation and setting the texture compression mode to %s."), String(E.key), compress_string));
  108. cf->set_value("params", "mipmaps/generate", true);
  109. changed = true;
  110. }
  111. if (changed) {
  112. cf->save(src_path);
  113. to_reimport.push_back(E.key);
  114. }
  115. }
  116. make_flags.clear();
  117. }
  118. if (to_reimport.size()) {
  119. EditorFileSystem::get_singleton()->reimport_files(to_reimport);
  120. }
  121. }
  122. String ResourceImporterTexture::get_importer_name() const {
  123. return "texture";
  124. }
  125. String ResourceImporterTexture::get_visible_name() const {
  126. return "Texture2D";
  127. }
  128. void ResourceImporterTexture::get_recognized_extensions(List<String> *p_extensions) const {
  129. ImageLoader::get_recognized_extensions(p_extensions);
  130. }
  131. String ResourceImporterTexture::get_save_extension() const {
  132. return "ctex";
  133. }
  134. String ResourceImporterTexture::get_resource_type() const {
  135. return "CompressedTexture2D";
  136. }
  137. bool ResourceImporterTexture::get_option_visibility(const String &p_path, const String &p_option, const HashMap<StringName, Variant> &p_options) const {
  138. if (p_option == "compress/high_quality" || p_option == "compress/hdr_compression") {
  139. int compress_mode = int(p_options["compress/mode"]);
  140. if (compress_mode != COMPRESS_VRAM_COMPRESSED) {
  141. return false;
  142. }
  143. } else if (p_option == "compress/lossy_quality") {
  144. int compress_mode = int(p_options["compress/mode"]);
  145. if (compress_mode != COMPRESS_LOSSY) {
  146. return false;
  147. }
  148. } else if (p_option == "compress/hdr_mode") {
  149. int compress_mode = int(p_options["compress/mode"]);
  150. if (compress_mode < COMPRESS_VRAM_COMPRESSED) {
  151. return false;
  152. }
  153. } else if (p_option == "compress/normal_map") {
  154. int compress_mode = int(p_options["compress/mode"]);
  155. if (compress_mode == COMPRESS_LOSSLESS) {
  156. return false;
  157. }
  158. } else if (p_option == "mipmaps/limit") {
  159. return p_options["mipmaps/generate"];
  160. }
  161. return true;
  162. }
  163. int ResourceImporterTexture::get_preset_count() const {
  164. return 3;
  165. }
  166. String ResourceImporterTexture::get_preset_name(int p_idx) const {
  167. static const char *preset_names[] = {
  168. TTRC("2D/3D (Auto-Detect)"),
  169. TTRC("2D"),
  170. TTRC("3D"),
  171. };
  172. return TTRGET(preset_names[p_idx]);
  173. }
  174. void ResourceImporterTexture::get_import_options(const String &p_path, List<ImportOption> *r_options, int p_preset) const {
  175. 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));
  176. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "compress/high_quality"), false));
  177. r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "compress/lossy_quality", PROPERTY_HINT_RANGE, "0,1,0.01"), 0.7));
  178. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "compress/hdr_compression", PROPERTY_HINT_ENUM, "Disabled,Opaque Only,Always"), 1));
  179. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "compress/normal_map", PROPERTY_HINT_ENUM, "Detect,Enable,Disabled"), 0));
  180. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "compress/channel_pack", PROPERTY_HINT_ENUM, "sRGB Friendly,Optimized"), 0));
  181. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "mipmaps/generate"), (p_preset == PRESET_3D ? true : false)));
  182. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "mipmaps/limit", PROPERTY_HINT_RANGE, "-1,256"), -1));
  183. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "roughness/mode", PROPERTY_HINT_ENUM, "Detect,Disabled,Red,Green,Blue,Alpha,Gray"), 0));
  184. r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "roughness/src_normal", PROPERTY_HINT_FILE, "*.bmp,*.dds,*.exr,*.jpeg,*.jpg,*.hdr,*.png,*.svg,*.tga,*.webp"), ""));
  185. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "process/fix_alpha_border"), p_preset != PRESET_3D));
  186. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "process/premult_alpha"), false));
  187. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "process/normal_map_invert_y"), false));
  188. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "process/hdr_as_srgb"), false));
  189. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "process/hdr_clamp_exposure"), false));
  190. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "process/size_limit", PROPERTY_HINT_RANGE, "0,4096,1"), 0));
  191. 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));
  192. // Do path based customization only if a path was passed.
  193. if (p_path.is_empty() || p_path.get_extension() == "svg") {
  194. r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "svg/scale", PROPERTY_HINT_RANGE, "0.001,100,0.001"), 1.0));
  195. // Editor use only, applies to SVG.
  196. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "editor/scale_with_editor_scale"), false));
  197. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "editor/convert_colors_with_editor_theme"), false));
  198. }
  199. }
  200. 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) {
  201. switch (p_compress_mode) {
  202. case COMPRESS_LOSSLESS: {
  203. bool lossless_force_png = GLOBAL_GET("rendering/textures/lossless_compression/force_png") ||
  204. !Image::_webp_mem_loader_func; // WebP module disabled.
  205. bool use_webp = !lossless_force_png && p_image->get_width() <= 16383 && p_image->get_height() <= 16383; // WebP has a size limit
  206. f->store_32(use_webp ? CompressedTexture2D::DATA_FORMAT_WEBP : CompressedTexture2D::DATA_FORMAT_PNG);
  207. f->store_16(p_image->get_width());
  208. f->store_16(p_image->get_height());
  209. f->store_32(p_image->get_mipmap_count());
  210. f->store_32(p_image->get_format());
  211. for (int i = 0; i < p_image->get_mipmap_count() + 1; i++) {
  212. Vector<uint8_t> data;
  213. if (use_webp) {
  214. data = Image::webp_lossless_packer(p_image->get_image_from_mipmap(i));
  215. } else {
  216. data = Image::png_packer(p_image->get_image_from_mipmap(i));
  217. }
  218. int data_len = data.size();
  219. f->store_32(data_len);
  220. const uint8_t *r = data.ptr();
  221. f->store_buffer(r, data_len);
  222. }
  223. } break;
  224. case COMPRESS_LOSSY: {
  225. f->store_32(CompressedTexture2D::DATA_FORMAT_WEBP);
  226. f->store_16(p_image->get_width());
  227. f->store_16(p_image->get_height());
  228. f->store_32(p_image->get_mipmap_count());
  229. f->store_32(p_image->get_format());
  230. for (int i = 0; i < p_image->get_mipmap_count() + 1; i++) {
  231. Vector<uint8_t> data = Image::webp_lossy_packer(p_image->get_image_from_mipmap(i), p_lossy_quality);
  232. int data_len = data.size();
  233. f->store_32(data_len);
  234. const uint8_t *r = data.ptr();
  235. f->store_buffer(r, data_len);
  236. }
  237. } break;
  238. case COMPRESS_VRAM_COMPRESSED: {
  239. Ref<Image> image = p_image->duplicate();
  240. image->compress_from_channels(p_compress_format, p_channels);
  241. f->store_32(CompressedTexture2D::DATA_FORMAT_IMAGE);
  242. f->store_16(image->get_width());
  243. f->store_16(image->get_height());
  244. f->store_32(image->get_mipmap_count());
  245. f->store_32(image->get_format());
  246. Vector<uint8_t> data = image->get_data();
  247. int dl = data.size();
  248. const uint8_t *r = data.ptr();
  249. f->store_buffer(r, dl);
  250. } break;
  251. case COMPRESS_VRAM_UNCOMPRESSED: {
  252. f->store_32(CompressedTexture2D::DATA_FORMAT_IMAGE);
  253. f->store_16(p_image->get_width());
  254. f->store_16(p_image->get_height());
  255. f->store_32(p_image->get_mipmap_count());
  256. f->store_32(p_image->get_format());
  257. Vector<uint8_t> data = p_image->get_data();
  258. int dl = data.size();
  259. const uint8_t *r = data.ptr();
  260. f->store_buffer(r, dl);
  261. } break;
  262. case COMPRESS_BASIS_UNIVERSAL: {
  263. f->store_32(CompressedTexture2D::DATA_FORMAT_BASIS_UNIVERSAL);
  264. f->store_16(p_image->get_width());
  265. f->store_16(p_image->get_height());
  266. f->store_32(p_image->get_mipmap_count());
  267. f->store_32(p_image->get_format());
  268. Vector<uint8_t> data = Image::basis_universal_packer(p_image, p_channels);
  269. int data_len = data.size();
  270. f->store_32(data_len);
  271. const uint8_t *r = data.ptr();
  272. f->store_buffer(r, data_len);
  273. } break;
  274. }
  275. }
  276. void ResourceImporterTexture::_save_ctex(const Ref<Image> &p_image, const String &p_to_path, CompressMode p_compress_mode, float p_lossy_quality, 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) {
  277. Ref<FileAccess> f = FileAccess::open(p_to_path, FileAccess::WRITE);
  278. ERR_FAIL_COND(f.is_null());
  279. f->store_8('G');
  280. f->store_8('S');
  281. f->store_8('T');
  282. f->store_8('2'); //godot streamable texture 2D
  283. //format version
  284. f->store_32(CompressedTexture2D::FORMAT_VERSION);
  285. //texture may be resized later, so original size must be saved first
  286. f->store_32(p_image->get_width());
  287. f->store_32(p_image->get_height());
  288. uint32_t flags = 0;
  289. if (p_streamable) {
  290. flags |= CompressedTexture2D::FORMAT_BIT_STREAM;
  291. }
  292. if (p_mipmaps) {
  293. flags |= CompressedTexture2D::FORMAT_BIT_HAS_MIPMAPS; //mipmaps bit
  294. }
  295. if (p_detect_3d) {
  296. flags |= CompressedTexture2D::FORMAT_BIT_DETECT_3D;
  297. }
  298. if (p_detect_roughness) {
  299. flags |= CompressedTexture2D::FORMAT_BIT_DETECT_ROUGNESS;
  300. }
  301. if (p_detect_normal) {
  302. flags |= CompressedTexture2D::FORMAT_BIT_DETECT_NORMAL;
  303. }
  304. f->store_32(flags);
  305. f->store_32(p_limit_mipmap);
  306. //reserved for future use
  307. f->store_32(0);
  308. f->store_32(0);
  309. f->store_32(0);
  310. /*
  311. print_line("streamable " + itos(p_streamable));
  312. print_line("mipmaps " + itos(p_mipmaps));
  313. print_line("detect_3d " + itos(p_detect_3d));
  314. print_line("roughness " + itos(p_detect_roughness));
  315. print_line("normal " + itos(p_detect_normal));
  316. */
  317. if ((p_compress_mode == COMPRESS_LOSSLESS || p_compress_mode == COMPRESS_LOSSY) && p_image->get_format() > Image::FORMAT_RGBA8) {
  318. p_compress_mode = COMPRESS_VRAM_UNCOMPRESSED; //these can't go as lossy
  319. }
  320. Ref<Image> image = p_image->duplicate();
  321. if (p_force_po2_for_compressed && p_mipmaps && ((p_compress_mode == COMPRESS_BASIS_UNIVERSAL) || (p_compress_mode == COMPRESS_VRAM_COMPRESSED))) {
  322. image->resize_to_po2();
  323. }
  324. if (p_mipmaps && (!image->has_mipmaps() || p_force_normal)) {
  325. image->generate_mipmaps(p_force_normal);
  326. }
  327. if (!p_mipmaps) {
  328. image->clear_mipmaps();
  329. }
  330. if (image->has_mipmaps() && p_normal.is_valid()) {
  331. image->generate_mipmap_roughness(p_roughness_channel, p_normal);
  332. }
  333. Image::CompressSource csource = Image::COMPRESS_SOURCE_GENERIC;
  334. if (p_force_normal) {
  335. csource = Image::COMPRESS_SOURCE_NORMAL;
  336. } else if (p_srgb_friendly) {
  337. csource = Image::COMPRESS_SOURCE_SRGB;
  338. }
  339. Image::UsedChannels used_channels = image->detect_used_channels(csource);
  340. save_to_ctex_format(f, image, p_compress_mode, used_channels, p_vram_compression, p_lossy_quality);
  341. }
  342. Error ResourceImporterTexture::import(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) {
  343. // Parse import options.
  344. int32_t loader_flags = ImageFormatLoader::FLAG_NONE;
  345. // Compression.
  346. CompressMode compress_mode = CompressMode(int(p_options["compress/mode"]));
  347. const float lossy = p_options["compress/lossy_quality"];
  348. const int pack_channels = p_options["compress/channel_pack"];
  349. const int normal = p_options["compress/normal_map"];
  350. const int hdr_compression = p_options["compress/hdr_compression"];
  351. const int high_quality = p_options["compress/high_quality"];
  352. // Mipmaps.
  353. const bool mipmaps = p_options["mipmaps/generate"];
  354. const uint32_t mipmap_limit = mipmaps ? uint32_t(p_options["mipmaps/limit"]) : uint32_t(-1);
  355. // Roughness.
  356. const int roughness = p_options["roughness/mode"];
  357. const String normal_map = p_options["roughness/src_normal"];
  358. // Processing.
  359. const bool fix_alpha_border = p_options["process/fix_alpha_border"];
  360. const bool premult_alpha = p_options["process/premult_alpha"];
  361. const bool normal_map_invert_y = p_options["process/normal_map_invert_y"];
  362. // Support for texture streaming is not implemented yet.
  363. const bool stream = false;
  364. const int size_limit = p_options["process/size_limit"];
  365. const bool hdr_as_srgb = p_options["process/hdr_as_srgb"];
  366. if (hdr_as_srgb) {
  367. loader_flags |= ImageFormatLoader::FLAG_FORCE_LINEAR;
  368. }
  369. const bool hdr_clamp_exposure = p_options["process/hdr_clamp_exposure"];
  370. float scale = 1.0;
  371. // SVG-specific options.
  372. if (p_options.has("svg/scale")) {
  373. scale = p_options["svg/scale"];
  374. }
  375. // Editor-specific options.
  376. bool use_editor_scale = p_options.has("editor/scale_with_editor_scale") && p_options["editor/scale_with_editor_scale"];
  377. bool convert_editor_colors = p_options.has("editor/convert_colors_with_editor_theme") && p_options["editor/convert_colors_with_editor_theme"];
  378. // Start importing images.
  379. List<Ref<Image>> images_imported;
  380. // Load the normal image.
  381. Ref<Image> normal_image;
  382. Image::RoughnessChannel roughness_channel = Image::ROUGHNESS_CHANNEL_R;
  383. if (mipmaps && roughness > 1 && FileAccess::exists(normal_map)) {
  384. normal_image.instantiate();
  385. if (ImageLoader::load_image(normal_map, normal_image) == OK) {
  386. roughness_channel = Image::RoughnessChannel(roughness - 2);
  387. }
  388. }
  389. // Load the main image.
  390. Ref<Image> image;
  391. image.instantiate();
  392. Error err = ImageLoader::load_image(p_source_file, image, nullptr, loader_flags, scale);
  393. if (err != OK) {
  394. return err;
  395. }
  396. images_imported.push_back(image);
  397. // Load the editor-only image.
  398. Ref<Image> editor_image;
  399. bool import_editor_image = use_editor_scale || convert_editor_colors;
  400. if (import_editor_image) {
  401. float editor_scale = scale;
  402. if (use_editor_scale) {
  403. editor_scale = scale * EDSCALE;
  404. }
  405. int32_t editor_loader_flags = loader_flags;
  406. if (convert_editor_colors) {
  407. editor_loader_flags |= ImageFormatLoader::FLAG_CONVERT_COLORS;
  408. }
  409. editor_image.instantiate();
  410. err = ImageLoader::load_image(p_source_file, editor_image, nullptr, editor_loader_flags, editor_scale);
  411. if (err != OK) {
  412. WARN_PRINT("Failed to import an image resource for editor use from '" + p_source_file + "'");
  413. } else {
  414. images_imported.push_back(editor_image);
  415. }
  416. }
  417. for (Ref<Image> &target_image : images_imported) {
  418. // Apply the size limit.
  419. if (size_limit > 0 && (target_image->get_width() > size_limit || target_image->get_height() > size_limit)) {
  420. if (target_image->get_width() >= target_image->get_height()) {
  421. int new_width = size_limit;
  422. int new_height = target_image->get_height() * new_width / target_image->get_width();
  423. target_image->resize(new_width, new_height, Image::INTERPOLATE_CUBIC);
  424. } else {
  425. int new_height = size_limit;
  426. int new_width = target_image->get_width() * new_height / target_image->get_height();
  427. target_image->resize(new_width, new_height, Image::INTERPOLATE_CUBIC);
  428. }
  429. if (normal == 1) {
  430. target_image->normalize();
  431. }
  432. }
  433. // Fix alpha border.
  434. if (fix_alpha_border) {
  435. target_image->fix_alpha_edges();
  436. }
  437. // Premultiply the alpha.
  438. if (premult_alpha) {
  439. target_image->premultiply_alpha();
  440. }
  441. // Invert the green channel of the image to flip the normal map it contains.
  442. if (normal_map_invert_y) {
  443. // Inverting the green channel can be used to flip a normal map's direction.
  444. // There's no standard when it comes to normal map Y direction, so this is
  445. // sometimes needed when using a normal map exported from another program.
  446. // See <http://wiki.polycount.com/wiki/Normal_Map_Technical_Details#Common_Swizzle_Coordinates>.
  447. const int height = target_image->get_height();
  448. const int width = target_image->get_width();
  449. for (int i = 0; i < width; i++) {
  450. for (int j = 0; j < height; j++) {
  451. const Color color = target_image->get_pixel(i, j);
  452. target_image->set_pixel(i, j, Color(color.r, 1 - color.g, color.b));
  453. }
  454. }
  455. }
  456. // Clamp HDR exposure.
  457. if (hdr_clamp_exposure) {
  458. // Clamp HDR exposure following Filament's tonemapping formula.
  459. // This can be used to reduce fireflies in environment maps or reduce the influence
  460. // of the sun from an HDRI panorama on environment lighting (when a DirectionalLight3D is used instead).
  461. const int height = target_image->get_height();
  462. const int width = target_image->get_width();
  463. // These values are chosen arbitrarily and seem to produce good results with 4,096 samples.
  464. const float linear = 4096.0;
  465. const float compressed = 16384.0;
  466. for (int i = 0; i < width; i++) {
  467. for (int j = 0; j < height; j++) {
  468. const Color color = target_image->get_pixel(i, j);
  469. const float luma = color.get_luminance();
  470. Color clamped_color;
  471. if (luma <= linear) {
  472. clamped_color = color;
  473. } else {
  474. clamped_color = (color / luma) * ((linear * linear - compressed * luma) / (2 * linear - compressed - luma));
  475. }
  476. target_image->set_pixel(i, j, clamped_color);
  477. }
  478. }
  479. }
  480. }
  481. if (compress_mode == COMPRESS_BASIS_UNIVERSAL && image->get_format() >= Image::FORMAT_RF) {
  482. // Basis universal does not support float formats, fallback.
  483. compress_mode = COMPRESS_VRAM_COMPRESSED;
  484. }
  485. bool detect_3d = int(p_options["detect_3d/compress_to"]) > 0;
  486. bool detect_roughness = roughness == 0;
  487. bool detect_normal = normal == 0;
  488. bool force_normal = normal == 1;
  489. bool srgb_friendly_pack = pack_channels == 0;
  490. Array formats_imported;
  491. if (compress_mode == COMPRESS_VRAM_COMPRESSED) {
  492. // Must import in all formats, in order of priority (so platform choses the best supported one. IE, etc2 over etc).
  493. // Android, GLES 2.x
  494. const bool is_hdr = (image->get_format() >= Image::FORMAT_RF && image->get_format() <= Image::FORMAT_RGBE9995);
  495. const bool can_s3tc_bptc = GLOBAL_GET("rendering/textures/vram_compression/import_s3tc_bptc") || OS::get_singleton()->get_preferred_texture_format() == OS::PREFERRED_TEXTURE_FORMAT_S3TC_BPTC;
  496. const bool can_etc2_astc = GLOBAL_GET("rendering/textures/vram_compression/import_etc2_astc") || OS::get_singleton()->get_preferred_texture_format() == OS::PREFERRED_TEXTURE_FORMAT_ETC2_ASTC;
  497. // Add list of formats imported
  498. if (can_s3tc_bptc) {
  499. formats_imported.push_back("s3tc_bptc");
  500. }
  501. if (can_etc2_astc) {
  502. formats_imported.push_back("etc2_astc");
  503. }
  504. bool can_compress_hdr = hdr_compression > 0;
  505. bool has_alpha = image->detect_alpha() != Image::ALPHA_NONE;
  506. bool use_uncompressed = false;
  507. if (is_hdr) {
  508. if (has_alpha) {
  509. // Can compress HDR, but HDR with alpha is not compressible.
  510. if (hdr_compression == 2) {
  511. // But user selected to compress HDR anyway, so force an alpha-less format.
  512. if (image->get_format() == Image::FORMAT_RGBAF) {
  513. image->convert(Image::FORMAT_RGBF);
  514. } else if (image->get_format() == Image::FORMAT_RGBAH) {
  515. image->convert(Image::FORMAT_RGBH);
  516. }
  517. } else {
  518. can_compress_hdr = false;
  519. }
  520. }
  521. if (!can_compress_hdr) {
  522. // Fallback to RGBE99995.
  523. if (image->get_format() != Image::FORMAT_RGBE9995) {
  524. image->convert(Image::FORMAT_RGBE9995);
  525. use_uncompressed = true;
  526. }
  527. }
  528. }
  529. if (use_uncompressed) {
  530. _save_ctex(image, p_save_path + ".ctex", COMPRESS_VRAM_UNCOMPRESSED, lossy, Image::COMPRESS_S3TC /*this is ignored */, mipmaps, stream, detect_3d, detect_roughness, detect_normal, force_normal, srgb_friendly_pack, false, mipmap_limit, normal_image, roughness_channel);
  531. } else {
  532. if (can_s3tc_bptc) {
  533. Image::CompressMode image_compress_mode;
  534. String image_compress_format;
  535. if (high_quality || is_hdr) {
  536. image_compress_mode = Image::COMPRESS_BPTC;
  537. image_compress_format = "bptc";
  538. } else {
  539. image_compress_mode = Image::COMPRESS_S3TC;
  540. image_compress_format = "s3tc";
  541. }
  542. _save_ctex(image, p_save_path + "." + image_compress_format + ".ctex", compress_mode, lossy, image_compress_mode, mipmaps, stream, detect_3d, detect_roughness, detect_normal, force_normal, srgb_friendly_pack, false, mipmap_limit, normal_image, roughness_channel);
  543. r_platform_variants->push_back(image_compress_format);
  544. }
  545. if (can_etc2_astc) {
  546. Image::CompressMode image_compress_mode;
  547. String image_compress_format;
  548. if (high_quality || is_hdr) {
  549. image_compress_mode = Image::COMPRESS_ASTC;
  550. image_compress_format = "astc";
  551. } else {
  552. image_compress_mode = Image::COMPRESS_ETC2;
  553. image_compress_format = "etc2";
  554. }
  555. _save_ctex(image, p_save_path + "." + image_compress_format + ".ctex", compress_mode, lossy, image_compress_mode, mipmaps, stream, detect_3d, detect_roughness, detect_normal, force_normal, srgb_friendly_pack, false, mipmap_limit, normal_image, roughness_channel);
  556. r_platform_variants->push_back(image_compress_format);
  557. }
  558. }
  559. } else {
  560. // Import normally.
  561. _save_ctex(image, p_save_path + ".ctex", compress_mode, lossy, Image::COMPRESS_S3TC /*this is ignored */, mipmaps, stream, detect_3d, detect_roughness, detect_normal, force_normal, srgb_friendly_pack, false, mipmap_limit, normal_image, roughness_channel);
  562. }
  563. if (editor_image.is_valid()) {
  564. _save_ctex(editor_image, p_save_path + ".editor.ctex", compress_mode, lossy, Image::COMPRESS_S3TC /*this is ignored */, mipmaps, stream, detect_3d, detect_roughness, detect_normal, force_normal, srgb_friendly_pack, false, mipmap_limit, normal_image, roughness_channel);
  565. }
  566. if (r_metadata) {
  567. Dictionary meta;
  568. meta["vram_texture"] = compress_mode == COMPRESS_VRAM_COMPRESSED;
  569. if (formats_imported.size()) {
  570. meta["imported_formats"] = formats_imported;
  571. }
  572. if (editor_image.is_valid()) {
  573. meta["has_editor_variant"] = true;
  574. if (use_editor_scale) {
  575. meta["editor_scale"] = EDSCALE;
  576. }
  577. if (convert_editor_colors) {
  578. meta["editor_dark_theme"] = EditorSettings::get_singleton()->is_dark_theme();
  579. }
  580. }
  581. *r_metadata = meta;
  582. }
  583. return OK;
  584. }
  585. const char *ResourceImporterTexture::compression_formats[] = {
  586. "s3tc_bptc",
  587. "etc2_astc",
  588. nullptr
  589. };
  590. String ResourceImporterTexture::get_import_settings_string() const {
  591. String s;
  592. int index = 0;
  593. while (compression_formats[index]) {
  594. String setting_path = "rendering/textures/vram_compression/import_" + String(compression_formats[index]);
  595. bool test = GLOBAL_GET(setting_path);
  596. if (test) {
  597. s += String(compression_formats[index]);
  598. }
  599. index++;
  600. }
  601. return s;
  602. }
  603. bool ResourceImporterTexture::are_import_settings_valid(const String &p_path) const {
  604. //will become invalid if formats are missing to import
  605. Dictionary meta = ResourceFormatImporter::get_singleton()->get_resource_metadata(p_path);
  606. if (meta.has("has_editor_variant")) {
  607. if (meta.has("editor_scale") && (float)meta["editor_scale"] != EDSCALE) {
  608. return false;
  609. }
  610. if (meta.has("editor_dark_theme") && (bool)meta["editor_dark_theme"] != EditorSettings::get_singleton()->is_dark_theme()) {
  611. return false;
  612. }
  613. }
  614. if (!meta.has("vram_texture")) {
  615. return false;
  616. }
  617. bool vram = meta["vram_texture"];
  618. if (!vram) {
  619. return true; // Do not care about non-VRAM.
  620. }
  621. Vector<String> formats_imported;
  622. if (meta.has("imported_formats")) {
  623. formats_imported = meta["imported_formats"];
  624. }
  625. int index = 0;
  626. bool valid = true;
  627. while (compression_formats[index]) {
  628. String setting_path = "rendering/textures/vram_compression/import_" + String(compression_formats[index]);
  629. if (ProjectSettings::get_singleton()->has_setting(setting_path)) {
  630. bool test = GLOBAL_GET(setting_path);
  631. if (test) {
  632. if (!formats_imported.has(compression_formats[index])) {
  633. valid = false;
  634. break;
  635. }
  636. }
  637. } else {
  638. WARN_PRINT("Setting for imported format not found: " + setting_path);
  639. }
  640. index++;
  641. }
  642. return valid;
  643. }
  644. ResourceImporterTexture *ResourceImporterTexture::singleton = nullptr;
  645. ResourceImporterTexture::ResourceImporterTexture() {
  646. singleton = this;
  647. CompressedTexture2D::request_3d_callback = _texture_reimport_3d;
  648. CompressedTexture2D::request_roughness_callback = _texture_reimport_roughness;
  649. CompressedTexture2D::request_normal_callback = _texture_reimport_normal;
  650. }
  651. ResourceImporterTexture::~ResourceImporterTexture() {
  652. }