fbx_material.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. /*************************************************************************/
  2. /* fbx_material.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 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 "fbx_material.h"
  31. #include "scene/resources/material.h"
  32. #include "scene/resources/texture.h"
  33. #include "tools/validation_tools.h"
  34. String FBXMaterial::get_material_name() const {
  35. return material_name;
  36. }
  37. void FBXMaterial::set_imported_material(FBXDocParser::Material *p_material) {
  38. material = p_material;
  39. }
  40. void FBXMaterial::add_search_string(String p_filename, String p_current_directory, String search_directory, Vector<String> &texture_search_paths) {
  41. if (search_directory.is_empty()) {
  42. texture_search_paths.push_back(p_current_directory.get_base_dir().plus_file(p_filename));
  43. } else {
  44. texture_search_paths.push_back(p_current_directory.get_base_dir().plus_file(search_directory + "/" + p_filename));
  45. texture_search_paths.push_back(p_current_directory.get_base_dir().plus_file("../" + search_directory + "/" + p_filename));
  46. }
  47. }
  48. String find_file(const String &p_base, const String &p_file_to_find) {
  49. _Directory dir;
  50. dir.open(p_base);
  51. dir.list_dir_begin();
  52. String n = dir.get_next();
  53. while (n != String()) {
  54. if (n == "." || n == "..") {
  55. n = dir.get_next();
  56. continue;
  57. }
  58. if (dir.current_is_dir()) {
  59. // Don't use `path_to` or the returned path will be wrong.
  60. const String f = find_file(p_base + "/" + n, p_file_to_find);
  61. if (f != "") {
  62. return f;
  63. }
  64. } else if (n == p_file_to_find) {
  65. return p_base + "/" + n;
  66. }
  67. n = dir.get_next();
  68. }
  69. dir.list_dir_end();
  70. return String();
  71. }
  72. // fbx will not give us good path information and let's not regex them to fix them
  73. // no relative paths are in fbx generally they have a rel field but it's populated incorrectly by the SDK.
  74. String FBXMaterial::find_texture_path_by_filename(const String p_filename, const String p_current_directory) {
  75. _Directory dir;
  76. Vector<String> paths;
  77. add_search_string(p_filename, p_current_directory, "", paths);
  78. add_search_string(p_filename, p_current_directory, "texture", paths);
  79. add_search_string(p_filename, p_current_directory, "textures", paths);
  80. add_search_string(p_filename, p_current_directory, "Textures", paths);
  81. add_search_string(p_filename, p_current_directory, "materials", paths);
  82. add_search_string(p_filename, p_current_directory, "mats", paths);
  83. add_search_string(p_filename, p_current_directory, "pictures", paths);
  84. add_search_string(p_filename, p_current_directory, "images", paths);
  85. for (int i = 0; i < paths.size(); i++) {
  86. if (dir.file_exists(paths[i])) {
  87. return paths[i];
  88. }
  89. }
  90. // We were not able to find the texture in the common locations,
  91. // try to find it into the project globally.
  92. // The common textures can be stored into one of those folders:
  93. // res://asset
  94. // res://texture
  95. // res://material
  96. // res://mat
  97. // res://image
  98. // res://picture
  99. //
  100. // Note the folders can also be called with custom names, like:
  101. // res://my_assets
  102. // since the keyword `asset` is into the directory name the textures will be
  103. // searched there too.
  104. dir.open("res://");
  105. dir.list_dir_begin();
  106. String n = dir.get_next();
  107. while (n != String()) {
  108. if (n == "." || n == "..") {
  109. n = dir.get_next();
  110. continue;
  111. }
  112. if (dir.current_is_dir()) {
  113. const String lower_n = n.to_lower();
  114. if (
  115. // Don't need to use plural.
  116. lower_n.find("asset") >= 0 ||
  117. lower_n.find("texture") >= 0 ||
  118. lower_n.find("material") >= 0 ||
  119. lower_n.find("mat") >= 0 ||
  120. lower_n.find("image") >= 0 ||
  121. lower_n.find("picture") >= 0) {
  122. // Don't use `path_to` or the returned path will be wrong.
  123. const String f = find_file(String("res://") + n, p_filename);
  124. if (f != "") {
  125. return f;
  126. }
  127. }
  128. }
  129. n = dir.get_next();
  130. }
  131. dir.list_dir_end();
  132. return "";
  133. }
  134. template <class T>
  135. T extract_from_prop(FBXDocParser::PropertyPtr prop, const T &p_default, const std::string &p_name, const String &p_type) {
  136. ERR_FAIL_COND_V_MSG(prop == nullptr, p_default, "invalid property passed to extractor");
  137. const FBXDocParser::TypedProperty<T> *val = dynamic_cast<const FBXDocParser::TypedProperty<T> *>(prop);
  138. ERR_FAIL_COND_V_MSG(val == nullptr, p_default, "The FBX is corrupted, the property `" + String(p_name.c_str()) + "` is a `" + String(typeid(*prop).name()) + "` but should be a " + p_type);
  139. // Make sure to not lost any eventual opacity.
  140. return val->Value();
  141. }
  142. Ref<StandardMaterial3D> FBXMaterial::import_material(ImportState &state) {
  143. ERR_FAIL_COND_V(material == nullptr, nullptr);
  144. const String p_fbx_current_directory = state.path;
  145. Ref<StandardMaterial3D> spatial_material;
  146. spatial_material.instance();
  147. // read the material file
  148. // is material two sided
  149. // read material name
  150. print_verbose("[material] material name: " + ImportUtils::FBXNodeToName(material->Name()));
  151. material_name = ImportUtils::FBXNodeToName(material->Name());
  152. for (const std::pair<std::string, const FBXDocParser::Texture *> iter : material->Textures()) {
  153. const uint64_t texture_id = iter.second->ID();
  154. const std::string &fbx_mapping_name = iter.first;
  155. const FBXDocParser::Texture *fbx_texture_data = iter.second;
  156. const String absolute_texture_path = iter.second->FileName().c_str();
  157. const String texture_name = absolute_texture_path.get_file();
  158. const String file_extension = absolute_texture_path.get_extension().to_upper();
  159. const String debug_string = "texture id: " + itos(texture_id) + " texture name: " + String(iter.second->Name().c_str()) + " mapping name: " + String(fbx_mapping_name.c_str());
  160. // remember errors STILL need this string at the end for when you aren't in verbose debug mode :) they need context for when you're not verbose-ing.
  161. print_verbose(debug_string);
  162. const String file_extension_uppercase = file_extension.to_upper();
  163. if (fbx_transparency_flags.count(fbx_mapping_name) > 0) {
  164. // just enable it later let's make this fine-tuned.
  165. spatial_material->set_transparency(BaseMaterial3D::TRANSPARENCY_ALPHA);
  166. }
  167. ERR_CONTINUE_MSG(file_extension.is_empty(), "your texture has no file extension so we had to ignore it, let us know if you think this is wrong file an issue on github! " + debug_string);
  168. ERR_CONTINUE_MSG(fbx_texture_map.count(fbx_mapping_name) <= 0, "This material has a texture with mapping name: " + String(fbx_mapping_name.c_str()) + " which is not yet supported by this importer. Consider opening an issue so we can support it.");
  169. ERR_CONTINUE_MSG(
  170. file_extension_uppercase != "PNG" &&
  171. file_extension_uppercase != "JPEG" &&
  172. file_extension_uppercase != "JPG" &&
  173. file_extension_uppercase != "TGA" &&
  174. file_extension_uppercase != "WEBP" &&
  175. file_extension_uppercase != "DDS",
  176. "The FBX file contains a texture with an unrecognized extension: " + file_extension_uppercase);
  177. print_verbose("Getting FBX mapping mode for " + String(fbx_mapping_name.c_str()));
  178. // get the texture map type
  179. const StandardMaterial3D::TextureParam mapping_mode = fbx_texture_map.at(fbx_mapping_name);
  180. print_verbose("Set FBX mapping mode to " + get_texture_param_name(mapping_mode));
  181. Ref<Texture> texture;
  182. print_verbose("texture mapping name: " + texture_name);
  183. if (state.cached_image_searches.has(texture_name)) {
  184. texture = state.cached_image_searches[texture_name];
  185. } else {
  186. String path = find_texture_path_by_filename(texture_name, p_fbx_current_directory);
  187. if (!path.is_empty()) {
  188. Ref<Texture2D> image_texture = ResourceLoader::load(path);
  189. ERR_CONTINUE(image_texture.is_null());
  190. texture = image_texture;
  191. state.cached_image_searches.insert(texture_name, texture);
  192. print_verbose("Created texture from loaded image file.");
  193. } else if (fbx_texture_data != nullptr && fbx_texture_data->Media() != nullptr && fbx_texture_data->Media()->IsEmbedded()) {
  194. // This is an embedded texture. Extract it.
  195. Ref<Image> image;
  196. //image.instance(); // oooo double instance bug? why make Image::_png_blah call
  197. const String extension = texture_name.get_extension().to_upper();
  198. if (extension == "PNG") {
  199. // The stored file is a PNG.
  200. image = Image::_png_mem_loader_func(fbx_texture_data->Media()->Content(), fbx_texture_data->Media()->ContentLength());
  201. ERR_CONTINUE_MSG(image.is_valid() == false, "FBX Embedded PNG image load fail.");
  202. } else if (
  203. extension == "JPEG" ||
  204. extension == "JPG") {
  205. // The stored file is a JPEG.
  206. image = Image::_jpg_mem_loader_func(fbx_texture_data->Media()->Content(), fbx_texture_data->Media()->ContentLength());
  207. ERR_CONTINUE_MSG(image.is_valid() == false, "FBX Embedded JPEG image load fail.");
  208. } else if (extension == "TGA") {
  209. // The stored file is a TGA.
  210. image = Image::_tga_mem_loader_func(fbx_texture_data->Media()->Content(), fbx_texture_data->Media()->ContentLength());
  211. ERR_CONTINUE_MSG(image.is_valid() == false, "FBX Embedded TGA image load fail.");
  212. } else if (extension == "WEBP") {
  213. // The stored file is a WEBP.
  214. image = Image::_webp_mem_loader_func(fbx_texture_data->Media()->Content(), fbx_texture_data->Media()->ContentLength());
  215. ERR_CONTINUE_MSG(image.is_valid() == false, "FBX Embedded WEBP image load fail.");
  216. // } else if (extension == "DDS") {
  217. // // In this moment is not possible to extract a DDS from a buffer, TODO consider add it to godot. See `textureloader_dds.cpp::load().
  218. // // The stored file is a DDS.
  219. } else {
  220. ERR_CONTINUE_MSG(true, "The embedded image with extension: " + extension + " is not yet supported. Open an issue please.");
  221. }
  222. Ref<ImageTexture> image_texture;
  223. image_texture.instance();
  224. image_texture->create_from_image(image);
  225. texture = image_texture;
  226. // TODO: this is potentially making something with the same name have a match incorrectly USE FBX ID as Hash. #fuck it later.
  227. state.cached_image_searches[texture_name] = texture;
  228. print_verbose("Created texture from embedded image.");
  229. } else {
  230. ERR_CONTINUE_MSG(true, "The FBX texture, with name: `" + texture_name + "`, is not found into the project nor is stored as embedded file. Make sure to insert the texture as embedded file or into the project, then reimport.");
  231. }
  232. }
  233. spatial_material->set_texture(mapping_mode, texture);
  234. }
  235. if (spatial_material.is_valid()) {
  236. spatial_material->set_name(material_name);
  237. }
  238. /// ALL below is related to properties
  239. for (FBXDocParser::LazyPropertyMap::value_type iter : material->Props()->GetLazyProperties()) {
  240. const std::string name = iter.first;
  241. if (name.empty()) {
  242. continue;
  243. }
  244. PropertyDesc desc = PROPERTY_DESC_NOT_FOUND;
  245. if (fbx_properties_desc.count(name) > 0) {
  246. desc = fbx_properties_desc.at(name);
  247. }
  248. // check if we can ignore this it will be done at the next phase
  249. if (desc == PROPERTY_DESC_NOT_FOUND || desc == PROPERTY_DESC_IGNORE) {
  250. // count the texture mapping references. Skip this one if it's found and we can't look up a property value.
  251. if (fbx_texture_map.count(name) > 0) {
  252. continue; // safe to ignore it's a texture mapping.
  253. }
  254. }
  255. if (desc == PROPERTY_DESC_IGNORE) {
  256. //WARN_PRINT("[Ignored] The FBX material parameter: `" + String(name.c_str()) + "` is ignored.");
  257. continue;
  258. } else {
  259. print_verbose("FBX Material parameter: " + String(name.c_str()));
  260. // Check for Diffuse material system / lambert materials / legacy basically
  261. if (name == "Diffuse" && !warning_non_pbr_material) {
  262. ValidationTracker::get_singleton()->add_validation_error(state.path, "Invalid material settings change to Ai Standard Surface shader, mat name: " + material_name.c_escape());
  263. warning_non_pbr_material = true;
  264. }
  265. }
  266. // DISABLE when adding support for all weird and wonderful material formats
  267. if (desc == PROPERTY_DESC_NOT_FOUND) {
  268. continue;
  269. }
  270. ERR_CONTINUE_MSG(desc == PROPERTY_DESC_NOT_FOUND, "The FBX material parameter: `" + String(name.c_str()) + "` was not recognized. Please open an issue so we can add the support to it.");
  271. const FBXDocParser::PropertyTable *tbl = material->Props();
  272. FBXDocParser::PropertyPtr prop = tbl->Get(name);
  273. ERR_CONTINUE_MSG(prop == nullptr, "This file may be corrupted because is not possible to extract the material parameter: " + String(name.c_str()));
  274. if (spatial_material.is_null()) {
  275. // Done here so if no data no material is created.
  276. spatial_material.instance();
  277. }
  278. const FBXDocParser::TypedProperty<real_t> *real_value = dynamic_cast<const FBXDocParser::TypedProperty<real_t> *>(prop);
  279. const FBXDocParser::TypedProperty<Vector3> *vector_value = dynamic_cast<const FBXDocParser::TypedProperty<Vector3> *>(prop);
  280. if (!real_value && !vector_value) {
  281. //WARN_PRINT("unsupported datatype in property: " + String(name.c_str()));
  282. continue;
  283. }
  284. if (vector_value && !real_value) {
  285. if (vector_value->Value() == Vector3(0, 0, 0) && !real_value) {
  286. continue;
  287. }
  288. }
  289. switch (desc) {
  290. case PROPERTY_DESC_ALBEDO_COLOR: {
  291. if (vector_value) {
  292. const Vector3 &color = vector_value->Value();
  293. // Make sure to not lost any eventual opacity.
  294. if (color != Vector3(0, 0, 0)) {
  295. Color c = Color();
  296. c[0] = color[0];
  297. c[1] = color[1];
  298. c[2] = color[2];
  299. spatial_material->set_albedo(c);
  300. }
  301. } else if (real_value) {
  302. print_error("albedo is unsupported format?");
  303. }
  304. } break;
  305. case PROPERTY_DESC_TRANSPARENT: {
  306. if (real_value) {
  307. const real_t opacity = real_value->Value();
  308. if (opacity < (1.0 - CMP_EPSILON)) {
  309. Color c = spatial_material->get_albedo();
  310. c.a = opacity;
  311. spatial_material->set_albedo(c);
  312. spatial_material->set_transparency(BaseMaterial3D::TRANSPARENCY_ALPHA);
  313. spatial_material->set_depth_draw_mode(BaseMaterial3D::DEPTH_DRAW_OPAQUE_ONLY);
  314. }
  315. } else if (vector_value) {
  316. print_error("unsupported transparent desc type vector!");
  317. }
  318. } break;
  319. case PROPERTY_DESC_SPECULAR: {
  320. if (real_value) {
  321. print_verbose("specular real value: " + rtos(real_value->Value()));
  322. spatial_material->set_specular(MIN(1.0, real_value->Value()));
  323. }
  324. if (vector_value) {
  325. print_error("unsupported specular vector value: " + vector_value->Value());
  326. }
  327. } break;
  328. case PROPERTY_DESC_SPECULAR_COLOR: {
  329. if (vector_value) {
  330. print_error("unsupported specular color: " + vector_value->Value());
  331. }
  332. } break;
  333. case PROPERTY_DESC_SHINYNESS: {
  334. if (real_value) {
  335. print_error("unsupported shinyness:" + rtos(real_value->Value()));
  336. }
  337. } break;
  338. case PROPERTY_DESC_METALLIC: {
  339. if (real_value) {
  340. print_verbose("metallic real value: " + rtos(real_value->Value()));
  341. spatial_material->set_metallic(MIN(1.0f, real_value->Value()));
  342. } else {
  343. print_error("unsupported value type for metallic");
  344. }
  345. } break;
  346. case PROPERTY_DESC_ROUGHNESS: {
  347. if (real_value) {
  348. print_verbose("roughness real value: " + rtos(real_value->Value()));
  349. spatial_material->set_roughness(MIN(1.0f, real_value->Value()));
  350. } else {
  351. print_error("unsupported value type for roughness");
  352. }
  353. } break;
  354. case PROPERTY_DESC_COAT: {
  355. if (real_value) {
  356. print_verbose("clearcoat real value: " + rtos(real_value->Value()));
  357. spatial_material->set_clearcoat(MIN(1.0f, real_value->Value()));
  358. } else {
  359. print_error("unsupported value type for clearcoat");
  360. }
  361. } break;
  362. case PROPERTY_DESC_COAT_ROUGHNESS: {
  363. // meaning is that approx equal to zero is disabled not actually zero. ;)
  364. if (real_value && Math::is_equal_approx(real_value->Value(), 0.0f)) {
  365. print_verbose("clearcoat real value: " + rtos(real_value->Value()));
  366. spatial_material->set_clearcoat_gloss(1.0 - real_value->Value());
  367. } else {
  368. print_error("unsupported value type for clearcoat gloss");
  369. }
  370. } break;
  371. case PROPERTY_DESC_EMISSIVE: {
  372. if (real_value && Math::is_equal_approx(real_value->Value(), 0.0f)) {
  373. print_verbose("Emissive real value: " + rtos(real_value->Value()));
  374. spatial_material->set_emission_energy(real_value->Value());
  375. } else if (vector_value && !vector_value->Value().is_equal_approx(Vector3(0, 0, 0))) {
  376. const Vector3 &color = vector_value->Value();
  377. Color c;
  378. c[0] = color[0];
  379. c[1] = color[1];
  380. c[2] = color[2];
  381. spatial_material->set_emission(c);
  382. }
  383. } break;
  384. case PROPERTY_DESC_EMISSIVE_COLOR: {
  385. if (vector_value && !vector_value->Value().is_equal_approx(Vector3(0, 0, 0))) {
  386. const Vector3 &color = vector_value->Value();
  387. Color c;
  388. c[0] = color[0];
  389. c[1] = color[1];
  390. c[2] = color[2];
  391. spatial_material->set_emission(c);
  392. } else {
  393. print_error("unsupported value type for emissive color");
  394. }
  395. } break;
  396. case PROPERTY_DESC_NOT_FOUND:
  397. case PROPERTY_DESC_IGNORE:
  398. break;
  399. default:
  400. break;
  401. }
  402. }
  403. return spatial_material;
  404. }