BsFBXImporter.cpp 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451
  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::Import() 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. normal = worldTransformIT.multiplyDirection(normal);
  353. transformedNormals[i] = Vector3::normalize(normal);
  354. Vector3 tangent = (Vector3)mesh->tangents[i];
  355. tangent = Vector3::normalize(worldTransformIT.multiplyDirection(tangent));
  356. Vector3 bitangent = (Vector3)mesh->bitangents[i];
  357. bitangent = worldTransformIT.multiplyDirection(bitangent);
  358. Vector3 engineBitangent = Vector3::cross(normal, tangent);
  359. float sign = Vector3::dot(engineBitangent, bitangent);
  360. transformedTangents[i] = Vector4(tangent.x, tangent.y, tangent.z, sign > 0 ? 1.0f : -1.0f);
  361. }
  362. meshData->setTangents(transformedTangents, tangentsSize);
  363. bs_stack_free(transformedTangents);
  364. }
  365. else // Just normals
  366. {
  367. for (UINT32 i = 0; i < (UINT32)numVertices; i++)
  368. transformedNormals[i] = Vector3::normalize(worldTransformIT.multiplyDirection((Vector3)mesh->normals[i]));
  369. }
  370. meshData->setNormals(transformedNormals, normalsSize);
  371. bs_stack_free(transformedNormals);
  372. }
  373. // Copy colors
  374. if (hasColors)
  375. {
  376. meshData->setColors(mesh->colors.data(), sizeof(UINT32) * (UINT32)numVertices);
  377. }
  378. // Copy UV
  379. int writeUVIDx = 0;
  380. for (auto& uvLayer : mesh->UV)
  381. {
  382. if (uvLayer.size() == numVertices)
  383. {
  384. UINT32 size = sizeof(Vector2) * (UINT32)numVertices;
  385. Vector2* transformedUV = (Vector2*)bs_stack_alloc(size);
  386. UINT32 i = 0;
  387. for (auto& uv : uvLayer)
  388. {
  389. transformedUV[i] = uv;
  390. transformedUV[i].y = 1.0f - uv.y;
  391. i++;
  392. }
  393. if (writeUVIDx == 0)
  394. meshData->setUV0(transformedUV, size);
  395. else if (writeUVIDx == 1)
  396. meshData->setUV1(transformedUV, size);
  397. bs_stack_free(transformedUV);
  398. writeUVIDx++;
  399. }
  400. }
  401. // TODO - Transform blend shapes?
  402. allMeshData.push_back(meshData->getData());
  403. allSubMeshes.push_back(subMeshes);
  404. }
  405. }
  406. if (allMeshData.size() > 1)
  407. {
  408. return RendererMeshData::create(MeshData::combine(allMeshData, allSubMeshes, outputSubMeshes));
  409. }
  410. else if (allMeshData.size() == 1)
  411. {
  412. outputSubMeshes = allSubMeshes[0];
  413. return RendererMeshData::create(allMeshData[0]);
  414. }
  415. return nullptr;
  416. }
  417. template<class TFBX, class TNative>
  418. class FBXDirectIndexer
  419. {
  420. public:
  421. FBXDirectIndexer(const FbxLayerElementTemplate<TFBX>& layer)
  422. :mElementArray(layer.GetDirectArray()),
  423. mElementCount(mElementArray.GetCount())
  424. {}
  425. bool get(int index, TNative& output) const
  426. {
  427. if (index < 0 || index >= mElementCount)
  428. return false;
  429. output = FBXToNativeType(mElementArray.GetAt(index));
  430. return true;
  431. }
  432. bool isEmpty() const
  433. {
  434. return mElementCount == 0;
  435. }
  436. private:
  437. const FbxLayerElementArrayTemplate<TFBX>& mElementArray;
  438. int mElementCount;
  439. };
  440. template<class TFBX, class TNative>
  441. class FBXIndexIndexer
  442. {
  443. public:
  444. FBXIndexIndexer(const FbxLayerElementTemplate<TFBX>& layer)
  445. :mElementArray(layer.GetDirectArray()),
  446. mIndexArray(layer.GetIndexArray()),
  447. mElementCount(mElementArray.GetCount()),
  448. mIndexCount(mIndexArray.GetCount())
  449. {}
  450. bool get(int index, TNative& output) const
  451. {
  452. if (index < 0 || index >= mIndexCount)
  453. return false;
  454. int actualIndex = mIndexArray.GetAt(index);
  455. if (actualIndex < 0 || actualIndex >= mElementCount)
  456. return false;
  457. output = FBXToNativeType(mElementArray.GetAt(actualIndex));
  458. return true;
  459. }
  460. bool isEmpty() const
  461. {
  462. return mElementCount == 0 || mIndexCount == 0;
  463. }
  464. private:
  465. const FbxLayerElementArrayTemplate<TFBX>& mElementArray;
  466. const FbxLayerElementArrayTemplate<int>& mIndexArray;
  467. int mElementCount;
  468. int mIndexCount;
  469. };
  470. template<class TFBX, class TNative, class TIndexer>
  471. void readLayerData(FbxLayerElementTemplate<TFBX>& layer, Vector<TNative>& output, const Vector<int>& indices)
  472. {
  473. TIndexer indexer(layer);
  474. if (indexer.isEmpty())
  475. return;
  476. output.resize(indices.size());
  477. FbxLayerElement::EMappingMode mappingMode = layer.GetMappingMode();
  478. UINT32 indexCount = (UINT32)indices.size();
  479. switch (mappingMode)
  480. {
  481. case FbxLayerElement::eByControlPoint:
  482. for (UINT32 i = 0; i < indexCount; i++)
  483. {
  484. int index = indices[i];
  485. indexer.get(index, output[i]);
  486. }
  487. break;
  488. case FbxLayerElement::eByPolygonVertex:
  489. for (UINT32 i = 0; i < indexCount; i++)
  490. indexer.get(i, output[i]);
  491. break;
  492. case FbxLayerElement::eByPolygon:
  493. // We expect mesh to be triangulated here
  494. {
  495. UINT32 polygonCount = indexCount / 3;
  496. UINT32 index = 0;
  497. for (UINT32 i = 0; i < polygonCount; i++)
  498. {
  499. TNative value;
  500. indexer.get(i, value);
  501. output[index++] = value;
  502. output[index++] = value;
  503. output[index++] = value;
  504. }
  505. }
  506. break;
  507. case FbxLayerElement::eAllSame:
  508. {
  509. TNative value;
  510. indexer.get(0, value);
  511. for (UINT32 i = 0; i < indexCount; i++)
  512. output[i] = value;
  513. }
  514. break;
  515. default:
  516. LOGWRN("FBX Import: Unsupported layer mapping mode.");
  517. break;
  518. }
  519. }
  520. template<class TFBX, class TNative>
  521. void readLayerData(FbxLayerElementTemplate<TFBX>& layer, Vector<TNative>& output, const Vector<int>& indices)
  522. {
  523. FbxLayerElement::EReferenceMode refMode = layer.GetReferenceMode();
  524. if (refMode == FbxLayerElement::eDirect)
  525. readLayerData<TFBX, TNative, FBXDirectIndexer<TFBX, TNative> >(layer, output, indices);
  526. else if (refMode == FbxLayerElement::eIndexToDirect)
  527. readLayerData<TFBX, TNative, FBXIndexIndexer<TFBX, TNative> >(layer, output, indices);
  528. else
  529. LOGWRN("FBX Import: Unsupported layer reference mode.");
  530. }
  531. void FBXImporter::parseMesh(FbxMesh* mesh, FBXImportNode* parentNode, const FBXImportOptions& options, FBXImportScene& outputScene)
  532. {
  533. // Check if valid
  534. if (!mesh->IsTriangleMesh())
  535. return;
  536. UINT32 vertexCount = mesh->GetControlPointsCount();
  537. UINT32 triangleCount = mesh->GetPolygonCount();
  538. if (vertexCount == 0 || triangleCount == 0)
  539. return;
  540. // Register in global mesh array
  541. FBXImportMesh* importMesh = nullptr;
  542. auto iterFindMesh = outputScene.meshMap.find(mesh);
  543. if (iterFindMesh != outputScene.meshMap.end())
  544. {
  545. UINT32 meshIdx = iterFindMesh->second;
  546. outputScene.meshes[meshIdx]->referencedBy.push_back(parentNode);
  547. return;
  548. }
  549. else
  550. {
  551. importMesh = bs_new<FBXImportMesh>();
  552. outputScene.meshes.push_back(importMesh);
  553. importMesh->referencedBy.push_back(parentNode);
  554. importMesh->fbxMesh = mesh;
  555. outputScene.meshMap[mesh] = (UINT32)outputScene.meshes.size() - 1;
  556. }
  557. // Import vertices
  558. importMesh->positions.resize(vertexCount);
  559. FbxVector4* controlPoints = mesh->GetControlPoints();
  560. for (UINT32 i = 0; i < vertexCount; i++)
  561. importMesh->positions[i] = FBXToNativeType(controlPoints[i]);
  562. // Import triangles
  563. UINT32 indexCount = triangleCount * 3;
  564. importMesh->indices.resize(indexCount);
  565. int* fbxIndices = mesh->GetPolygonVertices();
  566. importMesh->indices.assign(fbxIndices, fbxIndices + indexCount);
  567. // Import UVs
  568. Vector<FbxLayerElementUV*> fbxUVLayers;
  569. //// Search the diffuse layers first
  570. for (UINT32 i = 0; i < FBX_IMPORT_MAX_UV_LAYERS; i++)
  571. {
  572. FbxLayer* layer = mesh->GetLayer(i, FbxLayerElement::eUV);
  573. if (layer == nullptr)
  574. continue;
  575. for (int j = FbxLayerElement::eTextureDiffuse; j < FbxLayerElement::eTypeCount; j++)
  576. {
  577. FbxLayerElementUV* uvLayer = layer->GetUVs((FbxLayerElement::EType)j);
  578. if (uvLayer == nullptr)
  579. continue;
  580. fbxUVLayers.push_back(uvLayer);
  581. if (fbxUVLayers.size() == FBX_IMPORT_MAX_UV_LAYERS)
  582. break;
  583. }
  584. if (fbxUVLayers.size() == FBX_IMPORT_MAX_UV_LAYERS)
  585. break;
  586. }
  587. //// If there's room, search all others too
  588. if (fbxUVLayers.size() < FBX_IMPORT_MAX_UV_LAYERS)
  589. {
  590. UINT32 numLayers = mesh->GetLayerCount();
  591. for (UINT32 i = 0; i < numLayers; i++)
  592. {
  593. FbxLayer* layer = mesh->GetLayer(i);
  594. if (layer == nullptr)
  595. continue;
  596. for (int j = FbxLayerElement::eTextureDiffuse; j < FbxLayerElement::eTypeCount; j++)
  597. {
  598. FbxLayerElementUV* uvLayer = layer->GetUVs((FbxLayerElement::EType)j);
  599. if (uvLayer == nullptr)
  600. continue;
  601. auto iterFind = std::find(fbxUVLayers.begin(), fbxUVLayers.end(), uvLayer);
  602. if (iterFind != fbxUVLayers.end())
  603. continue;
  604. fbxUVLayers.push_back(uvLayer);
  605. if (fbxUVLayers.size() == FBX_IMPORT_MAX_UV_LAYERS)
  606. break;
  607. }
  608. if (fbxUVLayers.size() == FBX_IMPORT_MAX_UV_LAYERS)
  609. break;
  610. }
  611. }
  612. for (size_t i = 0; i < fbxUVLayers.size(); i++)
  613. readLayerData(*fbxUVLayers[i], importMesh->UV[i], importMesh->indices);
  614. FbxLayer* mainLayer = mesh->GetLayer(0);
  615. if (mainLayer != nullptr)
  616. {
  617. // Import colors
  618. if (mainLayer->GetVertexColors() != nullptr)
  619. readLayerData(*mainLayer->GetVertexColors(), importMesh->colors, importMesh->indices);
  620. // Import normals
  621. if (options.importNormals)
  622. {
  623. bool hasNormals = mainLayer->GetNormals() != nullptr;
  624. if (!hasNormals)
  625. {
  626. if (mainLayer->GetSmoothing() != nullptr)
  627. {
  628. FbxLayerElementSmoothing* smoothing = mainLayer->GetSmoothing();
  629. if (smoothing->GetMappingMode() == FbxLayerElement::eByEdge)
  630. {
  631. FbxGeometryConverter converter(mFBXManager);
  632. converter.ComputePolygonSmoothingFromEdgeSmoothing(mesh, 0);
  633. }
  634. readLayerData(*smoothing, importMesh->smoothingGroups, importMesh->indices);
  635. if (!importMesh->smoothingGroups.empty())
  636. {
  637. FBXUtility::normalsFromSmoothing(importMesh->positions, importMesh->indices,
  638. importMesh->smoothingGroups, importMesh->normals);
  639. }
  640. }
  641. }
  642. else
  643. readLayerData(*mainLayer->GetNormals(), importMesh->normals, importMesh->indices);
  644. }
  645. // Import tangents
  646. if (options.importTangents)
  647. {
  648. bool hasTangents = mainLayer->GetTangents() != nullptr && mainLayer->GetBinormals() != nullptr;
  649. if (!hasTangents)
  650. {
  651. if (fbxUVLayers.size() > 0)
  652. hasTangents = mesh->GenerateTangentsData(0, false);
  653. }
  654. if (hasTangents)
  655. {
  656. readLayerData(*mainLayer->GetTangents(), importMesh->tangents, importMesh->indices);
  657. readLayerData(*mainLayer->GetBinormals(), importMesh->bitangents, importMesh->indices);
  658. }
  659. }
  660. // Import material indexes
  661. if (mainLayer->GetMaterials() != nullptr)
  662. {
  663. Vector<FbxSurfaceMaterial*> fbxMaterials;
  664. readLayerData(*mainLayer->GetMaterials(), fbxMaterials, importMesh->indices);
  665. UnorderedMap<FbxSurfaceMaterial*, int> materialLookup;
  666. int nextMaterialIdx = 0;
  667. for (UINT32 i = 0; i < (UINT32)fbxMaterials.size(); i++)
  668. {
  669. auto iterFind = materialLookup.find(fbxMaterials[i]);
  670. int materialIdx = 0;
  671. if (iterFind != materialLookup.end())
  672. materialIdx = iterFind->second;
  673. else
  674. {
  675. materialIdx = nextMaterialIdx++;
  676. materialLookup[fbxMaterials[i]] = materialIdx;
  677. }
  678. importMesh->materials.push_back(materialIdx);
  679. }
  680. }
  681. }
  682. }
  683. void FBXImporter::importBlendShapes(FBXImportScene& scene, const FBXImportOptions& options)
  684. {
  685. for (auto& mesh : scene.meshes)
  686. {
  687. FbxMesh* fbxMesh = mesh->fbxMesh;
  688. UINT32 deformerCount = (UINT32)fbxMesh->GetDeformerCount(FbxDeformer::eBlendShape);
  689. for (UINT32 i = 0; i < deformerCount; i++)
  690. {
  691. FbxBlendShape* deformer = static_cast<FbxBlendShape*>(fbxMesh->GetDeformer(i, FbxDeformer::eBlendShape));
  692. UINT32 blendShapeChannelCount = (UINT32)deformer->GetBlendShapeChannelCount();
  693. for (UINT32 j = 0; j < blendShapeChannelCount; ++j)
  694. {
  695. FbxBlendShapeChannel* channel = deformer->GetBlendShapeChannel(j);
  696. double* weights = channel->GetTargetShapeFullWeights();
  697. UINT32 frameCount = channel->GetTargetShapeCount();
  698. if (frameCount == 0)
  699. continue;
  700. mesh->blendShapes.push_back(FBXBlendShape());
  701. FBXBlendShape& blendShape = mesh->blendShapes.back();
  702. blendShape.name = channel->GetName();
  703. blendShape.frames.resize(frameCount);
  704. for (UINT32 k = 0; k < frameCount; k++)
  705. {
  706. FbxShape* fbxShape = channel->GetTargetShape(k);
  707. FBXBlendShapeFrame& frame = blendShape.frames[k];
  708. frame.weight = (float)weights[k];
  709. importBlendShapeFrame(fbxShape, *mesh, options, frame);
  710. }
  711. }
  712. }
  713. }
  714. }
  715. void FBXImporter::importBlendShapeFrame(FbxShape* shape, const FBXImportMesh& mesh, const FBXImportOptions& options, FBXBlendShapeFrame& outFrame)
  716. {
  717. UINT32 vertexCount = (UINT32)shape->GetControlPointsCount();
  718. outFrame.positions.resize(vertexCount);
  719. FbxVector4* controlPoints = shape->GetControlPoints();
  720. for (UINT32 i = 0; i < vertexCount; i++)
  721. outFrame.positions[i] = FBXToNativeType(controlPoints[i]);
  722. FbxLayer* mainLayer = shape->GetLayer(0);
  723. if (options.importNormals)
  724. {
  725. bool hasNormals = mainLayer->GetNormals() != nullptr;
  726. if (!hasNormals)
  727. {
  728. if (!mesh.smoothingGroups.empty())
  729. {
  730. FBXUtility::normalsFromSmoothing(outFrame.positions, mesh.indices,
  731. mesh.smoothingGroups, outFrame.normals);
  732. }
  733. }
  734. else
  735. readLayerData(*mainLayer->GetNormals(), outFrame.normals, mesh.indices);
  736. }
  737. if (options.importTangents)
  738. {
  739. bool hasTangents = mainLayer->GetTangents() != nullptr && mainLayer->GetBinormals() != nullptr;
  740. if (hasTangents)
  741. {
  742. readLayerData(*mainLayer->GetTangents(), outFrame.tangents, mesh.indices);
  743. readLayerData(*mainLayer->GetBinormals(), outFrame.bitangents, mesh.indices);
  744. }
  745. }
  746. }
  747. void FBXImporter::importSkin(FBXImportScene& scene)
  748. {
  749. for (auto& mesh : scene.meshes)
  750. {
  751. FbxMesh* fbxMesh = mesh->fbxMesh;
  752. UINT32 deformerCount = (UINT32)fbxMesh->GetDeformerCount(FbxDeformer::eSkin);
  753. if (deformerCount > 0)
  754. {
  755. // We ignore other deformers if there's more than one
  756. FbxSkin* deformer = static_cast<FbxSkin*>(fbxMesh->GetDeformer(0, FbxDeformer::eSkin));
  757. UINT32 boneCount = (UINT32)deformer->GetClusterCount();
  758. if (boneCount == 0)
  759. continue;
  760. // If only one bone and it links to itself, ignore the bone
  761. if (boneCount == 1)
  762. {
  763. FbxCluster* cluster = deformer->GetCluster(0);
  764. if (mesh->referencedBy.size() == 1 && mesh->referencedBy[0]->fbxNode == cluster->GetLink())
  765. continue;
  766. }
  767. importSkin(scene, deformer, *mesh);
  768. }
  769. }
  770. }
  771. void FBXImporter::importSkin(FBXImportScene& scene, FbxSkin* skin, FBXImportMesh& mesh)
  772. {
  773. Vector<FBXBoneInfluence>& influences = mesh.boneInfluences;
  774. influences.resize(mesh.positions.size());
  775. UnorderedSet<FbxNode*> existingBones;
  776. UINT32 boneCount = (UINT32)skin->GetClusterCount();
  777. for (UINT32 i = 0; i < boneCount; i++)
  778. {
  779. FbxCluster* cluster = skin->GetCluster(i);
  780. FbxNode* link = cluster->GetLink();
  781. // The bone node doesn't exist, skip it
  782. auto iterFind = scene.nodeMap.find(link);
  783. if (iterFind == scene.nodeMap.end())
  784. continue;
  785. mesh.bones.push_back(FBXBone());
  786. FBXBone& bone = mesh.bones.back();
  787. bone.node = iterFind->second;
  788. FbxAMatrix clusterTransform;
  789. cluster->GetTransformMatrix(clusterTransform);
  790. FbxAMatrix linkTransform;
  791. cluster->GetTransformLinkMatrix(linkTransform);
  792. FbxAMatrix bindPose = linkTransform.Inverse() * clusterTransform;
  793. bone.bindPose = FBXToNativeType(bindPose);
  794. bool isDuplicate = existingBones.insert(link).second;
  795. bool isAdditive = cluster->GetLinkMode() == FbxCluster::eAdditive;
  796. // We avoid importing weights twice for duplicate bones and we don't
  797. // support additive link mode.
  798. bool importWeights = !isDuplicate && !isAdditive;
  799. if (!importWeights)
  800. continue;
  801. double* weights = cluster->GetControlPointWeights();
  802. INT32* indices = cluster->GetControlPointIndices();
  803. UINT32 numIndices = (UINT32)cluster->GetControlPointIndicesCount();
  804. INT32 numVertices = (INT32)influences.size();
  805. // Add new weights while keeping them in order and removing the smallest ones
  806. // if number of influences exceeds the set maximum value
  807. for (UINT32 j = 0; j < numIndices; j++)
  808. {
  809. INT32 vertexIndex = indices[j];
  810. float weight = (float)weights[j];
  811. for (UINT32 k = 0; k < FBX_IMPORT_MAX_BONE_INFLUENCES; k++)
  812. {
  813. if (vertexIndex < 0 || vertexIndex >= numVertices)
  814. continue;
  815. if (weight >= influences[vertexIndex].weights[k])
  816. {
  817. for (UINT32 l = FBX_IMPORT_MAX_BONE_INFLUENCES - 2; l >= k; l--)
  818. {
  819. influences[vertexIndex].weights[l + 1] = influences[vertexIndex].weights[l];
  820. influences[vertexIndex].indices[l + 1] = influences[vertexIndex].indices[l];
  821. }
  822. influences[vertexIndex].weights[k] = weight;
  823. influences[vertexIndex].indices[k] = i;
  824. break;
  825. }
  826. }
  827. }
  828. }
  829. if (mesh.bones.empty())
  830. mesh.boneInfluences.clear();
  831. // Normalize weights
  832. UINT32 numInfluences = (UINT32)mesh.boneInfluences.size();
  833. for (UINT32 i = 0; i < numInfluences; i++)
  834. {
  835. float sum = 0.0f;
  836. for (UINT32 j = 0; j < FBX_IMPORT_MAX_BONE_INFLUENCES; j++)
  837. sum += influences[i].weights[j];
  838. float invSum = 1.0f / sum;
  839. for (UINT32 j = 0; j < FBX_IMPORT_MAX_BONE_INFLUENCES; j++)
  840. influences[i].weights[j] *= invSum;
  841. }
  842. }
  843. void FBXImporter::generateMissingTangentSpace(FBXImportScene& scene, const FBXImportOptions& options)
  844. {
  845. for (auto& mesh : scene.meshes)
  846. {
  847. UINT32 numVertices = (UINT32)mesh->positions.size();
  848. UINT32 numIndices = (UINT32)mesh->indices.size();
  849. if ((options.importNormals || options.importTangents) && mesh->normals.empty())
  850. {
  851. mesh->normals.resize(numVertices);
  852. MeshUtility::calculateNormals(mesh->positions.data(), (UINT8*)mesh->indices.data(), numVertices, numIndices, mesh->normals.data());
  853. }
  854. if (options.importTangents && !mesh->UV[0].empty() && (mesh->tangents.empty() || mesh->bitangents.empty()))
  855. {
  856. mesh->tangents.resize(numVertices);
  857. mesh->bitangents.resize(numVertices);
  858. MeshUtility::calculateTangents(mesh->positions.data(), mesh->normals.data(), mesh->UV[0].data(), (UINT8*)mesh->indices.data(),
  859. numVertices, numIndices, mesh->tangents.data(), mesh->bitangents.data());
  860. }
  861. for (auto& shape : mesh->blendShapes)
  862. {
  863. for (auto& frame : shape.frames)
  864. {
  865. if ((options.importNormals || options.importTangents) && frame.normals.empty())
  866. {
  867. frame.normals.resize(numVertices);
  868. MeshUtility::calculateNormals(mesh->positions.data(), (UINT8*)mesh->indices.data(), numVertices, numIndices, frame.normals.data());
  869. }
  870. if (options.importTangents && !mesh->UV[0].empty() && (frame.tangents.empty() || frame.bitangents.empty()))
  871. {
  872. mesh->tangents.resize(numVertices);
  873. mesh->bitangents.resize(numVertices);
  874. MeshUtility::calculateTangents(mesh->positions.data(), frame.normals.data(), mesh->UV[0].data(), (UINT8*)mesh->indices.data(),
  875. numVertices, numIndices, frame.tangents.data(), frame.bitangents.data());
  876. }
  877. }
  878. }
  879. }
  880. }
  881. void FBXImporter::importAnimations(FbxScene* scene, FBXImportOptions& importOptions, FBXImportScene& importScene)
  882. {
  883. FbxNode* root = scene->GetRootNode();
  884. UINT32 numAnimStacks = (UINT32)scene->GetSrcObjectCount<FbxAnimStack>();
  885. for (UINT32 i = 0; i < numAnimStacks; i++)
  886. {
  887. FbxAnimStack* animStack = scene->GetSrcObject<FbxAnimStack>(i);
  888. importScene.clips.push_back(FBXAnimationClip());
  889. FBXAnimationClip& clip = importScene.clips.back();
  890. clip.name = animStack->GetName();
  891. FbxTimeSpan timeSpan = animStack->GetLocalTimeSpan();
  892. clip.start = (float)timeSpan.GetStart().GetSecondDouble();
  893. clip.end = (float)timeSpan.GetStop().GetSecondDouble();
  894. UINT32 layerCount = animStack->GetMemberCount<FbxAnimLayer>();
  895. if (layerCount > 1)
  896. {
  897. FbxAnimEvaluator* evaluator = scene->GetAnimationEvaluator();
  898. FbxTime startTime;
  899. startTime.SetSecondDouble(clip.start);
  900. FbxTime endTime;
  901. endTime.SetSecondDouble(clip.end);
  902. FbxTime sampleRate;
  903. if (importOptions.animResample)
  904. sampleRate.SetSecondDouble(importOptions.animSampleRate);
  905. else
  906. {
  907. FbxTime::EMode timeMode = scene->GetGlobalSettings().GetTimeMode();
  908. sampleRate.SetSecondDouble(1.0f / FbxTime::GetFrameRate(timeMode));
  909. }
  910. if (!animStack->BakeLayers(evaluator, startTime, endTime, sampleRate))
  911. continue;
  912. layerCount = animStack->GetMemberCount<FbxAnimLayer>();
  913. }
  914. if (layerCount == 1)
  915. {
  916. FbxAnimLayer* animLayer = animStack->GetMember<FbxAnimLayer>(0);
  917. importAnimations(animLayer, root, importOptions, clip, importScene);
  918. }
  919. }
  920. }
  921. void FBXImporter::importAnimations(FbxAnimLayer* layer, FbxNode* node, FBXImportOptions& importOptions,
  922. FBXAnimationClip& clip, FBXImportScene& importScene)
  923. {
  924. FbxAnimCurve* translation[3];
  925. translation[0] = node->LclTranslation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_X);
  926. translation[1] = node->LclTranslation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Y);
  927. translation[2] = node->LclTranslation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Z);
  928. FbxAnimCurve* rotation[3];
  929. rotation[0] = node->LclRotation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_X);
  930. rotation[1] = node->LclRotation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Y);
  931. rotation[2] = node->LclRotation.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Z);
  932. FbxAnimCurve* scale[3];
  933. scale[0] = node->LclScaling.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_X);
  934. scale[1] = node->LclScaling.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Y);
  935. scale[2] = node->LclScaling.GetCurve(layer, FBXSDK_CURVENODE_COMPONENT_Z);
  936. auto hasCurveValues = [](FbxAnimCurve* curves[3])
  937. {
  938. for (UINT32 i = 0; i < 3; i++)
  939. {
  940. if (curves[i] != nullptr && curves[i]->KeyGetCount() > 0)
  941. return true;
  942. }
  943. return false;
  944. };
  945. bool hasBoneAnimation = hasCurveValues(translation) || hasCurveValues(rotation) || hasCurveValues(scale);
  946. if (hasBoneAnimation)
  947. {
  948. clip.boneAnimations.push_back(FBXBoneAnimation());
  949. FBXBoneAnimation& boneAnim = clip.boneAnimations.back();
  950. boneAnim.node = importScene.nodeMap[node];
  951. importCurve(translation[0], importOptions, boneAnim.translation[0], clip.start, clip.end);
  952. importCurve(translation[1], importOptions, boneAnim.translation[1], clip.start, clip.end);
  953. importCurve(translation[2], importOptions, boneAnim.translation[2], clip.start, clip.end);
  954. importCurve(scale[0], importOptions, boneAnim.scale[0], clip.start, clip.end);
  955. importCurve(scale[1], importOptions, boneAnim.scale[1], clip.start, clip.end);
  956. importCurve(scale[2], importOptions, boneAnim.scale[2], clip.start, clip.end);
  957. FBXAnimationCurve tempCurveRotation[3];
  958. importCurve(rotation[0], importOptions, tempCurveRotation[0], clip.start, clip.end);
  959. importCurve(rotation[1], importOptions, tempCurveRotation[1], clip.start, clip.end);
  960. importCurve(rotation[2], importOptions, tempCurveRotation[2], clip.start, clip.end);
  961. eulerToQuaternionCurves(tempCurveRotation, boneAnim.rotation);
  962. }
  963. if (importOptions.importBlendShapes)
  964. {
  965. FbxMesh* fbxMesh = node->GetMesh();
  966. if (fbxMesh != nullptr)
  967. {
  968. INT32 deformerCount = fbxMesh->GetDeformerCount(FbxDeformer::eBlendShape);
  969. for (INT32 i = 0; i < deformerCount; i++)
  970. {
  971. FbxBlendShape* deformer = static_cast<FbxBlendShape*>(fbxMesh->GetDeformer(i, FbxDeformer::eBlendShape));
  972. INT32 channelCount = deformer->GetBlendShapeChannelCount();
  973. for (INT32 j = 0; j < channelCount; j++)
  974. {
  975. FbxBlendShapeChannel* channel = deformer->GetBlendShapeChannel(j);
  976. FbxAnimCurve* curve = fbxMesh->GetShapeChannel(i, j, layer);
  977. if (curve != nullptr && curve->KeyGetCount() > 0)
  978. {
  979. clip.blendShapeAnimations.push_back(FBXBlendShapeAnimation());
  980. FBXBlendShapeAnimation& blendShapeAnim = clip.blendShapeAnimations.back();
  981. blendShapeAnim.blendShape = channel->GetName();
  982. importCurve(curve, importOptions, blendShapeAnim.curve, clip.start, clip.end);
  983. }
  984. }
  985. }
  986. }
  987. }
  988. UINT32 childCount = (UINT32)node->GetChildCount();
  989. for (UINT32 i = 0; i < childCount; i++)
  990. {
  991. FbxNode* child = node->GetChild(i);
  992. importAnimations(layer, child, importOptions, clip, importScene);
  993. }
  994. }
  995. void FBXImporter::eulerToQuaternionCurves(FBXAnimationCurve(&eulerCurves)[3], FBXAnimationCurve(&quatCurves)[4])
  996. {
  997. const float FIT_TIME = 0.33f;
  998. INT32 numKeys = (INT32)eulerCurves[0].keyframes.size();
  999. if (numKeys != (INT32)eulerCurves[1].keyframes.size() || numKeys != (INT32)eulerCurves[2].keyframes.size())
  1000. return;
  1001. auto eulerToQuaternion = [&](INT32 keyIdx, float time, const Quaternion& lastQuat)
  1002. {
  1003. Degree x = (Degree)eulerCurves[0].evaluate(time);
  1004. Degree y = (Degree)eulerCurves[1].evaluate(time);
  1005. Degree z = (Degree)eulerCurves[2].evaluate(time);
  1006. Quaternion quat(x, y, z);
  1007. // Flip quaternion in case rotation is over 180 degrees
  1008. if (keyIdx > 0)
  1009. {
  1010. float dot = quat.dot(lastQuat);
  1011. if (dot < 0.0f)
  1012. quat = Quaternion(-quat.x, -quat.y, -quat.z, -quat.w);
  1013. }
  1014. return quat;
  1015. };
  1016. struct FitKeyframe
  1017. {
  1018. float time;
  1019. Quaternion value;
  1020. };
  1021. Vector<FitKeyframe> fitQuaternions(numKeys * 2);
  1022. Quaternion lastQuat;
  1023. for (INT32 i = 0; i < numKeys; i++)
  1024. {
  1025. float time = eulerCurves[0].keyframes[i].time;
  1026. Quaternion quat = eulerToQuaternion(i, time, lastQuat);
  1027. // Calculate extra values between keys so we can better approximate tangents
  1028. if ((i + 1) < numKeys)
  1029. {
  1030. float nextTime = eulerCurves[0].keyframes[i + 1].time;
  1031. float dt = nextTime - time;
  1032. FitKeyframe& fitStart = fitQuaternions[i * 2 + 0];
  1033. FitKeyframe& fitEnd = fitQuaternions[i * 2 + 1];
  1034. fitStart.time = time + dt * FIT_TIME;
  1035. fitEnd.time = time + dt * (1.0f - FIT_TIME);
  1036. fitStart.value = eulerToQuaternion(i, fitStart.time, quat);
  1037. fitEnd.value = eulerToQuaternion(i, fitEnd.time, fitStart.value);
  1038. lastQuat = fitStart.value;
  1039. }
  1040. // TODO - If animation is looping I should also compare last and first for continuity
  1041. for (INT32 j = 0; j < 4; j++)
  1042. {
  1043. quatCurves[j].keyframes.push_back(FBXKeyFrame());
  1044. FBXKeyFrame& keyFrame = quatCurves[j].keyframes.back();
  1045. keyFrame.time = time;
  1046. keyFrame.value = quat[j];
  1047. keyFrame.inTangent = 0;
  1048. keyFrame.outTangent = 0;
  1049. }
  1050. }
  1051. // Recalculate tangents for quaternion curves
  1052. // TODO - There must be an analytical way to convert euler angle tangents
  1053. // to quaternion tangents, but I don't want to bother figuring it out
  1054. // until I have a test-bed for animation.
  1055. if (numKeys > 1)
  1056. {
  1057. // TODO - I could check per-key curve interpolation originally assigned in FBX
  1058. // and use that to generate linear/constant slopes. Currently I assume
  1059. // its all cubic.
  1060. // First key
  1061. {
  1062. const FitKeyframe& fitKeyFrame = fitQuaternions[0];
  1063. for (INT32 j = 0; j < 4; j++)
  1064. {
  1065. FBXKeyFrame& keyFrame = quatCurves[j].keyframes[0];
  1066. float dt = fitKeyFrame.time - keyFrame.time;
  1067. keyFrame.inTangent = (fitKeyFrame.value[j] - keyFrame.value) / dt;
  1068. keyFrame.outTangent = keyFrame.inTangent;
  1069. }
  1070. }
  1071. // In-between keys
  1072. {
  1073. for (INT32 i = 1; i < (numKeys - 1); i++)
  1074. {
  1075. const FitKeyframe& fitPointStart = fitQuaternions[i * 2 - 1];
  1076. const FitKeyframe& fitPointEnd = fitQuaternions[i * 2 + 0];
  1077. for (INT32 j = 0; j < 4; j++)
  1078. {
  1079. FBXKeyFrame& keyFrame = quatCurves[j].keyframes[i];
  1080. float dt0 = fitPointEnd.time - keyFrame.time;
  1081. float dt1 = keyFrame.time - fitPointStart.time;
  1082. float t0 = fitPointEnd.value[j] - keyFrame.value;
  1083. float t1 = keyFrame.value - fitPointStart.value[j];
  1084. keyFrame.inTangent = t0 / (0.5f * dt0) + t1 / (0.5f * dt1);
  1085. keyFrame.outTangent = keyFrame.inTangent;
  1086. }
  1087. }
  1088. }
  1089. // Last key
  1090. {
  1091. const FitKeyframe& fitKeyFrame = fitQuaternions[(numKeys - 2) * 2];
  1092. for (INT32 j = 0; j < 4; j++)
  1093. {
  1094. FBXKeyFrame& keyFrame = quatCurves[j].keyframes[numKeys - 2];
  1095. float dt = keyFrame.time - fitKeyFrame.time;
  1096. keyFrame.inTangent = (keyFrame.value - fitKeyFrame.value[j]) / dt;
  1097. keyFrame.outTangent = keyFrame.inTangent;
  1098. }
  1099. }
  1100. }
  1101. }
  1102. void FBXImporter::importCurve(FbxAnimCurve* fbxCurve, FBXImportOptions& importOptions, FBXAnimationCurve& curve, float start, float end)
  1103. {
  1104. if (fbxCurve == nullptr)
  1105. return;
  1106. INT32 keyCount = fbxCurve->KeyGetCount();
  1107. if (importOptions.animResample)
  1108. {
  1109. float curveStart = std::numeric_limits<float>::infinity();
  1110. float curveEnd = -std::numeric_limits<float>::infinity();
  1111. for (INT32 i = 0; i < keyCount; i++)
  1112. {
  1113. FbxTime fbxTime = fbxCurve->KeyGetTime(i);
  1114. float time = (float)fbxTime.GetSecondDouble();
  1115. curveStart = std::min(time, curveStart);
  1116. curveEnd = std::max(time, curveEnd);
  1117. }
  1118. curveStart = Math::clamp(curveStart, start, end);
  1119. curveEnd = Math::clamp(curveEnd, start, end);
  1120. float curveLength = curveEnd - curveStart;
  1121. INT32 numSamples = Math::ceilToInt(curveLength / importOptions.animSampleRate);
  1122. // We don't use the exact provided sample rate but instead modify it slightly so it
  1123. // completely covers the curve range including start/end points while maintaining
  1124. // constant time step between keyframes.
  1125. float dt = curveLength / (float)numSamples;
  1126. INT32 lastKeyframe = 0;
  1127. INT32 lastLeftTangent = 0;
  1128. INT32 lastRightTangent = 0;
  1129. for (INT32 i = 0; i < numSamples; i++)
  1130. {
  1131. float sampleTime = std::min(curveStart + i * dt, curveEnd);
  1132. FbxTime fbxSampleTime;
  1133. fbxSampleTime.SetSecondDouble(sampleTime);
  1134. curve.keyframes.push_back(FBXKeyFrame());
  1135. FBXKeyFrame& keyFrame = curve.keyframes.back();
  1136. keyFrame.time = sampleTime;
  1137. keyFrame.value = fbxCurve->Evaluate(fbxSampleTime, &lastKeyframe);
  1138. keyFrame.inTangent = fbxCurve->EvaluateLeftDerivative(fbxSampleTime, &lastLeftTangent);
  1139. keyFrame.outTangent = fbxCurve->EvaluateRightDerivative(fbxSampleTime, &lastRightTangent);
  1140. }
  1141. }
  1142. else
  1143. {
  1144. for (int i = 0; i < keyCount; i++)
  1145. {
  1146. FbxTime fbxTime = fbxCurve->KeyGetTime(i);
  1147. float time = (float)fbxTime.GetSecondDouble();
  1148. if (time < start || time > end)
  1149. continue;
  1150. curve.keyframes.push_back(FBXKeyFrame());
  1151. FBXKeyFrame& keyFrame = curve.keyframes.back();
  1152. keyFrame.time = time;
  1153. keyFrame.value = fbxCurve->KeyGetValue(i);
  1154. keyFrame.inTangent = fbxCurve->KeyGetLeftDerivative(i);
  1155. keyFrame.outTangent = fbxCurve->KeyGetRightDerivative(i);
  1156. }
  1157. }
  1158. }
  1159. }