FBXSceneEncoder.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384
  1. #ifdef USE_FBX
  2. #include <algorithm>
  3. #include <string>
  4. #include <sstream>
  5. #include "FBXSceneEncoder.h"
  6. #include "FBXUtil.h"
  7. #include "Sampler.h"
  8. using namespace gameplay;
  9. using std::string;
  10. using std::vector;
  11. using std::map;
  12. using std::ostringstream;
  13. FBXSceneEncoder::FBXSceneEncoder()
  14. : _groupAnimation(NULL), _autoGroupAnimations(false)
  15. {
  16. }
  17. FBXSceneEncoder::~FBXSceneEncoder()
  18. {
  19. }
  20. void FBXSceneEncoder::write(const string& filepath, const EncoderArguments& arguments)
  21. {
  22. FbxManager* sdkManager = FbxManager::Create();
  23. FbxIOSettings *ios = FbxIOSettings::Create(sdkManager, IOSROOT);
  24. sdkManager->SetIOSettings(ios);
  25. FbxImporter* importer = FbxImporter::Create(sdkManager,"");
  26. if (!importer->Initialize(filepath.c_str(), -1, sdkManager->GetIOSettings()))
  27. {
  28. LOG(1, "Call to FbxImporter::Initialize() failed.\n");
  29. LOG(1, "Error returned: %s\n\n", importer->GetLastErrorString());
  30. exit(-1);
  31. }
  32. FbxScene* fbxScene = FbxScene::Create(sdkManager,"__FBX_SCENE__");
  33. print("Loading FBX file.");
  34. importer->Import(fbxScene);
  35. importer->Destroy();
  36. // Determine if animations should be grouped.
  37. if (arguments.getGroupAnimationAnimationId().empty() && isGroupAnimationPossible(fbxScene))
  38. {
  39. if ( arguments.getAnimationGrouping()==EncoderArguments::ANIMATIONGROUP_AUTO ||
  40. (arguments.getAnimationGrouping()==EncoderArguments::ANIMATIONGROUP_PROMPT && promptUserGroupAnimations()))
  41. {
  42. _autoGroupAnimations = true;
  43. }
  44. }
  45. if (arguments.tangentBinormalIdCount() > 0)
  46. {
  47. generateTangentsAndBinormals(fbxScene->GetRootNode(), arguments);
  48. }
  49. print("Loading Scene.");
  50. loadScene(fbxScene);
  51. if (arguments.outputMaterialEnabled())
  52. {
  53. print("Load materials");
  54. loadMaterials(fbxScene);
  55. }
  56. print("Loading animations.");
  57. loadAnimations(fbxScene, arguments);
  58. sdkManager->Destroy();
  59. print("Optimizing GamePlay Binary.");
  60. _gamePlayFile.adjust();
  61. if (_autoGroupAnimations)
  62. {
  63. _gamePlayFile.groupMeshSkinAnimations();
  64. }
  65. string outputFilePath = arguments.getOutputFilePath();
  66. if (arguments.textOutputEnabled())
  67. {
  68. int pos = outputFilePath.find_last_of('.');
  69. if (pos > 2)
  70. {
  71. string path = outputFilePath.substr(0, pos);
  72. path.append(".xml");
  73. LOG(1, "Saving debug file: %s\n", path.c_str());
  74. if (!_gamePlayFile.saveText(path))
  75. {
  76. LOG(1, "Error writing text file: %s\n", path.c_str());
  77. }
  78. }
  79. }
  80. else
  81. {
  82. LOG(1, "Saving binary file: %s\n", outputFilePath.c_str());
  83. if (!_gamePlayFile.saveBinary(outputFilePath))
  84. {
  85. LOG(1, "Error writing binary file: %s\n", outputFilePath.c_str());
  86. }
  87. }
  88. // Write the material file
  89. if (arguments.outputMaterialEnabled())
  90. {
  91. int pos = outputFilePath.find_last_of('.');
  92. if (pos > 2)
  93. {
  94. string path = outputFilePath.substr(0, pos);
  95. path.append(".material");
  96. writeMaterial(path);
  97. }
  98. }
  99. }
  100. bool FBXSceneEncoder::writeMaterial(const string& filepath)
  101. {
  102. FILE* file = fopen(filepath.c_str(), "w");
  103. if (!file)
  104. {
  105. return false;
  106. }
  107. // Finds the base materials that are used.
  108. std::set<Material*> baseMaterialsToWrite;
  109. for (map<string, Material*>::iterator it = _materials.begin(); it != _materials.end(); ++it)
  110. {
  111. baseMaterialsToWrite.insert(it->second->getParent());
  112. }
  113. // Write the base materials that are used.
  114. for (std::set<Material*>::iterator it = baseMaterialsToWrite.begin(); it != baseMaterialsToWrite.end(); ++it)
  115. {
  116. Material* material = *it;
  117. material->writeMaterial(file);
  118. fprintf(file, "\n");
  119. }
  120. // Write all of the non-base materials.
  121. for (map<string, Material*>::iterator it = _materials.begin(); it != _materials.end(); ++it)
  122. {
  123. (*it).second->writeMaterial(file);
  124. fprintf(file, "\n");
  125. }
  126. fclose(file);
  127. return true;
  128. }
  129. void FBXSceneEncoder::loadScene(FbxScene* fbxScene)
  130. {
  131. Scene* scene = new Scene();
  132. scene->setId(fbxScene->GetName());
  133. if (scene->getId().length() == 0)
  134. {
  135. scene->setId("__SCENE__");
  136. }
  137. // Load all of the nodes and their contents.
  138. FbxNode* rootNode = fbxScene->GetRootNode();
  139. if (rootNode)
  140. {
  141. print("Triangulate.");
  142. triangulateRecursive(rootNode);
  143. print("Load nodes.");
  144. // Don't include the FBX root node in the GPB.
  145. const int childCount = rootNode->GetChildCount();
  146. for (int i = 0; i < childCount; ++i)
  147. {
  148. Node* node = loadNode(rootNode->GetChild(i));
  149. if (node)
  150. {
  151. scene->add(node);
  152. }
  153. }
  154. }
  155. // Load the MeshSkin information from the scene's poses.
  156. loadBindShapes(fbxScene);
  157. // Find the ambient light of the scene
  158. FbxColor ambientColor = fbxScene->GetGlobalSettings().GetAmbientColor();
  159. scene->setAmbientColor((float)ambientColor.mRed, (float)ambientColor.mGreen, (float)ambientColor.mBlue);
  160. // Assign the first camera node (if there is one) in the scene as the active camera
  161. // This ensures that if there's a camera in the scene that it is assigned as the
  162. // active camera.
  163. // TODO: add logic to find the "active" camera node in the fbxScene
  164. scene->setActiveCameraNode(scene->getFirstCameraNode());
  165. _gamePlayFile.addScene(scene);
  166. }
  167. void FBXSceneEncoder::loadAnimationChannels(FbxAnimLayer* animLayer, FbxNode* fbxNode, Animation* animation)
  168. {
  169. const char* name = fbxNode->GetName();
  170. //Node* node = _gamePlayFile.getNode(name);
  171. // Determine which properties are animated on this node
  172. // Find the transform at each key frame
  173. // TODO: Ignore properties that are not animated (scale, rotation, translation)
  174. // This should result in only one animation channel per animated node.
  175. float startTime = FLT_MAX, stopTime = -1.0f, frameRate = -FLT_MAX;
  176. bool tx = false, ty = false, tz = false, rx = false, ry = false, rz = false, sx = false, sy = false, sz = false;
  177. FbxAnimCurve* animCurve = NULL;
  178. animCurve = getCurve(fbxNode->LclTranslation, animLayer, FBXSDK_CURVENODE_COMPONENT_X);
  179. if (animCurve)
  180. {
  181. tx = true;
  182. findMinMaxTime(animCurve, &startTime, &stopTime, &frameRate);
  183. }
  184. animCurve = getCurve(fbxNode->LclTranslation, animLayer, FBXSDK_CURVENODE_COMPONENT_Y);
  185. if (animCurve)
  186. {
  187. ty = true;
  188. findMinMaxTime(animCurve, &startTime, &stopTime, &frameRate);
  189. }
  190. animCurve = getCurve(fbxNode->LclTranslation, animLayer, FBXSDK_CURVENODE_COMPONENT_Z);
  191. if (animCurve)
  192. {
  193. tz = true;
  194. findMinMaxTime(animCurve, &startTime, &stopTime, &frameRate);
  195. }
  196. animCurve = getCurve(fbxNode->LclRotation, animLayer, FBXSDK_CURVENODE_COMPONENT_X);
  197. if (animCurve)
  198. {
  199. rx = true;
  200. findMinMaxTime(animCurve, &startTime, &stopTime, &frameRate);
  201. }
  202. animCurve = getCurve(fbxNode->LclRotation, animLayer, FBXSDK_CURVENODE_COMPONENT_Y);
  203. if (animCurve)
  204. {
  205. ry = true;
  206. findMinMaxTime(animCurve, &startTime, &stopTime, &frameRate);
  207. }
  208. animCurve = getCurve(fbxNode->LclRotation, animLayer, FBXSDK_CURVENODE_COMPONENT_Z);
  209. if (animCurve)
  210. {
  211. rz = true;
  212. findMinMaxTime(animCurve, &startTime, &stopTime, &frameRate);
  213. }
  214. animCurve = getCurve(fbxNode->LclScaling, animLayer, FBXSDK_CURVENODE_COMPONENT_X);
  215. if (animCurve)
  216. {
  217. sx = true;
  218. findMinMaxTime(animCurve, &startTime, &stopTime, &frameRate);
  219. }
  220. animCurve = getCurve(fbxNode->LclScaling, animLayer, FBXSDK_CURVENODE_COMPONENT_Y);
  221. if (animCurve)
  222. {
  223. sy = true;
  224. findMinMaxTime(animCurve, &startTime, &stopTime, &frameRate);
  225. }
  226. animCurve = getCurve(fbxNode->LclScaling, animLayer, FBXSDK_CURVENODE_COMPONENT_Z);
  227. if (animCurve)
  228. {
  229. sz = true;
  230. findMinMaxTime(animCurve, &startTime, &stopTime, &frameRate);
  231. }
  232. if (!(sx || sy || sz || rx || ry || rz || tx || ty || tz))
  233. return; // no animation channels
  234. assert(startTime != FLT_MAX);
  235. assert(stopTime >= 0.0f);
  236. // Determine which animation channels to create
  237. vector<unsigned int> channelAttribs;
  238. if (sx && sy && sz)
  239. {
  240. if (rx || ry || rz)
  241. {
  242. if (tx && ty && tz)
  243. {
  244. channelAttribs.push_back(Transform::ANIMATE_SCALE_ROTATE_TRANSLATE);
  245. }
  246. else
  247. {
  248. channelAttribs.push_back(Transform::ANIMATE_SCALE_ROTATE);
  249. if (tx)
  250. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_X);
  251. if (ty)
  252. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_Y);
  253. if (tz)
  254. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_Z);
  255. }
  256. }
  257. else
  258. {
  259. if (tx && ty && tz)
  260. {
  261. channelAttribs.push_back(Transform::ANIMATE_SCALE_TRANSLATE);
  262. }
  263. else
  264. {
  265. channelAttribs.push_back(Transform::ANIMATE_SCALE);
  266. if (tx)
  267. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_X);
  268. if (ty)
  269. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_Y);
  270. if (tz)
  271. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_Z);
  272. }
  273. }
  274. }
  275. else
  276. {
  277. if (rx || ry || rz)
  278. {
  279. if (tx && ty && tz)
  280. {
  281. channelAttribs.push_back(Transform::ANIMATE_ROTATE_TRANSLATE);
  282. }
  283. else
  284. {
  285. channelAttribs.push_back(Transform::ANIMATE_ROTATE);
  286. if (tx)
  287. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_X);
  288. if (ty)
  289. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_Y);
  290. if (tz)
  291. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_Z);
  292. }
  293. }
  294. else
  295. {
  296. if (tx && ty && tz)
  297. {
  298. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE);
  299. }
  300. else
  301. {
  302. if (tx)
  303. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_X);
  304. if (ty)
  305. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_Y);
  306. if (tz)
  307. channelAttribs.push_back(Transform::ANIMATE_TRANSLATE_Z);
  308. }
  309. }
  310. if (sx)
  311. channelAttribs.push_back(Transform::ANIMATE_SCALE_X);
  312. if (sy)
  313. channelAttribs.push_back(Transform::ANIMATE_SCALE_Y);
  314. if (sz)
  315. channelAttribs.push_back(Transform::ANIMATE_SCALE_Z);
  316. }
  317. unsigned int channelCount = channelAttribs.size();
  318. assert(channelCount > 0);
  319. // Allocate channel list
  320. const int channelStart = animation->getAnimationChannelCount();
  321. for (unsigned int i = 0; i < channelCount; ++i)
  322. {
  323. AnimationChannel* channel = new AnimationChannel();
  324. channel->setTargetId(name);
  325. channel->setInterpolation(AnimationChannel::LINEAR);
  326. channel->setTargetAttribute(channelAttribs[i]);
  327. animation->add(channel);
  328. }
  329. // Evaulate animation curve in increments of frameRate and populate channel data.
  330. FbxAMatrix fbxMatrix;
  331. Matrix matrix;
  332. double increment = 1000.0 / (double)frameRate;
  333. int frameCount = (int)ceil((double)(stopTime - startTime) / increment) + 1; // +1 because stop time is inclusive
  334. for (int frame = 0; frame < frameCount; ++frame)
  335. {
  336. double time = startTime + (frame * (double)increment);
  337. // Note: We used to clamp time to stop time, but FBX sdk does not always produce
  338. // and accurate stopTime (sometimes it is rounded down for some reason), so I'm
  339. // disabling this clamping for now as it seems more accurate under normal circumstances.
  340. //time = std::min(time, (double)stopTime);
  341. // Evalulate the animation at this time
  342. FbxTime kTime;
  343. kTime.SetMilliSeconds((FbxLongLong)time);
  344. fbxMatrix = fbxNode->EvaluateLocalTransform(kTime);
  345. copyMatrix(fbxMatrix, matrix);
  346. // Decompose the evalulated transformation matrix into separate
  347. // scale, rotation and translation.
  348. Vector3 scale;
  349. Quaternion rotation;
  350. Vector3 translation;
  351. matrix.decompose(&scale, &rotation, &translation);
  352. rotation.normalize();
  353. // Append keyframe data to all channels
  354. for (unsigned int i = channelStart, channelEnd = channelStart + channelCount; i < channelEnd; ++i)
  355. {
  356. appendKeyFrame(fbxNode, animation->getAnimationChannel(i), (float)time, scale, rotation, translation);
  357. }
  358. }
  359. if (_groupAnimation != animation)
  360. {
  361. _gamePlayFile.addAnimation(animation);
  362. }
  363. }
  364. void FBXSceneEncoder::loadAnimationLayer(FbxAnimLayer* fbxAnimLayer, FbxNode* fbxNode, const EncoderArguments& arguments)
  365. {
  366. bool animationGroupId = false;
  367. const char* name = fbxNode->GetName();
  368. // Check if this node's animations are supposed to be grouped
  369. if (name && arguments.containsGroupNodeId(name))
  370. {
  371. animationGroupId = true;
  372. _groupAnimation = new Animation();
  373. _groupAnimation->setId(arguments.getAnimationId(name));
  374. }
  375. Animation* animation = _groupAnimation;
  376. if (!animation)
  377. {
  378. animation = new Animation();
  379. animation->setId(name);
  380. }
  381. loadAnimationChannels(fbxAnimLayer, fbxNode, animation);
  382. const int childCount = fbxNode->GetChildCount();
  383. for (int modelCount = 0; modelCount < childCount; ++modelCount)
  384. {
  385. loadAnimationLayer(fbxAnimLayer, fbxNode->GetChild(modelCount), arguments);
  386. }
  387. if (animationGroupId)
  388. {
  389. _gamePlayFile.addAnimation(_groupAnimation);
  390. _groupAnimation = NULL;
  391. }
  392. }
  393. void FBXSceneEncoder::loadAnimations(FbxScene* fbxScene, const EncoderArguments& arguments)
  394. {
  395. FbxAnimEvaluator* evaluator = fbxScene->GetEvaluator();
  396. if (!evaluator)
  397. return;
  398. FbxAnimStack* animStack = evaluator->GetContext();
  399. if (!animStack)
  400. return;
  401. for (int i = 0; i < fbxScene->GetSrcObjectCount<FbxAnimStack>(); ++i)
  402. {
  403. FbxAnimStack* animStack = FbxCast<FbxAnimStack>(fbxScene->GetSrcObject<FbxAnimStack>(i));
  404. int nbAnimLayers = animStack->GetMemberCount<FbxAnimLayer>();
  405. for (int l = 0; l < nbAnimLayers; ++l)
  406. {
  407. FbxAnimLayer* animLayer = animStack->GetMember<FbxAnimLayer>(l);
  408. loadAnimationLayer(animLayer, fbxScene->GetRootNode(), arguments);
  409. }
  410. }
  411. }
  412. Node* FBXSceneEncoder::loadNode(FbxNode* fbxNode)
  413. {
  414. Node* node = NULL;
  415. // Check if this node has already been loaded
  416. const char* id = fbxNode->GetName();
  417. if (id && strlen(id) > 0)
  418. {
  419. node = _gamePlayFile.getNode(fbxNode->GetName());
  420. if (node)
  421. {
  422. return node;
  423. }
  424. }
  425. node = new Node();
  426. if (id)
  427. {
  428. node->setId(id);
  429. }
  430. _gamePlayFile.addNode(node);
  431. transformNode(fbxNode, node);
  432. loadCamera(fbxNode, node);
  433. loadLight(fbxNode, node);
  434. loadModel(fbxNode, node);
  435. if (fbxNode->GetSkeleton())
  436. {
  437. // Indicate that this is a joint node for the purpose of debugging.
  438. // The XML debug output will print that this node is a joint.
  439. node->setIsJoint(true);
  440. }
  441. // Load child nodes
  442. const int childCount = fbxNode->GetChildCount();
  443. for (int i = 0; i < childCount; ++i)
  444. {
  445. Node* child = loadNode(fbxNode->GetChild(i));
  446. if (child)
  447. {
  448. node->addChild(child);
  449. }
  450. }
  451. _nodeMap[fbxNode] = node;
  452. return node;
  453. }
  454. Mesh* FBXSceneEncoder::getMesh(FbxUInt64 meshId)
  455. {
  456. // Check if this mesh was already loaded.
  457. map<FbxUInt64, Mesh*>::iterator it = _meshes.find(meshId);
  458. if (it != _meshes.end())
  459. {
  460. return it->second;
  461. }
  462. return NULL;
  463. }
  464. void FBXSceneEncoder::saveMesh(FbxUInt64 meshId, Mesh* mesh)
  465. {
  466. assert(mesh);
  467. if (!getMesh(meshId))
  468. {
  469. _meshes[meshId] = mesh;
  470. }
  471. }
  472. void FBXSceneEncoder::print(const char* str)
  473. {
  474. LOG(1, "%s\n", str);
  475. }
  476. void FBXSceneEncoder::transformNode(FbxNode* fbxNode, Node* node)
  477. {
  478. FbxAMatrix matrix;
  479. float m[16];
  480. if (fbxNode->GetCamera() || fbxNode->GetLight())
  481. {
  482. FbxAMatrix rotateAdjust;
  483. if(fbxNode->GetLight())
  484. {
  485. /*
  486. * according to the fbx-documentation the light's forward vector
  487. * points along a node's negative Y axis.
  488. * so we have to rotate it by 90° around the X-axis to correct it.
  489. */
  490. if(fbxNode->RotationActive.Get())
  491. {
  492. const FbxVector4& postRotation = fbxNode->PostRotation.Get();
  493. fbxNode->SetPostRotation(FbxNode::eSourcePivot, FbxVector4(postRotation.mData[0] + 90.0,
  494. postRotation.mData[1],
  495. postRotation.mData[2])
  496. );
  497. }
  498. else
  499. {
  500. // if the rotation is deactivated we have to rotate it anyway to get the correct transformation in the end
  501. rotateAdjust.SetR(FbxVector4(-90.0, 0.0, 0.0));
  502. }
  503. matrix = fbxNode->EvaluateLocalTransform() * rotateAdjust;
  504. }
  505. else if(fbxNode->GetCamera())
  506. {
  507. // TODO: use the EvaluateLocalTransform() function for the transformations for the camera
  508. /*
  509. * the current implementation ignores pre- and postrotation among others (usually happens with fbx-export from blender)
  510. *
  511. * Some info for a future implementation:
  512. * according to the fbx-documentation the camera's forward vector
  513. * points along a node's positive X axis.
  514. * so we have to correct it if we use the EvaluateLocalTransform-function
  515. * just rotating it by 90° around the Y axis (similar to above) doesn't work
  516. */
  517. matrix.SetTRS(fbxNode->LclTranslation.Get(), fbxNode->LclRotation.Get(), fbxNode->LclScaling.Get());
  518. }
  519. copyMatrix(matrix, m);
  520. node->setTransformMatrix(m);
  521. }
  522. else
  523. {
  524. matrix = fbxNode->EvaluateLocalTransform();
  525. copyMatrix(matrix, m);
  526. node->setTransformMatrix(m);
  527. }
  528. }
  529. Material* FBXSceneEncoder::getBaseMaterial(const char* id)
  530. {
  531. map<string, Material*>::iterator it = _baseMaterials.find(string(id));
  532. if (it != _baseMaterials.end())
  533. {
  534. return it->second;
  535. }
  536. return NULL;
  537. }
  538. static string getBaseMaterialName(Material* material)
  539. {
  540. ostringstream baseName;
  541. if (material->isTextured())
  542. {
  543. baseName << "Textured";
  544. }
  545. else
  546. {
  547. baseName << "Colored";
  548. }
  549. if (material->isLit())
  550. {
  551. if (material->isSpecular())
  552. {
  553. baseName << "Specular";
  554. }
  555. }
  556. else
  557. {
  558. baseName << "Unlit";
  559. }
  560. return baseName.str();
  561. }
  562. Material* FBXSceneEncoder::findBaseMaterial(Material* material)
  563. {
  564. string baseMaterialName = getBaseMaterialName(material);
  565. Material* baseMaterial = getBaseMaterial(baseMaterialName.c_str());
  566. if (baseMaterial)
  567. {
  568. return baseMaterial;
  569. }
  570. baseMaterial = createBaseMaterial(baseMaterialName, material);
  571. _baseMaterials[baseMaterial->getId()] = baseMaterial;
  572. return baseMaterial;
  573. }
  574. Node* FBXSceneEncoder::findNode(FbxNode* fbxNode)
  575. {
  576. if (fbxNode)
  577. {
  578. map<FbxNode*, Node*>::const_iterator it = _nodeMap.find(fbxNode);
  579. if (it != _nodeMap.end())
  580. {
  581. return it->second;
  582. }
  583. }
  584. return NULL;
  585. }
  586. Material* FBXSceneEncoder::createBaseMaterial(const string& baseMaterialName, Material* childMaterial)
  587. {
  588. Material* baseMaterial = new Material(baseMaterialName);
  589. baseMaterial->setUniform("u_worldViewProjectionMatrix", "WORLD_VIEW_PROJECTION_MATRIX");
  590. baseMaterial->setRenderState("cullFace", "true");
  591. baseMaterial->setRenderState("depthTest", "true");
  592. if (childMaterial->isLit())
  593. {
  594. baseMaterial->setLit(true);
  595. baseMaterial->setUniform("u_inverseTransposeWorldViewMatrix", "INVERSE_TRANSPOSE_WORLD_VIEW_MATRIX");
  596. // Always use directional light
  597. baseMaterial->setUniform("u_lightDirection", "SCENE_LIGHT_DIRECTION");
  598. baseMaterial->setUniform("u_lightColor", "SCENE_LIGHT_COLOR");
  599. if (childMaterial->isSpecular())
  600. {
  601. baseMaterial->addDefine(SPECULAR);
  602. baseMaterial->setUniform("u_cameraPosition", "CAMERA_WORLD_POSITION");
  603. }
  604. }
  605. if (childMaterial->isTextured())
  606. {
  607. if (childMaterial->isLit())
  608. {
  609. if (childMaterial->isBumped())
  610. {
  611. baseMaterial->setVertexShader("res/shaders/textured-bumped.vert");
  612. baseMaterial->setFragmentShader("res/shaders/textured-bumped.frag");
  613. }
  614. else
  615. {
  616. baseMaterial->setVertexShader("res/shaders/textured.vert");
  617. baseMaterial->setFragmentShader("res/shaders/textured.frag");
  618. }
  619. }
  620. else
  621. {
  622. baseMaterial->setVertexShader("res/shaders/textured-unlit.vert");
  623. baseMaterial->setFragmentShader("res/shaders/textured-unlit.frag");
  624. }
  625. Sampler* sampler = baseMaterial->createSampler(u_diffuseTexture);
  626. sampler->set("mipmap", "true");
  627. sampler->set("wrapS", CLAMP);
  628. sampler->set("wrapT", CLAMP);
  629. sampler->set(MIN_FILTER, LINEAR_MIPMAP_LINEAR);
  630. sampler->set(MAG_FILTER, LINEAR);
  631. }
  632. else
  633. {
  634. if (childMaterial->isLit())
  635. {
  636. baseMaterial->setVertexShader("res/shaders/colored.vert");
  637. baseMaterial->setFragmentShader("res/shaders/colored.frag");
  638. }
  639. else
  640. {
  641. baseMaterial->setVertexShader("res/shaders/colored-unlit.vert");
  642. baseMaterial->setFragmentShader("res/shaders/colored-unlit.frag");
  643. }
  644. }
  645. assert(baseMaterial);
  646. return baseMaterial;
  647. }
  648. void FBXSceneEncoder::loadBindShapes(FbxScene* fbxScene)
  649. {
  650. float m[16];
  651. const int poseCount = fbxScene->GetPoseCount();
  652. for (int i = 0; i < poseCount; ++i)
  653. {
  654. FbxPose* pose = fbxScene->GetPose(i);
  655. assert(pose);
  656. if (pose->IsBindPose() && pose->GetCount() > 0)
  657. {
  658. FbxNode* fbxNode = pose->GetNode(0);
  659. if (fbxNode->GetMesh() != NULL)
  660. {
  661. Node* node = _gamePlayFile.getNode(fbxNode->GetName());
  662. assert(node && node->getModel());
  663. Model* model = node->getModel();
  664. if (model && model->getSkin())
  665. {
  666. MeshSkin* skin = model->getSkin();
  667. copyMatrix(pose->GetMatrix(0), m);
  668. skin->setBindShape(m);
  669. }
  670. }
  671. }
  672. }
  673. }
  674. void FBXSceneEncoder::loadCamera(FbxNode* fbxNode, Node* node)
  675. {
  676. FbxCamera* fbxCamera = fbxNode->GetCamera();
  677. if (!fbxCamera)
  678. {
  679. return;
  680. }
  681. Camera* camera = new Camera();
  682. const char* name = fbxNode->GetName();
  683. if (name)
  684. {
  685. string id(name);
  686. id.append("_Camera");
  687. camera->setId(id);
  688. }
  689. camera->setAspectRatio(getAspectRatio(fbxCamera));
  690. camera->setNearPlane((float)fbxCamera->NearPlane.Get());
  691. camera->setFarPlane((float)fbxCamera->FarPlane.Get());
  692. if (fbxCamera->ProjectionType.Get() == FbxCamera::eOrthogonal)
  693. {
  694. camera->setOrthographic();
  695. camera->setViewportWidth((float)fbxCamera->GetApertureWidth());
  696. camera->setViewportWidth((float)fbxCamera->GetApertureHeight());
  697. // xmag in FBX can be calculated from: OrthoZoom * 30.0 / 2.0
  698. camera->setViewportWidth((float)fbxCamera->OrthoZoom.Get() * 15.0f);
  699. }
  700. else if (fbxCamera->ProjectionType.Get() == FbxCamera::ePerspective)
  701. {
  702. camera->setPerspective();
  703. camera->setFieldOfView(getFieldOfView(fbxCamera));
  704. }
  705. else
  706. {
  707. LOG(2, "Warning: Unknown camera type in node.\n");
  708. return;
  709. }
  710. _gamePlayFile.addCamera(camera);
  711. node->setCamera(camera);
  712. }
  713. void FBXSceneEncoder::loadLight(FbxNode* fbxNode, Node* node)
  714. {
  715. FbxLight* fbxLight = fbxNode->GetLight();
  716. if (!fbxLight)
  717. {
  718. return;
  719. }
  720. Light* light = new Light();
  721. const char* name = fbxNode->GetName();
  722. if (name)
  723. {
  724. string id(name);
  725. id.append("_Light");
  726. light->setId(id);
  727. }
  728. FbxDouble3 color = fbxLight->Color.Get();
  729. light->setColor((float)color[0], (float)color[1], (float)color[2]);
  730. switch (fbxLight->LightType.Get())
  731. {
  732. case FbxLight::ePoint:
  733. {
  734. FbxLight::EDecayType decayType = fbxLight->DecayType.Get();
  735. switch (decayType)
  736. {
  737. case FbxLight::eNone:
  738. // FBX does not support ambients lights so ambient lights are converted
  739. // to point lights with no decay and visibility set to false.
  740. if (fbxNode->GetVisibility())
  741. {
  742. light->setPointLight();
  743. }
  744. else
  745. {
  746. light->setAmbientLight();
  747. }
  748. break;
  749. case FbxLight::eLinear:
  750. light->setPointLight();
  751. light->setLinearAttenuation((float)fbxLight->DecayStart.Get());
  752. break;
  753. case FbxLight::eQuadratic:
  754. light->setPointLight();
  755. light->setQuadraticAttenuation((float)fbxLight->DecayStart.Get());
  756. break;
  757. case FbxLight::eCubic:
  758. default:
  759. // Not supported..
  760. break;
  761. }
  762. break;
  763. }
  764. case FbxLight::eDirectional:
  765. {
  766. light->setDirectionalLight();
  767. break;
  768. }
  769. case FbxLight::eSpot:
  770. {
  771. light->setSpotLight();
  772. FbxLight::EDecayType decayType = fbxLight->DecayType.Get();
  773. switch (decayType)
  774. {
  775. case FbxLight::eNone:
  776. // No decay.
  777. break;
  778. case FbxLight::eLinear:
  779. light->setLinearAttenuation((float)fbxLight->DecayStart.Get());
  780. break;
  781. case FbxLight::eQuadratic:
  782. light->setQuadraticAttenuation((float)fbxLight->DecayStart.Get());
  783. break;
  784. case FbxLight::eCubic:
  785. // Not supported..
  786. break;
  787. }
  788. light->setFalloffAngle(MATH_DEG_TO_RAD((float)fbxLight->OuterAngle.Get())); // fall off angle
  789. break;
  790. }
  791. default:
  792. {
  793. LOG(2, "Warning: Unknown light type in node.\n");
  794. return;
  795. }
  796. }
  797. _gamePlayFile.addLight(light);
  798. node->setLight(light);
  799. }
  800. void FBXSceneEncoder::loadModel(FbxNode* fbxNode, Node* node)
  801. {
  802. FbxMesh* fbxMesh = fbxNode->GetMesh();
  803. if (!fbxMesh)
  804. {
  805. return;
  806. }
  807. if (fbxMesh->IsTriangleMesh())
  808. {
  809. Mesh* mesh = loadMesh(fbxMesh);
  810. Model* model = new Model();
  811. model->setMesh(mesh);
  812. node->setModel(model);
  813. loadSkin(fbxMesh, model);
  814. if (model->getSkin())
  815. {
  816. node->resetTransformMatrix();
  817. }
  818. }
  819. }
  820. void FBXSceneEncoder::loadMaterials(FbxScene* fbxScene)
  821. {
  822. FbxNode* rootNode = fbxScene->GetRootNode();
  823. if (rootNode)
  824. {
  825. // Don't include the FBX root node
  826. const int childCount = rootNode->GetChildCount();
  827. for (int i = 0; i < childCount; ++i)
  828. {
  829. FbxNode* fbxNode = rootNode->GetChild(i);
  830. if (fbxNode)
  831. {
  832. loadMaterial(fbxNode);
  833. }
  834. }
  835. }
  836. }
  837. // Fix bad material names
  838. void fixMaterialName(string& name)
  839. {
  840. static int unnamedCount = 0;
  841. for (string::size_type i = 0, len = name.length(); i < len; ++i)
  842. {
  843. if (!isalnum(name[i]))
  844. name[i] = '_';
  845. }
  846. if (name.length() == 0)
  847. {
  848. ostringstream stream;
  849. stream << "unnamed_" << (++unnamedCount);
  850. name = stream.str();
  851. }
  852. }
  853. void FBXSceneEncoder::loadMaterial(FbxNode* fbxNode)
  854. {
  855. Node* node = findNode(fbxNode);
  856. Model* model = (node) ? node->getModel() : NULL;
  857. const int materialCount = fbxNode->GetMaterialCount();
  858. for (int index = 0; index < materialCount; ++index)
  859. {
  860. FbxSurfaceMaterial* fbxMaterial = fbxNode->GetMaterial(index);
  861. string materialName(fbxMaterial->GetName());
  862. fixMaterialName(materialName);
  863. Material* material = NULL;
  864. map<string, Material*>::iterator it = _materials.find(materialName);
  865. if (it != _materials.end())
  866. {
  867. // This material was already loaded so don't load it again
  868. material = it->second;
  869. }
  870. else
  871. {
  872. material = createMaterial(materialName, fbxMaterial, node);
  873. _materials[materialName] = material;
  874. }
  875. if (materialCount == 1 && material && model)
  876. {
  877. model->setMaterial(material); // TODO: add support for materials per mesh part
  878. }
  879. else if (materialCount > 1 && material && model)
  880. {
  881. model->setMaterial(material, index);
  882. }
  883. }
  884. const int childCount = fbxNode->GetChildCount();
  885. for (int i = 0; i < childCount; ++i)
  886. {
  887. FbxNode* childNode = fbxNode->GetChild(i);
  888. if (childNode)
  889. {
  890. loadMaterial(childNode);
  891. }
  892. }
  893. }
  894. void FBXSceneEncoder::loadMaterialTextures(FbxSurfaceMaterial* fbxMaterial, Material* material)
  895. {
  896. FbxProperty fbxProperty;
  897. int textureIndex;
  898. FBXSDK_FOR_EACH_TEXTURE(textureIndex)
  899. {
  900. fbxProperty = fbxMaterial->FindProperty(FbxLayerElement::sTextureChannelNames[textureIndex]);
  901. //FindAndDisplayTextureInfoByProperty(fbxProperty, lDisplayHeader, lMaterialIndex);
  902. if ( fbxProperty.IsValid() )
  903. {
  904. int textureCount = fbxProperty.GetSrcObjectCount<FbxTexture>();
  905. for (int j = 0; j < textureCount; ++j)
  906. {
  907. FbxLayeredTexture *layeredTexture = fbxProperty.GetSrcObject<FbxLayeredTexture>(j);
  908. if (layeredTexture)
  909. {
  910. //DisplayInt(" Layered Texture: ", j);
  911. FbxLayeredTexture *layeredTexture = fbxProperty.GetSrcObject<FbxLayeredTexture>(j);
  912. int lNbTextures = layeredTexture->GetSrcObjectCount<FbxTexture>();
  913. for (int k = 0; k<lNbTextures; ++k)
  914. {
  915. FbxTexture* fbxTexture = layeredTexture->GetSrcObject<FbxTexture>(k);
  916. if (fbxTexture)
  917. {
  918. /*
  919. if (pDisplayHeader){
  920. DisplayInt(" Textures connected to Material ", pMaterialIndex);
  921. pDisplayHeader = false;
  922. }
  923. */
  924. //NOTE the blend mode is ALWAYS on the LayeredTexture and NOT the one on the texture.
  925. //Why is that? because one texture can be shared on different layered textures and might
  926. //have different blend modes.
  927. FbxLayeredTexture::EBlendMode lBlendMode;
  928. layeredTexture->GetTextureBlendMode(k, lBlendMode);
  929. //DisplayString(" Textures for ", pProperty.GetName());
  930. //DisplayInt(" Texture ", k);
  931. //DisplayTextureInfo(fbxTexture, (int) lBlendMode);
  932. }
  933. }
  934. }
  935. else if (FbxTexture* fbxTexture = fbxProperty.GetSrcObject<FbxTexture>(j))
  936. {
  937. //no layered texture simply get on the property
  938. if (FbxFileTexture* fileTexture = FbxCast<FbxFileTexture>(fbxTexture))
  939. {
  940. loadMaterialFileTexture(fileTexture, material);
  941. }
  942. }
  943. }
  944. }
  945. }
  946. }
  947. void FBXSceneEncoder::loadMaterialFileTexture(FbxFileTexture* fileTexture, Material* material)
  948. {
  949. FbxTexture::ETextureUse textureUse = fileTexture->GetTextureUse();
  950. Sampler* sampler = NULL;
  951. if (textureUse == FbxTexture::eStandard)
  952. {
  953. if (!material->getSampler("u_diffuseTexture"))
  954. sampler = material->createSampler("u_diffuseTexture");
  955. }
  956. else if (textureUse == FbxTexture::eBumpNormalMap)
  957. {
  958. if (!material->getSampler("u_normalmapTexture"))
  959. sampler = material->createSampler("u_normalmapTexture");
  960. }
  961. if (sampler)
  962. {
  963. sampler->set("absolutePath", fileTexture->GetFileName());
  964. sampler->set("relativePath", fileTexture->GetRelativeFileName());
  965. sampler->set("wrapS", fileTexture->GetWrapModeU() == FbxTexture::eClamp ? CLAMP : REPEAT);
  966. sampler->set("wrapT", fileTexture->GetWrapModeV() == FbxTexture::eClamp ? CLAMP : REPEAT);
  967. //sampler->set(MIN_FILTER, LINEAR_MIPMAP_LINEAR);
  968. //sampler->set(MAG_FILTER, LINEAR);
  969. if (textureUse == FbxTexture::eStandard)
  970. {
  971. double scaleU = fileTexture->GetScaleU();
  972. double scaleV = fileTexture->GetScaleV();
  973. if (scaleU != 1 || scaleV != 1)
  974. {
  975. ostringstream stream;
  976. stream << scaleU << ", " << scaleV;
  977. material->setUniform("u_textureRepeat", stream.str());
  978. material->addDefine(TEXTURE_REPEAT);
  979. }
  980. double translationU = fileTexture->GetTranslationU();
  981. double translationV = fileTexture->GetTranslationV();
  982. if (translationU != 0 || translationV != 0)
  983. {
  984. ostringstream stream;
  985. stream << translationU << ", " << translationV;
  986. material->setUniform("u_textureOffset", stream.str());
  987. material->addDefine(TEXTURE_OFFSET);
  988. }
  989. }
  990. }
  991. }
  992. void FBXSceneEncoder::loadMaterialUniforms(FbxSurfaceMaterial* fbxMaterial, Material* material)
  993. {
  994. if ( fbxMaterial->GetClassId().Is(FbxSurfaceLambert::ClassId) )
  995. {
  996. FbxSurfaceLambert* lambert = FbxCast<FbxSurfaceLambert>(fbxMaterial);
  997. if (material->isLit())
  998. {
  999. FbxDouble3 ambient = lambert->Ambient.Get();
  1000. if (!isBlack(ambient))
  1001. {
  1002. material->setUniform("u_ambientColor", toString(ambient));
  1003. }
  1004. }
  1005. if (!material->isTextured())
  1006. {
  1007. if (!material->isDefined(VERTEX_COLOR))
  1008. {
  1009. FbxDouble3 diffuse = lambert->Diffuse.Get();
  1010. if (!isBlack(diffuse))
  1011. {
  1012. material->setUniform("u_diffuseColor", toString(diffuse, 1.0));
  1013. }
  1014. }
  1015. }
  1016. }
  1017. if (fbxMaterial->GetClassId().Is(FbxSurfacePhong::ClassId))
  1018. {
  1019. FbxSurfacePhong* phong = FbxCast<FbxSurfacePhong>(fbxMaterial);
  1020. //FbxDouble specularFactor = phong->SpecularFactor.Get();
  1021. if (material->isLit())
  1022. {
  1023. FbxDouble shininess = phong->Shininess.Get();
  1024. if (shininess > 0)
  1025. {
  1026. ostringstream stream;
  1027. stream << shininess;
  1028. material->setUniform("u_specularExponent", stream.str());
  1029. material->addDefine(SPECULAR);
  1030. }
  1031. }
  1032. //
  1033. //((FbxSurfacePhong *) fbxMaterial)->GetAmbientColor();
  1034. //((FbxSurfacePhong *) fbxMaterial)->GetDiffuseColor();
  1035. }
  1036. }
  1037. Material* FBXSceneEncoder::createMaterial(const string& name, FbxSurfaceMaterial* fbxMaterial, Node* node)
  1038. {
  1039. assert(fbxMaterial);
  1040. Material* material = new Material(name);
  1041. Model* model = (node) ? node->getModel() : NULL;
  1042. Mesh* mesh = (model) ? model->getMesh() : NULL;
  1043. if (mesh)
  1044. {
  1045. // The material should be lit if the model has normals or there are lights in the scene.
  1046. material->setLit(mesh->hasNormals() || _gamePlayFile.getLightCount() > 0);
  1047. if (mesh->hasVertexColors())
  1048. {
  1049. material->addDefine(VERTEX_COLOR);
  1050. }
  1051. }
  1052. MeshSkin* skin = (model) ? model->getSkin() : NULL;
  1053. if (skin && skin->getJointCount() > 0)
  1054. {
  1055. material->setUniform("u_matrixPalette", "MATRIX_PALETTE");
  1056. material->addDefine("SKINNING");
  1057. ostringstream stream;
  1058. stream << "SKINNING_JOINT_COUNT " << skin->getJointCount();
  1059. material->addDefine(stream.str());
  1060. }
  1061. loadMaterialTextures(fbxMaterial, material);
  1062. loadMaterialUniforms(fbxMaterial, material);
  1063. material->setParent(findBaseMaterial(material));
  1064. assert(material);
  1065. return material;
  1066. }
  1067. void FBXSceneEncoder::loadSkin(FbxMesh* fbxMesh, Model* model)
  1068. {
  1069. const int deformerCount = fbxMesh->GetDeformerCount();
  1070. for (int i = 0; i < deformerCount; ++i)
  1071. {
  1072. FbxDeformer* deformer = fbxMesh->GetDeformer(i);
  1073. if (deformer->GetDeformerType() == FbxDeformer::eSkin)
  1074. {
  1075. FbxSkin* fbxSkin = FbxCast<FbxSkin>(deformer);
  1076. MeshSkin* skin = new MeshSkin();
  1077. vector<string> jointNames;
  1078. vector<Node*> joints;
  1079. vector<Matrix> bindPoses;
  1080. const int clusterCount = fbxSkin->GetClusterCount();
  1081. for (int j = 0; j < clusterCount; ++j)
  1082. {
  1083. FbxCluster* cluster = fbxSkin->GetCluster(j);
  1084. assert(cluster);
  1085. FbxNode* linkedNode = cluster->GetLink();
  1086. if (linkedNode && linkedNode->GetSkeleton())
  1087. {
  1088. const char* jointName = linkedNode->GetName();
  1089. assert(jointName);
  1090. jointNames.push_back(jointName);
  1091. Node* joint = loadNode(linkedNode);
  1092. assert(joint);
  1093. joints.push_back(joint);
  1094. FbxAMatrix matrix;
  1095. cluster->GetTransformLinkMatrix(matrix);
  1096. Matrix m;
  1097. copyMatrix(matrix.Inverse(), m);
  1098. bindPoses.push_back(m);
  1099. }
  1100. }
  1101. skin->setJointNames(jointNames);
  1102. skin->setJoints(joints);
  1103. skin->setBindPoses(bindPoses);
  1104. model->setSkin(skin);
  1105. break;
  1106. }
  1107. }
  1108. }
  1109. Mesh* FBXSceneEncoder::loadMesh(FbxMesh* fbxMesh)
  1110. {
  1111. // Check if this mesh has already been loaded.
  1112. Mesh* mesh = getMesh(fbxMesh->GetUniqueID());
  1113. if (mesh)
  1114. {
  1115. return mesh;
  1116. }
  1117. mesh = new Mesh();
  1118. // GamePlay requires that a mesh have a unique ID but FbxMesh doesn't have a string ID.
  1119. const char* name = fbxMesh->GetNode()->GetName();
  1120. if (name)
  1121. {
  1122. string id(name);
  1123. id.append("_Mesh");
  1124. mesh->setId(id);
  1125. }
  1126. // The number of mesh parts is equal to the number of materials that affect this mesh.
  1127. // There is always at least one mesh part.
  1128. vector<MeshPart*> meshParts;
  1129. const int materialCount = fbxMesh->GetNode()->GetMaterialCount();
  1130. int meshPartSize = (materialCount > 0) ? materialCount : 1;
  1131. for (int i = 0; i < meshPartSize; ++i)
  1132. {
  1133. meshParts.push_back(new MeshPart());
  1134. }
  1135. // Find the blend weights and blend indices if this mesh is skinned.
  1136. vector<vector<Vector2> > weights;
  1137. bool hasSkin = loadBlendWeights(fbxMesh, weights);
  1138. // Get list of uv sets for mesh
  1139. FbxStringList uvSetNameList;
  1140. fbxMesh->GetUVSetNames(uvSetNameList);
  1141. const int uvSetCount = uvSetNameList.GetCount();
  1142. int vertexIndex = 0;
  1143. FbxVector4* controlPoints = fbxMesh->GetControlPoints();
  1144. const int polygonCount = fbxMesh->GetPolygonCount();
  1145. for (int polyIndex = 0; polyIndex < polygonCount; ++polyIndex)
  1146. {
  1147. const int polygonSize = fbxMesh->GetPolygonSize(polyIndex);
  1148. for (int posInPoly = 0; posInPoly < polygonSize; ++posInPoly)
  1149. {
  1150. int controlPointIndex = fbxMesh->GetPolygonVertex(polyIndex, posInPoly);
  1151. Vertex vertex;
  1152. FbxVector4& position = controlPoints[controlPointIndex];
  1153. vertex.position.x = (float)position[0];
  1154. vertex.position.y = (float)position[1];
  1155. vertex.position.z = (float)position[2];
  1156. // Load tex coords for all uv sets
  1157. for (int uvSetIndex = 0; uvSetIndex < uvSetCount; ++uvSetIndex)
  1158. {
  1159. const FbxGeometryElementUV* uvElement = fbxMesh->GetElementUV(uvSetNameList.GetStringAt(uvSetIndex));
  1160. if (uvElement)
  1161. loadTextureCoords(fbxMesh, uvElement, uvSetIndex, polyIndex, posInPoly, vertexIndex, &vertex);
  1162. }
  1163. // Load other data
  1164. loadNormal(fbxMesh, vertexIndex, controlPointIndex, &vertex);
  1165. loadTangent(fbxMesh, vertexIndex, controlPointIndex, &vertex);
  1166. loadBinormal(fbxMesh, vertexIndex, controlPointIndex, &vertex);
  1167. loadVertexColor(fbxMesh, vertexIndex, controlPointIndex, &vertex);
  1168. if (hasSkin)
  1169. {
  1170. loadBlendData(weights[controlPointIndex], &vertex);
  1171. }
  1172. // Determine which mesh part this vertex index should be added to based on the material that affects it.
  1173. int meshPartIndex = 0;
  1174. const int elementMatrialCount = fbxMesh->GetElementMaterialCount();
  1175. for (int k = 0; k < elementMatrialCount; ++k)
  1176. {
  1177. FbxGeometryElementMaterial* elementMaterial = fbxMesh->GetElementMaterial(k);
  1178. meshPartIndex = elementMaterial->GetIndexArray().GetAt(polyIndex);
  1179. }
  1180. // Add the vertex to the mesh if it hasn't already been added and find the vertex index.
  1181. unsigned int index;
  1182. if (mesh->contains(vertex))
  1183. {
  1184. index = mesh->getVertexIndex(vertex);
  1185. }
  1186. else
  1187. {
  1188. index = mesh->addVertex(vertex);
  1189. }
  1190. meshParts[meshPartIndex]->addIndex(index);
  1191. vertexIndex++;
  1192. }
  1193. }
  1194. const size_t meshpartsSize = meshParts.size();
  1195. for (size_t i = 0; i < meshpartsSize; ++i)
  1196. {
  1197. mesh->addMeshPart(meshParts[i]);
  1198. }
  1199. // The order that the vertex elements are add to the list matters.
  1200. // It should be the same order as how the Vertex data is written.
  1201. // Position
  1202. mesh->addVetexAttribute(POSITION, Vertex::POSITION_COUNT);
  1203. const Vertex& vertex = mesh->vertices[0];
  1204. // Normals
  1205. if (vertex.hasNormal)
  1206. {
  1207. mesh->addVetexAttribute(NORMAL, Vertex::NORMAL_COUNT);
  1208. }
  1209. // Tangents
  1210. if (vertex.hasTangent)
  1211. {
  1212. mesh->addVetexAttribute(TANGENT, Vertex::TANGENT_COUNT);
  1213. }
  1214. // Binormals
  1215. if (vertex.hasBinormal)
  1216. {
  1217. mesh->addVetexAttribute(BINORMAL, Vertex::BINORMAL_COUNT);
  1218. }
  1219. // Texture Coordinates
  1220. for (unsigned int i = 0; i < MAX_UV_SETS; ++i)
  1221. {
  1222. if (vertex.hasTexCoord[i])
  1223. {
  1224. mesh->addVetexAttribute(TEXCOORD0 + i, Vertex::TEXCOORD_COUNT);
  1225. }
  1226. }
  1227. // Diffuse Color
  1228. if (vertex.hasDiffuse)
  1229. {
  1230. mesh->addVetexAttribute(COLOR, Vertex::DIFFUSE_COUNT);
  1231. }
  1232. // Skinning BlendWeights BlendIndices
  1233. if (vertex.hasWeights)
  1234. {
  1235. mesh->addVetexAttribute(BLENDWEIGHTS, Vertex::BLEND_WEIGHTS_COUNT);
  1236. mesh->addVetexAttribute(BLENDINDICES, Vertex::BLEND_INDICES_COUNT);
  1237. }
  1238. _gamePlayFile.addMesh(mesh);
  1239. saveMesh(fbxMesh->GetUniqueID(), mesh);
  1240. return mesh;
  1241. }
  1242. void FBXSceneEncoder::triangulateRecursive(FbxNode* fbxNode)
  1243. {
  1244. // Triangulate all NURBS, patch and mesh under this node recursively.
  1245. FbxNodeAttribute* nodeAttribute = fbxNode->GetNodeAttribute();
  1246. if (nodeAttribute)
  1247. {
  1248. FbxNodeAttribute::EType type = nodeAttribute->GetAttributeType();
  1249. if (type == FbxNodeAttribute::eMesh ||
  1250. type == FbxNodeAttribute::eNurbs ||
  1251. type == FbxNodeAttribute::eNurbsSurface ||
  1252. type == FbxNodeAttribute::ePatch)
  1253. {
  1254. FbxGeometryConverter converter(fbxNode->GetFbxManager());
  1255. converter.TriangulateInPlace(fbxNode);
  1256. }
  1257. }
  1258. const int childCount = fbxNode->GetChildCount();
  1259. for (int childIndex = 0; childIndex < childCount; ++childIndex)
  1260. {
  1261. triangulateRecursive(fbxNode->GetChild(childIndex));
  1262. }
  1263. }
  1264. #endif