editor_scene_importer_assimp.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516
  1. /*************************************************************************/
  2. /* editor_scene_importer_assimp.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 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 "editor_scene_importer_assimp.h"
  31. #include "core/io/image_loader.h"
  32. #include "editor/import/resource_importer_scene.h"
  33. #include "import_utils.h"
  34. #include "scene/3d/camera.h"
  35. #include "scene/3d/light.h"
  36. #include "scene/3d/mesh_instance.h"
  37. #include "scene/main/node.h"
  38. #include "scene/resources/material.h"
  39. #include "scene/resources/surface_tool.h"
  40. #include <assimp/matrix4x4.h>
  41. #include <assimp/postprocess.h>
  42. #include <assimp/scene.h>
  43. #include <assimp/Importer.hpp>
  44. #include <assimp/LogStream.hpp>
  45. #include <string>
  46. // move into assimp
  47. aiBone *get_bone_by_name(const aiScene *scene, aiString bone_name) {
  48. for (unsigned int mesh_id = 0; mesh_id < scene->mNumMeshes; ++mesh_id) {
  49. aiMesh *mesh = scene->mMeshes[mesh_id];
  50. // iterate over all the bones on the mesh for this node only!
  51. for (unsigned int boneIndex = 0; boneIndex < mesh->mNumBones; boneIndex++) {
  52. aiBone *bone = mesh->mBones[boneIndex];
  53. if (bone->mName == bone_name) {
  54. printf("matched bone by name: %s\n", bone->mName.C_Str());
  55. return bone;
  56. }
  57. }
  58. }
  59. return NULL;
  60. }
  61. void EditorSceneImporterAssimp::get_extensions(List<String> *r_extensions) const {
  62. const String import_setting_string = "filesystem/import/open_asset_import/";
  63. Map<String, ImportFormat> import_format;
  64. {
  65. Vector<String> exts;
  66. exts.push_back("fbx");
  67. ImportFormat import = { exts, true };
  68. import_format.insert("fbx", import);
  69. }
  70. for (Map<String, ImportFormat>::Element *E = import_format.front(); E; E = E->next()) {
  71. _register_project_setting_import(E->key(), import_setting_string, E->get().extensions, r_extensions,
  72. E->get().is_default);
  73. }
  74. }
  75. void EditorSceneImporterAssimp::_register_project_setting_import(const String generic, const String import_setting_string,
  76. const Vector<String> &exts, List<String> *r_extensions,
  77. const bool p_enabled) const {
  78. const String use_generic = "use_" + generic;
  79. _GLOBAL_DEF(import_setting_string + use_generic, p_enabled, true);
  80. if (ProjectSettings::get_singleton()->get(import_setting_string + use_generic)) {
  81. for (int32_t i = 0; i < exts.size(); i++) {
  82. r_extensions->push_back(exts[i]);
  83. }
  84. }
  85. }
  86. uint32_t EditorSceneImporterAssimp::get_import_flags() const {
  87. return IMPORT_SCENE;
  88. }
  89. void EditorSceneImporterAssimp::_bind_methods() {
  90. }
  91. Node *EditorSceneImporterAssimp::import_scene(const String &p_path, uint32_t p_flags, int p_bake_fps,
  92. List<String> *r_missing_deps, Error *r_err) {
  93. Assimp::Importer importer;
  94. std::wstring w_path = ProjectSettings::get_singleton()->globalize_path(p_path).c_str();
  95. std::string s_path(w_path.begin(), w_path.end());
  96. importer.SetPropertyBool(AI_CONFIG_PP_FD_REMOVE, true);
  97. // Cannot remove pivot points because the static mesh will be in the wrong place
  98. importer.SetPropertyBool(AI_CONFIG_IMPORT_FBX_PRESERVE_PIVOTS, false);
  99. int32_t max_bone_weights = 4;
  100. //if (p_flags & IMPORT_ANIMATION_EIGHT_WEIGHTS) {
  101. // const int eight_bones = 8;
  102. // importer.SetPropertyBool(AI_CONFIG_PP_LBW_MAX_WEIGHTS, eight_bones);
  103. // max_bone_weights = eight_bones;
  104. //}
  105. importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_LINE | aiPrimitiveType_POINT);
  106. //importer.SetPropertyFloat(AI_CONFIG_PP_DB_THRESHOLD, 1.0f);
  107. int32_t post_process_Steps = aiProcess_CalcTangentSpace |
  108. aiProcess_GlobalScale |
  109. // imports models and listens to their file scale for CM to M conversions
  110. //aiProcess_FlipUVs |
  111. aiProcess_FlipWindingOrder |
  112. // very important for culling so that it is done in the correct order.
  113. //aiProcess_DropNormals |
  114. //aiProcess_GenSmoothNormals |
  115. //aiProcess_JoinIdenticalVertices |
  116. aiProcess_ImproveCacheLocality |
  117. //aiProcess_RemoveRedundantMaterials | // Causes a crash
  118. //aiProcess_SplitLargeMeshes |
  119. aiProcess_Triangulate |
  120. aiProcess_GenUVCoords |
  121. //aiProcess_FindDegenerates |
  122. //aiProcess_SortByPType |
  123. // aiProcess_FindInvalidData |
  124. aiProcess_TransformUVCoords |
  125. aiProcess_FindInstances |
  126. //aiProcess_FixInfacingNormals |
  127. //aiProcess_ValidateDataStructure |
  128. aiProcess_OptimizeMeshes |
  129. aiProcess_PopulateArmatureData |
  130. //aiProcess_OptimizeGraph |
  131. //aiProcess_Debone |
  132. // aiProcess_EmbedTextures |
  133. //aiProcess_SplitByBoneCount |
  134. 0;
  135. aiScene *scene = (aiScene *)importer.ReadFile(s_path.c_str(), post_process_Steps);
  136. ERR_FAIL_COND_V_MSG(scene == NULL, NULL, String("Open Asset Import failed to open: ") + String(importer.GetErrorString()));
  137. return _generate_scene(p_path, scene, p_flags, p_bake_fps, max_bone_weights);
  138. }
  139. template <class T>
  140. struct EditorSceneImporterAssetImportInterpolate {
  141. T lerp(const T &a, const T &b, float c) const {
  142. return a + (b - a) * c;
  143. }
  144. T catmull_rom(const T &p0, const T &p1, const T &p2, const T &p3, float t) {
  145. float t2 = t * t;
  146. float t3 = t2 * t;
  147. return 0.5f * ((2.0f * p1) + (-p0 + p2) * t + (2.0f * p0 - 5.0f * p1 + 4 * p2 - p3) * t2 +
  148. (-p0 + 3.0f * p1 - 3.0f * p2 + p3) * t3);
  149. }
  150. T bezier(T start, T control_1, T control_2, T end, float t) {
  151. /* Formula from Wikipedia article on Bezier curves. */
  152. real_t omt = (1.0 - t);
  153. real_t omt2 = omt * omt;
  154. real_t omt3 = omt2 * omt;
  155. real_t t2 = t * t;
  156. real_t t3 = t2 * t;
  157. return start * omt3 + control_1 * omt2 * t * 3.0 + control_2 * omt * t2 * 3.0 + end * t3;
  158. }
  159. };
  160. //thank you for existing, partial specialization
  161. template <>
  162. struct EditorSceneImporterAssetImportInterpolate<Quat> {
  163. Quat lerp(const Quat &a, const Quat &b, float c) const {
  164. ERR_FAIL_COND_V_MSG(!a.is_normalized(), Quat(), "The quaternion \"a\" must be normalized.");
  165. ERR_FAIL_COND_V_MSG(!b.is_normalized(), Quat(), "The quaternion \"b\" must be normalized.");
  166. return a.slerp(b, c).normalized();
  167. }
  168. Quat catmull_rom(const Quat &p0, const Quat &p1, const Quat &p2, const Quat &p3, float c) {
  169. ERR_FAIL_COND_V_MSG(!p1.is_normalized(), Quat(), "The quaternion \"p1\" must be normalized.");
  170. ERR_FAIL_COND_V_MSG(!p2.is_normalized(), Quat(), "The quaternion \"p2\" must be normalized.");
  171. return p1.slerp(p2, c).normalized();
  172. }
  173. Quat bezier(Quat start, Quat control_1, Quat control_2, Quat end, float t) {
  174. ERR_FAIL_COND_V_MSG(!start.is_normalized(), Quat(), "The start quaternion must be normalized.");
  175. ERR_FAIL_COND_V_MSG(!end.is_normalized(), Quat(), "The end quaternion must be normalized.");
  176. return start.slerp(end, t).normalized();
  177. }
  178. };
  179. template <class T>
  180. T EditorSceneImporterAssimp::_interpolate_track(const Vector<float> &p_times, const Vector<T> &p_values, float p_time,
  181. AssetImportAnimation::Interpolation p_interp) {
  182. //could use binary search, worth it?
  183. int idx = -1;
  184. for (int i = 0; i < p_times.size(); i++) {
  185. if (p_times[i] > p_time)
  186. break;
  187. idx++;
  188. }
  189. EditorSceneImporterAssetImportInterpolate<T> interp;
  190. switch (p_interp) {
  191. case AssetImportAnimation::INTERP_LINEAR: {
  192. if (idx == -1) {
  193. return p_values[0];
  194. } else if (idx >= p_times.size() - 1) {
  195. return p_values[p_times.size() - 1];
  196. }
  197. float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
  198. return interp.lerp(p_values[idx], p_values[idx + 1], c);
  199. } break;
  200. case AssetImportAnimation::INTERP_STEP: {
  201. if (idx == -1) {
  202. return p_values[0];
  203. } else if (idx >= p_times.size() - 1) {
  204. return p_values[p_times.size() - 1];
  205. }
  206. return p_values[idx];
  207. } break;
  208. case AssetImportAnimation::INTERP_CATMULLROMSPLINE: {
  209. if (idx == -1) {
  210. return p_values[1];
  211. } else if (idx >= p_times.size() - 1) {
  212. return p_values[1 + p_times.size() - 1];
  213. }
  214. float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
  215. return interp.catmull_rom(p_values[idx - 1], p_values[idx], p_values[idx + 1], p_values[idx + 3], c);
  216. } break;
  217. case AssetImportAnimation::INTERP_CUBIC_SPLINE: {
  218. if (idx == -1) {
  219. return p_values[1];
  220. } else if (idx >= p_times.size() - 1) {
  221. return p_values[(p_times.size() - 1) * 3 + 1];
  222. }
  223. float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
  224. T from = p_values[idx * 3 + 1];
  225. T c1 = from + p_values[idx * 3 + 2];
  226. T to = p_values[idx * 3 + 4];
  227. T c2 = to + p_values[idx * 3 + 3];
  228. return interp.bezier(from, c1, c2, to, c);
  229. } break;
  230. }
  231. ERR_FAIL_V(p_values[0]);
  232. }
  233. aiBone *EditorSceneImporterAssimp::get_bone_from_stack(ImportState &state, aiString name) {
  234. List<aiBone *>::Element *iter;
  235. aiBone *bone = NULL;
  236. for (iter = state.bone_stack.front(); iter; iter = iter->next()) {
  237. bone = (aiBone *)iter->get();
  238. if (bone && bone->mName == name) {
  239. state.bone_stack.erase(bone);
  240. return bone;
  241. }
  242. }
  243. return NULL;
  244. }
  245. Spatial *
  246. EditorSceneImporterAssimp::_generate_scene(const String &p_path, aiScene *scene, const uint32_t p_flags, int p_bake_fps,
  247. const int32_t p_max_bone_weights) {
  248. ERR_FAIL_COND_V(scene == NULL, NULL);
  249. ImportState state;
  250. state.path = p_path;
  251. state.assimp_scene = scene;
  252. state.max_bone_weights = p_max_bone_weights;
  253. state.animation_player = NULL;
  254. // populate light map
  255. for (unsigned int l = 0; l < scene->mNumLights; l++) {
  256. aiLight *ai_light = scene->mLights[l];
  257. ERR_CONTINUE(ai_light == NULL);
  258. state.light_cache[AssimpUtils::get_assimp_string(ai_light->mName)] = l;
  259. }
  260. // fill camera cache
  261. for (unsigned int c = 0; c < scene->mNumCameras; c++) {
  262. aiCamera *ai_camera = scene->mCameras[c];
  263. ERR_CONTINUE(ai_camera == NULL);
  264. state.camera_cache[AssimpUtils::get_assimp_string(ai_camera->mName)] = c;
  265. }
  266. if (scene->mRootNode) {
  267. state.nodes.push_back(scene->mRootNode);
  268. // make flat node tree - in order to make processing deterministic
  269. for (unsigned int i = 0; i < scene->mRootNode->mNumChildren; i++) {
  270. _generate_node(state, scene->mRootNode->mChildren[i]);
  271. }
  272. RegenerateBoneStack(state);
  273. Node *last_valid_parent = NULL;
  274. List<const aiNode *>::Element *iter;
  275. for (iter = state.nodes.front(); iter; iter = iter->next()) {
  276. const aiNode *element_assimp_node = iter->get();
  277. const aiNode *parent_assimp_node = element_assimp_node->mParent;
  278. String node_name = AssimpUtils::get_assimp_string(element_assimp_node->mName);
  279. //print_verbose("node: " + node_name);
  280. Spatial *spatial = NULL;
  281. Transform transform = AssimpUtils::assimp_matrix_transform(element_assimp_node->mTransformation);
  282. // retrieve this node bone
  283. aiBone *bone = get_bone_from_stack(state, element_assimp_node->mName);
  284. if (state.light_cache.has(node_name)) {
  285. spatial = create_light(state, node_name, transform);
  286. } else if (state.camera_cache.has(node_name)) {
  287. spatial = create_camera(state, node_name, transform);
  288. } else if (state.armature_nodes.find(element_assimp_node)) {
  289. // create skeleton
  290. print_verbose("Making skeleton: " + node_name);
  291. Skeleton *skeleton = memnew(Skeleton);
  292. spatial = skeleton;
  293. if (!state.armature_skeletons.has(element_assimp_node)) {
  294. state.armature_skeletons.insert(element_assimp_node, skeleton);
  295. }
  296. } else if (bone != NULL) {
  297. continue;
  298. } else {
  299. spatial = memnew(Spatial);
  300. }
  301. ERR_CONTINUE_MSG(spatial == NULL, "FBX Import - are we out of ram?");
  302. // we on purpose set the transform and name after creating the node.
  303. spatial->set_name(node_name);
  304. spatial->set_global_transform(transform);
  305. // first element is root
  306. if (iter == state.nodes.front()) {
  307. state.root = spatial;
  308. }
  309. // flat node map parent lookup tool
  310. state.flat_node_map.insert(element_assimp_node, spatial);
  311. Map<const aiNode *, Spatial *>::Element *parent_lookup = state.flat_node_map.find(parent_assimp_node);
  312. // note: this always fails on the root node :) keep that in mind this is by design
  313. if (parent_lookup) {
  314. Spatial *parent_node = parent_lookup->value();
  315. ERR_FAIL_COND_V_MSG(parent_node == NULL, state.root,
  316. "Parent node invalid even though lookup successful, out of ram?")
  317. if (spatial != state.root) {
  318. parent_node->add_child(spatial);
  319. spatial->set_owner(state.root);
  320. } else {
  321. // required - think about it root never has a parent yet is valid, anything else without a parent is not valid.
  322. }
  323. } else if (spatial != state.root) {
  324. // if the ainode is not in the tree
  325. // parent it to the last good parent found
  326. if (last_valid_parent) {
  327. last_valid_parent->add_child(spatial);
  328. spatial->set_owner(state.root);
  329. } else {
  330. // this is a serious error?
  331. memdelete(spatial);
  332. }
  333. }
  334. // update last valid parent
  335. last_valid_parent = spatial;
  336. }
  337. print_verbose("node counts: " + itos(state.nodes.size()));
  338. // make clean bone stack
  339. RegenerateBoneStack(state);
  340. print_verbose("generating godot bone data");
  341. print_verbose("Godot bone stack count: " + itos(state.bone_stack.size()));
  342. // This is a list of bones, duplicates are from other meshes and must be dealt with properly
  343. for (List<aiBone *>::Element *element = state.bone_stack.front(); element; element = element->next()) {
  344. aiBone *bone = element->get();
  345. ERR_CONTINUE_MSG(!bone, "invalid bone read from assimp?");
  346. // Utilities for armature lookup - for now only FBX makes these
  347. aiNode *armature_for_bone = bone->mArmature;
  348. // Utilities for bone node lookup - for now only FBX makes these
  349. aiNode *bone_node = bone->mNode;
  350. aiNode *parent_node = bone_node->mParent;
  351. String bone_name = AssimpUtils::get_anim_string_from_assimp(bone->mName);
  352. ERR_CONTINUE_MSG(armature_for_bone == NULL, "Armature for bone invalid: " + bone_name);
  353. Skeleton *skeleton = state.armature_skeletons[armature_for_bone];
  354. state.skeleton_bone_map[bone] = skeleton;
  355. if (bone_name.empty()) {
  356. bone_name = "untitled_bone_name";
  357. WARN_PRINT("Untitled bone name detected... report with file please");
  358. }
  359. // todo: this is where skin support goes
  360. if (skeleton && skeleton->find_bone(bone_name) == -1) {
  361. print_verbose("[Godot Glue] Imported bone" + bone_name);
  362. int boneIdx = skeleton->get_bone_count();
  363. Transform pform = AssimpUtils::assimp_matrix_transform(bone->mNode->mTransformation);
  364. skeleton->add_bone(bone_name);
  365. skeleton->set_bone_rest(boneIdx, pform);
  366. skeleton->set_bone_pose(boneIdx, pform);
  367. if (parent_node != NULL) {
  368. int parent_bone_id = skeleton->find_bone(AssimpUtils::get_anim_string_from_assimp(parent_node->mName));
  369. int current_bone_id = boneIdx;
  370. skeleton->set_bone_parent(current_bone_id, parent_bone_id);
  371. }
  372. }
  373. }
  374. print_verbose("generating mesh phase from skeletal mesh");
  375. List<Spatial *> cleanup_template_nodes;
  376. for (Map<const aiNode *, Spatial *>::Element *key_value_pair = state.flat_node_map.front(); key_value_pair; key_value_pair = key_value_pair->next()) {
  377. const aiNode *assimp_node = key_value_pair->key();
  378. Spatial *mesh_template = key_value_pair->value();
  379. ERR_CONTINUE(assimp_node == NULL);
  380. ERR_CONTINUE(mesh_template == NULL);
  381. Node *parent_node = mesh_template->get_parent();
  382. if (mesh_template == state.root) {
  383. continue;
  384. }
  385. if (parent_node == NULL) {
  386. print_error("Found invalid parent node!");
  387. continue; // root node
  388. }
  389. String node_name = AssimpUtils::get_assimp_string(assimp_node->mName);
  390. Transform node_transform = AssimpUtils::assimp_matrix_transform(assimp_node->mTransformation);
  391. if (assimp_node->mNumMeshes > 0) {
  392. MeshInstance *mesh = create_mesh(state, assimp_node, node_name, parent_node, node_transform);
  393. if (mesh) {
  394. parent_node->remove_child(mesh_template);
  395. // re-parent children
  396. List<Node *> children;
  397. // re-parent all children to new node
  398. // note: since get_child_count will change during execution we must build a list first to be safe.
  399. for (int childId = 0; childId < mesh_template->get_child_count(); childId++) {
  400. // get child
  401. Node *child = mesh_template->get_child(childId);
  402. children.push_back(child);
  403. }
  404. for (List<Node *>::Element *element = children.front(); element; element = element->next()) {
  405. // reparent the children to the real mesh node.
  406. mesh_template->remove_child(element->get());
  407. mesh->add_child(element->get());
  408. element->get()->set_owner(state.root);
  409. }
  410. // update mesh in list so that each mesh node is available
  411. // this makes the template unavailable which is the desired behaviour
  412. state.flat_node_map[assimp_node] = mesh;
  413. cleanup_template_nodes.push_back(mesh_template);
  414. // clean up this list we don't need it
  415. children.clear();
  416. }
  417. }
  418. }
  419. for (List<Spatial *>::Element *element = cleanup_template_nodes.front(); element; element = element->next()) {
  420. if (element->get()) {
  421. memdelete(element->get());
  422. }
  423. }
  424. }
  425. if (p_flags & IMPORT_ANIMATION && scene->mNumAnimations) {
  426. state.animation_player = memnew(AnimationPlayer);
  427. state.root->add_child(state.animation_player);
  428. state.animation_player->set_owner(state.root);
  429. for (uint32_t i = 0; i < scene->mNumAnimations; i++) {
  430. _import_animation(state, i, p_bake_fps);
  431. }
  432. }
  433. //
  434. // Cleanup operations
  435. //
  436. state.mesh_cache.clear();
  437. state.material_cache.clear();
  438. state.light_cache.clear();
  439. state.camera_cache.clear();
  440. state.assimp_node_map.clear();
  441. state.path_to_image_cache.clear();
  442. state.nodes.clear();
  443. state.flat_node_map.clear();
  444. state.armature_skeletons.clear();
  445. state.bone_stack.clear();
  446. return state.root;
  447. }
  448. void EditorSceneImporterAssimp::_insert_animation_track(ImportState &scene, const aiAnimation *assimp_anim, int track_id,
  449. int anim_fps, Ref<Animation> animation, float ticks_per_second,
  450. Skeleton *skeleton, const NodePath &node_path,
  451. const String &node_name, aiBone *track_bone) {
  452. const aiNodeAnim *assimp_track = assimp_anim->mChannels[track_id];
  453. //make transform track
  454. int track_idx = animation->get_track_count();
  455. animation->add_track(Animation::TYPE_TRANSFORM);
  456. animation->track_set_path(track_idx, node_path);
  457. //first determine animation length
  458. float increment = 1.0 / float(anim_fps);
  459. float time = 0.0;
  460. bool last = false;
  461. Vector<Vector3> pos_values;
  462. Vector<float> pos_times;
  463. Vector<Vector3> scale_values;
  464. Vector<float> scale_times;
  465. Vector<Quat> rot_values;
  466. Vector<float> rot_times;
  467. for (size_t p = 0; p < assimp_track->mNumPositionKeys; p++) {
  468. aiVector3D pos = assimp_track->mPositionKeys[p].mValue;
  469. pos_values.push_back(Vector3(pos.x, pos.y, pos.z));
  470. pos_times.push_back(assimp_track->mPositionKeys[p].mTime / ticks_per_second);
  471. }
  472. for (size_t r = 0; r < assimp_track->mNumRotationKeys; r++) {
  473. aiQuaternion quat = assimp_track->mRotationKeys[r].mValue;
  474. rot_values.push_back(Quat(quat.x, quat.y, quat.z, quat.w).normalized());
  475. rot_times.push_back(assimp_track->mRotationKeys[r].mTime / ticks_per_second);
  476. }
  477. for (size_t sc = 0; sc < assimp_track->mNumScalingKeys; sc++) {
  478. aiVector3D scale = assimp_track->mScalingKeys[sc].mValue;
  479. scale_values.push_back(Vector3(scale.x, scale.y, scale.z));
  480. scale_times.push_back(assimp_track->mScalingKeys[sc].mTime / ticks_per_second);
  481. }
  482. while (true) {
  483. Vector3 pos;
  484. Quat rot;
  485. Vector3 scale(1, 1, 1);
  486. if (pos_values.size()) {
  487. pos = _interpolate_track<Vector3>(pos_times, pos_values, time, AssetImportAnimation::INTERP_LINEAR);
  488. }
  489. if (rot_values.size()) {
  490. rot = _interpolate_track<Quat>(rot_times, rot_values, time,
  491. AssetImportAnimation::INTERP_LINEAR)
  492. .normalized();
  493. }
  494. if (scale_values.size()) {
  495. scale = _interpolate_track<Vector3>(scale_times, scale_values, time, AssetImportAnimation::INTERP_LINEAR);
  496. }
  497. if (skeleton) {
  498. int skeleton_bone = skeleton->find_bone(node_name);
  499. if (skeleton_bone >= 0 && track_bone) {
  500. Transform xform;
  501. xform.basis.set_quat_scale(rot, scale);
  502. xform.origin = pos;
  503. xform = skeleton->get_bone_pose(skeleton_bone).inverse() * xform;
  504. rot = xform.basis.get_rotation_quat();
  505. rot.normalize();
  506. scale = xform.basis.get_scale();
  507. pos = xform.origin;
  508. } else {
  509. ERR_FAIL_MSG("Skeleton bone lookup failed for skeleton: " + skeleton->get_name());
  510. }
  511. }
  512. animation->track_set_interpolation_type(track_idx, Animation::INTERPOLATION_LINEAR);
  513. animation->transform_track_insert_key(track_idx, time, pos, rot, scale);
  514. if (last) { //done this way so a key is always inserted past the end (for proper interpolation)
  515. break;
  516. }
  517. time += increment;
  518. if (time >= animation->get_length()) {
  519. last = true;
  520. }
  521. }
  522. }
  523. // I really do not like this but need to figure out a better way of removing it later.
  524. Node *EditorSceneImporterAssimp::get_node_by_name(ImportState &state, String name) {
  525. for (Map<const aiNode *, Spatial *>::Element *key_value_pair = state.flat_node_map.front(); key_value_pair; key_value_pair = key_value_pair->next()) {
  526. const aiNode *assimp_node = key_value_pair->key();
  527. Spatial *node = key_value_pair->value();
  528. String node_name = AssimpUtils::get_assimp_string(assimp_node->mName);
  529. if (name == node_name && node) {
  530. return node;
  531. }
  532. }
  533. return NULL;
  534. }
  535. /* Bone stack is a fifo handler for multiple armatures since armatures aren't a thing in assimp (yet) */
  536. void EditorSceneImporterAssimp::RegenerateBoneStack(ImportState &state) {
  537. state.bone_stack.clear();
  538. // build bone stack list
  539. for (unsigned int mesh_id = 0; mesh_id < state.assimp_scene->mNumMeshes; ++mesh_id) {
  540. aiMesh *mesh = state.assimp_scene->mMeshes[mesh_id];
  541. // iterate over all the bones on the mesh for this node only!
  542. for (unsigned int boneIndex = 0; boneIndex < mesh->mNumBones; boneIndex++) {
  543. aiBone *bone = mesh->mBones[boneIndex];
  544. // doubtful this is required right now but best to check
  545. if (!state.bone_stack.find(bone)) {
  546. //print_verbose("[assimp] bone stack added: " + String(bone->mName.C_Str()) );
  547. state.bone_stack.push_back(bone);
  548. }
  549. }
  550. }
  551. }
  552. /* Bone stack is a fifo handler for multiple armatures since armatures aren't a thing in assimp (yet) */
  553. void EditorSceneImporterAssimp::RegenerateBoneStack(ImportState &state, aiMesh *mesh) {
  554. state.bone_stack.clear();
  555. // iterate over all the bones on the mesh for this node only!
  556. for (unsigned int boneIndex = 0; boneIndex < mesh->mNumBones; boneIndex++) {
  557. aiBone *bone = mesh->mBones[boneIndex];
  558. if (state.bone_stack.find(bone) == NULL) {
  559. state.bone_stack.push_back(bone);
  560. }
  561. }
  562. }
  563. // animation tracks are per bone
  564. void EditorSceneImporterAssimp::_import_animation(ImportState &state, int p_animation_index, int p_bake_fps) {
  565. ERR_FAIL_INDEX(p_animation_index, (int)state.assimp_scene->mNumAnimations);
  566. const aiAnimation *anim = state.assimp_scene->mAnimations[p_animation_index];
  567. String name = AssimpUtils::get_anim_string_from_assimp(anim->mName);
  568. if (name == String()) {
  569. name = "Animation " + itos(p_animation_index + 1);
  570. }
  571. print_verbose("import animation: " + name);
  572. float ticks_per_second = anim->mTicksPerSecond;
  573. if (state.assimp_scene->mMetaData != NULL && Math::is_equal_approx(ticks_per_second, 0.0f)) {
  574. int32_t time_mode = 0;
  575. state.assimp_scene->mMetaData->Get("TimeMode", time_mode);
  576. ticks_per_second = AssimpUtils::get_fbx_fps(time_mode, state.assimp_scene);
  577. }
  578. //?
  579. //if ((p_path.get_file().get_extension().to_lower() == "glb" || p_path.get_file().get_extension().to_lower() == "gltf") && Math::is_equal_approx(ticks_per_second, 0.0f)) {
  580. // ticks_per_second = 1000.0f;
  581. //}
  582. if (Math::is_equal_approx(ticks_per_second, 0.0f)) {
  583. ticks_per_second = 25.0f;
  584. }
  585. Ref<Animation> animation;
  586. animation.instance();
  587. animation->set_name(name);
  588. animation->set_length(anim->mDuration / ticks_per_second);
  589. if (name.begins_with("loop") || name.ends_with("loop") || name.begins_with("cycle") || name.ends_with("cycle")) {
  590. animation->set_loop(true);
  591. }
  592. // generate bone stack for animation import
  593. RegenerateBoneStack(state);
  594. //regular tracks
  595. for (size_t i = 0; i < anim->mNumChannels; i++) {
  596. const aiNodeAnim *track = anim->mChannels[i];
  597. String node_name = AssimpUtils::get_assimp_string(track->mNodeName);
  598. print_verbose("track name import: " + node_name);
  599. if (track->mNumRotationKeys == 0 && track->mNumPositionKeys == 0 && track->mNumScalingKeys == 0) {
  600. continue; //do not bother
  601. }
  602. Skeleton *skeleton = NULL;
  603. NodePath node_path;
  604. aiBone *bone = NULL;
  605. // Import skeleton bone animation for this track
  606. // Any bone will do, no point in processing more than just what is in the skeleton
  607. {
  608. bone = get_bone_from_stack(state, track->mNodeName);
  609. if (bone) {
  610. // get skeleton by bone
  611. skeleton = state.armature_skeletons[bone->mArmature];
  612. if (skeleton) {
  613. String path = state.root->get_path_to(skeleton);
  614. path += ":" + node_name;
  615. node_path = path;
  616. if (node_path != NodePath()) {
  617. _insert_animation_track(state, anim, i, p_bake_fps, animation, ticks_per_second, skeleton,
  618. node_path, node_name, bone);
  619. } else {
  620. print_error("Failed to find valid node path for animation");
  621. }
  622. }
  623. }
  624. }
  625. // not a bone
  626. // note this is flaky it uses node names which is unreliable
  627. Node *allocated_node = get_node_by_name(state, node_name);
  628. // todo: implement skeleton grabbing for node based animations too :)
  629. // check if node exists, if it does then also apply animation track for node and bones above are all handled.
  630. // this is now inclusive animation handling so that
  631. // we import all the data and do not miss anything.
  632. if (allocated_node) {
  633. node_path = state.root->get_path_to(allocated_node);
  634. if (node_path != NodePath()) {
  635. _insert_animation_track(state, anim, i, p_bake_fps, animation, ticks_per_second, skeleton,
  636. node_path, node_name, nullptr);
  637. }
  638. }
  639. }
  640. //blend shape tracks
  641. for (size_t i = 0; i < anim->mNumMorphMeshChannels; i++) {
  642. const aiMeshMorphAnim *anim_mesh = anim->mMorphMeshChannels[i];
  643. const String prop_name = AssimpUtils::get_assimp_string(anim_mesh->mName);
  644. const String mesh_name = prop_name.split("*")[0];
  645. ERR_CONTINUE(prop_name.split("*").size() != 2);
  646. Node *item = get_node_by_name(state, mesh_name);
  647. ERR_CONTINUE_MSG(!item, "failed to look up node by name");
  648. const MeshInstance *mesh_instance = Object::cast_to<MeshInstance>(item);
  649. ERR_CONTINUE(mesh_instance == NULL);
  650. String base_path = state.root->get_path_to(mesh_instance);
  651. Ref<Mesh> mesh = mesh_instance->get_mesh();
  652. ERR_CONTINUE(mesh.is_null());
  653. //add the tracks for this mesh
  654. int base_track = animation->get_track_count();
  655. for (int j = 0; j < mesh->get_blend_shape_count(); j++) {
  656. animation->add_track(Animation::TYPE_VALUE);
  657. animation->track_set_path(base_track + j, base_path + ":blend_shapes/" + mesh->get_blend_shape_name(j));
  658. }
  659. for (size_t k = 0; k < anim_mesh->mNumKeys; k++) {
  660. for (size_t j = 0; j < anim_mesh->mKeys[k].mNumValuesAndWeights; j++) {
  661. float t = anim_mesh->mKeys[k].mTime / ticks_per_second;
  662. float w = anim_mesh->mKeys[k].mWeights[j];
  663. animation->track_insert_key(base_track + j, t, w);
  664. }
  665. }
  666. }
  667. if (animation->get_track_count()) {
  668. state.animation_player->add_animation(name, animation);
  669. }
  670. }
  671. //
  672. // Mesh Generation from indices ? why do we need so much mesh code
  673. // [debt needs looked into]
  674. Ref<Mesh>
  675. EditorSceneImporterAssimp::_generate_mesh_from_surface_indices(ImportState &state, const Vector<int> &p_surface_indices,
  676. const aiNode *assimp_node, Ref<Skin> &skin,
  677. Skeleton *&skeleton_assigned) {
  678. Ref<ArrayMesh> mesh;
  679. mesh.instance();
  680. bool has_uvs = false;
  681. Map<String, uint32_t> morph_mesh_string_lookup;
  682. for (int i = 0; i < p_surface_indices.size(); i++) {
  683. const unsigned int mesh_idx = p_surface_indices[0];
  684. const aiMesh *ai_mesh = state.assimp_scene->mMeshes[mesh_idx];
  685. for (size_t j = 0; j < ai_mesh->mNumAnimMeshes; j++) {
  686. String ai_anim_mesh_name = AssimpUtils::get_assimp_string(ai_mesh->mAnimMeshes[j]->mName);
  687. if (!morph_mesh_string_lookup.has(ai_anim_mesh_name)) {
  688. morph_mesh_string_lookup.insert(ai_anim_mesh_name, j);
  689. mesh->set_blend_shape_mode(Mesh::BLEND_SHAPE_MODE_NORMALIZED);
  690. if (ai_anim_mesh_name.empty()) {
  691. ai_anim_mesh_name = String("morph_") + itos(j);
  692. }
  693. mesh->add_blend_shape(ai_anim_mesh_name);
  694. }
  695. }
  696. }
  697. //
  698. // Process Vertex Weights
  699. //
  700. for (int i = 0; i < p_surface_indices.size(); i++) {
  701. const unsigned int mesh_idx = p_surface_indices[i];
  702. const aiMesh *ai_mesh = state.assimp_scene->mMeshes[mesh_idx];
  703. Map<uint32_t, Vector<BoneInfo> > vertex_weights;
  704. if (ai_mesh->mNumBones > 0) {
  705. for (size_t b = 0; b < ai_mesh->mNumBones; b++) {
  706. aiBone *bone = ai_mesh->mBones[b];
  707. if (!skeleton_assigned) {
  708. print_verbose("Assigned mesh skeleton during mesh creation");
  709. skeleton_assigned = state.skeleton_bone_map[bone];
  710. if (!skin.is_valid()) {
  711. print_verbose("Configured new skin");
  712. skin.instance();
  713. } else {
  714. print_verbose("Reusing existing skin!");
  715. }
  716. }
  717. // skeleton_assigned =
  718. String bone_name = AssimpUtils::get_assimp_string(bone->mName);
  719. int bone_index = skeleton_assigned->find_bone(bone_name);
  720. ERR_CONTINUE(bone_index == -1);
  721. for (size_t w = 0; w < bone->mNumWeights; w++) {
  722. aiVertexWeight ai_weights = bone->mWeights[w];
  723. BoneInfo bi;
  724. uint32_t vertex_index = ai_weights.mVertexId;
  725. bi.bone = bone_index;
  726. bi.weight = ai_weights.mWeight;
  727. if (!vertex_weights.has(vertex_index)) {
  728. vertex_weights[vertex_index] = Vector<BoneInfo>();
  729. }
  730. vertex_weights[vertex_index].push_back(bi);
  731. }
  732. }
  733. }
  734. //
  735. // Create mesh from data from assimp
  736. //
  737. Ref<SurfaceTool> st;
  738. st.instance();
  739. st->begin(Mesh::PRIMITIVE_TRIANGLES);
  740. for (size_t j = 0; j < ai_mesh->mNumVertices; j++) {
  741. // Get the texture coordinates if they exist
  742. if (ai_mesh->HasTextureCoords(0)) {
  743. has_uvs = true;
  744. st->add_uv(Vector2(ai_mesh->mTextureCoords[0][j].x, 1.0f - ai_mesh->mTextureCoords[0][j].y));
  745. }
  746. if (ai_mesh->HasTextureCoords(1)) {
  747. has_uvs = true;
  748. st->add_uv2(Vector2(ai_mesh->mTextureCoords[1][j].x, 1.0f - ai_mesh->mTextureCoords[1][j].y));
  749. }
  750. // Assign vertex colors
  751. if (ai_mesh->HasVertexColors(0)) {
  752. Color color = Color(ai_mesh->mColors[0]->r, ai_mesh->mColors[0]->g, ai_mesh->mColors[0]->b,
  753. ai_mesh->mColors[0]->a);
  754. st->add_color(color);
  755. }
  756. // Work out normal calculations? - this needs work it doesn't work properly on huestos
  757. if (ai_mesh->mNormals != NULL) {
  758. const aiVector3D normals = ai_mesh->mNormals[j];
  759. const Vector3 godot_normal = Vector3(normals.x, normals.y, normals.z);
  760. st->add_normal(godot_normal);
  761. if (ai_mesh->HasTangentsAndBitangents()) {
  762. const aiVector3D tangents = ai_mesh->mTangents[j];
  763. const Vector3 godot_tangent = Vector3(tangents.x, tangents.y, tangents.z);
  764. const aiVector3D bitangent = ai_mesh->mBitangents[j];
  765. const Vector3 godot_bitangent = Vector3(bitangent.x, bitangent.y, bitangent.z);
  766. float d = godot_normal.cross(godot_tangent).dot(godot_bitangent) > 0.0f ? 1.0f : -1.0f;
  767. st->add_tangent(Plane(tangents.x, tangents.y, tangents.z, d));
  768. }
  769. }
  770. // We have vertex weights right?
  771. if (vertex_weights.has(j)) {
  772. Vector<BoneInfo> bone_info = vertex_weights[j];
  773. Vector<int> bones;
  774. bones.resize(bone_info.size());
  775. Vector<float> weights;
  776. weights.resize(bone_info.size());
  777. // todo? do we really need to loop over all bones? - assimp may have helper to find all influences on this vertex.
  778. for (int k = 0; k < bone_info.size(); k++) {
  779. bones.write[k] = bone_info[k].bone;
  780. weights.write[k] = bone_info[k].weight;
  781. }
  782. st->add_bones(bones);
  783. st->add_weights(weights);
  784. }
  785. // Assign vertex
  786. const aiVector3D pos = ai_mesh->mVertices[j];
  787. // note we must include node offset transform as this is relative to world space not local space.
  788. Vector3 godot_pos = Vector3(pos.x, pos.y, pos.z);
  789. st->add_vertex(godot_pos);
  790. }
  791. // fire replacement for face handling
  792. for (size_t j = 0; j < ai_mesh->mNumFaces; j++) {
  793. const aiFace face = ai_mesh->mFaces[j];
  794. for (unsigned int k = 0; k < face.mNumIndices; k++) {
  795. st->add_index(face.mIndices[k]);
  796. }
  797. }
  798. if (ai_mesh->HasTangentsAndBitangents() == false && has_uvs) {
  799. st->generate_tangents();
  800. }
  801. aiMaterial *ai_material = state.assimp_scene->mMaterials[ai_mesh->mMaterialIndex];
  802. Ref<SpatialMaterial> mat;
  803. mat.instance();
  804. int32_t mat_two_sided = 0;
  805. if (AI_SUCCESS == ai_material->Get(AI_MATKEY_TWOSIDED, mat_two_sided)) {
  806. if (mat_two_sided > 0) {
  807. mat->set_cull_mode(SpatialMaterial::CULL_DISABLED);
  808. } else {
  809. mat->set_cull_mode(SpatialMaterial::CULL_BACK);
  810. }
  811. }
  812. aiString mat_name;
  813. if (AI_SUCCESS == ai_material->Get(AI_MATKEY_NAME, mat_name)) {
  814. mat->set_name(AssimpUtils::get_assimp_string(mat_name));
  815. }
  816. // Culling handling for meshes
  817. // cull all back faces
  818. mat->set_cull_mode(SpatialMaterial::CULL_DISABLED);
  819. // Now process materials
  820. aiTextureType base_color = aiTextureType_BASE_COLOR;
  821. {
  822. String filename, path;
  823. AssimpImageData image_data;
  824. if (AssimpUtils::GetAssimpTexture(state, ai_material, base_color, filename, path, image_data)) {
  825. AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
  826. // anything transparent must be culled
  827. if (image_data.raw_image->detect_alpha() != Image::ALPHA_NONE) {
  828. mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  829. mat->set_depth_draw_mode(SpatialMaterial::DepthDrawMode::DEPTH_DRAW_ALPHA_OPAQUE_PREPASS);
  830. mat->set_cull_mode(
  831. SpatialMaterial::CULL_DISABLED); // since you can see both sides in transparent mode
  832. }
  833. mat->set_texture(SpatialMaterial::TEXTURE_ALBEDO, image_data.texture);
  834. }
  835. }
  836. aiTextureType tex_diffuse = aiTextureType_DIFFUSE;
  837. {
  838. String filename, path;
  839. AssimpImageData image_data;
  840. if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_diffuse, filename, path, image_data)) {
  841. AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
  842. // anything transparent must be culled
  843. if (image_data.raw_image->detect_alpha() != Image::ALPHA_NONE) {
  844. mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  845. mat->set_depth_draw_mode(SpatialMaterial::DepthDrawMode::DEPTH_DRAW_ALPHA_OPAQUE_PREPASS);
  846. mat->set_cull_mode(
  847. SpatialMaterial::CULL_DISABLED); // since you can see both sides in transparent mode
  848. }
  849. mat->set_texture(SpatialMaterial::TEXTURE_ALBEDO, image_data.texture);
  850. }
  851. aiColor4D clr_diffuse;
  852. if (AI_SUCCESS == ai_material->Get(AI_MATKEY_COLOR_DIFFUSE, clr_diffuse)) {
  853. if (Math::is_equal_approx(clr_diffuse.a, 1.0f) == false) {
  854. mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  855. mat->set_depth_draw_mode(SpatialMaterial::DepthDrawMode::DEPTH_DRAW_ALPHA_OPAQUE_PREPASS);
  856. mat->set_cull_mode(
  857. SpatialMaterial::CULL_DISABLED); // since you can see both sides in transparent mode
  858. }
  859. mat->set_albedo(Color(clr_diffuse.r, clr_diffuse.g, clr_diffuse.b, clr_diffuse.a));
  860. }
  861. }
  862. aiTextureType tex_normal = aiTextureType_NORMALS;
  863. {
  864. String filename, path;
  865. Ref<ImageTexture> texture;
  866. AssimpImageData image_data;
  867. // Process texture normal map
  868. if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_normal, filename, path, image_data)) {
  869. AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
  870. mat->set_feature(SpatialMaterial::Feature::FEATURE_NORMAL_MAPPING, true);
  871. mat->set_texture(SpatialMaterial::TEXTURE_NORMAL, image_data.texture);
  872. } else {
  873. aiString texture_path;
  874. if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_NORMAL_TEXTURE, AI_PROPERTIES, texture_path)) {
  875. if (AssimpUtils::CreateAssimpTexture(state, texture_path, filename, path, image_data)) {
  876. mat->set_feature(SpatialMaterial::Feature::FEATURE_NORMAL_MAPPING, true);
  877. mat->set_texture(SpatialMaterial::TEXTURE_NORMAL, image_data.texture);
  878. }
  879. }
  880. }
  881. }
  882. aiTextureType tex_normal_camera = aiTextureType_NORMAL_CAMERA;
  883. {
  884. String filename, path;
  885. Ref<ImageTexture> texture;
  886. AssimpImageData image_data;
  887. // Process texture normal map
  888. if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_normal_camera, filename, path, image_data)) {
  889. AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
  890. mat->set_feature(SpatialMaterial::Feature::FEATURE_NORMAL_MAPPING, true);
  891. mat->set_texture(SpatialMaterial::TEXTURE_NORMAL, image_data.texture);
  892. }
  893. }
  894. aiTextureType tex_emission_color = aiTextureType_EMISSION_COLOR;
  895. {
  896. String filename, path;
  897. Ref<ImageTexture> texture;
  898. AssimpImageData image_data;
  899. // Process texture normal map
  900. if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_emission_color, filename, path, image_data)) {
  901. AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
  902. mat->set_feature(SpatialMaterial::Feature::FEATURE_NORMAL_MAPPING, true);
  903. mat->set_texture(SpatialMaterial::TEXTURE_NORMAL, image_data.texture);
  904. }
  905. }
  906. aiTextureType tex_metalness = aiTextureType_METALNESS;
  907. {
  908. String filename, path;
  909. Ref<ImageTexture> texture;
  910. AssimpImageData image_data;
  911. // Process texture normal map
  912. if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_metalness, filename, path, image_data)) {
  913. AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
  914. mat->set_texture(SpatialMaterial::TEXTURE_METALLIC, image_data.texture);
  915. }
  916. }
  917. aiTextureType tex_roughness = aiTextureType_DIFFUSE_ROUGHNESS;
  918. {
  919. String filename, path;
  920. Ref<ImageTexture> texture;
  921. AssimpImageData image_data;
  922. // Process texture normal map
  923. if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_roughness, filename, path, image_data)) {
  924. AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
  925. mat->set_texture(SpatialMaterial::TEXTURE_ROUGHNESS, image_data.texture);
  926. }
  927. }
  928. aiTextureType tex_emissive = aiTextureType_EMISSIVE;
  929. {
  930. String filename = "";
  931. String path = "";
  932. Ref<Image> texture;
  933. AssimpImageData image_data;
  934. if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_emissive, filename, path, image_data)) {
  935. AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
  936. mat->set_feature(SpatialMaterial::FEATURE_EMISSION, true);
  937. mat->set_texture(SpatialMaterial::TEXTURE_EMISSION, image_data.texture);
  938. } else {
  939. // Process emission textures
  940. aiString texture_emissive_path;
  941. if (AI_SUCCESS ==
  942. ai_material->Get(AI_MATKEY_FBX_MAYA_EMISSION_TEXTURE, AI_PROPERTIES, texture_emissive_path)) {
  943. if (AssimpUtils::CreateAssimpTexture(state, texture_emissive_path, filename, path, image_data)) {
  944. mat->set_feature(SpatialMaterial::FEATURE_EMISSION, true);
  945. mat->set_texture(SpatialMaterial::TEXTURE_EMISSION, image_data.texture);
  946. }
  947. } else {
  948. float pbr_emission = 0.0f;
  949. if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_EMISSIVE_FACTOR, AI_NULL, pbr_emission)) {
  950. mat->set_emission(Color(pbr_emission, pbr_emission, pbr_emission, 1.0f));
  951. }
  952. }
  953. }
  954. }
  955. aiTextureType tex_specular = aiTextureType_SPECULAR;
  956. {
  957. String filename, path;
  958. Ref<ImageTexture> texture;
  959. AssimpImageData image_data;
  960. // Process texture normal map
  961. if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_specular, filename, path, image_data)) {
  962. AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
  963. mat->set_texture(SpatialMaterial::TEXTURE_METALLIC, image_data.texture);
  964. }
  965. }
  966. aiTextureType tex_ao_map = aiTextureType_AMBIENT_OCCLUSION;
  967. {
  968. String filename, path;
  969. Ref<ImageTexture> texture;
  970. AssimpImageData image_data;
  971. // Process texture normal map
  972. if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_ao_map, filename, path, image_data)) {
  973. AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
  974. mat->set_feature(SpatialMaterial::FEATURE_AMBIENT_OCCLUSION, true);
  975. mat->set_texture(SpatialMaterial::TEXTURE_AMBIENT_OCCLUSION, image_data.texture);
  976. }
  977. }
  978. Array array_mesh = st->commit_to_arrays();
  979. Array morphs;
  980. morphs.resize(ai_mesh->mNumAnimMeshes);
  981. Mesh::PrimitiveType primitive = Mesh::PRIMITIVE_TRIANGLES;
  982. for (size_t j = 0; j < ai_mesh->mNumAnimMeshes; j++) {
  983. String ai_anim_mesh_name = AssimpUtils::get_assimp_string(ai_mesh->mAnimMeshes[j]->mName);
  984. if (ai_anim_mesh_name.empty()) {
  985. ai_anim_mesh_name = String("morph_") + itos(j);
  986. }
  987. Array array_copy;
  988. array_copy.resize(VisualServer::ARRAY_MAX);
  989. for (int l = 0; l < VisualServer::ARRAY_MAX; l++) {
  990. array_copy[l] = array_mesh[l].duplicate(true);
  991. }
  992. const size_t num_vertices = ai_mesh->mAnimMeshes[j]->mNumVertices;
  993. array_copy[Mesh::ARRAY_INDEX] = Variant();
  994. if (ai_mesh->mAnimMeshes[j]->HasPositions()) {
  995. PoolVector3Array vertices;
  996. vertices.resize(num_vertices);
  997. for (size_t l = 0; l < num_vertices; l++) {
  998. const aiVector3D ai_pos = ai_mesh->mAnimMeshes[j]->mVertices[l];
  999. Vector3 position = Vector3(ai_pos.x, ai_pos.y, ai_pos.z);
  1000. vertices.write()[l] = position;
  1001. }
  1002. PoolVector3Array new_vertices = array_copy[VisualServer::ARRAY_VERTEX].duplicate(true);
  1003. ERR_CONTINUE(vertices.size() != new_vertices.size());
  1004. for (int32_t l = 0; l < new_vertices.size(); l++) {
  1005. PoolVector3Array::Write w = new_vertices.write();
  1006. w[l] = vertices[l];
  1007. }
  1008. array_copy[VisualServer::ARRAY_VERTEX] = new_vertices;
  1009. }
  1010. int32_t color_set = 0;
  1011. if (ai_mesh->mAnimMeshes[j]->HasVertexColors(color_set)) {
  1012. PoolColorArray colors;
  1013. colors.resize(num_vertices);
  1014. for (size_t l = 0; l < num_vertices; l++) {
  1015. const aiColor4D ai_color = ai_mesh->mAnimMeshes[j]->mColors[color_set][l];
  1016. Color color = Color(ai_color.r, ai_color.g, ai_color.b, ai_color.a);
  1017. colors.write()[l] = color;
  1018. }
  1019. PoolColorArray new_colors = array_copy[VisualServer::ARRAY_COLOR].duplicate(true);
  1020. ERR_CONTINUE(colors.size() != new_colors.size());
  1021. for (int32_t l = 0; l < colors.size(); l++) {
  1022. PoolColorArray::Write w = new_colors.write();
  1023. w[l] = colors[l];
  1024. }
  1025. array_copy[VisualServer::ARRAY_COLOR] = new_colors;
  1026. }
  1027. if (ai_mesh->mAnimMeshes[j]->HasNormals()) {
  1028. PoolVector3Array normals;
  1029. normals.resize(num_vertices);
  1030. for (size_t l = 0; l < num_vertices; l++) {
  1031. const aiVector3D ai_normal = ai_mesh->mAnimMeshes[j]->mNormals[l];
  1032. Vector3 normal = Vector3(ai_normal.x, ai_normal.y, ai_normal.z);
  1033. normals.write()[l] = normal;
  1034. }
  1035. PoolVector3Array new_normals = array_copy[VisualServer::ARRAY_NORMAL].duplicate(true);
  1036. ERR_CONTINUE(normals.size() != new_normals.size());
  1037. for (int l = 0; l < normals.size(); l++) {
  1038. PoolVector3Array::Write w = new_normals.write();
  1039. w[l] = normals[l];
  1040. }
  1041. array_copy[VisualServer::ARRAY_NORMAL] = new_normals;
  1042. }
  1043. if (ai_mesh->mAnimMeshes[j]->HasTangentsAndBitangents()) {
  1044. PoolColorArray tangents;
  1045. tangents.resize(num_vertices);
  1046. PoolColorArray::Write w = tangents.write();
  1047. for (size_t l = 0; l < num_vertices; l++) {
  1048. AssimpUtils::calc_tangent_from_mesh(ai_mesh, j, l, l, w);
  1049. }
  1050. PoolRealArray new_tangents = array_copy[VisualServer::ARRAY_TANGENT].duplicate(true);
  1051. ERR_CONTINUE(new_tangents.size() != tangents.size() * 4);
  1052. for (int32_t l = 0; l < tangents.size(); l++) {
  1053. new_tangents.write()[l + 0] = tangents[l].r;
  1054. new_tangents.write()[l + 1] = tangents[l].g;
  1055. new_tangents.write()[l + 2] = tangents[l].b;
  1056. new_tangents.write()[l + 3] = tangents[l].a;
  1057. }
  1058. array_copy[VisualServer::ARRAY_TANGENT] = new_tangents;
  1059. }
  1060. morphs[j] = array_copy;
  1061. }
  1062. mesh->add_surface_from_arrays(primitive, array_mesh, morphs);
  1063. mesh->surface_set_material(i, mat);
  1064. mesh->surface_set_name(i, AssimpUtils::get_assimp_string(ai_mesh->mName));
  1065. }
  1066. return mesh;
  1067. }
  1068. /**
  1069. * Create a new mesh for the node supplied
  1070. */
  1071. MeshInstance *
  1072. EditorSceneImporterAssimp::create_mesh(ImportState &state, const aiNode *assimp_node, const String &node_name, Node *active_node, Transform node_transform) {
  1073. /* MESH NODE */
  1074. Ref<Mesh> mesh;
  1075. Ref<Skin> skin;
  1076. // see if we have mesh cache for this.
  1077. Vector<int> surface_indices;
  1078. RegenerateBoneStack(state);
  1079. // Configure indices
  1080. for (uint32_t i = 0; i < assimp_node->mNumMeshes; i++) {
  1081. int mesh_index = assimp_node->mMeshes[i];
  1082. // create list of mesh indexes
  1083. surface_indices.push_back(mesh_index);
  1084. }
  1085. //surface_indices.sort();
  1086. String mesh_key;
  1087. for (int i = 0; i < surface_indices.size(); i++) {
  1088. if (i > 0) {
  1089. mesh_key += ":";
  1090. }
  1091. mesh_key += itos(surface_indices[i]);
  1092. }
  1093. Skeleton *skeleton = NULL;
  1094. aiNode *armature = NULL;
  1095. if (!state.mesh_cache.has(mesh_key)) {
  1096. mesh = _generate_mesh_from_surface_indices(state, surface_indices, assimp_node, skin, skeleton);
  1097. state.mesh_cache[mesh_key] = mesh;
  1098. }
  1099. MeshInstance *mesh_node = memnew(MeshInstance);
  1100. mesh = state.mesh_cache[mesh_key];
  1101. mesh_node->set_mesh(mesh);
  1102. // if we have a valid skeleton set it up
  1103. if (skin.is_valid()) {
  1104. for (uint32_t i = 0; i < assimp_node->mNumMeshes; i++) {
  1105. unsigned int mesh_index = assimp_node->mMeshes[i];
  1106. const aiMesh *ai_mesh = state.assimp_scene->mMeshes[mesh_index];
  1107. // please remember bone id relative to the skin is NOT the mesh relative index.
  1108. // it is the index relative to the skeleton that is why
  1109. // we have state.bone_id_map, it allows for duplicate bone id's too :)
  1110. // hope this makes sense
  1111. int bind_count = 0;
  1112. for (unsigned int boneId = 0; boneId < ai_mesh->mNumBones; ++boneId) {
  1113. aiBone *iterBone = ai_mesh->mBones[boneId];
  1114. // used to reparent mesh to the correct armature later on if assigned.
  1115. if (!armature) {
  1116. print_verbose("Configured mesh armature, will reparent later to armature");
  1117. armature = iterBone->mArmature;
  1118. }
  1119. if (skeleton) {
  1120. int id = skeleton->find_bone(AssimpUtils::get_assimp_string(iterBone->mName));
  1121. if (id != -1) {
  1122. print_verbose("Set bind bone: mesh: " + itos(mesh_index) + " bone index: " + itos(id));
  1123. Transform t = AssimpUtils::assimp_matrix_transform(iterBone->mOffsetMatrix);
  1124. skin->add_bind(bind_count, t);
  1125. skin->set_bind_bone(bind_count, id);
  1126. bind_count++;
  1127. }
  1128. }
  1129. }
  1130. }
  1131. print_verbose("Finished configuring bind pose for skin mesh");
  1132. }
  1133. // this code parents all meshes with bones to the armature they are for
  1134. // GLTF2 specification relies on this and we are enforcing it for FBX.
  1135. if (armature && state.flat_node_map[armature]) {
  1136. Node *armature_parent = state.flat_node_map[armature];
  1137. print_verbose("Parented mesh " + node_name + " to armature " + armature_parent->get_name());
  1138. // static mesh handling
  1139. armature_parent->add_child(mesh_node);
  1140. // transform must be identity
  1141. mesh_node->set_global_transform(Transform());
  1142. mesh_node->set_name(node_name);
  1143. mesh_node->set_owner(state.root);
  1144. } else {
  1145. // static mesh handling
  1146. active_node->add_child(mesh_node);
  1147. mesh_node->set_global_transform(node_transform);
  1148. mesh_node->set_name(node_name);
  1149. mesh_node->set_owner(state.root);
  1150. }
  1151. if (skeleton) {
  1152. print_verbose("Attempted to set skeleton path!");
  1153. mesh_node->set_skeleton_path(mesh_node->get_path_to(skeleton));
  1154. mesh_node->set_skin(skin);
  1155. }
  1156. return mesh_node;
  1157. }
  1158. /**
  1159. * Create a light for the scene
  1160. * Automatically caches lights for lookup later
  1161. */
  1162. Spatial *EditorSceneImporterAssimp::create_light(
  1163. ImportState &state,
  1164. const String &node_name,
  1165. Transform &look_at_transform) {
  1166. Light *light = NULL;
  1167. aiLight *assimp_light = state.assimp_scene->mLights[state.light_cache[node_name]];
  1168. ERR_FAIL_COND_V(!assimp_light, NULL);
  1169. if (assimp_light->mType == aiLightSource_DIRECTIONAL) {
  1170. light = memnew(DirectionalLight);
  1171. } else if (assimp_light->mType == aiLightSource_POINT) {
  1172. light = memnew(OmniLight);
  1173. } else if (assimp_light->mType == aiLightSource_SPOT) {
  1174. light = memnew(SpotLight);
  1175. }
  1176. ERR_FAIL_COND_V(light == NULL, NULL);
  1177. if (assimp_light->mType != aiLightSource_POINT) {
  1178. Vector3 pos = Vector3(
  1179. assimp_light->mPosition.x,
  1180. assimp_light->mPosition.y,
  1181. assimp_light->mPosition.z);
  1182. Vector3 look_at = Vector3(
  1183. assimp_light->mDirection.y,
  1184. assimp_light->mDirection.x,
  1185. assimp_light->mDirection.z)
  1186. .normalized();
  1187. Vector3 up = Vector3(
  1188. assimp_light->mUp.x,
  1189. assimp_light->mUp.y,
  1190. assimp_light->mUp.z);
  1191. look_at_transform.set_look_at(pos, look_at, up);
  1192. }
  1193. // properties for light variables should be put here.
  1194. // not really hugely important yet but we will need them in the future
  1195. light->set_color(
  1196. Color(assimp_light->mColorDiffuse.r, assimp_light->mColorDiffuse.g, assimp_light->mColorDiffuse.b));
  1197. return light;
  1198. }
  1199. /**
  1200. * Create camera for the scene
  1201. */
  1202. Spatial *EditorSceneImporterAssimp::create_camera(
  1203. ImportState &state,
  1204. const String &node_name,
  1205. Transform &look_at_transform) {
  1206. aiCamera *camera = state.assimp_scene->mCameras[state.camera_cache[node_name]];
  1207. ERR_FAIL_COND_V(!camera, NULL);
  1208. Camera *camera_node = memnew(Camera);
  1209. ERR_FAIL_COND_V(!camera_node, NULL);
  1210. float near = camera->mClipPlaneNear;
  1211. if (Math::is_equal_approx(near, 0.0f)) {
  1212. near = 0.1f;
  1213. }
  1214. camera_node->set_perspective(Math::rad2deg(camera->mHorizontalFOV) * 2.0f, near, camera->mClipPlaneFar);
  1215. Vector3 pos = Vector3(camera->mPosition.x, camera->mPosition.y, camera->mPosition.z);
  1216. Vector3 look_at = Vector3(camera->mLookAt.y, camera->mLookAt.x, camera->mLookAt.z).normalized();
  1217. Vector3 up = Vector3(camera->mUp.x, camera->mUp.y, camera->mUp.z);
  1218. look_at_transform.set_look_at(pos + look_at_transform.origin, look_at, up);
  1219. return camera_node;
  1220. }
  1221. /**
  1222. * Generate node
  1223. * Recursive call to iterate over all nodes
  1224. */
  1225. void EditorSceneImporterAssimp::_generate_node(
  1226. ImportState &state,
  1227. const aiNode *assimp_node) {
  1228. ERR_FAIL_COND(assimp_node == NULL);
  1229. state.nodes.push_back(assimp_node);
  1230. String parent_name = AssimpUtils::get_assimp_string(assimp_node->mParent->mName);
  1231. // please note
  1232. // duplicate bone names exist
  1233. // this is why we only check if the bone exists
  1234. // so everything else is useless but the name
  1235. // please do not copy any other values from get_bone_by_name.
  1236. aiBone *parent_bone = get_bone_by_name(state.assimp_scene, assimp_node->mParent->mName);
  1237. aiBone *current_bone = get_bone_by_name(state.assimp_scene, assimp_node->mName);
  1238. // is this an armature
  1239. // parent null
  1240. // and this is the first bone :)
  1241. if (parent_bone == NULL && current_bone) {
  1242. state.armature_nodes.push_back(assimp_node->mParent);
  1243. print_verbose("found valid armature: " + parent_name);
  1244. }
  1245. for (size_t i = 0; i < assimp_node->mNumChildren; i++) {
  1246. _generate_node(state, assimp_node->mChildren[i]);
  1247. }
  1248. }