resource_importer_texture.cpp 27 KB

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