editor_scene_importer_assimp.cpp 52 KB

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