BsFBXImporter.cpp 67 KB

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