FBXConverter.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2012, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. /** @file FBXConverter.cpp
  34. * @brief Implementation of the FBX DOM -> aiScene converter
  35. */
  36. #include "AssimpPCH.h"
  37. #ifndef ASSIMP_BUILD_NO_FBX_IMPORTER
  38. #include <boost/tuple/tuple.hpp>
  39. #include "FBXParser.h"
  40. #include "FBXConverter.h"
  41. #include "FBXDocument.h"
  42. #include "FBXUtil.h"
  43. #include "FBXProperties.h"
  44. #include "FBXImporter.h"
  45. namespace Assimp {
  46. namespace FBX {
  47. using namespace Util;
  48. // XXX vc9's debugger won't step into anonymous namespaces
  49. //namespace {
  50. /** Dummy class to encapsulate the conversion process */
  51. class Converter
  52. {
  53. public:
  54. Converter(aiScene* out, const Document& doc)
  55. : out(out)
  56. , doc(doc)
  57. {
  58. ConvertRootNode();
  59. ConvertAnimations();
  60. if(doc.Settings().readAllMaterials) {
  61. // unfortunately this means we have to evaluate all objects
  62. BOOST_FOREACH(const ObjectMap::value_type& v,doc.Objects()) {
  63. const Object* ob = v.second->Get();
  64. if(!ob) {
  65. continue;
  66. }
  67. const Material* mat = dynamic_cast<const Material*>(ob);
  68. if(mat) {
  69. if (materials_converted.find(mat) == materials_converted.end()) {
  70. ConvertMaterial(*mat);
  71. }
  72. }
  73. }
  74. }
  75. TransferDataToScene();
  76. }
  77. ~Converter()
  78. {
  79. std::for_each(meshes.begin(),meshes.end(),Util::delete_fun<aiMesh>());
  80. std::for_each(materials.begin(),materials.end(),Util::delete_fun<aiMaterial>());
  81. std::for_each(animations.begin(),animations.end(),Util::delete_fun<aiAnimation>());
  82. }
  83. private:
  84. // ------------------------------------------------------------------------------------------------
  85. // find scene root and trigger recursive scene conversion
  86. void ConvertRootNode()
  87. {
  88. out->mRootNode = new aiNode();
  89. out->mRootNode->mName.Set("RootNode");
  90. // root has ID 0
  91. ConvertNodes(0L, *out->mRootNode);
  92. }
  93. // ------------------------------------------------------------------------------------------------
  94. // collect and assign child nodes
  95. void ConvertNodes(uint64_t id, aiNode& parent)
  96. {
  97. const std::vector<const Connection*>& conns = doc.GetConnectionsByDestinationSequenced(id, "Model");
  98. std::vector<aiNode*> nodes;
  99. nodes.reserve(conns.size());
  100. BOOST_FOREACH(const Connection* con, conns) {
  101. // ignore object-property links
  102. if(con->PropertyName().length()) {
  103. continue;
  104. }
  105. const Object* const object = con->SourceObject();
  106. if(!object) {
  107. FBXImporter::LogWarn("failed to convert source object for node link");
  108. continue;
  109. }
  110. const Model* const model = dynamic_cast<const Model*>(object);
  111. if(model) {
  112. aiNode* nd = new aiNode();
  113. nodes.push_back(nd);
  114. nd->mName.Set(FixNodeName(model->Name()));
  115. nd->mParent = &parent;
  116. ConvertTransformation(*model,*nd);
  117. ConvertModel(*model, *nd);
  118. ConvertNodes(model->ID(), *nd);
  119. }
  120. }
  121. if(nodes.size()) {
  122. parent.mChildren = new aiNode*[nodes.size()]();
  123. parent.mNumChildren = static_cast<unsigned int>(nodes.size());
  124. std::swap_ranges(nodes.begin(),nodes.end(),parent.mChildren);
  125. }
  126. }
  127. // ------------------------------------------------------------------------------------------------
  128. void ConvertTransformation(const Model& model, aiNode& nd)
  129. {
  130. const PropertyTable& props = model.Props();
  131. bool ok;
  132. aiVector3D Translation = PropertyGet<aiVector3D>(props,"Lcl Translation",ok);
  133. if(!ok) {
  134. Translation = aiVector3D(0.0f,0.0f,0.0f);
  135. }
  136. aiVector3D Scaling = PropertyGet<aiVector3D>(props,"Lcl Scaling",ok);
  137. if(!ok) {
  138. Scaling = aiVector3D(1.0f,1.0f,1.0f);
  139. }
  140. // XXX euler angles, radians, xyz order?
  141. aiVector3D Rotation = PropertyGet<aiVector3D>(props,"Lcl Rotation",ok);
  142. if(!ok) {
  143. Rotation = aiVector3D(0.0f,0.0f,0.0f);
  144. }
  145. aiMatrix4x4 temp;
  146. nd.mTransformation = aiMatrix4x4::Scaling(Scaling,temp);
  147. if(fabs(Rotation.x) > 1e-6f) {
  148. nd.mTransformation *= aiMatrix4x4::RotationX(Rotation.x,temp);
  149. }
  150. if(fabs(Rotation.y) > 1e-6f) {
  151. nd.mTransformation *= aiMatrix4x4::RotationY(Rotation.y,temp);
  152. }
  153. if(fabs(Rotation.z) > 1e-6f) {
  154. nd.mTransformation *= aiMatrix4x4::RotationZ(Rotation.z,temp);
  155. }
  156. nd.mTransformation.a4 = Translation.x;
  157. nd.mTransformation.b4 = Translation.y;
  158. nd.mTransformation.c4 = Translation.z;
  159. }
  160. // ------------------------------------------------------------------------------------------------
  161. void ConvertModel(const Model& model, aiNode& nd)
  162. {
  163. const std::vector<const Geometry*>& geos = model.GetGeometry();
  164. std::vector<unsigned int> meshes;
  165. meshes.reserve(geos.size());
  166. BOOST_FOREACH(const Geometry* geo, geos) {
  167. const MeshGeometry* const mesh = dynamic_cast<const MeshGeometry*>(geo);
  168. if(mesh) {
  169. const std::vector<unsigned int>& indices = ConvertMesh(*mesh, model);
  170. std::copy(indices.begin(),indices.end(),std::back_inserter(meshes) );
  171. }
  172. else {
  173. FBXImporter::LogWarn("ignoring unrecognized geometry: " + geo->Name());
  174. }
  175. }
  176. if(meshes.size()) {
  177. nd.mMeshes = new unsigned int[meshes.size()]();
  178. nd.mNumMeshes = static_cast<unsigned int>(meshes.size());
  179. std::swap_ranges(meshes.begin(),meshes.end(),nd.mMeshes);
  180. }
  181. }
  182. // ------------------------------------------------------------------------------------------------
  183. // MeshGeometry -> aiMesh, return mesh index + 1 or 0 if the conversion failed
  184. std::vector<unsigned int> ConvertMesh(const MeshGeometry& mesh, const Model& model)
  185. {
  186. std::vector<unsigned int> temp;
  187. MeshMap::const_iterator it = meshes_converted.find(&mesh);
  188. if (it != meshes_converted.end()) {
  189. std::copy((*it).second.begin(),(*it).second.end(),std::back_inserter(temp));
  190. return temp;
  191. }
  192. const std::vector<aiVector3D>& vertices = mesh.GetVertices();
  193. const std::vector<unsigned int>& faces = mesh.GetFaceIndexCounts();
  194. if(vertices.empty() || faces.empty()) {
  195. FBXImporter::LogWarn("ignoring empty geometry: " + mesh.Name());
  196. return temp;
  197. }
  198. // one material per mesh maps easily to aiMesh. Multiple material
  199. // meshes need to be split.
  200. const std::vector<unsigned int>& mindices = mesh.GetMaterialIndices();
  201. if (doc.Settings().readMaterials && !mindices.empty()) {
  202. const unsigned int base = mindices[0];
  203. BOOST_FOREACH(unsigned int index, mindices) {
  204. if(index != base) {
  205. return ConvertMeshMultiMaterial(mesh, model);
  206. }
  207. }
  208. }
  209. // faster codepath, just copy the data
  210. temp.push_back(ConvertMeshSingleMaterial(mesh, model));
  211. return temp;
  212. }
  213. // ------------------------------------------------------------------------------------------------
  214. aiMesh* SetupEmptyMesh(const MeshGeometry& mesh, unsigned int material_index)
  215. {
  216. aiMesh* const out_mesh = new aiMesh();
  217. meshes.push_back(out_mesh);
  218. meshes_converted[&mesh].push_back(static_cast<unsigned int>(meshes.size()-1));
  219. // set name
  220. std::string name = mesh.Name();
  221. if (name.substr(0,10) == "Geometry::") {
  222. name = name.substr(10);
  223. }
  224. if(name.length()) {
  225. out_mesh->mName.Set(name);
  226. }
  227. return out_mesh;
  228. }
  229. // ------------------------------------------------------------------------------------------------
  230. unsigned int ConvertMeshSingleMaterial(const MeshGeometry& mesh, const Model& model)
  231. {
  232. const std::vector<unsigned int>& mindices = mesh.GetMaterialIndices();
  233. aiMesh* const out_mesh = SetupEmptyMesh(mesh,mindices.size() ? mindices[0] : static_cast<unsigned int>(-1));
  234. const std::vector<aiVector3D>& vertices = mesh.GetVertices();
  235. const std::vector<unsigned int>& faces = mesh.GetFaceIndexCounts();
  236. // copy vertices
  237. out_mesh->mNumVertices = static_cast<unsigned int>(vertices.size());
  238. out_mesh->mVertices = new aiVector3D[vertices.size()];
  239. std::copy(vertices.begin(),vertices.end(),out_mesh->mVertices);
  240. // generate dummy faces
  241. out_mesh->mNumFaces = static_cast<unsigned int>(faces.size());
  242. aiFace* fac = out_mesh->mFaces = new aiFace[faces.size()]();
  243. unsigned int cursor = 0;
  244. BOOST_FOREACH(unsigned int pcount, faces) {
  245. aiFace& f = *fac++;
  246. f.mNumIndices = pcount;
  247. f.mIndices = new unsigned int[pcount];
  248. switch(pcount)
  249. {
  250. case 1:
  251. out_mesh->mPrimitiveTypes |= aiPrimitiveType_POINT;
  252. break;
  253. case 2:
  254. out_mesh->mPrimitiveTypes |= aiPrimitiveType_LINE;
  255. break;
  256. case 3:
  257. out_mesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  258. break;
  259. default:
  260. out_mesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  261. break;
  262. }
  263. for (unsigned int i = 0; i < pcount; ++i) {
  264. f.mIndices[i] = cursor++;
  265. }
  266. }
  267. // copy normals
  268. const std::vector<aiVector3D>& normals = mesh.GetNormals();
  269. if(normals.size()) {
  270. ai_assert(normals.size() == vertices.size());
  271. out_mesh->mNormals = new aiVector3D[vertices.size()];
  272. std::copy(normals.begin(),normals.end(),out_mesh->mNormals);
  273. }
  274. // copy tangents - assimp requires both tangents and bitangents (binormals)
  275. // to be present, or neither of them. Compute binormals from normals
  276. // and tangents if needed.
  277. const std::vector<aiVector3D>& tangents = mesh.GetTangents();
  278. const std::vector<aiVector3D>* binormals = &mesh.GetBinormals();
  279. if(tangents.size()) {
  280. std::vector<aiVector3D> tempBinormals;
  281. if (!binormals->size()) {
  282. if (normals.size()) {
  283. tempBinormals.resize(normals.size());
  284. for (unsigned int i = 0; i < tangents.size(); ++i) {
  285. tempBinormals[i] = normals[i] ^ tangents[i];
  286. }
  287. binormals = &tempBinormals;
  288. }
  289. else {
  290. binormals = NULL;
  291. }
  292. }
  293. if(binormals) {
  294. ai_assert(tangents.size() == vertices.size() && binormals->size() == vertices.size());
  295. out_mesh->mTangents = new aiVector3D[vertices.size()];
  296. std::copy(tangents.begin(),tangents.end(),out_mesh->mTangents);
  297. out_mesh->mBitangents = new aiVector3D[vertices.size()];
  298. std::copy(binormals->begin(),binormals->end(),out_mesh->mBitangents);
  299. }
  300. }
  301. // copy texture coords
  302. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  303. const std::vector<aiVector2D>& uvs = mesh.GetTextureCoords(i);
  304. if(uvs.empty()) {
  305. break;
  306. }
  307. aiVector3D* out_uv = out_mesh->mTextureCoords[i] = new aiVector3D[vertices.size()];
  308. BOOST_FOREACH(const aiVector2D& v, uvs) {
  309. *out_uv++ = aiVector3D(v.x,v.y,0.0f);
  310. }
  311. out_mesh->mNumUVComponents[i] = 2;
  312. }
  313. // copy vertex colors
  314. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_COLOR_SETS; ++i) {
  315. const std::vector<aiColor4D>& colors = mesh.GetVertexColors(i);
  316. if(colors.empty()) {
  317. break;
  318. }
  319. out_mesh->mColors[i] = new aiColor4D[vertices.size()];
  320. std::copy(colors.begin(),colors.end(),out_mesh->mColors[i]);
  321. }
  322. if(!doc.Settings().readMaterials || mindices.empty()) {
  323. FBXImporter::LogError("no material assigned to mesh, setting default material");
  324. out_mesh->mMaterialIndex = GetDefaultMaterial();
  325. }
  326. else {
  327. ConvertMaterialForMesh(out_mesh,model,mesh,mindices[0]);
  328. }
  329. return static_cast<unsigned int>(meshes.size() - 1);
  330. }
  331. // ------------------------------------------------------------------------------------------------
  332. std::vector<unsigned int> ConvertMeshMultiMaterial(const MeshGeometry& mesh, const Model& model)
  333. {
  334. const std::vector<unsigned int>& mindices = mesh.GetMaterialIndices();
  335. ai_assert(mindices.size());
  336. std::set<unsigned int> had;
  337. std::vector<unsigned int> indices;
  338. BOOST_FOREACH(unsigned int index, mindices) {
  339. if(had.find(index) == had.end()) {
  340. indices.push_back(ConvertMeshMultiMaterial(mesh, model, index));
  341. had.insert(index);
  342. }
  343. }
  344. return indices;
  345. }
  346. // ------------------------------------------------------------------------------------------------
  347. unsigned int ConvertMeshMultiMaterial(const MeshGeometry& mesh, const Model& model, unsigned int index)
  348. {
  349. aiMesh* const out_mesh = SetupEmptyMesh(mesh, index);
  350. const std::vector<unsigned int>& mindices = mesh.GetMaterialIndices();
  351. const std::vector<aiVector3D>& vertices = mesh.GetVertices();
  352. const std::vector<unsigned int>& faces = mesh.GetFaceIndexCounts();
  353. unsigned int count_faces = 0;
  354. unsigned int count_vertices = 0;
  355. // count faces
  356. for(std::vector<unsigned int>::const_iterator it = mindices.begin(),
  357. end = mindices.end(), itf = faces.begin(); it != end; ++it, ++itf)
  358. {
  359. if ((*it) != index) {
  360. continue;
  361. }
  362. ++count_faces;
  363. count_vertices += *itf;
  364. }
  365. ai_assert(count_faces);
  366. // allocate output data arrays, but don't fill them yet
  367. out_mesh->mNumVertices = count_vertices;
  368. out_mesh->mVertices = new aiVector3D[count_vertices];
  369. out_mesh->mNumFaces = count_faces;
  370. aiFace* fac = out_mesh->mFaces = new aiFace[count_faces]();
  371. // allocate normals
  372. const std::vector<aiVector3D>& normals = mesh.GetNormals();
  373. if(normals.size()) {
  374. ai_assert(normals.size() == vertices.size());
  375. out_mesh->mNormals = new aiVector3D[vertices.size()];
  376. }
  377. // allocate tangents, binormals.
  378. const std::vector<aiVector3D>& tangents = mesh.GetTangents();
  379. const std::vector<aiVector3D>* binormals = &mesh.GetBinormals();
  380. if(tangents.size()) {
  381. std::vector<aiVector3D> tempBinormals;
  382. if (!binormals->size()) {
  383. if (normals.size()) {
  384. // XXX this computes the binormals for the entire mesh, not only
  385. // the part for which we need them.
  386. tempBinormals.resize(normals.size());
  387. for (unsigned int i = 0; i < tangents.size(); ++i) {
  388. tempBinormals[i] = normals[i] ^ tangents[i];
  389. }
  390. binormals = &tempBinormals;
  391. }
  392. else {
  393. binormals = NULL;
  394. }
  395. }
  396. if(binormals) {
  397. ai_assert(tangents.size() == vertices.size() && binormals->size() == vertices.size());
  398. out_mesh->mTangents = new aiVector3D[vertices.size()];
  399. out_mesh->mBitangents = new aiVector3D[vertices.size()];
  400. }
  401. }
  402. // allocate texture coords
  403. unsigned int num_uvs = 0;
  404. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i, ++num_uvs) {
  405. const std::vector<aiVector2D>& uvs = mesh.GetTextureCoords(i);
  406. if(uvs.empty()) {
  407. break;
  408. }
  409. out_mesh->mTextureCoords[i] = new aiVector3D[vertices.size()];
  410. out_mesh->mNumUVComponents[i] = 2;
  411. }
  412. // allocate vertex colors
  413. unsigned int num_vcs = 0;
  414. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_COLOR_SETS; ++i, ++num_vcs) {
  415. const std::vector<aiColor4D>& colors = mesh.GetVertexColors(i);
  416. if(colors.empty()) {
  417. break;
  418. }
  419. out_mesh->mColors[i] = new aiColor4D[vertices.size()];
  420. }
  421. unsigned int cursor = 0, in_cursor = 0;
  422. for(std::vector<unsigned int>::const_iterator it = mindices.begin(),
  423. end = mindices.end(), itf = faces.begin(); it != end; ++it, ++itf)
  424. {
  425. const unsigned int pcount = *itf;
  426. if ((*it) != index) {
  427. in_cursor += pcount;
  428. continue;
  429. }
  430. aiFace& f = *fac++;
  431. f.mNumIndices = pcount;
  432. f.mIndices = new unsigned int[pcount];
  433. switch(pcount)
  434. {
  435. case 1:
  436. out_mesh->mPrimitiveTypes |= aiPrimitiveType_POINT;
  437. break;
  438. case 2:
  439. out_mesh->mPrimitiveTypes |= aiPrimitiveType_LINE;
  440. break;
  441. case 3:
  442. out_mesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  443. break;
  444. default:
  445. out_mesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  446. break;
  447. }
  448. for (unsigned int i = 0; i < pcount; ++i, ++cursor, ++in_cursor) {
  449. f.mIndices[i] = cursor;
  450. out_mesh->mVertices[cursor] = vertices[in_cursor];
  451. if(out_mesh->mNormals) {
  452. out_mesh->mNormals[cursor] = normals[in_cursor];
  453. }
  454. if(out_mesh->mTangents) {
  455. out_mesh->mTangents[cursor] = tangents[in_cursor];
  456. out_mesh->mBitangents[cursor] = (*binormals)[in_cursor];
  457. }
  458. for (unsigned int i = 0; i < num_uvs; ++i) {
  459. const std::vector<aiVector2D>& uvs = mesh.GetTextureCoords(i);
  460. out_mesh->mTextureCoords[i][cursor] = aiVector3D(uvs[in_cursor].x,uvs[in_cursor].y, 0.0f);
  461. }
  462. for (unsigned int i = 0; i < num_vcs; ++i) {
  463. const std::vector<aiColor4D>& cols = mesh.GetVertexColors(i);
  464. out_mesh->mColors[i][cursor] = cols[in_cursor];
  465. }
  466. }
  467. }
  468. ConvertMaterialForMesh(out_mesh,model,mesh,index);
  469. return static_cast<unsigned int>(meshes.size() - 1);
  470. }
  471. // ------------------------------------------------------------------------------------------------
  472. void ConvertMaterialForMesh(aiMesh* out, const Model& model, const MeshGeometry& geo, unsigned int materialIndex)
  473. {
  474. // locate source materials for this mesh
  475. const std::vector<const Material*>& mats = model.GetMaterials();
  476. if (materialIndex >= mats.size()) {
  477. FBXImporter::LogError("material index out of bounds, setting default material");
  478. out->mMaterialIndex = GetDefaultMaterial();
  479. return;
  480. }
  481. const Material* const mat = mats[materialIndex];
  482. MaterialMap::const_iterator it = materials_converted.find(mat);
  483. if (it != materials_converted.end()) {
  484. out->mMaterialIndex = (*it).second;
  485. return;
  486. }
  487. out->mMaterialIndex = ConvertMaterial(*mat);
  488. materials_converted[mat] = out->mMaterialIndex;
  489. }
  490. // ------------------------------------------------------------------------------------------------
  491. unsigned int GetDefaultMaterial()
  492. {
  493. if (defaultMaterialIndex) {
  494. return defaultMaterialIndex - 1;
  495. }
  496. aiMaterial* out_mat = new aiMaterial();
  497. materials.push_back(out_mat);
  498. const aiColor3D diffuse = aiColor3D(0.8f,0.8f,0.8f);
  499. out_mat->AddProperty(&diffuse,1,AI_MATKEY_COLOR_DIFFUSE);
  500. aiString s;
  501. s.Set(AI_DEFAULT_MATERIAL_NAME);
  502. out_mat->AddProperty(&s,AI_MATKEY_NAME);
  503. defaultMaterialIndex = static_cast<unsigned int>(materials.size());
  504. return defaultMaterialIndex - 1;
  505. }
  506. // ------------------------------------------------------------------------------------------------
  507. // Material -> aiMaterial
  508. unsigned int ConvertMaterial(const Material& material)
  509. {
  510. const PropertyTable& props = material.Props();
  511. // generate empty output material
  512. aiMaterial* out_mat = new aiMaterial();
  513. materials_converted[&material] = static_cast<unsigned int>(materials.size());
  514. materials.push_back(out_mat);
  515. aiString str;
  516. // stip Material:: prefix
  517. std::string name = material.Name();
  518. if(name.substr(0,10) == "Material::") {
  519. name = name.substr(10);
  520. }
  521. // set material name if not empty - this could happen
  522. // and there should be no key for it in this case.
  523. if(name.length()) {
  524. str.Set(name);
  525. out_mat->AddProperty(&str,AI_MATKEY_NAME);
  526. }
  527. // shading stuff and colors
  528. SetShadingPropertiesCommon(out_mat,props);
  529. // texture assignments
  530. SetTextureProperties(out_mat,material.Textures());
  531. return static_cast<unsigned int>(materials.size() - 1);
  532. }
  533. // ------------------------------------------------------------------------------------------------
  534. void TrySetTextureProperties(aiMaterial* out_mat, const TextureMap& textures, const std::string& propName, aiTextureType target)
  535. {
  536. TextureMap::const_iterator it = textures.find(propName);
  537. if(it == textures.end()) {
  538. return;
  539. }
  540. const Texture* const tex = (*it).second;
  541. aiString path;
  542. path.Set(tex->RelativeFilename());
  543. out_mat->AddProperty(&path,_AI_MATKEY_TEXTURE_BASE,target,0);
  544. aiUVTransform uvTrafo;
  545. // XXX handle all kinds of UV transformations
  546. uvTrafo.mScaling = tex->UVScaling();
  547. uvTrafo.mTranslation = tex->UVTranslation();
  548. out_mat->AddProperty(&uvTrafo,1,_AI_MATKEY_UVTRANSFORM_BASE,target,0);
  549. const PropertyTable& props = tex->Props();
  550. int uvIndex = 0;
  551. bool ok;
  552. const std::string& uvSet = PropertyGet<std::string>(props,"UVSet",ok);
  553. if(ok) {
  554. // "default" is the name which usually appears in the FbxFileTexture template
  555. if(uvSet != "default" && uvSet.length()) {
  556. // this is a bit awkward - we need to find a mesh that uses this
  557. // material and scan its UV channels for the given UV name because
  558. // assimp references UV channels by index, not by name.
  559. // XXX: the case that UV channels may appear in different orders
  560. // in meshes is unhandled. A possible solution would be to sort
  561. // the UV channels alphabetically, but this would have the side
  562. // effect that the primary (first) UV channel would sometimes
  563. // be moved, causing trouble when users read only the first
  564. // UV channel and ignore UV channel assignments altogether.
  565. const unsigned int matIndex = static_cast<unsigned int>(std::distance(materials.begin(),
  566. std::find(materials.begin(),materials.end(),out_mat)
  567. ));
  568. uvIndex = -1;
  569. BOOST_FOREACH(const MeshMap::value_type& v,meshes_converted) {
  570. const MeshGeometry* const mesh = dynamic_cast<const MeshGeometry*> (v.first);
  571. if(!mesh) {
  572. continue;
  573. }
  574. const std::vector<unsigned int>& mats = mesh->GetMaterialIndices();
  575. if(std::find(mats.begin(),mats.end(),matIndex) == mats.end()) {
  576. continue;
  577. }
  578. int index = -1;
  579. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  580. if(mesh->GetTextureCoords(i).empty()) {
  581. break;
  582. }
  583. const std::string& name = mesh->GetTextureCoordChannelName(i);
  584. if(name == uvSet) {
  585. index = static_cast<int>(i);
  586. break;
  587. }
  588. }
  589. if(index == -1) {
  590. FBXImporter::LogWarn("did not find UV channel named " + uvSet + " in a mesh using this material");
  591. continue;
  592. }
  593. if(uvIndex == -1) {
  594. uvIndex = index;
  595. }
  596. else {
  597. FBXImporter::LogWarn("the UV channel named " + uvSet +
  598. " appears at different positions in meshes, results will be wrong");
  599. }
  600. }
  601. if(uvIndex == -1) {
  602. FBXImporter::LogWarn("failed to resolve UV channel " + uvSet + ", using first UV channel");
  603. uvIndex = 0;
  604. }
  605. }
  606. }
  607. out_mat->AddProperty(&uvIndex,1,_AI_MATKEY_UVWSRC_BASE,target,0);
  608. }
  609. // ------------------------------------------------------------------------------------------------
  610. void SetTextureProperties(aiMaterial* out_mat, const TextureMap& textures)
  611. {
  612. TrySetTextureProperties(out_mat, textures, "DiffuseColor", aiTextureType_DIFFUSE);
  613. TrySetTextureProperties(out_mat, textures, "AmbientColor", aiTextureType_AMBIENT);
  614. TrySetTextureProperties(out_mat, textures, "EmissiveColor", aiTextureType_EMISSIVE);
  615. TrySetTextureProperties(out_mat, textures, "SpecularColor", aiTextureType_SPECULAR);
  616. TrySetTextureProperties(out_mat, textures, "TransparentColor", aiTextureType_OPACITY);
  617. TrySetTextureProperties(out_mat, textures, "ReflectionColor", aiTextureType_REFLECTION);
  618. TrySetTextureProperties(out_mat, textures, "DisplacementColor", aiTextureType_DISPLACEMENT);
  619. TrySetTextureProperties(out_mat, textures, "NormalMap", aiTextureType_NORMALS);
  620. TrySetTextureProperties(out_mat, textures, "Bump", aiTextureType_HEIGHT);
  621. }
  622. // ------------------------------------------------------------------------------------------------
  623. aiColor3D GetColorPropertyFromMaterial(const PropertyTable& props,const std::string& baseName, bool& result)
  624. {
  625. result = true;
  626. bool ok;
  627. const aiVector3D& Diffuse = PropertyGet<aiVector3D>(props,baseName,ok);
  628. if(ok) {
  629. return aiColor3D(Diffuse.x,Diffuse.y,Diffuse.z);
  630. }
  631. else {
  632. aiVector3D DiffuseColor = PropertyGet<aiVector3D>(props,baseName + "Color",ok);
  633. if(ok) {
  634. float DiffuseFactor = PropertyGet<float>(props,baseName + "Factor",ok);
  635. if(ok) {
  636. DiffuseColor *= DiffuseFactor;
  637. }
  638. return aiColor3D(DiffuseColor.x,DiffuseColor.y,DiffuseColor.z);
  639. }
  640. }
  641. result = false;
  642. return aiColor3D(0.0f,0.0f,0.0f);
  643. }
  644. // ------------------------------------------------------------------------------------------------
  645. void SetShadingPropertiesCommon(aiMaterial* out_mat, const PropertyTable& props)
  646. {
  647. // set shading properties. There are various, redundant ways in which FBX materials
  648. // specify their shading settings (depending on shading models, prop
  649. // template etc.). No idea which one is right in a particular context.
  650. // Just try to make sense of it - there's no spec to verify this against,
  651. // so why should we.
  652. bool ok;
  653. const aiColor3D& Diffuse = GetColorPropertyFromMaterial(props,"Diffuse",ok);
  654. if(ok) {
  655. out_mat->AddProperty(&Diffuse,1,AI_MATKEY_COLOR_DIFFUSE);
  656. }
  657. const aiColor3D& Emissive = GetColorPropertyFromMaterial(props,"Emissive",ok);
  658. if(ok) {
  659. out_mat->AddProperty(&Emissive,1,AI_MATKEY_COLOR_EMISSIVE);
  660. }
  661. const aiColor3D& Ambient = GetColorPropertyFromMaterial(props,"Ambient",ok);
  662. if(ok) {
  663. out_mat->AddProperty(&Ambient,1,AI_MATKEY_COLOR_AMBIENT);
  664. }
  665. const aiColor3D& Specular = GetColorPropertyFromMaterial(props,"Specular",ok);
  666. if(ok) {
  667. out_mat->AddProperty(&Specular,1,AI_MATKEY_COLOR_SPECULAR);
  668. }
  669. const float Opacity = PropertyGet<float>(props,"Opacity",ok);
  670. if(ok) {
  671. out_mat->AddProperty(&Opacity,1,AI_MATKEY_OPACITY);
  672. }
  673. const float Reflectivity = PropertyGet<float>(props,"Reflectivity",ok);
  674. if(ok) {
  675. out_mat->AddProperty(&Reflectivity,1,AI_MATKEY_REFLECTIVITY);
  676. }
  677. const float Shininess = PropertyGet<float>(props,"Shininess",ok);
  678. if(ok) {
  679. out_mat->AddProperty(&Shininess,1,AI_MATKEY_SHININESS_STRENGTH);
  680. }
  681. const float ShininessExponent = PropertyGet<float>(props,"ShininessExponent",ok);
  682. if(ok) {
  683. out_mat->AddProperty(&ShininessExponent,1,AI_MATKEY_SHININESS);
  684. }
  685. }
  686. // ------------------------------------------------------------------------------------------------
  687. // convert animation data to aiAnimation et al
  688. void ConvertAnimations()
  689. {
  690. const std::vector<const AnimationStack*>& animations = doc.AnimationStacks();
  691. BOOST_FOREACH(const AnimationStack* stack, animations) {
  692. ConvertAnimationStack(*stack);
  693. }
  694. }
  695. // name -> prefix_stripped?
  696. typedef std::map<std::string, bool> NodeNameMap;
  697. NodeNameMap node_names;
  698. // ------------------------------------------------------------------------------------------------
  699. std::string FixNodeName(const std::string& name)
  700. {
  701. // strip Model:: prefix, avoiding ambiguities (i.e. don't strip if
  702. // this causes ambiguities, well possible between empty identifiers,
  703. // such as "Model::" and ""). Make sure the behaviour is consistent
  704. // across multiple calls to FixNodeName().
  705. if(name.substr(0,7) == "Model::") {
  706. std::string temp = name.substr(7);
  707. const NodeNameMap::const_iterator it = node_names.find(temp);
  708. if (it != node_names.end()) {
  709. if (!(*it).second) {
  710. return FixNodeName(name + "_");
  711. }
  712. }
  713. node_names[temp] = true;
  714. return temp;
  715. }
  716. const NodeNameMap::const_iterator it = node_names.find(name);
  717. if (it != node_names.end()) {
  718. if ((*it).second) {
  719. return FixNodeName(name + "_");
  720. }
  721. }
  722. node_names[name] = false;
  723. return name;
  724. }
  725. typedef std::map<const AnimationCurveNode*, const AnimationLayer*> LayerMap;
  726. // ------------------------------------------------------------------------------------------------
  727. void ConvertAnimationStack(const AnimationStack& st)
  728. {
  729. aiAnimation* const anim = new aiAnimation();
  730. animations.push_back(anim);
  731. // strip AnimationStack:: prefix
  732. std::string name = st.Name();
  733. if(name.substr(0,16) == "AnimationStack::") {
  734. name = name.substr(16);
  735. }
  736. anim->mName.Set(name);
  737. const AnimationLayerList& layers = st.Layers();
  738. // need to find all nodes for which we need to generate node animations -
  739. // it may happen that we need to merge multiple layers, though.
  740. // XXX: better use multi_map ..
  741. typedef std::map<std::string, std::vector<const AnimationCurveNode*> > NodeMap;
  742. NodeMap node_map;
  743. // reverse mapping from curves to layers, much faster than querying
  744. // the FBX DOM for it.
  745. LayerMap layer_map;
  746. BOOST_FOREACH(const AnimationLayer* layer, layers) {
  747. ai_assert(layer);
  748. const AnimationCurveNodeList& nodes = layer->Nodes();
  749. BOOST_FOREACH(const AnimationCurveNode* node, nodes) {
  750. ai_assert(node);
  751. const Model* const model = dynamic_cast<const Model*>(node->Target());
  752. // this can happen - it could also be a NodeAttribute (i.e. for camera animations)
  753. if(!model) {
  754. continue;
  755. }
  756. const std::string& name = FixNodeName(model->Name());
  757. node_map[name].push_back(node);
  758. layer_map[node] = layer;
  759. }
  760. }
  761. // generate node animations
  762. std::vector<aiNodeAnim*> node_anims;
  763. double min_time = 1e10;
  764. double max_time = -1e10;
  765. try {
  766. NodeMap node_property_map;
  767. BOOST_FOREACH(const NodeMap::value_type& kv, node_map) {
  768. node_property_map.clear();
  769. ai_assert(kv.second.size());
  770. const AnimationCurveNode* curve_node;
  771. BOOST_FOREACH(const AnimationCurveNode* node, kv.second) {
  772. ai_assert(node);
  773. if (node->TargetProperty().empty()) {
  774. FBXImporter::LogWarn("target property for animation curve not set");
  775. continue;
  776. }
  777. curve_node = node;
  778. if (node->Curves().empty()) {
  779. FBXImporter::LogWarn("no animation curves assigned to AnimationCurveNode");
  780. continue;
  781. }
  782. node_property_map[node->TargetProperty()].push_back(node);
  783. }
  784. ai_assert(curve_node);
  785. const NodeMap::const_iterator itScale = node_property_map.find("Lcl Scaling");
  786. const NodeMap::const_iterator itRotation = node_property_map.find("Lcl Rotation");
  787. const NodeMap::const_iterator itTranslation = node_property_map.find("Lcl Translation");
  788. const bool hasScale = itScale != node_property_map.end();
  789. const bool hasRotation = itRotation != node_property_map.end();
  790. const bool hasTranslation = itTranslation != node_property_map.end();
  791. if (!hasScale && !hasRotation && !hasTranslation) {
  792. FBXImporter::LogWarn("ignoring node animation, did not find transformation key frames");
  793. continue;
  794. }
  795. aiNodeAnim* const na = new aiNodeAnim();
  796. node_anims.push_back(na);
  797. na->mNodeName.Set(kv.first);
  798. ai_assert(curve_node->TargetAsModel());
  799. const PropertyTable& props = curve_node->TargetAsModel()->Props();
  800. // if a particular transformation is not given, grab it from
  801. // the corresponding node to meet the semantics of aiNodeAnim,
  802. // which requires all of rotation, scaling and translation
  803. // to be set.
  804. if(hasScale) {
  805. ConvertScaleKeys(na, (*itScale).second, layer_map,
  806. max_time, min_time);
  807. }
  808. else {
  809. na->mScalingKeys = new aiVectorKey[1];
  810. na->mNumScalingKeys = 1;
  811. na->mScalingKeys[0].mTime = 0.;
  812. na->mScalingKeys[0].mValue = PropertyGet(props,"Lcl Scaling",aiVector3D(1.f,1.f,1.f));
  813. }
  814. if(hasRotation) {
  815. ConvertRotationKeys(na, (*itRotation).second, layer_map,
  816. max_time, min_time);
  817. }
  818. else {
  819. na->mRotationKeys = new aiQuatKey[1];
  820. na->mNumRotationKeys = 1;
  821. na->mRotationKeys[0].mTime = 0.;
  822. na->mRotationKeys[0].mValue = EulerToQuaternion(
  823. PropertyGet(props,"Lcl Rotation",aiVector3D(0.f,0.f,0.f))
  824. );
  825. }
  826. if(hasTranslation) {
  827. ConvertTranslationKeys(na, (*itTranslation).second, layer_map,
  828. max_time, min_time);
  829. }
  830. else {
  831. na->mPositionKeys = new aiVectorKey[1];
  832. na->mNumPositionKeys = 1;
  833. na->mPositionKeys[0].mTime = 0.;
  834. na->mPositionKeys[0].mValue = PropertyGet(props,"Lcl Translation",aiVector3D(0.f,0.f,0.f));
  835. }
  836. }
  837. }
  838. catch(std::exception&) {
  839. std::for_each(node_anims.begin(), node_anims.end(), Util::delete_fun<aiNodeAnim>());
  840. throw;
  841. }
  842. if(node_anims.size()) {
  843. anim->mChannels = new aiNodeAnim*[node_anims.size()]();
  844. anim->mNumChannels = static_cast<unsigned int>(node_anims.size());
  845. std::swap_ranges(node_anims.begin(),node_anims.end(),anim->mChannels);
  846. }
  847. // for some mysterious reason, mDuration is simply the maximum key -- the
  848. // validator always assumes animations to start at zero.
  849. anim->mDuration = max_time /*- min_time */;
  850. anim->mTicksPerSecond = 1000.0;
  851. }
  852. // key (time), value, mapto (component index)
  853. typedef boost::tuple< const KeyTimeList*, const KeyValueList*, unsigned int > KeyFrameList;
  854. typedef std::vector<KeyFrameList> KeyFrameListList;
  855. // ------------------------------------------------------------------------------------------------
  856. KeyFrameListList GetKeyframeList(const std::vector<const AnimationCurveNode*>& nodes)
  857. {
  858. KeyFrameListList inputs;
  859. inputs.reserve(nodes.size()*3);
  860. BOOST_FOREACH(const AnimationCurveNode* node, nodes) {
  861. ai_assert(node);
  862. const AnimationCurveMap& curves = node->Curves();
  863. BOOST_FOREACH(const AnimationCurveMap::value_type& kv, curves) {
  864. unsigned int mapto;
  865. if (kv.first == "d|X") {
  866. mapto = 0;
  867. }
  868. else if (kv.first == "d|Y") {
  869. mapto = 1;
  870. }
  871. else if (kv.first == "d|Z") {
  872. mapto = 2;
  873. }
  874. else {
  875. FBXImporter::LogWarn("ignoring scale animation curve, did not recognize target component");
  876. continue;
  877. }
  878. const AnimationCurve* const curve = kv.second;
  879. ai_assert(curve->GetKeys().size() == curve->GetValues().size() && curve->GetKeys().size());
  880. inputs.push_back(boost::make_tuple(&curve->GetKeys(), &curve->GetValues(), mapto));
  881. }
  882. }
  883. return inputs; // pray for NRVO :-)
  884. }
  885. // ------------------------------------------------------------------------------------------------
  886. KeyTimeList GetKeyTimeList(const KeyFrameListList& inputs)
  887. {
  888. ai_assert(inputs.size());
  889. // reserve some space upfront - it is likely that the keyframe lists
  890. // have matching time values, so max(of all keyframe lists) should
  891. // be a good estimate.
  892. KeyTimeList keys;
  893. size_t estimate = 0;
  894. BOOST_FOREACH(const KeyFrameList& kfl, inputs) {
  895. estimate = std::max(estimate, kfl.get<0>()->size());
  896. }
  897. keys.reserve(estimate);
  898. std::vector<unsigned int> next_pos;
  899. next_pos.resize(inputs.size(),0);
  900. const size_t count = inputs.size();
  901. while(true) {
  902. uint64_t min_tick = std::numeric_limits<uint64_t>::max();
  903. for (size_t i = 0; i < count; ++i) {
  904. const KeyFrameList& kfl = inputs[i];
  905. if (kfl.get<0>()->size() > next_pos[i] && kfl.get<0>()->at(next_pos[i]) < min_tick) {
  906. min_tick = kfl.get<0>()->at(next_pos[i]);
  907. }
  908. }
  909. if (min_tick == std::numeric_limits<uint64_t>::max()) {
  910. break;
  911. }
  912. keys.push_back(min_tick);
  913. for (size_t i = 0; i < count; ++i) {
  914. const KeyFrameList& kfl = inputs[i];
  915. while(kfl.get<0>()->size() > next_pos[i] && kfl.get<0>()->at(next_pos[i]) == min_tick) {
  916. ++next_pos[i];
  917. }
  918. }
  919. }
  920. return keys;
  921. }
  922. // ------------------------------------------------------------------------------------------------
  923. void InterpolateKeys(aiVectorKey* valOut,const KeyTimeList& keys, const KeyFrameListList& inputs, const bool geom,
  924. double& maxTime,
  925. double& minTime)
  926. {
  927. ai_assert(keys.size());
  928. ai_assert(valOut);
  929. std::vector<unsigned int> next_pos;
  930. const size_t count = inputs.size();
  931. next_pos.resize(inputs.size(),0);
  932. BOOST_FOREACH(KeyTimeList::value_type time, keys) {
  933. float result[3] = {0.0f, 0.0f, 0.0f};
  934. if(geom) {
  935. result[0] = result[1] = result[2] = 1.0f;
  936. }
  937. for (size_t i = 0; i < count; ++i) {
  938. const KeyFrameList& kfl = inputs[i];
  939. const size_t ksize = kfl.get<0>()->size();
  940. if (ksize > next_pos[i] && kfl.get<0>()->at(next_pos[i]) == time) {
  941. ++next_pos[i];
  942. }
  943. const size_t id0 = next_pos[i]>0 ? next_pos[i]-1 : 0;
  944. const size_t id1 = next_pos[i]==ksize ? ksize-1 : next_pos[i];
  945. // use lerp for interpolation
  946. const KeyValueList::value_type valueA = kfl.get<1>()->at(id0);
  947. const KeyValueList::value_type valueB = kfl.get<1>()->at(id1);
  948. const KeyTimeList::value_type timeA = kfl.get<0>()->at(id0);
  949. const KeyTimeList::value_type timeB = kfl.get<0>()->at(id1);
  950. // do the actual interpolation in double-precision arithmetics
  951. // because it is a bit sensitive to rounding errors.
  952. const double factor = timeB == timeA ? 0. : static_cast<double>((time - timeA) / (timeB - timeA));
  953. const float interpValue = static_cast<float>(valueA + (valueB - valueA) * factor);
  954. if(geom) {
  955. result[kfl.get<2>()] *= interpValue;
  956. }
  957. else {
  958. result[kfl.get<2>()] += interpValue;
  959. }
  960. }
  961. // magic value to convert fbx times to milliseconds
  962. valOut->mTime = static_cast<double>(time) / 46186158;
  963. minTime = std::min(minTime, valOut->mTime);
  964. maxTime = std::max(maxTime, valOut->mTime);
  965. valOut->mValue.x = result[0];
  966. valOut->mValue.y = result[1];
  967. valOut->mValue.z = result[2];
  968. ++valOut;
  969. }
  970. }
  971. // ------------------------------------------------------------------------------------------------
  972. void InterpolateKeys(aiQuatKey* valOut,const KeyTimeList& keys, const KeyFrameListList& inputs, const bool geom,
  973. double& maxTime,
  974. double& minTime)
  975. {
  976. ai_assert(keys.size());
  977. ai_assert(valOut);
  978. boost::scoped_array<aiVectorKey> temp(new aiVectorKey[keys.size()]);
  979. InterpolateKeys(temp.get(),keys,inputs,geom,maxTime, minTime);
  980. for (size_t i = 0, c = keys.size(); i < c; ++i) {
  981. valOut[i].mTime = temp[i].mTime;
  982. valOut[i].mValue = EulerToQuaternion(temp[i].mValue);
  983. }
  984. }
  985. // ------------------------------------------------------------------------------------------------
  986. // euler xyz -> quat
  987. aiQuaternion EulerToQuaternion(const aiVector3D& rot)
  988. {
  989. aiMatrix4x4 m, mtemp;
  990. if(fabs(rot.x) > 1e-6f) {
  991. m *= aiMatrix4x4::RotationX(rot.x,mtemp);
  992. }
  993. if(fabs(rot.y) > 1e-6f) {
  994. m *= aiMatrix4x4::RotationY(rot.y,mtemp);
  995. }
  996. if(fabs(rot.z) > 1e-6f) {
  997. m *= aiMatrix4x4::RotationZ(rot.z,mtemp);
  998. }
  999. return aiQuaternion(aiMatrix3x3(m));
  1000. }
  1001. // ------------------------------------------------------------------------------------------------
  1002. void ConvertScaleKeys(aiNodeAnim* na, const std::vector<const AnimationCurveNode*>& nodes, const LayerMap& layers,
  1003. double& maxTime,
  1004. double& minTime)
  1005. {
  1006. ai_assert(nodes.size());
  1007. // XXX for now, assume scale should be blended geometrically (i.e. two
  1008. // layers should be multiplied with each other). There is a FBX
  1009. // property in the layer to specify the behaviour, though.
  1010. const KeyFrameListList& inputs = GetKeyframeList(nodes);
  1011. const KeyTimeList& keys = GetKeyTimeList(inputs);
  1012. na->mNumScalingKeys = static_cast<unsigned int>(keys.size());
  1013. na->mScalingKeys = new aiVectorKey[keys.size()];
  1014. InterpolateKeys(na->mScalingKeys, keys, inputs, true, maxTime, minTime);
  1015. }
  1016. // ------------------------------------------------------------------------------------------------
  1017. void ConvertTranslationKeys(aiNodeAnim* na, const std::vector<const AnimationCurveNode*>& nodes, const LayerMap& layers,
  1018. double& maxTime,
  1019. double& minTime)
  1020. {
  1021. ai_assert(nodes.size());
  1022. // XXX see notes in ConvertScaleKeys()
  1023. const KeyFrameListList& inputs = GetKeyframeList(nodes);
  1024. const KeyTimeList& keys = GetKeyTimeList(inputs);
  1025. na->mNumPositionKeys = static_cast<unsigned int>(keys.size());
  1026. na->mPositionKeys = new aiVectorKey[keys.size()];
  1027. InterpolateKeys(na->mPositionKeys, keys, inputs, false, maxTime, minTime);
  1028. }
  1029. // ------------------------------------------------------------------------------------------------
  1030. void ConvertRotationKeys(aiNodeAnim* na, const std::vector<const AnimationCurveNode*>& nodes, const LayerMap& layers,
  1031. double& maxTime,
  1032. double& minTime)
  1033. {
  1034. ai_assert(nodes.size());
  1035. // XXX see notes in ConvertScaleKeys()
  1036. const std::vector< KeyFrameList >& inputs = GetKeyframeList(nodes);
  1037. const KeyTimeList& keys = GetKeyTimeList(inputs);
  1038. na->mNumRotationKeys = static_cast<unsigned int>(keys.size());
  1039. na->mRotationKeys = new aiQuatKey[keys.size()];
  1040. InterpolateKeys(na->mRotationKeys, keys, inputs, false, maxTime, minTime);
  1041. }
  1042. // ------------------------------------------------------------------------------------------------
  1043. // copy generated meshes, animations, lights, cameras and textures to the output scene
  1044. void TransferDataToScene()
  1045. {
  1046. ai_assert(!out->mMeshes && !out->mNumMeshes);
  1047. // note: the trailing () ensures initialization with NULL - not
  1048. // many C++ users seem to know this, so pointing it out to avoid
  1049. // confusion why this code works.
  1050. out->mMeshes = new aiMesh*[meshes.size()]();
  1051. out->mNumMeshes = static_cast<unsigned int>(meshes.size());
  1052. std::swap_ranges(meshes.begin(),meshes.end(),out->mMeshes);
  1053. if(materials.size()) {
  1054. out->mMaterials = new aiMaterial*[materials.size()]();
  1055. out->mNumMaterials = static_cast<unsigned int>(materials.size());
  1056. std::swap_ranges(materials.begin(),materials.end(),out->mMaterials);
  1057. }
  1058. if(animations.size()) {
  1059. out->mAnimations = new aiAnimation*[animations.size()]();
  1060. out->mNumAnimations = static_cast<unsigned int>(animations.size());
  1061. std::swap_ranges(animations.begin(),animations.end(),out->mAnimations);
  1062. }
  1063. }
  1064. private:
  1065. // 0: not assigned yet, others: index is value - 1
  1066. unsigned int defaultMaterialIndex;
  1067. std::vector<aiMesh*> meshes;
  1068. std::vector<aiMaterial*> materials;
  1069. std::vector<aiAnimation*> animations;
  1070. typedef std::map<const Material*, unsigned int> MaterialMap;
  1071. MaterialMap materials_converted;
  1072. typedef std::map<const Geometry*, std::vector<unsigned int> > MeshMap;
  1073. MeshMap meshes_converted;
  1074. aiScene* const out;
  1075. const FBX::Document& doc;
  1076. };
  1077. //} // !anon
  1078. // ------------------------------------------------------------------------------------------------
  1079. void ConvertToAssimpScene(aiScene* out, const Document& doc)
  1080. {
  1081. Converter converter(out,doc);
  1082. }
  1083. } // !FBX
  1084. } // !Assimp
  1085. #endif