BsFBXImporter.cpp 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsFBXImporter.h"
  4. #include "BsResource.h"
  5. #include "BsCoreApplication.h"
  6. #include "BsDebug.h"
  7. #include "BsDataStream.h"
  8. #include "BsMeshData.h"
  9. #include "BsMesh.h"
  10. #include "BsVector2.h"
  11. #include "BsVector3.h"
  12. #include "BsVector4.h"
  13. #include "BsVertexDataDesc.h"
  14. #include "BsFBXUtility.h"
  15. #include "BsMeshUtility.h"
  16. #include "BsRendererMeshData.h"
  17. #include "BsMeshImportOptions.h"
  18. #include "BsPhysicsMesh.h"
  19. #include "BsAnimationCurve.h"
  20. #include "BsAnimationClip.h"
  21. #include "BsAnimationUtility.h"
  22. #include "BsSkeleton.h"
  23. #include "BsMorphShapes.h"
  24. #include "BsPhysics.h"
  25. namespace bs
  26. {
  27. Matrix4 FBXToNativeType(const FbxAMatrix& value)
  28. {
  29. Matrix4 native;
  30. for (UINT32 row = 0; row < 4; row++)
  31. for (UINT32 col = 0; col < 4; col++)
  32. native[row][col] = (float)value[col][row];
  33. return native;
  34. }
  35. Vector3 FBXToNativeType(const FbxVector4& value)
  36. {
  37. Vector3 native;
  38. native.x = (float)value[0];
  39. native.y = (float)value[1];
  40. native.z = (float)value[2];
  41. return native;
  42. }
  43. Vector3 FBXToNativeType(const FbxDouble3& value)
  44. {
  45. Vector3 native;
  46. native.x = (float)value[0];
  47. native.y = (float)value[1];
  48. native.z = (float)value[2];
  49. return native;
  50. }
  51. Vector2 FBXToNativeType(const FbxVector2& value)
  52. {
  53. Vector2 native;
  54. native.x = (float)value[0];
  55. native.y = (float)value[1];
  56. return native;
  57. }
  58. RGBA FBXToNativeType(const FbxColor& value)
  59. {
  60. Color native;
  61. native.r = (float)value[0];
  62. native.g = (float)value[1];
  63. native.b = (float)value[2];
  64. native.a = (float)value[3];
  65. return native.getAsRGBA();
  66. }
  67. FbxSurfaceMaterial* FBXToNativeType(FbxSurfaceMaterial* const& value)
  68. {
  69. return value;
  70. }
  71. int FBXToNativeType(const int & value)
  72. {
  73. return value;
  74. }
  75. FBXImporter::FBXImporter()
  76. :SpecificImporter(), mFBXManager(nullptr)
  77. {
  78. mExtensions.push_back(L"fbx");
  79. mExtensions.push_back(L"obj");
  80. mExtensions.push_back(L"dae");
  81. }
  82. FBXImporter::~FBXImporter()
  83. {
  84. }
  85. bool FBXImporter::isExtensionSupported(const WString& ext) const
  86. {
  87. WString lowerCaseExt = ext;
  88. StringUtil::toLowerCase(lowerCaseExt);
  89. return find(mExtensions.begin(), mExtensions.end(), lowerCaseExt) != mExtensions.end();
  90. }
  91. bool FBXImporter::isMagicNumberSupported(const UINT8* magicNumPtr, UINT32 numBytes) const
  92. {
  93. return true; // FBX files can be plain-text so I don't even check for magic number
  94. }
  95. SPtr<ImportOptions> FBXImporter::createImportOptions() const
  96. {
  97. return bs_shared_ptr_new<MeshImportOptions>();
  98. }
  99. SPtr<Resource> FBXImporter::import(const Path& filePath, SPtr<const ImportOptions> importOptions)
  100. {
  101. MESH_DESC desc;
  102. Vector<FBXAnimationClipData> dummy;
  103. SPtr<RendererMeshData> rendererMeshData = importMeshData(filePath, importOptions, desc.subMeshes, dummy,
  104. desc.skeleton, desc.morphShapes);
  105. const MeshImportOptions* meshImportOptions = static_cast<const MeshImportOptions*>(importOptions.get());
  106. desc.usage = MU_STATIC;
  107. if (meshImportOptions->getCPUCached())
  108. desc.usage |= MU_CPUCACHED;
  109. SPtr<Mesh> mesh = Mesh::_createPtr(rendererMeshData->getData(), desc);
  110. WString fileName = filePath.getWFilename(false);
  111. mesh->setName(fileName);
  112. return mesh;
  113. }
  114. Vector<SubResourceRaw> FBXImporter::importAll(const Path& filePath, SPtr<const ImportOptions> importOptions)
  115. {
  116. MESH_DESC desc;
  117. Vector<FBXAnimationClipData> animationClips;
  118. SPtr<RendererMeshData> rendererMeshData = importMeshData(filePath, importOptions, desc.subMeshes, animationClips,
  119. desc.skeleton, desc.morphShapes);
  120. const MeshImportOptions* meshImportOptions = static_cast<const MeshImportOptions*>(importOptions.get());
  121. desc.usage = MU_STATIC;
  122. if (meshImportOptions->getCPUCached())
  123. desc.usage |= MU_CPUCACHED;
  124. SPtr<Mesh> mesh = Mesh::_createPtr(rendererMeshData->getData(), desc);
  125. WString fileName = filePath.getWFilename(false);
  126. mesh->setName(fileName);
  127. Vector<SubResourceRaw> output;
  128. if(mesh != nullptr)
  129. {
  130. output.push_back({ L"primary", mesh });
  131. CollisionMeshType collisionMeshType = meshImportOptions->getCollisionMeshType();
  132. if(collisionMeshType != CollisionMeshType::None)
  133. {
  134. if(Physics::isStarted())
  135. {
  136. PhysicsMeshType type = collisionMeshType == CollisionMeshType::Convex ?
  137. PhysicsMeshType::Convex : PhysicsMeshType::Triangle;
  138. SPtr<PhysicsMesh> physicsMesh = PhysicsMesh::_createPtr(rendererMeshData->getData(), type);
  139. output.push_back({ L"collision", physicsMesh });
  140. }
  141. else
  142. {
  143. LOGWRN("Cannot generate a collision mesh as the physics module was not started.");
  144. }
  145. }
  146. Vector<ImportedAnimationEvents> events = meshImportOptions->getAnimationEvents();
  147. for(auto& entry : animationClips)
  148. {
  149. SPtr<AnimationClip> clip = AnimationClip::_createPtr(entry.curves, entry.isAdditive, entry.sampleRate,
  150. entry.rootMotion);
  151. for(auto& eventsEntry : events)
  152. {
  153. if(entry.name == eventsEntry.name)
  154. {
  155. clip->setEvents(eventsEntry.events);
  156. break;
  157. }
  158. }
  159. output.push_back({ toWString(entry.name), clip });
  160. }
  161. }
  162. return output;
  163. }
  164. SPtr<RendererMeshData> FBXImporter::importMeshData(const Path& filePath, SPtr<const ImportOptions> importOptions,
  165. Vector<SubMesh>& subMeshes, Vector<FBXAnimationClipData>& animation, SPtr<Skeleton>& skeleton,
  166. SPtr<MorphShapes>& morphShapes)
  167. {
  168. FbxScene* fbxScene = nullptr;
  169. if (!startUpSdk(fbxScene))
  170. return nullptr;
  171. if (!loadFBXFile(fbxScene, filePath))
  172. return nullptr;
  173. const MeshImportOptions* meshImportOptions = static_cast<const MeshImportOptions*>(importOptions.get());
  174. FBXImportOptions fbxImportOptions;
  175. fbxImportOptions.importNormals = meshImportOptions->getImportNormals();
  176. fbxImportOptions.importTangents = meshImportOptions->getImportTangents();
  177. fbxImportOptions.importAnimation = meshImportOptions->getImportAnimation();
  178. fbxImportOptions.importBlendShapes = meshImportOptions->getImportBlendShapes();
  179. fbxImportOptions.importSkin = meshImportOptions->getImportSkin();
  180. fbxImportOptions.importScale = meshImportOptions->getImportScale();
  181. FBXImportScene importedScene;
  182. bakeTransforms(fbxScene);
  183. parseScene(fbxScene, fbxImportOptions, importedScene);
  184. if (fbxImportOptions.importBlendShapes)
  185. importBlendShapes(importedScene, fbxImportOptions);
  186. if (fbxImportOptions.importSkin)
  187. importSkin(importedScene, fbxImportOptions);
  188. if (fbxImportOptions.importAnimation)
  189. importAnimations(fbxScene, fbxImportOptions, importedScene);
  190. splitMeshVertices(importedScene);
  191. generateMissingTangentSpace(importedScene, fbxImportOptions);
  192. SPtr<RendererMeshData> rendererMeshData = generateMeshData(importedScene, fbxImportOptions, subMeshes);
  193. skeleton = createSkeleton(importedScene, subMeshes.size() > 1);
  194. morphShapes = createMorphShapes(importedScene);
  195. // Import animation clips
  196. if (!importedScene.clips.empty())
  197. {
  198. Vector<AnimationSplitInfo> splits = meshImportOptions->getAnimationClipSplits();
  199. convertAnimations(importedScene.clips, splits, skeleton, meshImportOptions->getImportRootMotion(), animation);
  200. }
  201. // TODO - Later: Optimize mesh: Remove bad and degenerate polygons, weld nearby vertices, optimize for vertex cache
  202. shutDownSdk();
  203. return rendererMeshData;
  204. }
  205. SPtr<Skeleton> FBXImporter::createSkeleton(const FBXImportScene& scene, bool sharedRoot)
  206. {
  207. Vector<BONE_DESC> allBones;
  208. UnorderedMap<FBXImportNode*, UINT32> boneMap;
  209. for (auto& mesh : scene.meshes)
  210. {
  211. // Create bones
  212. UINT32 numBones = (UINT32)mesh->bones.size();
  213. for (auto& fbxBone : mesh->bones)
  214. {
  215. UINT32 boneIdx = (UINT32)allBones.size();
  216. boneMap[fbxBone.node] = boneIdx;
  217. allBones.push_back(BONE_DESC());
  218. BONE_DESC& bone = allBones.back();
  219. bone.name = fbxBone.node->name;
  220. bone.invBindPose = fbxBone.bindPose;
  221. }
  222. }
  223. // Generate skeleton
  224. if (allBones.size() > 0)
  225. {
  226. // Find bone parents
  227. UINT32 numProcessedBones = 0;
  228. // Generate common root bone for all meshes
  229. UINT32 rootBoneIdx = (UINT32)-1;
  230. if (sharedRoot)
  231. {
  232. rootBoneIdx = (UINT32)allBones.size();
  233. allBones.push_back(BONE_DESC());
  234. BONE_DESC& bone = allBones.back();
  235. bone.name = "MultiMeshRoot";
  236. bone.invBindPose = Matrix4::IDENTITY;
  237. bone.parent = (UINT32)-1;
  238. numProcessedBones++;
  239. }
  240. Stack<std::pair<FBXImportNode*, UINT32>> todo;
  241. todo.push({ scene.rootNode, rootBoneIdx });
  242. while (!todo.empty())
  243. {
  244. auto entry = todo.top();
  245. todo.pop();
  246. FBXImportNode* node = entry.first;
  247. UINT32 parentBoneIdx = entry.second;
  248. auto boneIter = boneMap.find(node);
  249. if (boneIter != boneMap.end())
  250. {
  251. UINT32 boneIdx = boneIter->second;
  252. allBones[boneIdx].parent = parentBoneIdx;
  253. numProcessedBones++;
  254. parentBoneIdx = boneIdx;
  255. }
  256. for (auto& child : node->children)
  257. todo.push({ child, parentBoneIdx });
  258. }
  259. UINT32 numAllBones = (UINT32)allBones.size();
  260. if (numProcessedBones == numAllBones)
  261. return Skeleton::create(allBones.data(), numAllBones);
  262. LOGERR("Not all bones were found in the node hierarchy. Skeleton invalid.");
  263. }
  264. return nullptr;
  265. }
  266. SPtr<MorphShapes> FBXImporter::createMorphShapes(const FBXImportScene& scene)
  267. {
  268. // Combine morph shapes from all sub-meshes, and transform them
  269. struct RawMorphShape
  270. {
  271. String name;
  272. float weight;
  273. Vector<MorphVertex> vertices;
  274. };
  275. UnorderedMap<String, UnorderedMap<String, RawMorphShape>> allRawMorphShapes;
  276. UINT32 totalNumVertices = 0;
  277. // Note: Order in which we combine meshes must match the order in MeshData::combine
  278. for (auto& mesh : scene.meshes)
  279. {
  280. UINT32 numVertices = (UINT32)mesh->positions.size();
  281. UINT32 numNormals = (UINT32)mesh->normals.size();
  282. bool hasNormals = numVertices == numNormals;
  283. for (auto& node : mesh->referencedBy)
  284. {
  285. Matrix4 worldTransform = node->worldTransform * scene.globalScale;
  286. Matrix4 worldTransformIT = worldTransform.inverse();
  287. worldTransformIT = worldTransformIT.transpose();
  288. // Copy & transform positions
  289. for(auto& blendShape : mesh->blendShapes)
  290. {
  291. UnorderedMap<String, RawMorphShape>& channelShapes = allRawMorphShapes[blendShape.name];
  292. for(auto& blendFrame : blendShape.frames)
  293. {
  294. RawMorphShape& shape = channelShapes[blendFrame.name];
  295. shape.name = blendFrame.name;
  296. shape.weight = blendFrame.weight;
  297. UINT32 frameNumVertices = (UINT32)blendFrame.positions.size();
  298. if (frameNumVertices == numVertices)
  299. {
  300. for (UINT32 i = 0; i < numVertices; i++)
  301. {
  302. Vector3 meshPosition = worldTransform.multiplyAffine(mesh->positions[i]);
  303. Vector3 blendPosition = worldTransform.multiplyAffine(blendFrame.positions[i]);
  304. Vector3 positionDelta = blendPosition - meshPosition;
  305. Vector3 normalDelta;
  306. if (hasNormals)
  307. {
  308. Vector3 blendNormal = worldTransformIT.multiplyDirection(blendFrame.normals[i]);
  309. blendNormal = Vector3::normalize(blendNormal);
  310. Vector3 meshNormal = worldTransformIT.multiplyDirection(mesh->normals[i]);
  311. meshNormal = Vector3::normalize(meshNormal);
  312. normalDelta = blendNormal - meshNormal;
  313. }
  314. else
  315. normalDelta = Vector3::ZERO;
  316. if (positionDelta.squaredLength() > 0.000001f || normalDelta.squaredLength() > 0.0001f)
  317. shape.vertices.push_back(MorphVertex(positionDelta, normalDelta, totalNumVertices + i));
  318. }
  319. }
  320. else
  321. {
  322. LOGERR("Corrupt blend shape frame. Number of vertices doesn't match the number of mesh vertices.");
  323. }
  324. }
  325. }
  326. totalNumVertices += numVertices;
  327. }
  328. }
  329. // Create morph shape object from combined shape data
  330. SPtr<MorphShapes> morphShapes;
  331. Vector<SPtr<MorphChannel>> allChannels;
  332. for (auto& channel : allRawMorphShapes)
  333. {
  334. Vector<SPtr<MorphShape>> channelShapes;
  335. for (auto& entry : channel.second)
  336. {
  337. RawMorphShape& shape = entry.second;
  338. shape.vertices.shrink_to_fit();
  339. SPtr<MorphShape> morphShape = MorphShape::create(shape.name, shape.weight, shape.vertices);
  340. channelShapes.push_back(morphShape);
  341. }
  342. if(channelShapes.size() > 0)
  343. {
  344. SPtr<MorphChannel> morphChannel = MorphChannel::create(channel.first, channelShapes);
  345. allChannels.push_back(morphChannel);
  346. }
  347. }
  348. if (!allChannels.empty())
  349. return MorphShapes::create(allChannels, totalNumVertices);
  350. return morphShapes;
  351. }
  352. bool FBXImporter::startUpSdk(FbxScene*& scene)
  353. {
  354. mFBXManager = FbxManager::Create();
  355. if (mFBXManager == nullptr)
  356. {
  357. LOGERR("FBX import failed: FBX SDK failed to initialize. FbxManager::Create() failed.");
  358. return false;
  359. }
  360. FbxIOSettings* ios = FbxIOSettings::Create(mFBXManager, IOSROOT);
  361. mFBXManager->SetIOSettings(ios);
  362. scene = FbxScene::Create(mFBXManager, "Import Scene");
  363. if (scene == nullptr)
  364. {
  365. LOGWRN("FBX import failed: Failed to create FBX scene.");
  366. return false;
  367. }
  368. return true;
  369. }
  370. void FBXImporter::shutDownSdk()
  371. {
  372. mFBXManager->Destroy();
  373. mFBXManager = nullptr;
  374. }
  375. bool FBXImporter::loadFBXFile(FbxScene* scene, const Path& filePath)
  376. {
  377. int lFileMajor, lFileMinor, lFileRevision;
  378. int lSDKMajor, lSDKMinor, lSDKRevision;
  379. FbxManager::GetFileFormatVersion(lSDKMajor, lSDKMinor, lSDKRevision);
  380. FbxImporter* importer = FbxImporter::Create(mFBXManager, "");
  381. bool importStatus = importer->Initialize(filePath.toString().c_str(), -1, mFBXManager->GetIOSettings());
  382. importer->GetFileVersion(lFileMajor, lFileMinor, lFileRevision);
  383. if(!importStatus)
  384. {
  385. LOGERR("FBX import failed: Call to FbxImporter::Initialize() failed.\n" +
  386. String("Error returned: %s\n\n") + String(importer->GetStatus().GetErrorString()));
  387. return false;
  388. }
  389. mFBXManager->GetIOSettings()->SetBoolProp(IMP_FBX_TEXTURE, false);
  390. mFBXManager->GetIOSettings()->SetBoolProp(IMP_FBX_GOBO, false);
  391. importStatus = importer->Import(scene);
  392. if(!importStatus)
  393. {
  394. importer->Destroy();
  395. LOGERR("FBX import failed: Call to FbxImporter::Import() failed.\n" +
  396. String("Error returned: %s\n\n") + String(importer->GetStatus().GetErrorString()));
  397. return false;
  398. }
  399. FbxAxisSystem fileCoordSystem = scene->GetGlobalSettings().GetAxisSystem();
  400. FbxAxisSystem bsCoordSystem(FbxAxisSystem::eYAxis, FbxAxisSystem::eParityOdd, FbxAxisSystem::eRightHanded);
  401. if (fileCoordSystem != bsCoordSystem)
  402. bsCoordSystem.ConvertScene(scene);
  403. importer->Destroy();
  404. return true;
  405. }
  406. void FBXImporter::parseScene(FbxScene* scene, const FBXImportOptions& options, FBXImportScene& outputScene)
  407. {
  408. float importScale = 1.0f;
  409. if (options.importScale > 0.0001f)
  410. importScale = options.importScale;
  411. FbxSystemUnit units = scene->GetGlobalSettings().GetSystemUnit();
  412. FbxSystemUnit bsScaledUnits(100.0f);
  413. outputScene.scaleFactor = (float)units.GetConversionFactorTo(bsScaledUnits) * importScale;
  414. outputScene.globalScale = Matrix4::scaling(outputScene.scaleFactor);
  415. outputScene.rootNode = createImportNode(outputScene, scene->GetRootNode(), nullptr);
  416. Stack<FbxNode*> todo;
  417. todo.push(scene->GetRootNode());
  418. while(!todo.empty())
  419. {
  420. FbxNode* curNode = todo.top();
  421. FBXImportNode* curImportNode = outputScene.nodeMap[curNode];
  422. todo.pop();
  423. FbxNodeAttribute* attrib = curNode->GetNodeAttribute();
  424. if(attrib != nullptr)
  425. {
  426. FbxNodeAttribute::EType attribType = attrib->GetAttributeType();
  427. switch(attribType)
  428. {
  429. case FbxNodeAttribute::eNurbs:
  430. case FbxNodeAttribute::eNurbsSurface:
  431. case FbxNodeAttribute::ePatch:
  432. {
  433. FbxGeometryConverter geomConverter(mFBXManager);
  434. attrib = geomConverter.Triangulate(attrib, true);
  435. if (attrib->GetAttributeType() == FbxNodeAttribute::eMesh)
  436. {
  437. FbxMesh* mesh = static_cast<FbxMesh*>(attrib);
  438. mesh->RemoveBadPolygons();
  439. parseMesh(mesh, curImportNode, options, outputScene);
  440. }
  441. }
  442. break;
  443. case FbxNodeAttribute::eMesh:
  444. {
  445. FbxMesh* mesh = static_cast<FbxMesh*>(attrib);
  446. mesh->RemoveBadPolygons();
  447. if(!mesh->IsTriangleMesh())
  448. {
  449. FbxGeometryConverter geomConverter(mFBXManager);
  450. geomConverter.Triangulate(mesh, true);
  451. attrib = curNode->GetNodeAttribute();
  452. mesh = static_cast<FbxMesh*>(attrib);
  453. }
  454. parseMesh(mesh, curImportNode, options, outputScene);
  455. }
  456. break;
  457. default:
  458. break;
  459. }
  460. }
  461. for (int i = 0; i < curNode->GetChildCount(); i++)
  462. {
  463. FbxNode* childNode = curNode->GetChild(i);
  464. createImportNode(outputScene, childNode, curImportNode);
  465. todo.push(childNode);
  466. }
  467. }
  468. }
  469. FBXImportNode* FBXImporter::createImportNode(FBXImportScene& scene, FbxNode* fbxNode, FBXImportNode* parent)
  470. {
  471. FBXImportNode* node = bs_new<FBXImportNode>();
  472. Vector3 translation = FBXToNativeType(fbxNode->LclTranslation.Get());
  473. Vector3 rotationEuler = FBXToNativeType(fbxNode->LclRotation.Get());
  474. Vector3 scale = FBXToNativeType(fbxNode->LclScaling.Get());
  475. Quaternion rotation((Radian)rotationEuler.x, (Radian)rotationEuler.y, (Radian)rotationEuler.z);
  476. node->localTransform.setTRS(translation, rotation, scale);
  477. node->name = fbxNode->GetNameWithoutNameSpacePrefix().Buffer();
  478. node->fbxNode = fbxNode;
  479. if (parent != nullptr)
  480. {
  481. node->worldTransform = node->localTransform * parent->worldTransform;
  482. parent->children.push_back(node);
  483. }
  484. else
  485. node->worldTransform = node->localTransform;
  486. scene.nodeMap.insert(std::make_pair(fbxNode, node));
  487. return node;
  488. }
  489. void FBXImporter::splitMeshVertices(FBXImportScene& scene)
  490. {
  491. Vector<FBXImportMesh*> splitMeshes;
  492. for (auto& mesh : scene.meshes)
  493. {
  494. FBXImportMesh* splitMesh = bs_new<FBXImportMesh>();
  495. splitMesh->fbxMesh = mesh->fbxMesh;
  496. splitMesh->referencedBy = mesh->referencedBy;
  497. splitMesh->bones = mesh->bones;
  498. FBXUtility::splitVertices(*mesh, *splitMesh);
  499. FBXUtility::flipWindingOrder(*splitMesh);
  500. splitMeshes.push_back(splitMesh);
  501. bs_delete(mesh);
  502. }
  503. scene.meshes = splitMeshes;
  504. }
  505. void FBXImporter::convertAnimations(const Vector<FBXAnimationClip>& clips, const Vector<AnimationSplitInfo>& splits,
  506. const SPtr<Skeleton>& skeleton, bool importRootMotion, Vector<FBXAnimationClipData>& output)
  507. {
  508. UnorderedSet<String> names;
  509. String rootBoneName;
  510. if (skeleton == nullptr)
  511. importRootMotion = false;
  512. else
  513. {
  514. UINT32 rootBoneIdx = skeleton->getRootBoneIndex();
  515. if (rootBoneIdx == (UINT32)-1)
  516. importRootMotion = false;
  517. else
  518. rootBoneName = skeleton->getBoneInfo(rootBoneIdx).name;
  519. }
  520. bool isFirstClip = true;
  521. for (auto& clip : clips)
  522. {
  523. SPtr<AnimationCurves> curves = bs_shared_ptr_new<AnimationCurves>();
  524. SPtr<RootMotion> rootMotion;
  525. // Find offset so animations start at time 0
  526. float animStart = std::numeric_limits<float>::infinity();
  527. for (auto& bone : clip.boneAnimations)
  528. {
  529. if(bone.translation.getNumKeyFrames() > 0)
  530. animStart = std::min(bone.translation.getKeyFrame(0).time, animStart);
  531. if (bone.rotation.getNumKeyFrames() > 0)
  532. animStart = std::min(bone.rotation.getKeyFrame(0).time, animStart);
  533. if (bone.scale.getNumKeyFrames() > 0)
  534. animStart = std::min(bone.scale.getKeyFrame(0).time, animStart);
  535. }
  536. for (auto& anim : clip.blendShapeAnimations)
  537. {
  538. if (anim.curve.getNumKeyFrames() > 0)
  539. animStart = std::min(anim.curve.getKeyFrame(0).time, animStart);
  540. }
  541. AnimationCurveFlags blendShapeFlags = AnimationCurveFlag::ImportedCurve | AnimationCurveFlag::MorphFrame;
  542. if (animStart != 0.0f && animStart != std::numeric_limits<float>::infinity())
  543. {
  544. for (auto& bone : clip.boneAnimations)
  545. {
  546. TAnimationCurve<Vector3> translation = AnimationUtility::offsetCurve(bone.translation, -animStart);
  547. TAnimationCurve<Quaternion> rotation = AnimationUtility::offsetCurve(bone.rotation, -animStart);
  548. TAnimationCurve<Vector3> scale = AnimationUtility::offsetCurve(bone.scale, -animStart);
  549. if(importRootMotion && bone.node->name == rootBoneName)
  550. rootMotion = bs_shared_ptr_new<RootMotion>(translation, rotation);
  551. else
  552. {
  553. curves->position.push_back({ bone.node->name, AnimationCurveFlag::ImportedCurve, translation });
  554. curves->rotation.push_back({ bone.node->name, AnimationCurveFlag::ImportedCurve, rotation });
  555. curves->scale.push_back({ bone.node->name, AnimationCurveFlag::ImportedCurve, scale });
  556. }
  557. }
  558. for (auto& anim : clip.blendShapeAnimations)
  559. {
  560. TAnimationCurve<float> curve = AnimationUtility::offsetCurve(anim.curve, -animStart);
  561. curves->generic.push_back({ anim.blendShape, blendShapeFlags, curve });
  562. }
  563. }
  564. else
  565. {
  566. for (auto& bone : clip.boneAnimations)
  567. {
  568. if (importRootMotion && bone.node->name == rootBoneName)
  569. rootMotion = bs_shared_ptr_new<RootMotion>(bone.translation, bone.rotation);
  570. else
  571. {
  572. curves->position.push_back({ bone.node->name, AnimationCurveFlag::ImportedCurve, bone.translation });
  573. curves->rotation.push_back({ bone.node->name, AnimationCurveFlag::ImportedCurve, bone.rotation });
  574. curves->scale.push_back({ bone.node->name, AnimationCurveFlag::ImportedCurve, bone.scale });
  575. }
  576. }
  577. for (auto& anim : clip.blendShapeAnimations)
  578. curves->generic.push_back({ anim.blendShape, blendShapeFlags, anim.curve });
  579. }
  580. // See if any splits are required. We only split the first clip as it is assumed if FBX has multiple clips the
  581. // user has the ability to split them externally.
  582. if(isFirstClip && !splits.empty())
  583. {
  584. float secondsPerFrame = 1.0f / clip.sampleRate;
  585. for(auto& split : splits)
  586. {
  587. SPtr<AnimationCurves> splitClipCurve = bs_shared_ptr_new<AnimationCurves>();
  588. SPtr<RootMotion> splitRootMotion;
  589. auto splitCurves = [&](auto& inCurves, auto& outCurves)
  590. {
  591. UINT32 numCurves = (UINT32)inCurves.size();
  592. outCurves.resize(numCurves);
  593. for (UINT32 i = 0; i < numCurves; i++)
  594. {
  595. auto& animCurve = inCurves[i].curve;
  596. outCurves[i].name = inCurves[i].name;
  597. UINT32 numFrames = animCurve.getNumKeyFrames();
  598. if (numFrames == 0)
  599. continue;
  600. float startTime = split.startFrame * secondsPerFrame;
  601. float endTime = split.endFrame * secondsPerFrame;
  602. outCurves[i].curve = inCurves[i].curve.split(startTime, endTime);
  603. if (split.isAdditive)
  604. outCurves[i].curve.makeAdditive();
  605. }
  606. };
  607. splitCurves(curves->position, splitClipCurve->position);
  608. splitCurves(curves->rotation, splitClipCurve->rotation);
  609. splitCurves(curves->scale, splitClipCurve->scale);
  610. splitCurves(curves->generic, splitClipCurve->generic);
  611. if(rootMotion != nullptr)
  612. {
  613. auto splitCurve = [&](auto& inCurve, auto& outCurve)
  614. {
  615. UINT32 numFrames = inCurve.getNumKeyFrames();
  616. if (numFrames > 0)
  617. {
  618. float startTime = split.startFrame * secondsPerFrame;
  619. float endTime = split.endFrame * secondsPerFrame;
  620. outCurve = inCurve.split(startTime, endTime);
  621. if (split.isAdditive)
  622. outCurve.makeAdditive();
  623. }
  624. };
  625. splitRootMotion = bs_shared_ptr_new<RootMotion>();
  626. splitCurve(rootMotion->position, splitRootMotion->position);
  627. splitCurve(rootMotion->rotation, splitRootMotion->rotation);
  628. }
  629. // Search for a unique name
  630. String name = split.name;
  631. UINT32 attemptIdx = 0;
  632. while (names.find(name) != names.end())
  633. {
  634. name = clip.name + "_" + toString(attemptIdx);
  635. attemptIdx++;
  636. }
  637. names.insert(name);
  638. output.push_back(FBXAnimationClipData(name, split.isAdditive, clip.sampleRate, splitClipCurve,
  639. splitRootMotion));
  640. }
  641. }
  642. else
  643. {
  644. // Search for a unique name
  645. String name = clip.name;
  646. UINT32 attemptIdx = 0;
  647. while(names.find(name) != names.end())
  648. {
  649. name = clip.name + "_" + toString(attemptIdx);
  650. attemptIdx++;
  651. }
  652. names.insert(name);
  653. output.push_back(FBXAnimationClipData(name, false, clip.sampleRate, curves, rootMotion));
  654. }
  655. isFirstClip = false;
  656. }
  657. }
  658. SPtr<RendererMeshData> FBXImporter::generateMeshData(const FBXImportScene& scene, const FBXImportOptions& options,
  659. Vector<SubMesh>& outputSubMeshes)
  660. {
  661. Vector<SPtr<MeshData>> allMeshData;
  662. Vector<Vector<SubMesh>> allSubMeshes;
  663. Vector<BONE_DESC> allBones;
  664. UnorderedMap<FBXImportNode*, UINT32> boneMap;
  665. UINT32 boneIndexOffset = 0;
  666. for (auto& mesh : scene.meshes)
  667. {
  668. Vector<Vector<UINT32>> indicesPerMaterial;
  669. for (UINT32 i = 0; i < (UINT32)mesh->indices.size(); i++)
  670. {
  671. while ((UINT32)mesh->materials[i] >= (UINT32)indicesPerMaterial.size())
  672. indicesPerMaterial.push_back(Vector<UINT32>());
  673. indicesPerMaterial[mesh->materials[i]].push_back(mesh->indices[i]);
  674. }
  675. UINT32* orderedIndices = (UINT32*)bs_alloc((UINT32)mesh->indices.size() * sizeof(UINT32));
  676. Vector<SubMesh> subMeshes;
  677. UINT32 currentIndex = 0;
  678. for (auto& subMeshIndices : indicesPerMaterial)
  679. {
  680. UINT32 indexCount = (UINT32)subMeshIndices.size();
  681. UINT32* dest = orderedIndices + currentIndex;
  682. memcpy(dest, subMeshIndices.data(), indexCount * sizeof(UINT32));
  683. subMeshes.push_back(SubMesh(currentIndex, indexCount, DOT_TRIANGLE_LIST));
  684. currentIndex += indexCount;
  685. }
  686. UINT32 vertexLayout = (UINT32)VertexLayout::Position;
  687. size_t numVertices = mesh->positions.size();
  688. bool hasColors = mesh->colors.size() == numVertices;
  689. bool hasNormals = mesh->normals.size() == numVertices;
  690. bool hasBoneInfluences = mesh->boneInfluences.size() == numVertices;
  691. if (hasColors)
  692. vertexLayout |= (UINT32)VertexLayout::Color;
  693. bool hasTangents = false;
  694. if (hasNormals)
  695. {
  696. vertexLayout |= (UINT32)VertexLayout::Normal;
  697. if (mesh->tangents.size() == numVertices &&
  698. mesh->bitangents.size() == numVertices)
  699. {
  700. vertexLayout |= (UINT32)VertexLayout::Tangent;
  701. hasTangents = true;
  702. }
  703. }
  704. if (hasBoneInfluences)
  705. vertexLayout |= (UINT32)VertexLayout::BoneWeights;
  706. for (UINT32 i = 0; i < FBX_IMPORT_MAX_UV_LAYERS; i++)
  707. {
  708. if (mesh->UV[i].size() == numVertices)
  709. {
  710. if (i == 0)
  711. vertexLayout |= (UINT32)VertexLayout::UV0;
  712. else if (i == 1)
  713. vertexLayout |= (UINT32)VertexLayout::UV1;
  714. }
  715. }
  716. UINT32 numIndices = (UINT32)mesh->indices.size();
  717. for (auto& node : mesh->referencedBy)
  718. {
  719. Matrix4 worldTransform = node->worldTransform * scene.globalScale;
  720. Matrix4 worldTransformIT = worldTransform.inverse();
  721. worldTransformIT = worldTransformIT.transpose();
  722. SPtr<RendererMeshData> meshData = RendererMeshData::create((UINT32)numVertices, numIndices, (VertexLayout)vertexLayout);
  723. // Copy indices
  724. meshData->setIndices((UINT32*)mesh->indices.data(), numIndices * sizeof(UINT32));
  725. // Copy & transform positions
  726. UINT32 positionsSize = sizeof(Vector3) * (UINT32)numVertices;
  727. Vector3* transformedPositions = (Vector3*)bs_stack_alloc(positionsSize);
  728. for (UINT32 i = 0; i < (UINT32)numVertices; i++)
  729. transformedPositions[i] = worldTransform.multiplyAffine((Vector3)mesh->positions[i]);
  730. meshData->setPositions(transformedPositions, positionsSize);
  731. bs_stack_free(transformedPositions);
  732. // Copy & transform normals
  733. if (hasNormals)
  734. {
  735. UINT32 normalsSize = sizeof(Vector3) * (UINT32)numVertices;
  736. Vector3* transformedNormals = (Vector3*)bs_stack_alloc(normalsSize);
  737. // Copy, convert & transform tangents & bitangents
  738. if (hasTangents)
  739. {
  740. UINT32 tangentsSize = sizeof(Vector4) * (UINT32)numVertices;
  741. Vector4* transformedTangents = (Vector4*)bs_stack_alloc(tangentsSize);
  742. for (UINT32 i = 0; i < (UINT32)numVertices; i++)
  743. {
  744. Vector3 normal = (Vector3)mesh->normals[i];
  745. normal = worldTransformIT.multiplyDirection(normal);
  746. transformedNormals[i] = Vector3::normalize(normal);
  747. Vector3 tangent = (Vector3)mesh->tangents[i];
  748. tangent = Vector3::normalize(worldTransformIT.multiplyDirection(tangent));
  749. Vector3 bitangent = (Vector3)mesh->bitangents[i];
  750. bitangent = worldTransformIT.multiplyDirection(bitangent);
  751. Vector3 engineBitangent = Vector3::cross(normal, tangent);
  752. float sign = Vector3::dot(engineBitangent, bitangent);
  753. transformedTangents[i] = Vector4(tangent.x, tangent.y, tangent.z, sign > 0 ? 1.0f : -1.0f);
  754. }
  755. meshData->setTangents(transformedTangents, tangentsSize);
  756. bs_stack_free(transformedTangents);
  757. }
  758. else // Just normals
  759. {
  760. for (UINT32 i = 0; i < (UINT32)numVertices; i++)
  761. transformedNormals[i] = Vector3::normalize(worldTransformIT.multiplyDirection((Vector3)mesh->normals[i]));
  762. }
  763. meshData->setNormals(transformedNormals, normalsSize);
  764. bs_stack_free(transformedNormals);
  765. }
  766. // Copy colors
  767. if (hasColors)
  768. {
  769. meshData->setColors(mesh->colors.data(), sizeof(UINT32) * (UINT32)numVertices);
  770. }
  771. // Copy UV
  772. int writeUVIDx = 0;
  773. for (auto& uvLayer : mesh->UV)
  774. {
  775. if (uvLayer.size() == numVertices)
  776. {
  777. UINT32 size = sizeof(Vector2) * (UINT32)numVertices;
  778. Vector2* transformedUV = (Vector2*)bs_stack_alloc(size);
  779. UINT32 i = 0;
  780. for (auto& uv : uvLayer)
  781. {
  782. transformedUV[i] = uv;
  783. transformedUV[i].y = 1.0f - uv.y;
  784. i++;
  785. }
  786. if (writeUVIDx == 0)
  787. meshData->setUV0(transformedUV, size);
  788. else if (writeUVIDx == 1)
  789. meshData->setUV1(transformedUV, size);
  790. bs_stack_free(transformedUV);
  791. writeUVIDx++;
  792. }
  793. }
  794. // Copy bone influences
  795. if(hasBoneInfluences)
  796. {
  797. UINT32 bufferSize = sizeof(BoneWeight) * (UINT32)numVertices;
  798. BoneWeight* weights = (BoneWeight*)bs_stack_alloc(bufferSize);
  799. for(UINT32 i = 0; i < (UINT32)numVertices; i++)
  800. {
  801. weights[i].index0 = mesh->boneInfluences[i].indices[0] + boneIndexOffset;
  802. weights[i].index1 = mesh->boneInfluences[i].indices[1] + boneIndexOffset;
  803. weights[i].index2 = mesh->boneInfluences[i].indices[2] + boneIndexOffset;
  804. weights[i].index3 = mesh->boneInfluences[i].indices[3] + boneIndexOffset;
  805. weights[i].weight0 = mesh->boneInfluences[i].weights[0];
  806. weights[i].weight1 = mesh->boneInfluences[i].weights[1];
  807. weights[i].weight2 = mesh->boneInfluences[i].weights[2];
  808. weights[i].weight3 = mesh->boneInfluences[i].weights[3];
  809. }
  810. meshData->setBoneWeights(weights, bufferSize);
  811. bs_stack_free(weights);
  812. }
  813. allMeshData.push_back(meshData->getData());
  814. allSubMeshes.push_back(subMeshes);
  815. }
  816. UINT32 numBones = (UINT32)mesh->bones.size();
  817. boneIndexOffset += numBones;
  818. }
  819. if (allMeshData.size() > 1)
  820. {
  821. return RendererMeshData::create(MeshData::combine(allMeshData, allSubMeshes, outputSubMeshes));
  822. }
  823. else if (allMeshData.size() == 1)
  824. {
  825. outputSubMeshes = allSubMeshes[0];
  826. return RendererMeshData::create(allMeshData[0]);
  827. }
  828. return nullptr;
  829. }
  830. template<class TFBX, class TNative>
  831. class FBXDirectIndexer
  832. {
  833. public:
  834. FBXDirectIndexer(const FbxLayerElementTemplate<TFBX>& layer)
  835. :mElementArray(layer.GetDirectArray()),
  836. mElementCount(mElementArray.GetCount())
  837. {}
  838. bool get(int index, TNative& output) const
  839. {
  840. if (index < 0 || index >= mElementCount)
  841. return false;
  842. output = FBXToNativeType(mElementArray.GetAt(index));
  843. return true;
  844. }
  845. bool isEmpty() const
  846. {
  847. return mElementCount == 0;
  848. }
  849. private:
  850. const FbxLayerElementArrayTemplate<TFBX>& mElementArray;
  851. int mElementCount;
  852. };
  853. template<class TFBX, class TNative>
  854. class FBXIndexIndexer
  855. {
  856. public:
  857. FBXIndexIndexer(const FbxLayerElementTemplate<TFBX>& layer)
  858. :mElementArray(layer.GetDirectArray()),
  859. mIndexArray(layer.GetIndexArray()),
  860. mElementCount(mElementArray.GetCount()),
  861. mIndexCount(mIndexArray.GetCount())
  862. {}
  863. bool get(int index, TNative& output) const
  864. {
  865. if (index < 0 || index >= mIndexCount)
  866. return false;
  867. int actualIndex = mIndexArray.GetAt(index);
  868. if (actualIndex < 0 || actualIndex >= mElementCount)
  869. return false;
  870. output = FBXToNativeType(mElementArray.GetAt(actualIndex));
  871. return true;
  872. }
  873. bool isEmpty() const
  874. {
  875. return mElementCount == 0 || mIndexCount == 0;
  876. }
  877. private:
  878. const FbxLayerElementArrayTemplate<TFBX>& mElementArray;
  879. const FbxLayerElementArrayTemplate<int>& mIndexArray;
  880. int mElementCount;
  881. int mIndexCount;
  882. };
  883. template<class TFBX, class TNative, class TIndexer>
  884. void readLayerData(FbxLayerElementTemplate<TFBX>& layer, Vector<TNative>& output, const Vector<int>& indices)
  885. {
  886. TIndexer indexer(layer);
  887. if (indexer.isEmpty())
  888. return;
  889. output.resize(indices.size());
  890. FbxLayerElement::EMappingMode mappingMode = layer.GetMappingMode();
  891. UINT32 indexCount = (UINT32)indices.size();
  892. switch (mappingMode)
  893. {
  894. case FbxLayerElement::eByControlPoint:
  895. for (UINT32 i = 0; i < indexCount; i++)
  896. {
  897. int index = indices[i];
  898. indexer.get(index, output[i]);
  899. }
  900. break;
  901. case FbxLayerElement::eByPolygonVertex:
  902. for (UINT32 i = 0; i < indexCount; i++)
  903. indexer.get(i, output[i]);
  904. break;
  905. case FbxLayerElement::eByPolygon:
  906. // We expect mesh to be triangulated here
  907. {
  908. UINT32 polygonCount = indexCount / 3;
  909. UINT32 index = 0;
  910. for (UINT32 i = 0; i < polygonCount; i++)
  911. {
  912. TNative value;
  913. indexer.get(i, value);
  914. output[index++] = value;
  915. output[index++] = value;
  916. output[index++] = value;
  917. }
  918. }
  919. break;
  920. case FbxLayerElement::eAllSame:
  921. {
  922. TNative value;
  923. indexer.get(0, value);
  924. for (UINT32 i = 0; i < indexCount; i++)
  925. output[i] = value;
  926. }
  927. break;
  928. default:
  929. LOGWRN("FBX Import: Unsupported layer mapping mode.");
  930. break;
  931. }
  932. }
  933. template<class TFBX, class TNative>
  934. void readLayerData(FbxLayerElementTemplate<TFBX>& layer, Vector<TNative>& output, const Vector<int>& indices)
  935. {
  936. FbxLayerElement::EReferenceMode refMode = layer.GetReferenceMode();
  937. if (refMode == FbxLayerElement::eDirect)
  938. readLayerData<TFBX, TNative, FBXDirectIndexer<TFBX, TNative> >(layer, output, indices);
  939. else if (refMode == FbxLayerElement::eIndexToDirect)
  940. readLayerData<TFBX, TNative, FBXIndexIndexer<TFBX, TNative> >(layer, output, indices);
  941. else
  942. LOGWRN("FBX Import: Unsupported layer reference mode.");
  943. }
  944. void FBXImporter::parseMesh(FbxMesh* mesh, FBXImportNode* parentNode, const FBXImportOptions& options, FBXImportScene& outputScene)
  945. {
  946. // Check if valid
  947. if (!mesh->IsTriangleMesh())
  948. return;
  949. UINT32 vertexCount = mesh->GetControlPointsCount();
  950. UINT32 triangleCount = mesh->GetPolygonCount();
  951. if (vertexCount == 0 || triangleCount == 0)
  952. return;
  953. // Register in global mesh array
  954. FBXImportMesh* importMesh = nullptr;
  955. auto iterFindMesh = outputScene.meshMap.find(mesh);
  956. if (iterFindMesh != outputScene.meshMap.end())
  957. {
  958. UINT32 meshIdx = iterFindMesh->second;
  959. outputScene.meshes[meshIdx]->referencedBy.push_back(parentNode);
  960. return;
  961. }
  962. else
  963. {
  964. importMesh = bs_new<FBXImportMesh>();
  965. outputScene.meshes.push_back(importMesh);
  966. importMesh->referencedBy.push_back(parentNode);
  967. importMesh->fbxMesh = mesh;
  968. outputScene.meshMap[mesh] = (UINT32)outputScene.meshes.size() - 1;
  969. }
  970. // Import vertices
  971. importMesh->positions.resize(vertexCount);
  972. FbxVector4* controlPoints = mesh->GetControlPoints();
  973. for (UINT32 i = 0; i < vertexCount; i++)
  974. importMesh->positions[i] = FBXToNativeType(controlPoints[i]);
  975. // Import triangles
  976. UINT32 indexCount = triangleCount * 3;
  977. importMesh->indices.resize(indexCount);
  978. int* fbxIndices = mesh->GetPolygonVertices();
  979. importMesh->indices.assign(fbxIndices, fbxIndices + indexCount);
  980. // Import UVs
  981. Vector<FbxLayerElementUV*> fbxUVLayers;
  982. //// Search the diffuse layers first
  983. for (UINT32 i = 0; i < FBX_IMPORT_MAX_UV_LAYERS; i++)
  984. {
  985. FbxLayer* layer = mesh->GetLayer(i, FbxLayerElement::eUV);
  986. if (layer == nullptr)
  987. continue;
  988. for (int j = FbxLayerElement::eTextureDiffuse; j < FbxLayerElement::eTypeCount; j++)
  989. {
  990. FbxLayerElementUV* uvLayer = layer->GetUVs((FbxLayerElement::EType)j);
  991. if (uvLayer == nullptr)
  992. continue;
  993. fbxUVLayers.push_back(uvLayer);
  994. if (fbxUVLayers.size() == FBX_IMPORT_MAX_UV_LAYERS)
  995. break;
  996. }
  997. if (fbxUVLayers.size() == FBX_IMPORT_MAX_UV_LAYERS)
  998. break;
  999. }
  1000. //// If there's room, search all others too
  1001. if (fbxUVLayers.size() < FBX_IMPORT_MAX_UV_LAYERS)
  1002. {
  1003. UINT32 numLayers = mesh->GetLayerCount();
  1004. for (UINT32 i = 0; i < numLayers; i++)
  1005. {
  1006. FbxLayer* layer = mesh->GetLayer(i);
  1007. if (layer == nullptr)
  1008. continue;
  1009. for (int j = FbxLayerElement::eTextureDiffuse; j < FbxLayerElement::eTypeCount; j++)
  1010. {
  1011. FbxLayerElementUV* uvLayer = layer->GetUVs((FbxLayerElement::EType)j);
  1012. if (uvLayer == nullptr)
  1013. continue;
  1014. auto iterFind = std::find(fbxUVLayers.begin(), fbxUVLayers.end(), uvLayer);
  1015. if (iterFind != fbxUVLayers.end())
  1016. continue;
  1017. fbxUVLayers.push_back(uvLayer);
  1018. if (fbxUVLayers.size() == FBX_IMPORT_MAX_UV_LAYERS)
  1019. break;
  1020. }
  1021. if (fbxUVLayers.size() == FBX_IMPORT_MAX_UV_LAYERS)
  1022. break;
  1023. }
  1024. }
  1025. for (size_t i = 0; i < fbxUVLayers.size(); i++)
  1026. readLayerData(*fbxUVLayers[i], importMesh->UV[i], importMesh->indices);
  1027. FbxLayer* mainLayer = mesh->GetLayer(0);
  1028. if (mainLayer != nullptr)
  1029. {
  1030. // Import colors
  1031. if (mainLayer->GetVertexColors() != nullptr)
  1032. readLayerData(*mainLayer->GetVertexColors(), importMesh->colors, importMesh->indices);
  1033. // Import normals
  1034. if (options.importNormals)
  1035. {
  1036. bool hasNormals = mainLayer->GetNormals() != nullptr;
  1037. if (!hasNormals)
  1038. {
  1039. if (mainLayer->GetSmoothing() != nullptr)
  1040. {
  1041. FbxLayerElementSmoothing* smoothing = mainLayer->GetSmoothing();
  1042. if (smoothing->GetMappingMode() == FbxLayerElement::eByEdge)
  1043. {
  1044. FbxGeometryConverter converter(mFBXManager);
  1045. converter.ComputePolygonSmoothingFromEdgeSmoothing(mesh, 0);
  1046. }
  1047. readLayerData(*smoothing, importMesh->smoothingGroups, importMesh->indices);
  1048. if (!importMesh->smoothingGroups.empty())
  1049. {
  1050. FBXUtility::normalsFromSmoothing(importMesh->positions, importMesh->indices,
  1051. importMesh->smoothingGroups, importMesh->normals);
  1052. }
  1053. }
  1054. }
  1055. else
  1056. readLayerData(*mainLayer->GetNormals(), importMesh->normals, importMesh->indices);
  1057. }
  1058. // Import tangents
  1059. if (options.importTangents)
  1060. {
  1061. bool hasTangents = mainLayer->GetTangents() != nullptr && mainLayer->GetBinormals() != nullptr;
  1062. if (!hasTangents)
  1063. {
  1064. if (fbxUVLayers.size() > 0)
  1065. hasTangents = mesh->GenerateTangentsData(0, false);
  1066. }
  1067. if (hasTangents)
  1068. {
  1069. readLayerData(*mainLayer->GetTangents(), importMesh->tangents, importMesh->indices);
  1070. readLayerData(*mainLayer->GetBinormals(), importMesh->bitangents, importMesh->indices);
  1071. }
  1072. }
  1073. // Import material indexes
  1074. if (mainLayer->GetMaterials() != nullptr)
  1075. {
  1076. Vector<FbxSurfaceMaterial*> fbxMaterials;
  1077. readLayerData(*mainLayer->GetMaterials(), fbxMaterials, importMesh->indices);
  1078. UnorderedMap<FbxSurfaceMaterial*, int> materialLookup;
  1079. int nextMaterialIdx = 0;
  1080. for (UINT32 i = 0; i < (UINT32)fbxMaterials.size(); i++)
  1081. {
  1082. auto iterFind = materialLookup.find(fbxMaterials[i]);
  1083. int materialIdx = 0;
  1084. if (iterFind != materialLookup.end())
  1085. materialIdx = iterFind->second;
  1086. else
  1087. {
  1088. materialIdx = nextMaterialIdx++;
  1089. materialLookup[fbxMaterials[i]] = materialIdx;
  1090. }
  1091. importMesh->materials.push_back(materialIdx);
  1092. }
  1093. }
  1094. else
  1095. {
  1096. importMesh->materials.resize(importMesh->indices.size(), 0);
  1097. }
  1098. }
  1099. }
  1100. void FBXImporter::importBlendShapes(FBXImportScene& scene, const FBXImportOptions& options)
  1101. {
  1102. for (auto& mesh : scene.meshes)
  1103. {
  1104. FbxMesh* fbxMesh = mesh->fbxMesh;
  1105. UINT32 deformerCount = (UINT32)fbxMesh->GetDeformerCount(FbxDeformer::eBlendShape);
  1106. for (UINT32 i = 0; i < deformerCount; i++)
  1107. {
  1108. FbxBlendShape* deformer = static_cast<FbxBlendShape*>(fbxMesh->GetDeformer(i, FbxDeformer::eBlendShape));
  1109. UINT32 blendShapeChannelCount = (UINT32)deformer->GetBlendShapeChannelCount();
  1110. for (UINT32 j = 0; j < blendShapeChannelCount; ++j)
  1111. {
  1112. FbxBlendShapeChannel* channel = deformer->GetBlendShapeChannel(j);
  1113. double* weights = channel->GetTargetShapeFullWeights();
  1114. UINT32 frameCount = channel->GetTargetShapeCount();
  1115. if (frameCount == 0)
  1116. continue;
  1117. mesh->blendShapes.push_back(FBXBlendShape());
  1118. FBXBlendShape& blendShape = mesh->blendShapes.back();
  1119. blendShape.name = channel->GetName();
  1120. blendShape.frames.resize(frameCount);
  1121. // Get name without invalid characters
  1122. blendShape.name = StringUtil::replaceAll(blendShape.name, ".", "_");
  1123. blendShape.name = StringUtil::replaceAll(blendShape.name, "/", "_");
  1124. for (UINT32 k = 0; k < frameCount; k++)
  1125. {
  1126. FbxShape* fbxShape = channel->GetTargetShape(k);
  1127. FBXBlendShapeFrame& frame = blendShape.frames[k];
  1128. frame.name = fbxShape->GetName();
  1129. frame.weight = (float)(weights[k] / 100.0);
  1130. // Get name without invalid characters
  1131. frame.name = StringUtil::replaceAll(frame.name, ".", "_");
  1132. frame.name = StringUtil::replaceAll(frame.name, "/", "_");
  1133. importBlendShapeFrame(fbxShape, *mesh, options, frame);
  1134. }
  1135. }
  1136. }
  1137. }
  1138. }
  1139. void FBXImporter::importBlendShapeFrame(FbxShape* shape, const FBXImportMesh& mesh, const FBXImportOptions& options, FBXBlendShapeFrame& outFrame)
  1140. {
  1141. UINT32 vertexCount = (UINT32)shape->GetControlPointsCount();
  1142. outFrame.positions.resize(vertexCount);
  1143. FbxVector4* controlPoints = shape->GetControlPoints();
  1144. for (UINT32 i = 0; i < vertexCount; i++)
  1145. outFrame.positions[i] = FBXToNativeType(controlPoints[i]);
  1146. FbxLayer* mainLayer = shape->GetLayer(0);
  1147. if (options.importNormals)
  1148. {
  1149. bool hasNormals = mainLayer->GetNormals() != nullptr;
  1150. if (!hasNormals)
  1151. {
  1152. if (!mesh.smoothingGroups.empty())
  1153. {
  1154. FBXUtility::normalsFromSmoothing(outFrame.positions, mesh.indices,
  1155. mesh.smoothingGroups, outFrame.normals);
  1156. }
  1157. }
  1158. else
  1159. readLayerData(*mainLayer->GetNormals(), outFrame.normals, mesh.indices);
  1160. }
  1161. if (options.importTangents)
  1162. {
  1163. bool hasTangents = mainLayer->GetTangents() != nullptr && mainLayer->GetBinormals() != nullptr;
  1164. if (hasTangents)
  1165. {
  1166. readLayerData(*mainLayer->GetTangents(), outFrame.tangents, mesh.indices);
  1167. readLayerData(*mainLayer->GetBinormals(), outFrame.bitangents, mesh.indices);
  1168. }
  1169. }
  1170. }
  1171. void FBXImporter::importSkin(FBXImportScene& scene, const FBXImportOptions& options)
  1172. {
  1173. for (auto& mesh : scene.meshes)
  1174. {
  1175. FbxMesh* fbxMesh = mesh->fbxMesh;
  1176. UINT32 deformerCount = (UINT32)fbxMesh->GetDeformerCount(FbxDeformer::eSkin);
  1177. if (deformerCount > 0)
  1178. {
  1179. // We ignore other deformers if there's more than one
  1180. FbxSkin* deformer = static_cast<FbxSkin*>(fbxMesh->GetDeformer(0, FbxDeformer::eSkin));
  1181. UINT32 boneCount = (UINT32)deformer->GetClusterCount();
  1182. if (boneCount == 0)
  1183. continue;
  1184. // If only one bone and it links to itself, ignore the bone
  1185. if (boneCount == 1)
  1186. {
  1187. FbxCluster* cluster = deformer->GetCluster(0);
  1188. if (mesh->referencedBy.size() == 1 && mesh->referencedBy[0]->fbxNode == cluster->GetLink())
  1189. continue;
  1190. }
  1191. importSkin(scene, deformer, *mesh, options);
  1192. }
  1193. }
  1194. }
  1195. void FBXImporter::importSkin(FBXImportScene& scene, FbxSkin* skin, FBXImportMesh& mesh, const FBXImportOptions& options)
  1196. {
  1197. Vector<FBXBoneInfluence>& influences = mesh.boneInfluences;
  1198. influences.resize(mesh.positions.size());
  1199. Matrix4 invGlobalScale = scene.globalScale.inverseAffine();
  1200. UnorderedSet<FbxNode*> existingBones;
  1201. UINT32 boneCount = (UINT32)skin->GetClusterCount();
  1202. for (UINT32 i = 0; i < boneCount; i++)
  1203. {
  1204. FbxCluster* cluster = skin->GetCluster(i);
  1205. FbxNode* link = cluster->GetLink();
  1206. // The bone node doesn't exist, skip it
  1207. auto iterFind = scene.nodeMap.find(link);
  1208. if (iterFind == scene.nodeMap.end())
  1209. continue;
  1210. mesh.bones.push_back(FBXBone());
  1211. FBXBone& bone = mesh.bones.back();
  1212. bone.node = iterFind->second;
  1213. if(mesh.referencedBy.size() > 1)
  1214. {
  1215. // Note: If this becomes a relevant issue (unlikely), then I will have to duplicate skeleton bones for
  1216. // each such mesh, since they will all require their own bind poses. Animation curves will also need to be
  1217. // handled specially (likely by allowing them to be applied to multiple bones at once). The other option is
  1218. // not to bake the node transform into mesh vertices and handle it on a Scene Object level.
  1219. LOGWRN("Skinned mesh has multiple different instances. This is not supported.");
  1220. }
  1221. // Calculate bind pose
  1222. FbxAMatrix clusterTransform;
  1223. cluster->GetTransformMatrix(clusterTransform);
  1224. FbxAMatrix linkTransform;
  1225. cluster->GetTransformLinkMatrix(linkTransform);
  1226. FbxAMatrix invLinkTransform = linkTransform.Inverse() * clusterTransform;
  1227. bone.bindPose = FBXToNativeType(invLinkTransform);
  1228. // Apply global scale to bind pose (we only apply the scale to translation portion because we scale the
  1229. // translation animation curves)
  1230. const Matrix4& nodeTfrm = iterFind->second->worldTransform;
  1231. Matrix4 nodeTfrmScaledTranslation = nodeTfrm;
  1232. nodeTfrmScaledTranslation[0][3] = nodeTfrmScaledTranslation[0][3] / scene.scaleFactor;
  1233. nodeTfrmScaledTranslation[1][3] = nodeTfrmScaledTranslation[1][3] / scene.scaleFactor;
  1234. nodeTfrmScaledTranslation[2][3] = nodeTfrmScaledTranslation[2][3] / scene.scaleFactor;
  1235. Matrix4 nodeTfrmInv = nodeTfrm.inverseAffine();
  1236. Matrix4 scaledTranslation = nodeTfrmInv * scene.globalScale * nodeTfrmScaledTranslation;
  1237. bone.bindPose = scaledTranslation * bone.bindPose * invGlobalScale;
  1238. bool isDuplicate = !existingBones.insert(link).second;
  1239. bool isAdditive = cluster->GetLinkMode() == FbxCluster::eAdditive;
  1240. // We avoid importing weights twice for duplicate bones and we don't
  1241. // support additive link mode.
  1242. bool importWeights = !isDuplicate && !isAdditive;
  1243. if (!importWeights)
  1244. continue;
  1245. double* weights = cluster->GetControlPointWeights();
  1246. INT32* indices = cluster->GetControlPointIndices();
  1247. UINT32 numIndices = (UINT32)cluster->GetControlPointIndicesCount();
  1248. INT32 numVertices = (INT32)influences.size();
  1249. // Add new weights while keeping them in order and removing the smallest ones
  1250. // if number of influences exceeds the set maximum value
  1251. for (UINT32 j = 0; j < numIndices; j++)
  1252. {
  1253. INT32 vertexIndex = indices[j];
  1254. float weight = (float)weights[j];
  1255. for (INT32 k = 0; k < FBX_IMPORT_MAX_BONE_INFLUENCES; k++)
  1256. {
  1257. if (vertexIndex < 0 || vertexIndex >= numVertices)
  1258. continue;
  1259. if (weight >= influences[vertexIndex].weights[k])
  1260. {
  1261. for (INT32 l = FBX_IMPORT_MAX_BONE_INFLUENCES - 2; l >= k; l--)
  1262. {
  1263. influences[vertexIndex].weights[l + 1] = influences[vertexIndex].weights[l];
  1264. influences[vertexIndex].indices[l + 1] = influences[vertexIndex].indices[l];
  1265. }
  1266. influences[vertexIndex].weights[k] = weight;
  1267. influences[vertexIndex].indices[k] = i;
  1268. break;
  1269. }
  1270. }
  1271. }
  1272. }
  1273. if (mesh.bones.empty())
  1274. mesh.boneInfluences.clear();
  1275. UINT32 numBones = (UINT32)mesh.bones.size();
  1276. if (numBones > 256)
  1277. LOGWRN("A maximum of 256 bones per skeleton are supported. Imported skeleton has " + toString(numBones) + " bones");
  1278. // Normalize weights
  1279. UINT32 numInfluences = (UINT32)mesh.boneInfluences.size();
  1280. for (UINT32 i = 0; i < numInfluences; i++)
  1281. {
  1282. float sum = 0.0f;
  1283. for (UINT32 j = 0; j < FBX_IMPORT_MAX_BONE_INFLUENCES; j++)
  1284. sum += influences[i].weights[j];
  1285. float invSum = 1.0f / sum;
  1286. for (UINT32 j = 0; j < FBX_IMPORT_MAX_BONE_INFLUENCES; j++)
  1287. influences[i].weights[j] *= invSum;
  1288. }
  1289. }
  1290. void FBXImporter::generateMissingTangentSpace(FBXImportScene& scene, const FBXImportOptions& options)
  1291. {
  1292. for (auto& mesh : scene.meshes)
  1293. {
  1294. UINT32 numVertices = (UINT32)mesh->positions.size();
  1295. UINT32 numIndices = (UINT32)mesh->indices.size();
  1296. if ((options.importNormals || options.importTangents) && mesh->normals.empty())
  1297. {
  1298. mesh->normals.resize(numVertices);
  1299. MeshUtility::calculateNormals(mesh->positions.data(), (UINT8*)mesh->indices.data(), numVertices, numIndices, mesh->normals.data());
  1300. }
  1301. if (options.importTangents && !mesh->UV[0].empty() && (mesh->tangents.empty() || mesh->bitangents.empty()))
  1302. {
  1303. mesh->tangents.resize(numVertices);
  1304. mesh->bitangents.resize(numVertices);
  1305. MeshUtility::calculateTangents(mesh->positions.data(), mesh->normals.data(), mesh->UV[0].data(), (UINT8*)mesh->indices.data(),
  1306. numVertices, numIndices, mesh->tangents.data(), mesh->bitangents.data());
  1307. }
  1308. for (auto& shape : mesh->blendShapes)
  1309. {
  1310. for (auto& frame : shape.frames)
  1311. {
  1312. if ((options.importNormals || options.importTangents) && frame.normals.empty())
  1313. {
  1314. frame.normals.resize(numVertices);
  1315. MeshUtility::calculateNormals(mesh->positions.data(), (UINT8*)mesh->indices.data(), numVertices, numIndices, frame.normals.data());
  1316. }
  1317. if (options.importTangents && !mesh->UV[0].empty() && (frame.tangents.empty() || frame.bitangents.empty()))
  1318. {
  1319. frame.tangents.resize(numVertices);
  1320. frame.bitangents.resize(numVertices);
  1321. MeshUtility::calculateTangents(mesh->positions.data(), frame.normals.data(), mesh->UV[0].data(), (UINT8*)mesh->indices.data(),
  1322. numVertices, numIndices, frame.tangents.data(), frame.bitangents.data());
  1323. }
  1324. }
  1325. }
  1326. }
  1327. }
  1328. void FBXImporter::importAnimations(FbxScene* scene, FBXImportOptions& importOptions, FBXImportScene& importScene)
  1329. {
  1330. FbxNode* root = scene->GetRootNode();
  1331. UINT32 numAnimStacks = (UINT32)scene->GetSrcObjectCount<FbxAnimStack>();
  1332. for (UINT32 i = 0; i < numAnimStacks; i++)
  1333. {
  1334. FbxAnimStack* animStack = scene->GetSrcObject<FbxAnimStack>(i);
  1335. importScene.clips.push_back(FBXAnimationClip());
  1336. FBXAnimationClip& clip = importScene.clips.back();
  1337. clip.name = animStack->GetName();
  1338. FbxTimeSpan timeSpan = animStack->GetLocalTimeSpan();
  1339. clip.start = (float)timeSpan.GetStart().GetSecondDouble();
  1340. clip.end = (float)timeSpan.GetStop().GetSecondDouble();
  1341. clip.sampleRate = (UINT32)FbxTime::GetFrameRate(scene->GetGlobalSettings().GetTimeMode());
  1342. UINT32 layerCount = animStack->GetMemberCount<FbxAnimLayer>();
  1343. if (layerCount > 1)
  1344. {
  1345. FbxAnimEvaluator* evaluator = scene->GetAnimationEvaluator();
  1346. FbxTime startTime;
  1347. startTime.SetSecondDouble(clip.start);
  1348. FbxTime endTime;
  1349. endTime.SetSecondDouble(clip.end);
  1350. FbxTime sampleRate;
  1351. if (importOptions.animResample)
  1352. sampleRate.SetSecondDouble(importOptions.animSampleRate);
  1353. else
  1354. {
  1355. FbxTime::EMode timeMode = scene->GetGlobalSettings().GetTimeMode();
  1356. sampleRate.SetSecondDouble(1.0f / FbxTime::GetFrameRate(timeMode));
  1357. }
  1358. if (!animStack->BakeLayers(evaluator, startTime, endTime, sampleRate))
  1359. continue;
  1360. layerCount = animStack->GetMemberCount<FbxAnimLayer>();
  1361. }
  1362. if (layerCount == 1)
  1363. {
  1364. FbxAnimLayer* animLayer = animStack->GetMember<FbxAnimLayer>(0);
  1365. importAnimations(animLayer, root, importOptions, clip, importScene);
  1366. }
  1367. }
  1368. }
  1369. void FBXImporter::importAnimations(FbxAnimLayer* layer, FbxNode* node, FBXImportOptions& importOptions,
  1370. FBXAnimationClip& clip, FBXImportScene& importScene)
  1371. {
  1372. FbxAnimCurve* translation[3];
  1373. translation[0] = node->LclTranslation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_X);
  1374. translation[1] = node->LclTranslation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Y);
  1375. translation[2] = node->LclTranslation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Z);
  1376. FbxAnimCurve* rotation[3];
  1377. rotation[0] = node->LclRotation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_X);
  1378. rotation[1] = node->LclRotation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Y);
  1379. rotation[2] = node->LclRotation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Z);
  1380. FbxAnimCurve* scale[3];
  1381. scale[0] = node->LclScaling.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_X);
  1382. scale[1] = node->LclScaling.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Y);
  1383. scale[2] = node->LclScaling.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Z);
  1384. auto hasCurveValues = [](FbxAnimCurve* curves[3])
  1385. {
  1386. for (UINT32 i = 0; i < 3; i++)
  1387. {
  1388. if (curves[i] != nullptr && curves[i]->KeyGetCount() > 0)
  1389. return true;
  1390. }
  1391. return false;
  1392. };
  1393. bool hasBoneAnimation = hasCurveValues(translation) || hasCurveValues(rotation) || hasCurveValues(scale);
  1394. if (hasBoneAnimation)
  1395. {
  1396. clip.boneAnimations.push_back(FBXBoneAnimation());
  1397. FBXBoneAnimation& boneAnim = clip.boneAnimations.back();
  1398. boneAnim.node = importScene.nodeMap[node];
  1399. boneAnim.translation = importCurve<Vector3, 3>(translation, importOptions, clip.start, clip.end);
  1400. boneAnim.scale = importCurve<Vector3, 3>(scale, importOptions, clip.start, clip.end);
  1401. TAnimationCurve<Vector3> eulerAnimation = importCurve<Vector3, 3>(rotation, importOptions, clip.start, clip.end);
  1402. if(importOptions.reduceKeyframes)
  1403. {
  1404. boneAnim.translation = reduceKeyframes(boneAnim.translation);
  1405. boneAnim.scale = reduceKeyframes(boneAnim.scale);
  1406. eulerAnimation = reduceKeyframes(eulerAnimation);
  1407. }
  1408. boneAnim.translation = AnimationUtility::scaleCurve(boneAnim.translation, importScene.scaleFactor);
  1409. boneAnim.rotation = AnimationUtility::eulerToQuaternionCurve(eulerAnimation);
  1410. }
  1411. if (importOptions.importBlendShapes)
  1412. {
  1413. FbxMesh* fbxMesh = node->GetMesh();
  1414. if (fbxMesh != nullptr)
  1415. {
  1416. INT32 deformerCount = fbxMesh->GetDeformerCount(FbxDeformer::eBlendShape);
  1417. for (INT32 i = 0; i < deformerCount; i++)
  1418. {
  1419. FbxBlendShape* deformer = static_cast<FbxBlendShape*>(fbxMesh->GetDeformer(i, FbxDeformer::eBlendShape));
  1420. INT32 channelCount = deformer->GetBlendShapeChannelCount();
  1421. for (INT32 j = 0; j < channelCount; j++)
  1422. {
  1423. FbxBlendShapeChannel* channel = deformer->GetBlendShapeChannel(j);
  1424. FbxAnimCurve* curve = fbxMesh->GetShapeChannel(i, j, layer);
  1425. if (curve != nullptr && curve->KeyGetCount() > 0)
  1426. {
  1427. clip.blendShapeAnimations.push_back(FBXBlendShapeAnimation());
  1428. FBXBlendShapeAnimation& blendShapeAnim = clip.blendShapeAnimations.back();
  1429. blendShapeAnim.blendShape = channel->GetName();
  1430. // Get name without invalid characters
  1431. blendShapeAnim.blendShape = StringUtil::replaceAll(blendShapeAnim.blendShape, ".", "_");
  1432. blendShapeAnim.blendShape = StringUtil::replaceAll(blendShapeAnim.blendShape, "/", "_");
  1433. FbxAnimCurve* curves[1] = { curve };
  1434. blendShapeAnim.curve = importCurve<float, 1>(curves, importOptions, clip.start, clip.end);
  1435. // FBX contains data in [0, 100] range, but we need it in [0, 1] range
  1436. blendShapeAnim.curve = AnimationUtility::scaleCurve(blendShapeAnim.curve, 0.01f);
  1437. }
  1438. }
  1439. }
  1440. }
  1441. }
  1442. UINT32 childCount = (UINT32)node->GetChildCount();
  1443. for (UINT32 i = 0; i < childCount; i++)
  1444. {
  1445. FbxNode* child = node->GetChild(i);
  1446. importAnimations(layer, child, importOptions, clip, importScene);
  1447. }
  1448. }
  1449. void FBXImporter::bakeTransforms(FbxScene* scene)
  1450. {
  1451. // FBX stores transforms in a more complex way than just translation-rotation-scale as used by Banshee.
  1452. // Instead they also support rotations offsets and pivots, scaling pivots and more. We wish to bake all this data
  1453. // into a standard transform so we can access it using node's local TRS properties (e.g. FbxNode::LclTranslation).
  1454. double frameRate = FbxTime::GetFrameRate(scene->GetGlobalSettings().GetTimeMode());
  1455. bs_frame_mark();
  1456. {
  1457. FrameStack<FbxNode*> todo;
  1458. todo.push(scene->GetRootNode());
  1459. while(todo.size() > 0)
  1460. {
  1461. FbxNode* node = todo.top();
  1462. todo.pop();
  1463. FbxVector4 zero(0, 0, 0);
  1464. FbxVector4 one(1, 1, 1);
  1465. // Activate pivot converting
  1466. node->SetPivotState(FbxNode::eSourcePivot, FbxNode::ePivotActive);
  1467. node->SetPivotState(FbxNode::eDestinationPivot, FbxNode::ePivotActive);
  1468. // We want to set all these to 0 (1 for scale) and bake them into the transforms
  1469. node->SetPostRotation(FbxNode::eDestinationPivot, zero);
  1470. node->SetPreRotation(FbxNode::eDestinationPivot, zero);
  1471. node->SetRotationOffset(FbxNode::eDestinationPivot, zero);
  1472. node->SetScalingOffset(FbxNode::eDestinationPivot, zero);
  1473. node->SetRotationPivot(FbxNode::eDestinationPivot, zero);
  1474. node->SetScalingPivot(FbxNode::eDestinationPivot, zero);
  1475. node->SetGeometricTranslation(FbxNode::eDestinationPivot, zero);
  1476. node->SetGeometricRotation(FbxNode::eDestinationPivot, zero);
  1477. node->SetGeometricScaling(FbxNode::eDestinationPivot, one);
  1478. // Banshee assumes euler angles are in YXZ order
  1479. node->SetRotationOrder(FbxNode::eDestinationPivot, FbxEuler::eOrderYXZ);
  1480. // Keep interpolation as is
  1481. node->SetQuaternionInterpolation(FbxNode::eDestinationPivot, node->GetQuaternionInterpolation(FbxNode::eSourcePivot));
  1482. for (int i = 0; i < node->GetChildCount(); i++)
  1483. {
  1484. FbxNode* childNode = node->GetChild(i);
  1485. todo.push(childNode);
  1486. }
  1487. }
  1488. scene->GetRootNode()->ConvertPivotAnimationRecursive(nullptr, FbxNode::eDestinationPivot, frameRate, false);
  1489. }
  1490. bs_frame_clear();
  1491. }
  1492. TAnimationCurve<Vector3> FBXImporter::reduceKeyframes(TAnimationCurve<Vector3>& curve)
  1493. {
  1494. UINT32 keyCount = curve.getNumKeyFrames();
  1495. Vector<TKeyframe<Vector3>> newKeyframes;
  1496. bool lastWasEqual = false;
  1497. for (UINT32 i = 0; i < keyCount; i++)
  1498. {
  1499. bool isEqual = true;
  1500. const TKeyframe<Vector3>& curKey = curve.getKeyFrame(i);
  1501. if (i > 0)
  1502. {
  1503. TKeyframe<Vector3>& prevKey = newKeyframes.back();
  1504. isEqual = Math::approxEquals(prevKey.value, curKey.value) &&
  1505. Math::approxEquals(prevKey.outTangent, curKey.inTangent) && isEqual;
  1506. }
  1507. else
  1508. isEqual = false;
  1509. // More than two keys in a row are equal, remove previous key by replacing it with this one
  1510. if (lastWasEqual && isEqual)
  1511. {
  1512. TKeyframe<Vector3>& prevKey = newKeyframes.back();
  1513. // Other properties are guaranteed unchanged
  1514. prevKey.time = curKey.time;
  1515. prevKey.outTangent = curKey.outTangent;
  1516. continue;
  1517. }
  1518. newKeyframes.push_back(curKey);
  1519. lastWasEqual = isEqual;
  1520. }
  1521. return TAnimationCurve<Vector3>(newKeyframes);
  1522. }
  1523. template<class T>
  1524. void setKeyframeValues(TKeyframe<T>& keyFrame, int idx, float value, float inTangent, float outTangent)
  1525. {
  1526. keyFrame.value = value;
  1527. keyFrame.inTangent = inTangent;
  1528. keyFrame.outTangent = outTangent;
  1529. }
  1530. template<>
  1531. void setKeyframeValues<Vector3>(TKeyframe<Vector3>& keyFrame, int idx, float value, float inTangent, float outTangent)
  1532. {
  1533. keyFrame.value[idx] = value;
  1534. keyFrame.inTangent[idx] = inTangent;
  1535. keyFrame.outTangent[idx] = outTangent;
  1536. }
  1537. template<class T, int C>
  1538. TAnimationCurve<T> FBXImporter::importCurve(FbxAnimCurve*(&fbxCurve)[C], FBXImportOptions& importOptions,
  1539. float start, float end)
  1540. {
  1541. // If curve key-counts don't match, we need to force resampling
  1542. bool forceResample = false;
  1543. for(int i = 1; i < C; i++)
  1544. {
  1545. forceResample |= fbxCurve[i - 1]->KeyGetCount() != fbxCurve[i]->KeyGetCount();
  1546. if (forceResample)
  1547. break;
  1548. }
  1549. // Read keys directly
  1550. if(!importOptions.animResample && !forceResample)
  1551. {
  1552. bool foundMismatch = false;
  1553. int keyCount = fbxCurve[0]->KeyGetCount();
  1554. Vector<TKeyframe<T>> keyframes;
  1555. for (int i = 0; i < keyCount; i++)
  1556. {
  1557. FbxTime fbxTime = fbxCurve[0]->KeyGetTime(i);
  1558. float time = (float)fbxTime.GetSecondDouble();
  1559. // Ensure times from other curves match
  1560. for (int j = 1; j < C; j++)
  1561. {
  1562. fbxTime = fbxCurve[j]->KeyGetTime(i);
  1563. float otherTime = (float)fbxTime.GetSecondDouble();
  1564. if (!Math::approxEquals(time, otherTime))
  1565. {
  1566. foundMismatch = true;
  1567. break;
  1568. }
  1569. }
  1570. if(foundMismatch)
  1571. break;
  1572. if (time < start || time > end)
  1573. continue;
  1574. keyframes.push_back(TKeyframe<T>());
  1575. TKeyframe<T>& keyFrame = keyframes.back();
  1576. keyFrame.time = time;
  1577. for (int j = 0; j < C; j++)
  1578. {
  1579. setKeyframeValues(keyFrame, j,
  1580. fbxCurve[j]->KeyGetValue(i),
  1581. fbxCurve[j]->KeyGetLeftDerivative(i),
  1582. fbxCurve[j]->KeyGetRightDerivative(i));
  1583. }
  1584. }
  1585. if (!foundMismatch)
  1586. return TAnimationCurve<T>(keyframes);
  1587. else
  1588. forceResample = true;
  1589. }
  1590. if (!importOptions.animResample && forceResample)
  1591. LOGWRN("Animation has different keyframes for different curve components, forcing resampling.");
  1592. // Resample keys
  1593. float curveStart = std::numeric_limits<float>::infinity();
  1594. float curveEnd = -std::numeric_limits<float>::infinity();
  1595. for (INT32 i = 0; i < C; i++)
  1596. {
  1597. int keyCount = fbxCurve[i]->KeyGetCount();
  1598. for (INT32 j = 0; j < keyCount; j++)
  1599. {
  1600. FbxTime fbxTime = fbxCurve[i]->KeyGetTime(j);
  1601. float time = (float)fbxTime.GetSecondDouble();
  1602. curveStart = std::min(time, curveStart);
  1603. curveEnd = std::max(time, curveEnd);
  1604. }
  1605. }
  1606. curveStart = Math::clamp(curveStart, start, end);
  1607. curveEnd = Math::clamp(curveEnd, start, end);
  1608. float curveLength = curveEnd - curveStart;
  1609. INT32 numSamples = Math::ceilToInt(curveLength / importOptions.animSampleRate);
  1610. // We don't use the exact provided sample rate but instead modify it slightly so it
  1611. // completely covers the curve range including start/end points while maintaining
  1612. // constant time step between keyframes.
  1613. float dt = curveLength / (float)numSamples;
  1614. INT32 lastKeyframe[] = { 0, 0, 0 };
  1615. INT32 lastLeftTangent[] = { 0, 0, 0 };
  1616. INT32 lastRightTangent[] = { 0, 0, 0 };
  1617. Vector<TKeyframe<T>> keyframes(numSamples);
  1618. for (INT32 i = 0; i < numSamples; i++)
  1619. {
  1620. float sampleTime = std::min(curveStart + i * dt, curveEnd);
  1621. FbxTime fbxSampleTime;
  1622. fbxSampleTime.SetSecondDouble(sampleTime);
  1623. TKeyframe<T>& keyFrame = keyframes[i];
  1624. keyFrame.time = sampleTime;
  1625. for (int j = 0; j < C; j++)
  1626. {
  1627. setKeyframeValues(keyFrame, j,
  1628. fbxCurve[j]->Evaluate(fbxSampleTime, &lastKeyframe[j]),
  1629. fbxCurve[j]->EvaluateLeftDerivative(fbxSampleTime, &lastLeftTangent[j]),
  1630. fbxCurve[j]->EvaluateRightDerivative(fbxSampleTime, &lastRightTangent[j]));
  1631. }
  1632. }
  1633. return TAnimationCurve<T>(keyframes);
  1634. }
  1635. }