BsFBXImporter.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448
  1. #include "BsFBXImporter.h"
  2. #include "BsResource.h"
  3. #include "BsCoreApplication.h"
  4. #include "BsDebug.h"
  5. #include "BsDataStream.h"
  6. #include "BsMeshData.h"
  7. #include "BsMesh.h"
  8. #include "BsVector2.h"
  9. #include "BsVector3.h"
  10. #include "BsVector4.h"
  11. #include "BsQuaternion.h"
  12. #include "BsVertexDataDesc.h"
  13. #include "BsFBXUtility.h"
  14. #include "BsMeshUtility.h"
  15. #include "BsRendererMeshData.h"
  16. #include "BsMeshImportOptions.h"
  17. namespace BansheeEngine
  18. {
  19. Matrix4 FBXToNativeType(const FbxAMatrix& value)
  20. {
  21. Matrix4 native;
  22. for (UINT32 row = 0; row < 4; row++)
  23. for (UINT32 col = 0; col < 4; col++)
  24. native[row][col] = (float)value[col][row];
  25. return native;
  26. }
  27. Vector3 FBXToNativeType(const FbxVector4& value)
  28. {
  29. Vector3 native;
  30. native.x = (float)value[0];
  31. native.y = (float)value[1];
  32. native.z = (float)value[2];
  33. return native;
  34. }
  35. Vector3 FBXToNativeType(const FbxDouble3& 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. Vector2 FBXToNativeType(const FbxVector2& value)
  44. {
  45. Vector2 native;
  46. native.x = (float)value[0];
  47. native.y = (float)value[1];
  48. return native;
  49. }
  50. RGBA FBXToNativeType(const FbxColor& value)
  51. {
  52. Color native;
  53. native.r = (float)value[0];
  54. native.g = (float)value[1];
  55. native.b = (float)value[2];
  56. native.a = (float)value[3];
  57. return native.getAsRGBA();
  58. }
  59. FbxSurfaceMaterial* FBXToNativeType(FbxSurfaceMaterial* const& value)
  60. {
  61. return value;
  62. }
  63. int FBXToNativeType(const int & value)
  64. {
  65. return value;
  66. }
  67. FBXImporter::FBXImporter()
  68. :SpecificImporter(), mFBXManager(nullptr)
  69. {
  70. mExtensions.push_back(L"fbx");
  71. }
  72. FBXImporter::~FBXImporter()
  73. {
  74. }
  75. bool FBXImporter::isExtensionSupported(const WString& ext) const
  76. {
  77. WString lowerCaseExt = ext;
  78. StringUtil::toLowerCase(lowerCaseExt);
  79. return find(mExtensions.begin(), mExtensions.end(), lowerCaseExt) != mExtensions.end();
  80. }
  81. bool FBXImporter::isMagicNumberSupported(const UINT8* magicNumPtr, UINT32 numBytes) const
  82. {
  83. return true; // FBX files can be plain-text so I don't even check for magic number
  84. }
  85. ImportOptionsPtr FBXImporter::createImportOptions() const
  86. {
  87. return bs_shared_ptr_new<MeshImportOptions>();
  88. }
  89. ResourcePtr FBXImporter::import(const Path& filePath, ConstImportOptionsPtr importOptions)
  90. {
  91. FbxScene* fbxScene = nullptr;
  92. if (!startUpSdk(fbxScene))
  93. return nullptr;
  94. if (!loadFBXFile(fbxScene, filePath))
  95. return nullptr;
  96. const MeshImportOptions* meshImportOptions = static_cast<const MeshImportOptions*>(importOptions.get());
  97. FBXImportOptions fbxImportOptions;
  98. fbxImportOptions.importNormals = meshImportOptions->getImportNormals();
  99. fbxImportOptions.importTangents = meshImportOptions->getImportTangents();
  100. fbxImportOptions.importAnimation = meshImportOptions->getImportAnimation();
  101. fbxImportOptions.importBlendShapes = meshImportOptions->getImportBlendShapes();
  102. fbxImportOptions.importSkin = meshImportOptions->getImportSkin();
  103. fbxImportOptions.importScale = meshImportOptions->getImportScale();
  104. FBXImportScene importedScene;
  105. parseScene(fbxScene, fbxImportOptions, importedScene);
  106. if (fbxImportOptions.importBlendShapes)
  107. importBlendShapes(importedScene, fbxImportOptions);
  108. if (fbxImportOptions.importSkin)
  109. importSkin(importedScene);
  110. if (fbxImportOptions.importAnimation)
  111. importAnimations(fbxScene, fbxImportOptions, importedScene);
  112. splitMeshVertices(importedScene);
  113. generateMissingTangentSpace(importedScene, fbxImportOptions);
  114. Vector<SubMesh> subMeshes;
  115. RendererMeshDataPtr rendererMeshData = generateMeshData(importedScene, fbxImportOptions, subMeshes);
  116. // TODO - Later: Optimize mesh: Remove bad and degenerate polygons, weld nearby vertices, optimize for vertex cache
  117. shutDownSdk();
  118. INT32 usage = MU_STATIC;
  119. if (meshImportOptions->getCPUReadable())
  120. usage |= MU_CPUCACHED;
  121. MeshPtr mesh = Mesh::_createPtr(rendererMeshData->getData(), subMeshes, usage);
  122. WString fileName = filePath.getWFilename(false);
  123. mesh->setName(fileName);
  124. return mesh;
  125. }
  126. bool FBXImporter::startUpSdk(FbxScene*& scene)
  127. {
  128. mFBXManager = FbxManager::Create();
  129. if (mFBXManager == nullptr)
  130. {
  131. LOGERR("FBX import failed: FBX SDK failed to initialize. FbxManager::Create() failed.");
  132. return false;
  133. }
  134. FbxIOSettings* ios = FbxIOSettings::Create(mFBXManager, IOSROOT);
  135. mFBXManager->SetIOSettings(ios);
  136. scene = FbxScene::Create(mFBXManager, "Import Scene");
  137. if (scene == nullptr)
  138. {
  139. LOGWRN("FBX import failed: Failed to create FBX scene.");
  140. return false;
  141. }
  142. return true;
  143. }
  144. void FBXImporter::shutDownSdk()
  145. {
  146. mFBXManager->Destroy();
  147. mFBXManager = nullptr;
  148. }
  149. bool FBXImporter::loadFBXFile(FbxScene* scene, const Path& filePath)
  150. {
  151. int lFileMajor, lFileMinor, lFileRevision;
  152. int lSDKMajor, lSDKMinor, lSDKRevision;
  153. FbxManager::GetFileFormatVersion(lSDKMajor, lSDKMinor, lSDKRevision);
  154. FbxImporter* importer = FbxImporter::Create(mFBXManager, "");
  155. bool importStatus = importer->Initialize(filePath.toString().c_str(), -1, mFBXManager->GetIOSettings());
  156. importer->GetFileVersion(lFileMajor, lFileMinor, lFileRevision);
  157. if(!importStatus)
  158. {
  159. LOGERR("FBX import failed: Call to FbxImporter::Initialize() failed.\n" +
  160. String("Error returned: %s\n\n") + String(importer->GetStatus().GetErrorString()));
  161. return false;
  162. }
  163. mFBXManager->GetIOSettings()->SetBoolProp(IMP_FBX_TEXTURE, false);
  164. mFBXManager->GetIOSettings()->SetBoolProp(IMP_FBX_GOBO, false);
  165. importStatus = importer->Import(scene);
  166. if(!importStatus)
  167. {
  168. importer->Destroy();
  169. LOGERR("FBX import failed: Call to FbxImporter::Initialize() failed.\n" +
  170. String("Error returned: %s\n\n") + String(importer->GetStatus().GetErrorString()));
  171. return false;
  172. }
  173. FbxAxisSystem fileCoordSystem = scene->GetGlobalSettings().GetAxisSystem();
  174. FbxAxisSystem bsCoordSystem(FbxAxisSystem::eYAxis, FbxAxisSystem::eParityOdd, FbxAxisSystem::eRightHanded);
  175. if (fileCoordSystem != bsCoordSystem)
  176. bsCoordSystem.ConvertScene(scene);
  177. importer->Destroy();
  178. return true;
  179. }
  180. void FBXImporter::parseScene(FbxScene* scene, const FBXImportOptions& options, FBXImportScene& outputScene)
  181. {
  182. outputScene.rootNode = createImportNode(outputScene, scene->GetRootNode(), nullptr);
  183. Stack<FbxNode*> todo;
  184. todo.push(scene->GetRootNode());
  185. while(!todo.empty())
  186. {
  187. FbxNode* curNode = todo.top();
  188. FBXImportNode* curImportNode = outputScene.nodeMap[curNode];
  189. todo.pop();
  190. const char* name = curNode->GetName();
  191. FbxNodeAttribute* attrib = curNode->GetNodeAttribute();
  192. if(attrib != nullptr)
  193. {
  194. FbxNodeAttribute::EType attribType = attrib->GetAttributeType();
  195. switch(attribType)
  196. {
  197. case FbxNodeAttribute::eNurbs:
  198. case FbxNodeAttribute::eNurbsSurface:
  199. case FbxNodeAttribute::ePatch:
  200. {
  201. FbxGeometryConverter geomConverter(mFBXManager);
  202. attrib = geomConverter.Triangulate(attrib, true);
  203. if (attrib->GetAttributeType() == FbxNodeAttribute::eMesh)
  204. {
  205. FbxMesh* mesh = static_cast<FbxMesh*>(attrib);
  206. mesh->RemoveBadPolygons();
  207. parseMesh(mesh, curImportNode, options, outputScene);
  208. }
  209. }
  210. break;
  211. case FbxNodeAttribute::eMesh:
  212. {
  213. FbxMesh* mesh = static_cast<FbxMesh*>(attrib);
  214. mesh->RemoveBadPolygons();
  215. if(!mesh->IsTriangleMesh())
  216. {
  217. FbxGeometryConverter geomConverter(mFBXManager);
  218. geomConverter.Triangulate(mesh, true);
  219. attrib = curNode->GetNodeAttribute();
  220. mesh = static_cast<FbxMesh*>(attrib);
  221. }
  222. parseMesh(mesh, curImportNode, options, outputScene);
  223. }
  224. break;
  225. }
  226. }
  227. for (int i = 0; i < curNode->GetChildCount(); i++)
  228. {
  229. FbxNode* childNode = curNode->GetChild(i);
  230. createImportNode(outputScene, childNode, curImportNode);
  231. todo.push(childNode);
  232. }
  233. }
  234. }
  235. FBXImportNode* FBXImporter::createImportNode(FBXImportScene& scene, FbxNode* fbxNode, FBXImportNode* parent)
  236. {
  237. FBXImportNode* node = bs_new<FBXImportNode>();
  238. Vector3 translation = FBXToNativeType(fbxNode->LclTranslation.Get());
  239. Vector3 rotationEuler = FBXToNativeType(fbxNode->LclRotation.Get());
  240. Vector3 scale = FBXToNativeType(fbxNode->LclScaling.Get());
  241. Quaternion rotation((Radian)rotationEuler.x, (Radian)rotationEuler.y, (Radian)rotationEuler.z);
  242. node->localTransform.setTRS(translation, rotation, scale);
  243. node->fbxNode = fbxNode;
  244. if (parent != nullptr)
  245. {
  246. node->worldTransform = node->localTransform * parent->worldTransform;
  247. parent->children.push_back(node);
  248. }
  249. else
  250. node->worldTransform = node->localTransform;
  251. scene.nodeMap.insert(std::make_pair(fbxNode, node));
  252. return node;
  253. }
  254. void FBXImporter::splitMeshVertices(FBXImportScene& scene)
  255. {
  256. Vector<FBXImportMesh*> splitMeshes;
  257. for (auto& mesh : scene.meshes)
  258. {
  259. FBXImportMesh* splitMesh = bs_new<FBXImportMesh>();
  260. splitMesh->fbxMesh = mesh->fbxMesh;
  261. splitMesh->referencedBy = mesh->referencedBy;
  262. splitMesh->bones = mesh->bones;
  263. FBXUtility::splitVertices(*mesh, *splitMesh);
  264. FBXUtility::flipWindingOrder(*splitMesh);
  265. splitMeshes.push_back(splitMesh);
  266. bs_delete(mesh);
  267. }
  268. scene.meshes = splitMeshes;
  269. }
  270. RendererMeshDataPtr FBXImporter::generateMeshData(const FBXImportScene& scene, const FBXImportOptions& options, Vector<SubMesh>& outputSubMeshes)
  271. {
  272. Matrix4 importScale = Matrix4::scaling(options.importScale);
  273. Vector<MeshDataPtr> allMeshData;
  274. Vector<Vector<SubMesh>> allSubMeshes;
  275. for (auto& mesh : scene.meshes)
  276. {
  277. Vector<Vector<UINT32>> indicesPerMaterial;
  278. for (UINT32 i = 0; i < (UINT32)mesh->indices.size(); i++)
  279. {
  280. while (mesh->materials[i] >= indicesPerMaterial.size())
  281. indicesPerMaterial.push_back(Vector<UINT32>());
  282. indicesPerMaterial[mesh->materials[i]].push_back(mesh->indices[i]);
  283. }
  284. UINT32* orderedIndices = (UINT32*)bs_alloc((UINT32)mesh->indices.size() * sizeof(UINT32));
  285. Vector<SubMesh> subMeshes;
  286. UINT32 currentIndex = 0;
  287. for (auto& subMeshIndices : indicesPerMaterial)
  288. {
  289. UINT32 indexCount = (UINT32)subMeshIndices.size();
  290. UINT32* dest = orderedIndices + currentIndex;
  291. memcpy(dest, subMeshIndices.data(), indexCount * sizeof(UINT32));
  292. subMeshes.push_back(SubMesh(currentIndex, indexCount, DOT_TRIANGLE_LIST));
  293. currentIndex += indexCount;
  294. }
  295. UINT32 vertexLayout = (UINT32)VertexLayout::Position;
  296. size_t numVertices = mesh->positions.size();
  297. bool hasColors = mesh->colors.size() == numVertices;
  298. bool hasNormals = mesh->normals.size() == numVertices;
  299. if (hasColors)
  300. vertexLayout |= (UINT32)VertexLayout::Color;
  301. bool hasTangents = false;
  302. if (hasNormals)
  303. {
  304. vertexLayout |= (UINT32)VertexLayout::Normal;
  305. if (mesh->tangents.size() == numVertices &&
  306. mesh->bitangents.size() == numVertices)
  307. {
  308. vertexLayout |= (UINT32)VertexLayout::Tangent;
  309. hasTangents = true;
  310. }
  311. }
  312. int UVIdx = 0;
  313. for (UINT32 i = 0; i < FBX_IMPORT_MAX_UV_LAYERS; i++)
  314. {
  315. if (mesh->UV[i].size() == numVertices)
  316. {
  317. if (i == 0)
  318. vertexLayout |= (UINT32)VertexLayout::UV0;
  319. else if (i == 1)
  320. vertexLayout |= (UINT32)VertexLayout::UV1;
  321. }
  322. }
  323. UINT32 numIndices = (UINT32)mesh->indices.size();
  324. for (auto& node : mesh->referencedBy)
  325. {
  326. Matrix4 worldTransform = node->worldTransform * importScale;
  327. Matrix4 worldTransformIT = worldTransform.transpose();
  328. worldTransformIT = worldTransformIT.inverse();
  329. RendererMeshDataPtr meshData = RendererMeshData::create((UINT32)numVertices, numIndices, (VertexLayout)vertexLayout);
  330. // Copy indices
  331. meshData->setIndices((UINT32*)mesh->indices.data(), numIndices * sizeof(UINT32));
  332. // Copy & transform positions
  333. UINT32 positionsSize = sizeof(Vector3) * (UINT32)numVertices;
  334. Vector3* transformedPositions = (Vector3*)bs_stack_alloc(positionsSize);
  335. for (UINT32 i = 0; i < (UINT32)numVertices; i++)
  336. transformedPositions[i] = worldTransform.multiplyAffine((Vector3)mesh->positions[i]);
  337. meshData->setPositions(transformedPositions, positionsSize);
  338. bs_stack_free(transformedPositions);
  339. // Copy & transform normals
  340. if (hasNormals)
  341. {
  342. UINT32 normalsSize = sizeof(Vector3) * (UINT32)numVertices;
  343. Vector3* transformedNormals = (Vector3*)bs_stack_alloc(normalsSize);
  344. // Copy, convert & transform tangents & bitangents
  345. if (hasTangents)
  346. {
  347. UINT32 tangentsSize = sizeof(Vector4) * (UINT32)numVertices;
  348. Vector4* transformedTangents = (Vector4*)bs_stack_alloc(tangentsSize);
  349. for (UINT32 i = 0; i < (UINT32)numVertices; i++)
  350. {
  351. Vector3 normal = (Vector3)mesh->normals[i];
  352. transformedNormals[i] = worldTransformIT.multiplyAffine(normal);
  353. Vector3 tangent = (Vector3)mesh->tangents[i];
  354. tangent = worldTransformIT.multiplyAffine(tangent);
  355. Vector3 bitangent = (Vector3)mesh->bitangents[i];
  356. bitangent = worldTransformIT.multiplyAffine(bitangent);
  357. Vector3 engineBitangent = Vector3::cross(normal, tangent);
  358. float sign = Vector3::dot(engineBitangent, bitangent);
  359. transformedTangents[i] = Vector4(tangent.x, tangent.y, tangent.z, sign > 0 ? 1.0f : -1.0f);
  360. }
  361. meshData->setTangents(transformedTangents, tangentsSize);
  362. bs_stack_free(transformedTangents);
  363. }
  364. else // Just normals
  365. {
  366. for (UINT32 i = 0; i < (UINT32)numVertices; i++)
  367. transformedNormals[i] = worldTransformIT.multiplyAffine((Vector3)mesh->normals[i]);
  368. }
  369. meshData->setNormals(transformedNormals, normalsSize);
  370. bs_stack_free(transformedNormals);
  371. }
  372. // Copy colors
  373. if (hasColors)
  374. {
  375. meshData->setColors(mesh->colors.data(), sizeof(UINT32) * (UINT32)numVertices);
  376. }
  377. // Copy UV
  378. int writeUVIDx = 0;
  379. for (auto& uvLayer : mesh->UV)
  380. {
  381. if (uvLayer.size() == numVertices)
  382. {
  383. UINT32 size = sizeof(Vector2) * (UINT32)numVertices;
  384. Vector2* transformedUV = (Vector2*)bs_stack_alloc(size);
  385. UINT32 i = 0;
  386. for (auto& uv : uvLayer)
  387. {
  388. transformedUV[i] = uv;
  389. transformedUV[i].y = 1.0f - uv.y;
  390. i++;
  391. }
  392. if (writeUVIDx == 0)
  393. meshData->setUV0(transformedUV, size);
  394. else if (writeUVIDx == 1)
  395. meshData->setUV1(transformedUV, size);
  396. bs_stack_free(transformedUV);
  397. writeUVIDx++;
  398. }
  399. }
  400. allMeshData.push_back(meshData->getData());
  401. allSubMeshes.push_back(subMeshes);
  402. }
  403. }
  404. if (allMeshData.size() > 1)
  405. {
  406. return RendererMeshData::create(MeshData::combine(allMeshData, allSubMeshes, outputSubMeshes));
  407. }
  408. else if (allMeshData.size() == 1)
  409. {
  410. outputSubMeshes = allSubMeshes[0];
  411. return RendererMeshData::create(allMeshData[0]);
  412. }
  413. return nullptr;
  414. }
  415. template<class TFBX, class TNative>
  416. class FBXDirectIndexer
  417. {
  418. public:
  419. FBXDirectIndexer(const FbxLayerElementTemplate<TFBX>& layer)
  420. :mElementArray(layer.GetDirectArray()),
  421. mElementCount(mElementArray.GetCount())
  422. {}
  423. bool get(int index, TNative& output) const
  424. {
  425. if (index < 0 || index >= mElementCount)
  426. return false;
  427. output = FBXToNativeType(mElementArray.GetAt(index));
  428. return true;
  429. }
  430. bool isEmpty() const
  431. {
  432. return mElementCount == 0;
  433. }
  434. private:
  435. const FbxLayerElementArrayTemplate<TFBX>& mElementArray;
  436. int mElementCount;
  437. };
  438. template<class TFBX, class TNative>
  439. class FBXIndexIndexer
  440. {
  441. public:
  442. FBXIndexIndexer(const FbxLayerElementTemplate<TFBX>& layer)
  443. :mElementArray(layer.GetDirectArray()),
  444. mIndexArray(layer.GetIndexArray()),
  445. mElementCount(mElementArray.GetCount()),
  446. mIndexCount(mIndexArray.GetCount())
  447. {}
  448. bool get(int index, TNative& output) const
  449. {
  450. if (index < 0 || index >= mIndexCount)
  451. return false;
  452. int actualIndex = mIndexArray.GetAt(index);
  453. if (actualIndex < 0 || actualIndex >= mElementCount)
  454. return false;
  455. output = FBXToNativeType(mElementArray.GetAt(actualIndex));
  456. return true;
  457. }
  458. bool isEmpty() const
  459. {
  460. return mElementCount == 0 || mIndexCount == 0;
  461. }
  462. private:
  463. const FbxLayerElementArrayTemplate<TFBX>& mElementArray;
  464. const FbxLayerElementArrayTemplate<int>& mIndexArray;
  465. int mElementCount;
  466. int mIndexCount;
  467. };
  468. template<class TFBX, class TNative, class TIndexer>
  469. void readLayerData(FbxLayerElementTemplate<TFBX>& layer, Vector<TNative>& output, const Vector<int>& indices)
  470. {
  471. TIndexer indexer(layer);
  472. if (indexer.isEmpty())
  473. return;
  474. output.resize(indices.size());
  475. FbxLayerElement::EMappingMode mappingMode = layer.GetMappingMode();
  476. UINT32 indexCount = (UINT32)indices.size();
  477. switch (mappingMode)
  478. {
  479. case FbxLayerElement::eByControlPoint:
  480. for (UINT32 i = 0; i < indexCount; i++)
  481. {
  482. int index = indices[i];
  483. indexer.get(index, output[i]);
  484. }
  485. break;
  486. case FbxLayerElement::eByPolygonVertex:
  487. for (UINT32 i = 0; i < indexCount; i++)
  488. indexer.get(i, output[i]);
  489. break;
  490. case FbxLayerElement::eByPolygon:
  491. // We expect mesh to be triangulated here
  492. {
  493. UINT32 polygonCount = indexCount / 3;
  494. UINT32 index = 0;
  495. for (UINT32 i = 0; i < polygonCount; i++)
  496. {
  497. TNative value;
  498. indexer.get(i, value);
  499. output[index++] = value;
  500. output[index++] = value;
  501. output[index++] = value;
  502. }
  503. }
  504. break;
  505. case FbxLayerElement::eAllSame:
  506. {
  507. TNative value;
  508. indexer.get(0, value);
  509. for (UINT32 i = 0; i < indexCount; i++)
  510. output[i] = value;
  511. }
  512. break;
  513. default:
  514. LOGWRN("FBX Import: Unsupported layer mapping mode.");
  515. break;
  516. }
  517. }
  518. template<class TFBX, class TNative>
  519. void readLayerData(FbxLayerElementTemplate<TFBX>& layer, Vector<TNative>& output, const Vector<int>& indices)
  520. {
  521. FbxLayerElement::EReferenceMode refMode = layer.GetReferenceMode();
  522. if (refMode == FbxLayerElement::eDirect)
  523. readLayerData<TFBX, TNative, FBXDirectIndexer<TFBX, TNative> >(layer, output, indices);
  524. else if (refMode == FbxLayerElement::eIndexToDirect)
  525. readLayerData<TFBX, TNative, FBXIndexIndexer<TFBX, TNative> >(layer, output, indices);
  526. else
  527. LOGWRN("FBX Import: Unsupported layer reference mode.");
  528. }
  529. void FBXImporter::parseMesh(FbxMesh* mesh, FBXImportNode* parentNode, const FBXImportOptions& options, FBXImportScene& outputScene)
  530. {
  531. // Check if valid
  532. if (!mesh->IsTriangleMesh())
  533. return;
  534. UINT32 vertexCount = mesh->GetControlPointsCount();
  535. UINT32 triangleCount = mesh->GetPolygonCount();
  536. if (vertexCount == 0 || triangleCount == 0)
  537. return;
  538. // Register in global mesh array
  539. FBXImportMesh* importMesh = nullptr;
  540. auto iterFindMesh = outputScene.meshMap.find(mesh);
  541. if (iterFindMesh != outputScene.meshMap.end())
  542. {
  543. UINT32 meshIdx = iterFindMesh->second;
  544. outputScene.meshes[meshIdx]->referencedBy.push_back(parentNode);
  545. return;
  546. }
  547. else
  548. {
  549. importMesh = bs_new<FBXImportMesh>();
  550. outputScene.meshes.push_back(importMesh);
  551. importMesh->referencedBy.push_back(parentNode);
  552. importMesh->fbxMesh = mesh;
  553. outputScene.meshMap[mesh] = (UINT32)outputScene.meshes.size() - 1;
  554. }
  555. // Import vertices
  556. importMesh->positions.resize(vertexCount);
  557. FbxVector4* controlPoints = mesh->GetControlPoints();
  558. for (UINT32 i = 0; i < vertexCount; i++)
  559. importMesh->positions[i] = FBXToNativeType(controlPoints[i]);
  560. // Import triangles
  561. UINT32 indexCount = triangleCount * 3;
  562. importMesh->indices.resize(indexCount);
  563. int* fbxIndices = mesh->GetPolygonVertices();
  564. importMesh->indices.assign(fbxIndices, fbxIndices + indexCount);
  565. // Import UVs
  566. Vector<FbxLayerElementUV*> fbxUVLayers;
  567. //// Search the diffuse layers first
  568. for (UINT32 i = 0; i < FBX_IMPORT_MAX_UV_LAYERS; i++)
  569. {
  570. FbxLayer* layer = mesh->GetLayer(i, FbxLayerElement::eUV);
  571. if (layer == nullptr)
  572. continue;
  573. for (int j = FbxLayerElement::eTextureDiffuse; j < FbxLayerElement::eTypeCount; j++)
  574. {
  575. FbxLayerElementUV* uvLayer = layer->GetUVs((FbxLayerElement::EType)j);
  576. if (uvLayer == nullptr)
  577. continue;
  578. fbxUVLayers.push_back(uvLayer);
  579. if (fbxUVLayers.size() == FBX_IMPORT_MAX_UV_LAYERS)
  580. break;
  581. }
  582. if (fbxUVLayers.size() == FBX_IMPORT_MAX_UV_LAYERS)
  583. break;
  584. }
  585. //// If there's room, search all others too
  586. if (fbxUVLayers.size() < FBX_IMPORT_MAX_UV_LAYERS)
  587. {
  588. UINT32 numLayers = mesh->GetLayerCount();
  589. for (UINT32 i = 0; i < numLayers; i++)
  590. {
  591. FbxLayer* layer = mesh->GetLayer(i);
  592. if (layer == nullptr)
  593. continue;
  594. for (int j = FbxLayerElement::eTextureDiffuse; j < FbxLayerElement::eTypeCount; j++)
  595. {
  596. FbxLayerElementUV* uvLayer = layer->GetUVs((FbxLayerElement::EType)j);
  597. if (uvLayer == nullptr)
  598. continue;
  599. auto iterFind = std::find(fbxUVLayers.begin(), fbxUVLayers.end(), uvLayer);
  600. if (iterFind != fbxUVLayers.end())
  601. continue;
  602. fbxUVLayers.push_back(uvLayer);
  603. if (fbxUVLayers.size() == FBX_IMPORT_MAX_UV_LAYERS)
  604. break;
  605. }
  606. if (fbxUVLayers.size() == FBX_IMPORT_MAX_UV_LAYERS)
  607. break;
  608. }
  609. }
  610. for (size_t i = 0; i < fbxUVLayers.size(); i++)
  611. readLayerData(*fbxUVLayers[i], importMesh->UV[i], importMesh->indices);
  612. FbxLayer* mainLayer = mesh->GetLayer(0);
  613. if (mainLayer != nullptr)
  614. {
  615. // Import colors
  616. if (mainLayer->GetVertexColors() != nullptr)
  617. readLayerData(*mainLayer->GetVertexColors(), importMesh->colors, importMesh->indices);
  618. // Import normals
  619. if (options.importNormals)
  620. {
  621. bool hasNormals = mainLayer->GetNormals() != nullptr;
  622. if (!hasNormals)
  623. {
  624. if (mainLayer->GetSmoothing() != nullptr)
  625. {
  626. FbxLayerElementSmoothing* smoothing = mainLayer->GetSmoothing();
  627. if (smoothing->GetMappingMode() == FbxLayerElement::eByEdge)
  628. {
  629. FbxGeometryConverter converter(mFBXManager);
  630. converter.ComputePolygonSmoothingFromEdgeSmoothing(mesh, 0);
  631. }
  632. readLayerData(*smoothing, importMesh->smoothingGroups, importMesh->indices);
  633. if (!importMesh->smoothingGroups.empty())
  634. {
  635. FBXUtility::normalsFromSmoothing(importMesh->positions, importMesh->indices,
  636. importMesh->smoothingGroups, importMesh->normals);
  637. }
  638. }
  639. }
  640. else
  641. readLayerData(*mainLayer->GetNormals(), importMesh->normals, importMesh->indices);
  642. }
  643. // Import tangents
  644. if (options.importTangents)
  645. {
  646. bool hasTangents = mainLayer->GetTangents() != nullptr && mainLayer->GetBinormals() != nullptr;
  647. if (!hasTangents)
  648. {
  649. if (fbxUVLayers.size() > 0)
  650. hasTangents = mesh->GenerateTangentsData(0, false);
  651. }
  652. if (hasTangents)
  653. {
  654. readLayerData(*mainLayer->GetTangents(), importMesh->tangents, importMesh->indices);
  655. readLayerData(*mainLayer->GetBinormals(), importMesh->bitangents, importMesh->indices);
  656. }
  657. }
  658. // Import material indexes
  659. if (mainLayer->GetMaterials() != nullptr)
  660. {
  661. Vector<FbxSurfaceMaterial*> fbxMaterials;
  662. readLayerData(*mainLayer->GetMaterials(), fbxMaterials, importMesh->indices);
  663. UnorderedMap<FbxSurfaceMaterial*, int> materialLookup;
  664. int nextMaterialIdx = 0;
  665. for (UINT32 i = 0; i < (UINT32)fbxMaterials.size(); i++)
  666. {
  667. auto iterFind = materialLookup.find(fbxMaterials[i]);
  668. int materialIdx = 0;
  669. if (iterFind != materialLookup.end())
  670. materialIdx = iterFind->second;
  671. else
  672. {
  673. materialIdx = nextMaterialIdx++;
  674. materialLookup[fbxMaterials[i]] = materialIdx;
  675. }
  676. importMesh->materials.push_back(materialIdx);
  677. }
  678. }
  679. }
  680. }
  681. void FBXImporter::importBlendShapes(FBXImportScene& scene, const FBXImportOptions& options)
  682. {
  683. for (auto& mesh : scene.meshes)
  684. {
  685. FbxMesh* fbxMesh = mesh->fbxMesh;
  686. UINT32 deformerCount = (UINT32)fbxMesh->GetDeformerCount(FbxDeformer::eBlendShape);
  687. for (UINT32 i = 0; i < deformerCount; i++)
  688. {
  689. FbxBlendShape* deformer = static_cast<FbxBlendShape*>(fbxMesh->GetDeformer(i, FbxDeformer::eBlendShape));
  690. UINT32 blendShapeChannelCount = (UINT32)deformer->GetBlendShapeChannelCount();
  691. for (UINT32 j = 0; j < blendShapeChannelCount; ++j)
  692. {
  693. FbxBlendShapeChannel* channel = deformer->GetBlendShapeChannel(j);
  694. double* weights = channel->GetTargetShapeFullWeights();
  695. UINT32 frameCount = channel->GetTargetShapeCount();
  696. if (frameCount == 0)
  697. continue;
  698. mesh->blendShapes.push_back(FBXBlendShape());
  699. FBXBlendShape& blendShape = mesh->blendShapes.back();
  700. blendShape.name = channel->GetName();
  701. blendShape.frames.resize(frameCount);
  702. for (UINT32 k = 0; k < frameCount; k++)
  703. {
  704. FbxShape* fbxShape = channel->GetTargetShape(k);
  705. FBXBlendShapeFrame& frame = blendShape.frames[k];
  706. frame.weight = (float)weights[k];
  707. importBlendShapeFrame(fbxShape, *mesh, options, frame);
  708. }
  709. }
  710. }
  711. }
  712. }
  713. void FBXImporter::importBlendShapeFrame(FbxShape* shape, const FBXImportMesh& mesh, const FBXImportOptions& options, FBXBlendShapeFrame& outFrame)
  714. {
  715. UINT32 vertexCount = (UINT32)shape->GetControlPointsCount();
  716. outFrame.positions.resize(vertexCount);
  717. FbxVector4* controlPoints = shape->GetControlPoints();
  718. for (UINT32 i = 0; i < vertexCount; i++)
  719. outFrame.positions[i] = FBXToNativeType(controlPoints[i]);
  720. FbxLayer* mainLayer = shape->GetLayer(0);
  721. if (options.importNormals)
  722. {
  723. bool hasNormals = mainLayer->GetNormals() != nullptr;
  724. if (!hasNormals)
  725. {
  726. if (!mesh.smoothingGroups.empty())
  727. {
  728. FBXUtility::normalsFromSmoothing(outFrame.positions, mesh.indices,
  729. mesh.smoothingGroups, outFrame.normals);
  730. }
  731. }
  732. else
  733. readLayerData(*mainLayer->GetNormals(), outFrame.normals, mesh.indices);
  734. }
  735. if (options.importTangents)
  736. {
  737. bool hasTangents = mainLayer->GetTangents() != nullptr && mainLayer->GetBinormals() != nullptr;
  738. if (hasTangents)
  739. {
  740. readLayerData(*mainLayer->GetTangents(), outFrame.tangents, mesh.indices);
  741. readLayerData(*mainLayer->GetBinormals(), outFrame.bitangents, mesh.indices);
  742. }
  743. }
  744. }
  745. void FBXImporter::importSkin(FBXImportScene& scene)
  746. {
  747. for (auto& mesh : scene.meshes)
  748. {
  749. FbxMesh* fbxMesh = mesh->fbxMesh;
  750. UINT32 deformerCount = (UINT32)fbxMesh->GetDeformerCount(FbxDeformer::eSkin);
  751. if (deformerCount > 0)
  752. {
  753. // We ignore other deformers if there's more than one
  754. FbxSkin* deformer = static_cast<FbxSkin*>(fbxMesh->GetDeformer(0, FbxDeformer::eSkin));
  755. UINT32 boneCount = (UINT32)deformer->GetClusterCount();
  756. if (boneCount == 0)
  757. continue;
  758. // If only one bone and it links to itself, ignore the bone
  759. if (boneCount == 1)
  760. {
  761. FbxCluster* cluster = deformer->GetCluster(0);
  762. if (mesh->referencedBy.size() == 1 && mesh->referencedBy[0]->fbxNode == cluster->GetLink())
  763. continue;
  764. }
  765. importSkin(scene, deformer, *mesh);
  766. }
  767. }
  768. }
  769. void FBXImporter::importSkin(FBXImportScene& scene, FbxSkin* skin, FBXImportMesh& mesh)
  770. {
  771. Vector<FBXBoneInfluence>& influences = mesh.boneInfluences;
  772. influences.resize(mesh.positions.size());
  773. UnorderedSet<FbxNode*> existingBones;
  774. UINT32 boneCount = (UINT32)skin->GetClusterCount();
  775. for (UINT32 i = 0; i < boneCount; i++)
  776. {
  777. FbxCluster* cluster = skin->GetCluster(i);
  778. FbxNode* link = cluster->GetLink();
  779. // The bone node doesn't exist, skip it
  780. auto iterFind = scene.nodeMap.find(link);
  781. if (iterFind == scene.nodeMap.end())
  782. continue;
  783. mesh.bones.push_back(FBXBone());
  784. FBXBone& bone = mesh.bones.back();
  785. bone.node = iterFind->second;
  786. FbxAMatrix clusterTransform;
  787. cluster->GetTransformMatrix(clusterTransform);
  788. FbxAMatrix linkTransform;
  789. cluster->GetTransformLinkMatrix(linkTransform);
  790. FbxAMatrix bindPose = linkTransform.Inverse() * clusterTransform;
  791. bone.bindPose = FBXToNativeType(bindPose);
  792. bool isDuplicate = existingBones.insert(link).second;
  793. bool isAdditive = cluster->GetLinkMode() == FbxCluster::eAdditive;
  794. // We avoid importing weights twice for duplicate bones and we don't
  795. // support additive link mode.
  796. bool importWeights = !isDuplicate && !isAdditive;
  797. if (!importWeights)
  798. continue;
  799. double* weights = cluster->GetControlPointWeights();
  800. INT32* indices = cluster->GetControlPointIndices();
  801. UINT32 numIndices = (UINT32)cluster->GetControlPointIndicesCount();
  802. INT32 numVertices = (INT32)influences.size();
  803. // Add new weights while keeping them in order and removing the smallest ones
  804. // if number of influences exceeds the set maximum value
  805. for (UINT32 j = 0; j < numIndices; j++)
  806. {
  807. INT32 vertexIndex = indices[j];
  808. float weight = (float)weights[j];
  809. for (UINT32 k = 0; k < FBX_IMPORT_MAX_BONE_INFLUENCES; k++)
  810. {
  811. if (vertexIndex < 0 || vertexIndex >= numVertices)
  812. continue;
  813. if (weight >= influences[vertexIndex].weights[k])
  814. {
  815. for (UINT32 l = FBX_IMPORT_MAX_BONE_INFLUENCES - 2; l >= k; l--)
  816. {
  817. influences[vertexIndex].weights[l + 1] = influences[vertexIndex].weights[l];
  818. influences[vertexIndex].indices[l + 1] = influences[vertexIndex].indices[l];
  819. }
  820. influences[vertexIndex].weights[k] = weight;
  821. influences[vertexIndex].indices[k] = i;
  822. break;
  823. }
  824. }
  825. }
  826. }
  827. if (mesh.bones.empty())
  828. mesh.boneInfluences.clear();
  829. // Normalize weights
  830. UINT32 numInfluences = (UINT32)mesh.boneInfluences.size();
  831. for (UINT32 i = 0; i < numInfluences; i++)
  832. {
  833. float sum = 0.0f;
  834. for (UINT32 j = 0; j < FBX_IMPORT_MAX_BONE_INFLUENCES; j++)
  835. sum += influences[i].weights[j];
  836. float invSum = 1.0f / sum;
  837. for (UINT32 j = 0; j < FBX_IMPORT_MAX_BONE_INFLUENCES; j++)
  838. influences[i].weights[j] *= invSum;
  839. }
  840. }
  841. void FBXImporter::generateMissingTangentSpace(FBXImportScene& scene, const FBXImportOptions& options)
  842. {
  843. for (auto& mesh : scene.meshes)
  844. {
  845. UINT32 numVertices = (UINT32)mesh->positions.size();
  846. UINT32 numIndices = (UINT32)mesh->indices.size();
  847. if ((options.importNormals || options.importTangents) && mesh->normals.empty())
  848. {
  849. mesh->normals.resize(numVertices);
  850. MeshUtility::calculateNormals(mesh->positions.data(), (UINT8*)mesh->indices.data(), numVertices, numIndices, mesh->normals.data());
  851. }
  852. if (options.importTangents && !mesh->UV[0].empty() && (mesh->tangents.empty() || mesh->bitangents.empty()))
  853. {
  854. mesh->tangents.resize(numVertices);
  855. mesh->bitangents.resize(numVertices);
  856. MeshUtility::calculateTangents(mesh->positions.data(), mesh->normals.data(), mesh->UV[0].data(), (UINT8*)mesh->indices.data(),
  857. numVertices, numIndices, mesh->tangents.data(), mesh->bitangents.data());
  858. }
  859. for (auto& shape : mesh->blendShapes)
  860. {
  861. for (auto& frame : shape.frames)
  862. {
  863. if ((options.importNormals || options.importTangents) && frame.normals.empty())
  864. {
  865. frame.normals.resize(numVertices);
  866. MeshUtility::calculateNormals(mesh->positions.data(), (UINT8*)mesh->indices.data(), numVertices, numIndices, frame.normals.data());
  867. }
  868. if (options.importTangents && !mesh->UV[0].empty() && (frame.tangents.empty() || frame.bitangents.empty()))
  869. {
  870. mesh->tangents.resize(numVertices);
  871. mesh->bitangents.resize(numVertices);
  872. MeshUtility::calculateTangents(mesh->positions.data(), frame.normals.data(), mesh->UV[0].data(), (UINT8*)mesh->indices.data(),
  873. numVertices, numIndices, frame.tangents.data(), frame.bitangents.data());
  874. }
  875. }
  876. }
  877. }
  878. }
  879. void FBXImporter::importAnimations(FbxScene* scene, FBXImportOptions& importOptions, FBXImportScene& importScene)
  880. {
  881. FbxNode* root = scene->GetRootNode();
  882. UINT32 numAnimStacks = (UINT32)scene->GetSrcObjectCount<FbxAnimStack>();
  883. for (UINT32 i = 0; i < numAnimStacks; i++)
  884. {
  885. FbxAnimStack* animStack = scene->GetSrcObject<FbxAnimStack>(i);
  886. importScene.clips.push_back(FBXAnimationClip());
  887. FBXAnimationClip& clip = importScene.clips.back();
  888. clip.name = animStack->GetName();
  889. FbxTimeSpan timeSpan = animStack->GetLocalTimeSpan();
  890. clip.start = (float)timeSpan.GetStart().GetSecondDouble();
  891. clip.end = (float)timeSpan.GetStop().GetSecondDouble();
  892. UINT32 layerCount = animStack->GetMemberCount<FbxAnimLayer>();
  893. if (layerCount > 1)
  894. {
  895. FbxAnimEvaluator* evaluator = scene->GetAnimationEvaluator();
  896. FbxTime startTime;
  897. startTime.SetSecondDouble(clip.start);
  898. FbxTime endTime;
  899. endTime.SetSecondDouble(clip.end);
  900. FbxTime sampleRate;
  901. if (importOptions.animResample)
  902. sampleRate.SetSecondDouble(importOptions.animSampleRate);
  903. else
  904. {
  905. FbxTime::EMode timeMode = scene->GetGlobalSettings().GetTimeMode();
  906. sampleRate.SetSecondDouble(1.0f / FbxTime::GetFrameRate(timeMode));
  907. }
  908. if (!animStack->BakeLayers(evaluator, startTime, endTime, sampleRate))
  909. continue;
  910. layerCount = animStack->GetMemberCount<FbxAnimLayer>();
  911. }
  912. if (layerCount == 1)
  913. {
  914. FbxAnimLayer* animLayer = animStack->GetMember<FbxAnimLayer>(0);
  915. importAnimations(animLayer, root, importOptions, clip, importScene);
  916. }
  917. }
  918. }
  919. void FBXImporter::importAnimations(FbxAnimLayer* layer, FbxNode* node, FBXImportOptions& importOptions,
  920. FBXAnimationClip& clip, FBXImportScene& importScene)
  921. {
  922. FbxAnimCurve* translation[3];
  923. translation[0] = node->LclTranslation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_X);
  924. translation[1] = node->LclTranslation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Y);
  925. translation[2] = node->LclTranslation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Z);
  926. FbxAnimCurve* rotation[3];
  927. rotation[0] = node->LclRotation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_X);
  928. rotation[1] = node->LclRotation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Y);
  929. rotation[2] = node->LclRotation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Z);
  930. FbxAnimCurve* scale[3];
  931. scale[0] = node->LclScaling.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_X);
  932. scale[1] = node->LclScaling.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Y);
  933. scale[2] = node->LclScaling.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Z);
  934. auto hasCurveValues = [](FbxAnimCurve* curves[3])
  935. {
  936. for (UINT32 i = 0; i < 3; i++)
  937. {
  938. if (curves[i] != nullptr && curves[i]->KeyGetCount() > 0)
  939. return true;
  940. }
  941. return false;
  942. };
  943. bool hasBoneAnimation = hasCurveValues(translation) || hasCurveValues(rotation) || hasCurveValues(scale);
  944. if (hasBoneAnimation)
  945. {
  946. clip.boneAnimations.push_back(FBXBoneAnimation());
  947. FBXBoneAnimation& boneAnim = clip.boneAnimations.back();
  948. boneAnim.node = importScene.nodeMap[node];
  949. importCurve(translation[0], importOptions, boneAnim.translation[0], clip.start, clip.end);
  950. importCurve(translation[1], importOptions, boneAnim.translation[1], clip.start, clip.end);
  951. importCurve(translation[2], importOptions, boneAnim.translation[2], clip.start, clip.end);
  952. importCurve(scale[0], importOptions, boneAnim.scale[0], clip.start, clip.end);
  953. importCurve(scale[1], importOptions, boneAnim.scale[1], clip.start, clip.end);
  954. importCurve(scale[2], importOptions, boneAnim.scale[2], clip.start, clip.end);
  955. FBXAnimationCurve tempCurveRotation[3];
  956. importCurve(rotation[0], importOptions, tempCurveRotation[0], clip.start, clip.end);
  957. importCurve(rotation[1], importOptions, tempCurveRotation[1], clip.start, clip.end);
  958. importCurve(rotation[2], importOptions, tempCurveRotation[2], clip.start, clip.end);
  959. eulerToQuaternionCurves(tempCurveRotation, boneAnim.rotation);
  960. }
  961. if (importOptions.importBlendShapes)
  962. {
  963. FbxMesh* fbxMesh = node->GetMesh();
  964. if (fbxMesh != nullptr)
  965. {
  966. INT32 deformerCount = fbxMesh->GetDeformerCount(FbxDeformer::eBlendShape);
  967. for (INT32 i = 0; i < deformerCount; i++)
  968. {
  969. FbxBlendShape* deformer = static_cast<FbxBlendShape*>(fbxMesh->GetDeformer(i, FbxDeformer::eBlendShape));
  970. INT32 channelCount = deformer->GetBlendShapeChannelCount();
  971. for (INT32 j = 0; j < channelCount; j++)
  972. {
  973. FbxBlendShapeChannel* channel = deformer->GetBlendShapeChannel(j);
  974. FbxAnimCurve* curve = fbxMesh->GetShapeChannel(i, j, layer);
  975. if (curve != nullptr && curve->KeyGetCount() > 0)
  976. {
  977. clip.blendShapeAnimations.push_back(FBXBlendShapeAnimation());
  978. FBXBlendShapeAnimation& blendShapeAnim = clip.blendShapeAnimations.back();
  979. blendShapeAnim.blendShape = channel->GetName();
  980. importCurve(curve, importOptions, blendShapeAnim.curve, clip.start, clip.end);
  981. }
  982. }
  983. }
  984. }
  985. }
  986. UINT32 childCount = (UINT32)node->GetChildCount();
  987. for (UINT32 i = 0; i < childCount; i++)
  988. {
  989. FbxNode* child = node->GetChild(i);
  990. importAnimations(layer, child, importOptions, clip, importScene);
  991. }
  992. }
  993. void FBXImporter::eulerToQuaternionCurves(FBXAnimationCurve(&eulerCurves)[3], FBXAnimationCurve(&quatCurves)[4])
  994. {
  995. const float FIT_TIME = 0.33f;
  996. INT32 numKeys = (INT32)eulerCurves[0].keyframes.size();
  997. if (numKeys != (INT32)eulerCurves[1].keyframes.size() || numKeys != (INT32)eulerCurves[2].keyframes.size())
  998. return;
  999. auto eulerToQuaternion = [&](INT32 keyIdx, float time, const Quaternion& lastQuat)
  1000. {
  1001. Degree x = (Degree)eulerCurves[0].evaluate(time);
  1002. Degree y = (Degree)eulerCurves[1].evaluate(time);
  1003. Degree z = (Degree)eulerCurves[2].evaluate(time);
  1004. Quaternion quat(x, y, z);
  1005. // Flip quaternion in case rotation is over 180 degrees
  1006. if (keyIdx > 0)
  1007. {
  1008. float dot = quat.dot(lastQuat);
  1009. if (dot < 0.0f)
  1010. quat = Quaternion(-quat.x, -quat.y, -quat.z, -quat.w);
  1011. }
  1012. return quat;
  1013. };
  1014. struct FitKeyframe
  1015. {
  1016. float time;
  1017. Quaternion value;
  1018. };
  1019. Vector<FitKeyframe> fitQuaternions(numKeys * 2);
  1020. Quaternion lastQuat;
  1021. for (INT32 i = 0; i < numKeys; i++)
  1022. {
  1023. float time = eulerCurves[0].keyframes[i].time;
  1024. Quaternion quat = eulerToQuaternion(i, time, lastQuat);
  1025. // Calculate extra values between keys so we can better approximate tangents
  1026. if ((i + 1) < numKeys)
  1027. {
  1028. float nextTime = eulerCurves[0].keyframes[i + 1].time;
  1029. float dt = nextTime - time;
  1030. FitKeyframe& fitStart = fitQuaternions[i * 2 + 0];
  1031. FitKeyframe& fitEnd = fitQuaternions[i * 2 + 1];
  1032. fitStart.time = time + dt * FIT_TIME;
  1033. fitEnd.time = time + dt * (1.0f - FIT_TIME);
  1034. fitStart.value = eulerToQuaternion(i, fitStart.time, quat);
  1035. fitEnd.value = eulerToQuaternion(i, fitEnd.time, fitStart.value);
  1036. lastQuat = fitStart.value;
  1037. }
  1038. // TODO - If animation is looping I should also compare last and first for continuity
  1039. for (INT32 j = 0; j < 4; j++)
  1040. {
  1041. quatCurves[j].keyframes.push_back(FBXKeyFrame());
  1042. FBXKeyFrame& keyFrame = quatCurves[j].keyframes.back();
  1043. keyFrame.time = time;
  1044. keyFrame.value = quat[j];
  1045. keyFrame.inTangent = 0;
  1046. keyFrame.outTangent = 0;
  1047. }
  1048. }
  1049. // Recalculate tangents for quaternion curves
  1050. // TODO - There must be an analytical way to convert euler angle tangents
  1051. // to quaternion tangents, but I don't want to bother figuring it out
  1052. // until I have a test-bed for animation.
  1053. if (numKeys > 1)
  1054. {
  1055. // TODO - I could check per-key curve interpolation originally assigned in FBX
  1056. // and use that to generate linear/constant slopes. Currently I assume
  1057. // its all cubic.
  1058. // First key
  1059. {
  1060. const FitKeyframe& fitKeyFrame = fitQuaternions[0];
  1061. for (INT32 j = 0; j < 4; j++)
  1062. {
  1063. FBXKeyFrame& keyFrame = quatCurves[j].keyframes[0];
  1064. float dt = fitKeyFrame.time - keyFrame.time;
  1065. keyFrame.inTangent = (fitKeyFrame.value[j] - keyFrame.value) / dt;
  1066. keyFrame.outTangent = keyFrame.inTangent;
  1067. }
  1068. }
  1069. // In-between keys
  1070. {
  1071. for (INT32 i = 1; i < (numKeys - 1); i++)
  1072. {
  1073. const FitKeyframe& fitPointStart = fitQuaternions[i * 2 - 1];
  1074. const FitKeyframe& fitPointEnd = fitQuaternions[i * 2 + 0];
  1075. for (INT32 j = 0; j < 4; j++)
  1076. {
  1077. FBXKeyFrame& keyFrame = quatCurves[j].keyframes[i];
  1078. float dt0 = fitPointEnd.time - keyFrame.time;
  1079. float dt1 = keyFrame.time - fitPointStart.time;
  1080. float t0 = fitPointEnd.value[j] - keyFrame.value;
  1081. float t1 = keyFrame.value - fitPointStart.value[j];
  1082. keyFrame.inTangent = t0 / (0.5f * dt0) + t1 / (0.5f * dt1);
  1083. keyFrame.outTangent = keyFrame.inTangent;
  1084. }
  1085. }
  1086. }
  1087. // Last key
  1088. {
  1089. const FitKeyframe& fitKeyFrame = fitQuaternions[(numKeys - 2) * 2];
  1090. for (INT32 j = 0; j < 4; j++)
  1091. {
  1092. FBXKeyFrame& keyFrame = quatCurves[j].keyframes[numKeys - 2];
  1093. float dt = keyFrame.time - fitKeyFrame.time;
  1094. keyFrame.inTangent = (keyFrame.value - fitKeyFrame.value[j]) / dt;
  1095. keyFrame.outTangent = keyFrame.inTangent;
  1096. }
  1097. }
  1098. }
  1099. }
  1100. void FBXImporter::importCurve(FbxAnimCurve* fbxCurve, FBXImportOptions& importOptions, FBXAnimationCurve& curve, float start, float end)
  1101. {
  1102. if (fbxCurve == nullptr)
  1103. return;
  1104. INT32 keyCount = fbxCurve->KeyGetCount();
  1105. if (importOptions.animResample)
  1106. {
  1107. float curveStart = std::numeric_limits<float>::infinity();
  1108. float curveEnd = -std::numeric_limits<float>::infinity();
  1109. for (INT32 i = 0; i < keyCount; i++)
  1110. {
  1111. FbxTime fbxTime = fbxCurve->KeyGetTime(i);
  1112. float time = (float)fbxTime.GetSecondDouble();
  1113. curveStart = std::min(time, curveStart);
  1114. curveEnd = std::max(time, curveEnd);
  1115. }
  1116. curveStart = Math::clamp(curveStart, start, end);
  1117. curveEnd = Math::clamp(curveEnd, start, end);
  1118. float curveLength = curveEnd - curveStart;
  1119. INT32 numSamples = Math::ceilToInt(curveLength / importOptions.animSampleRate);
  1120. // We don't use the exact provided sample rate but instead modify it slightly so it
  1121. // completely covers the curve range including start/end points while maintaining
  1122. // constant time step between keyframes.
  1123. float dt = curveLength / (float)numSamples;
  1124. INT32 lastKeyframe = 0;
  1125. INT32 lastLeftTangent = 0;
  1126. INT32 lastRightTangent = 0;
  1127. for (INT32 i = 0; i < numSamples; i++)
  1128. {
  1129. float sampleTime = std::min(curveStart + i * dt, curveEnd);
  1130. FbxTime fbxSampleTime;
  1131. fbxSampleTime.SetSecondDouble(sampleTime);
  1132. curve.keyframes.push_back(FBXKeyFrame());
  1133. FBXKeyFrame& keyFrame = curve.keyframes.back();
  1134. keyFrame.time = sampleTime;
  1135. keyFrame.value = fbxCurve->Evaluate(fbxSampleTime, &lastKeyframe);
  1136. keyFrame.inTangent = fbxCurve->EvaluateLeftDerivative(fbxSampleTime, &lastLeftTangent);
  1137. keyFrame.outTangent = fbxCurve->EvaluateRightDerivative(fbxSampleTime, &lastRightTangent);
  1138. }
  1139. }
  1140. else
  1141. {
  1142. for (int i = 0; i < keyCount; i++)
  1143. {
  1144. FbxTime fbxTime = fbxCurve->KeyGetTime(i);
  1145. float time = (float)fbxTime.GetSecondDouble();
  1146. if (time < start || time > end)
  1147. continue;
  1148. curve.keyframes.push_back(FBXKeyFrame());
  1149. FBXKeyFrame& keyFrame = curve.keyframes.back();
  1150. keyFrame.time = time;
  1151. keyFrame.value = fbxCurve->KeyGetValue(i);
  1152. keyFrame.inTangent = fbxCurve->KeyGetLeftDerivative(i);
  1153. keyFrame.outTangent = fbxCurve->KeyGetRightDerivative(i);
  1154. }
  1155. }
  1156. }
  1157. }