FBXConverter.cpp 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887
  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. #define MAGIC_NODE_TAG "_$AssimpFbx$"
  49. // XXX vc9's debugger won't step into anonymous namespaces
  50. //namespace {
  51. /** Dummy class to encapsulate the conversion process */
  52. class Converter
  53. {
  54. public:
  55. Converter(aiScene* out, const Document& doc)
  56. : out(out)
  57. , doc(doc)
  58. {
  59. ConvertRootNode();
  60. ConvertAnimations();
  61. if(doc.Settings().readAllMaterials) {
  62. // unfortunately this means we have to evaluate all objects
  63. BOOST_FOREACH(const ObjectMap::value_type& v,doc.Objects()) {
  64. const Object* ob = v.second->Get();
  65. if(!ob) {
  66. continue;
  67. }
  68. const Material* mat = dynamic_cast<const Material*>(ob);
  69. if(mat) {
  70. if (materials_converted.find(mat) == materials_converted.end()) {
  71. ConvertMaterial(*mat);
  72. }
  73. }
  74. }
  75. }
  76. TransferDataToScene();
  77. }
  78. ~Converter()
  79. {
  80. std::for_each(meshes.begin(),meshes.end(),Util::delete_fun<aiMesh>());
  81. std::for_each(materials.begin(),materials.end(),Util::delete_fun<aiMaterial>());
  82. std::for_each(animations.begin(),animations.end(),Util::delete_fun<aiAnimation>());
  83. }
  84. private:
  85. // ------------------------------------------------------------------------------------------------
  86. // find scene root and trigger recursive scene conversion
  87. void ConvertRootNode()
  88. {
  89. out->mRootNode = new aiNode();
  90. out->mRootNode->mName.Set("RootNode");
  91. // root has ID 0
  92. ConvertNodes(0L, *out->mRootNode);
  93. }
  94. // ------------------------------------------------------------------------------------------------
  95. // collect and assign child nodes
  96. void ConvertNodes(uint64_t id, aiNode& parent)
  97. {
  98. const std::vector<const Connection*>& conns = doc.GetConnectionsByDestinationSequenced(id, "Model");
  99. std::vector<aiNode*> nodes;
  100. nodes.reserve(conns.size());
  101. std::vector<aiNode*> nodes_chain;
  102. try {
  103. BOOST_FOREACH(const Connection* con, conns) {
  104. // ignore object-property links
  105. if(con->PropertyName().length()) {
  106. continue;
  107. }
  108. const Object* const object = con->SourceObject();
  109. if(!object) {
  110. FBXImporter::LogWarn("failed to convert source object for Model link");
  111. continue;
  112. }
  113. const Model* const model = dynamic_cast<const Model*>(object);
  114. if(model) {
  115. nodes_chain.clear();
  116. GenerateTransformationNodeChain(*model,nodes_chain);
  117. ai_assert(nodes_chain.size());
  118. // link all nodes in a row
  119. aiNode* last_parent = &parent;
  120. BOOST_FOREACH(aiNode* prenode, nodes_chain) {
  121. ai_assert(prenode);
  122. prenode->mParent = last_parent;
  123. last_parent = prenode;
  124. }
  125. // attach geometry
  126. ConvertModel(*model, *nodes_chain.back());
  127. // attach sub-nodes
  128. ConvertNodes(model->ID(), *last_parent);
  129. nodes.push_back(nodes_chain.back());
  130. }
  131. }
  132. if(nodes.size()) {
  133. parent.mChildren = new aiNode*[nodes.size()]();
  134. parent.mNumChildren = static_cast<unsigned int>(nodes.size());
  135. std::swap_ranges(nodes.begin(),nodes.end(),parent.mChildren);
  136. }
  137. }
  138. catch(std::exception&) {
  139. Util::delete_fun<aiNode> deleter;
  140. std::for_each(nodes.begin(),nodes.end(),deleter);
  141. std::for_each(nodes_chain.begin(),nodes_chain.end(),deleter);
  142. }
  143. }
  144. /** the different parts that make up the final local transformation of a fbx node */
  145. enum TransformationComp
  146. {
  147. TransformationComp_Translation = 0,
  148. TransformationComp_RotationOffset,
  149. TransformationComp_RotationPivot,
  150. TransformationComp_PreRotation,
  151. TransformationComp_Rotation,
  152. TransformationComp_PostRotation,
  153. TransformationComp_RotationPivotInverse,
  154. TransformationComp_ScalingOffset,
  155. TransformationComp_ScalingPivot,
  156. TransformationComp_Scaling,
  157. TransformationComp_ScalingPivotInverse,
  158. TransformationComp_MAXIMUM
  159. };
  160. // ------------------------------------------------------------------------------------------------
  161. // this returns unified names usable within assimp identifiers (i.e. no space characters -
  162. // while these would be allowed, they are a potential trouble spot so better not use them).
  163. const char* NameTransformationComp(TransformationComp comp)
  164. {
  165. switch(comp)
  166. {
  167. case TransformationComp_Translation:
  168. return "Translation";
  169. case TransformationComp_RotationOffset:
  170. return "RotationOffset";
  171. case TransformationComp_RotationPivot:
  172. return "RotationPivot";
  173. case TransformationComp_PreRotation:
  174. return "PreRotation";
  175. case TransformationComp_Rotation:
  176. return "Rotation";
  177. case TransformationComp_PostRotation:
  178. return "PostRotation";
  179. case TransformationComp_RotationPivotInverse:
  180. return "RotationPivotInverse";
  181. case TransformationComp_ScalingOffset:
  182. return "ScalingOffset";
  183. case TransformationComp_ScalingPivot:
  184. return "ScalingPivot";
  185. case TransformationComp_Scaling:
  186. return "Scaling";
  187. case TransformationComp_ScalingPivotInverse:
  188. return "ScalingPivotInverse";
  189. }
  190. ai_assert(false);
  191. return NULL;
  192. }
  193. // ------------------------------------------------------------------------------------------------
  194. // note: this returns the REAL fbx property names
  195. const char* NameTransformationCompProperty(TransformationComp comp)
  196. {
  197. switch(comp)
  198. {
  199. case TransformationComp_Translation:
  200. return "Lcl Translation";
  201. case TransformationComp_RotationOffset:
  202. return "RotationOffset";
  203. case TransformationComp_RotationPivot:
  204. return "RotationPivot";
  205. case TransformationComp_PreRotation:
  206. return "PreRotation";
  207. case TransformationComp_Rotation:
  208. return "Lcl Rotation";
  209. case TransformationComp_PostRotation:
  210. return "PostRotation";
  211. case TransformationComp_RotationPivotInverse:
  212. return "RotationPivotInverse";
  213. case TransformationComp_ScalingOffset:
  214. return "ScalingOffset";
  215. case TransformationComp_ScalingPivot:
  216. return "ScalingPivot";
  217. case TransformationComp_Scaling:
  218. return "Lcl Scaling";
  219. case TransformationComp_ScalingPivotInverse:
  220. return "ScalingPivotInverse";
  221. }
  222. ai_assert(false);
  223. return NULL;
  224. }
  225. enum RotationMode
  226. {
  227. RotationMode_Euler_XYZ
  228. };
  229. // ------------------------------------------------------------------------------------------------
  230. void GetRotationMatrix(RotationMode mode, const aiVector3D& rotation, aiMatrix4x4& out)
  231. {
  232. const float angle_epsilon = 1e-6f;
  233. aiMatrix4x4 temp;
  234. out = aiMatrix4x4();
  235. switch(mode)
  236. {
  237. case RotationMode_Euler_XYZ:
  238. if(fabs(rotation.x) > angle_epsilon) {
  239. out *= aiMatrix4x4::RotationX(rotation.x,temp);
  240. }
  241. if(fabs(rotation.y) > angle_epsilon) {
  242. out *= aiMatrix4x4::RotationY(rotation.y,temp);
  243. }
  244. if(fabs(rotation.z) > angle_epsilon) {
  245. out *= aiMatrix4x4::RotationZ(rotation.z,temp);
  246. }
  247. return;
  248. }
  249. ai_assert(false);
  250. }
  251. // ------------------------------------------------------------------------------------------------
  252. /** checks if a node has more than just scaling, rotation and translation components */
  253. bool NeedsComplexTransformationChain(const Model& model)
  254. {
  255. const PropertyTable& props = model.Props();
  256. bool ok;
  257. const float zero_epsilon = 1e-6f;
  258. for (size_t i = 0; i < TransformationComp_MAXIMUM; ++i) {
  259. const TransformationComp comp = static_cast<TransformationComp>(i);
  260. if(comp == TransformationComp_Rotation || comp == TransformationComp_Scaling || comp == TransformationComp_Translation) {
  261. continue;
  262. }
  263. const aiVector3D& v = PropertyGet<aiVector3D>(props,NameTransformationCompProperty(comp),ok);
  264. if(ok && v.SquareLength() > zero_epsilon) {
  265. return true;
  266. }
  267. }
  268. return false;
  269. }
  270. // ------------------------------------------------------------------------------------------------
  271. /** note: memory for output_nodes will be managed by the caller */
  272. void GenerateTransformationNodeChain(const Model& model,
  273. std::vector<aiNode*>& output_nodes)
  274. {
  275. const PropertyTable& props = model.Props();
  276. // XXX handle different rotation modes
  277. const RotationMode rot = RotationMode_Euler_XYZ;
  278. bool ok;
  279. aiMatrix4x4 chain[TransformationComp_MAXIMUM];
  280. std::fill_n(chain, static_cast<unsigned int>(TransformationComp_MAXIMUM), aiMatrix4x4());
  281. // generate transformation matrices for all the different transformation components
  282. const float zero_epsilon = 1e-6f;
  283. bool is_complex = false;
  284. const aiVector3D& PreRotation = PropertyGet<aiVector3D>(props,"PreRotation",ok);
  285. if(ok && PreRotation.SquareLength() > zero_epsilon) {
  286. is_complex = true;
  287. GetRotationMatrix(rot, PreRotation, chain[TransformationComp_PreRotation]);
  288. }
  289. const aiVector3D& PostRotation = PropertyGet<aiVector3D>(props,"PostRotation",ok);
  290. if(ok && PostRotation.SquareLength() > zero_epsilon) {
  291. is_complex = true;
  292. GetRotationMatrix(rot, PostRotation, chain[TransformationComp_PostRotation]);
  293. }
  294. const aiVector3D& RotationPivot = PropertyGet<aiVector3D>(props,"RotationPivot",ok);
  295. if(ok && RotationPivot.SquareLength() > zero_epsilon) {
  296. is_complex = true;
  297. aiMatrix4x4::Translation(RotationPivot,chain[TransformationComp_RotationPivot]);
  298. aiMatrix4x4::Translation(-RotationPivot,chain[TransformationComp_RotationPivotInverse]);
  299. }
  300. const aiVector3D& RotationOffset = PropertyGet<aiVector3D>(props,"RotationOffset",ok);
  301. if(ok && RotationOffset.SquareLength() > zero_epsilon) {
  302. is_complex = true;
  303. aiMatrix4x4::Translation(RotationOffset,chain[TransformationComp_RotationOffset]);
  304. }
  305. const aiVector3D& ScalingOffset = PropertyGet<aiVector3D>(props,"ScalingOffset",ok);
  306. if(ok && ScalingOffset.SquareLength() > zero_epsilon) {
  307. is_complex = true;
  308. aiMatrix4x4::Translation(ScalingOffset,chain[TransformationComp_ScalingOffset]);
  309. }
  310. const aiVector3D& ScalingPivot = PropertyGet<aiVector3D>(props,"ScalingPivot",ok);
  311. if(ok && ScalingPivot.SquareLength() > zero_epsilon) {
  312. is_complex = true;
  313. aiMatrix4x4::Translation(ScalingPivot,chain[TransformationComp_ScalingPivot]);
  314. aiMatrix4x4::Translation(-ScalingPivot,chain[TransformationComp_ScalingPivotInverse]);
  315. }
  316. const aiVector3D& Translation = PropertyGet<aiVector3D>(props,"Lcl Translation",ok);
  317. if(ok && Translation.SquareLength() > zero_epsilon) {
  318. aiMatrix4x4::Translation(Translation,chain[TransformationComp_Translation]);
  319. }
  320. const aiVector3D& Scaling = PropertyGet<aiVector3D>(props,"Lcl Scaling",ok);
  321. if(ok && fabs(Scaling.SquareLength()-1.0f) > zero_epsilon) {
  322. aiMatrix4x4::Scaling(Scaling,chain[TransformationComp_Scaling]);
  323. }
  324. const aiVector3D& Rotation = PropertyGet<aiVector3D>(props,"Lcl Rotation",ok);
  325. if(ok && Translation.SquareLength() > zero_epsilon) {
  326. GetRotationMatrix(rot, Rotation, chain[TransformationComp_Rotation]);
  327. }
  328. // is_complex needs to be consistent with NeedsComplexTransformationChain()
  329. // or the interplay between this code and the animation converter would
  330. // not be guaranteed.
  331. ai_assert(NeedsComplexTransformationChain(model) == is_complex);
  332. const std::string& name = FixNodeName(model.Name());
  333. // now, if we have more than just Translation, Scaling and Rotation,
  334. // we need to generate a full node chain to accommodate for assimp's
  335. // lack to express pivots and offsets.
  336. if(is_complex && doc.Settings().preservePivots) {
  337. FBXImporter::LogInfo("generating full transformation chain for node: " + name);
  338. const std::string mid = std::string(MAGIC_NODE_TAG) + "_";
  339. for (size_t i = 0; i < TransformationComp_MAXIMUM; ++i) {
  340. // XXX this may cause trouble with animations
  341. if (chain[i].IsIdentity()) {
  342. continue;
  343. }
  344. aiNode* nd = new aiNode();
  345. output_nodes.push_back(nd);
  346. nd->mName.Set(name + mid + NameTransformationComp(static_cast<TransformationComp>(i)));
  347. nd->mTransformation = chain[i];
  348. }
  349. ai_assert(output_nodes.size());
  350. return;
  351. }
  352. // else, we can just multiply the matrices together
  353. aiNode* nd = new aiNode();
  354. output_nodes.push_back(nd);
  355. nd->mName.Set(name);
  356. for (size_t i = 0; i < TransformationComp_MAXIMUM; ++i) {
  357. nd->mTransformation *= chain[i];
  358. }
  359. }
  360. // ------------------------------------------------------------------------------------------------
  361. void ConvertModel(const Model& model, aiNode& nd)
  362. {
  363. const std::vector<const Geometry*>& geos = model.GetGeometry();
  364. std::vector<unsigned int> meshes;
  365. meshes.reserve(geos.size());
  366. BOOST_FOREACH(const Geometry* geo, geos) {
  367. const MeshGeometry* const mesh = dynamic_cast<const MeshGeometry*>(geo);
  368. if(mesh) {
  369. const std::vector<unsigned int>& indices = ConvertMesh(*mesh, model);
  370. std::copy(indices.begin(),indices.end(),std::back_inserter(meshes) );
  371. }
  372. else {
  373. FBXImporter::LogWarn("ignoring unrecognized geometry: " + geo->Name());
  374. }
  375. }
  376. if(meshes.size()) {
  377. nd.mMeshes = new unsigned int[meshes.size()]();
  378. nd.mNumMeshes = static_cast<unsigned int>(meshes.size());
  379. std::swap_ranges(meshes.begin(),meshes.end(),nd.mMeshes);
  380. }
  381. }
  382. // ------------------------------------------------------------------------------------------------
  383. // MeshGeometry -> aiMesh, return mesh index + 1 or 0 if the conversion failed
  384. std::vector<unsigned int> ConvertMesh(const MeshGeometry& mesh, const Model& model)
  385. {
  386. std::vector<unsigned int> temp;
  387. MeshMap::const_iterator it = meshes_converted.find(&mesh);
  388. if (it != meshes_converted.end()) {
  389. std::copy((*it).second.begin(),(*it).second.end(),std::back_inserter(temp));
  390. return temp;
  391. }
  392. const std::vector<aiVector3D>& vertices = mesh.GetVertices();
  393. const std::vector<unsigned int>& faces = mesh.GetFaceIndexCounts();
  394. if(vertices.empty() || faces.empty()) {
  395. FBXImporter::LogWarn("ignoring empty geometry: " + mesh.Name());
  396. return temp;
  397. }
  398. // one material per mesh maps easily to aiMesh. Multiple material
  399. // meshes need to be split.
  400. const std::vector<unsigned int>& mindices = mesh.GetMaterialIndices();
  401. if (doc.Settings().readMaterials && !mindices.empty()) {
  402. const unsigned int base = mindices[0];
  403. BOOST_FOREACH(unsigned int index, mindices) {
  404. if(index != base) {
  405. return ConvertMeshMultiMaterial(mesh, model);
  406. }
  407. }
  408. }
  409. // faster codepath, just copy the data
  410. temp.push_back(ConvertMeshSingleMaterial(mesh, model));
  411. return temp;
  412. }
  413. // ------------------------------------------------------------------------------------------------
  414. aiMesh* SetupEmptyMesh(const MeshGeometry& mesh, unsigned int material_index)
  415. {
  416. aiMesh* const out_mesh = new aiMesh();
  417. meshes.push_back(out_mesh);
  418. meshes_converted[&mesh].push_back(static_cast<unsigned int>(meshes.size()-1));
  419. // set name
  420. std::string name = mesh.Name();
  421. if (name.substr(0,10) == "Geometry::") {
  422. name = name.substr(10);
  423. }
  424. if(name.length()) {
  425. out_mesh->mName.Set(name);
  426. }
  427. return out_mesh;
  428. }
  429. // ------------------------------------------------------------------------------------------------
  430. unsigned int ConvertMeshSingleMaterial(const MeshGeometry& mesh, const Model& model)
  431. {
  432. const std::vector<unsigned int>& mindices = mesh.GetMaterialIndices();
  433. aiMesh* const out_mesh = SetupEmptyMesh(mesh,mindices.size() ? mindices[0] : static_cast<unsigned int>(-1));
  434. const std::vector<aiVector3D>& vertices = mesh.GetVertices();
  435. const std::vector<unsigned int>& faces = mesh.GetFaceIndexCounts();
  436. // copy vertices
  437. out_mesh->mNumVertices = static_cast<unsigned int>(vertices.size());
  438. out_mesh->mVertices = new aiVector3D[vertices.size()];
  439. std::copy(vertices.begin(),vertices.end(),out_mesh->mVertices);
  440. // generate dummy faces
  441. out_mesh->mNumFaces = static_cast<unsigned int>(faces.size());
  442. aiFace* fac = out_mesh->mFaces = new aiFace[faces.size()]();
  443. unsigned int cursor = 0;
  444. BOOST_FOREACH(unsigned int pcount, faces) {
  445. aiFace& f = *fac++;
  446. f.mNumIndices = pcount;
  447. f.mIndices = new unsigned int[pcount];
  448. switch(pcount)
  449. {
  450. case 1:
  451. out_mesh->mPrimitiveTypes |= aiPrimitiveType_POINT;
  452. break;
  453. case 2:
  454. out_mesh->mPrimitiveTypes |= aiPrimitiveType_LINE;
  455. break;
  456. case 3:
  457. out_mesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  458. break;
  459. default:
  460. out_mesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  461. break;
  462. }
  463. for (unsigned int i = 0; i < pcount; ++i) {
  464. f.mIndices[i] = cursor++;
  465. }
  466. }
  467. // copy normals
  468. const std::vector<aiVector3D>& normals = mesh.GetNormals();
  469. if(normals.size()) {
  470. ai_assert(normals.size() == vertices.size());
  471. out_mesh->mNormals = new aiVector3D[vertices.size()];
  472. std::copy(normals.begin(),normals.end(),out_mesh->mNormals);
  473. }
  474. // copy tangents - assimp requires both tangents and bitangents (binormals)
  475. // to be present, or neither of them. Compute binormals from normals
  476. // and tangents if needed.
  477. const std::vector<aiVector3D>& tangents = mesh.GetTangents();
  478. const std::vector<aiVector3D>* binormals = &mesh.GetBinormals();
  479. if(tangents.size()) {
  480. std::vector<aiVector3D> tempBinormals;
  481. if (!binormals->size()) {
  482. if (normals.size()) {
  483. tempBinormals.resize(normals.size());
  484. for (unsigned int i = 0; i < tangents.size(); ++i) {
  485. tempBinormals[i] = normals[i] ^ tangents[i];
  486. }
  487. binormals = &tempBinormals;
  488. }
  489. else {
  490. binormals = NULL;
  491. }
  492. }
  493. if(binormals) {
  494. ai_assert(tangents.size() == vertices.size() && binormals->size() == vertices.size());
  495. out_mesh->mTangents = new aiVector3D[vertices.size()];
  496. std::copy(tangents.begin(),tangents.end(),out_mesh->mTangents);
  497. out_mesh->mBitangents = new aiVector3D[vertices.size()];
  498. std::copy(binormals->begin(),binormals->end(),out_mesh->mBitangents);
  499. }
  500. }
  501. // copy texture coords
  502. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  503. const std::vector<aiVector2D>& uvs = mesh.GetTextureCoords(i);
  504. if(uvs.empty()) {
  505. break;
  506. }
  507. aiVector3D* out_uv = out_mesh->mTextureCoords[i] = new aiVector3D[vertices.size()];
  508. BOOST_FOREACH(const aiVector2D& v, uvs) {
  509. *out_uv++ = aiVector3D(v.x,v.y,0.0f);
  510. }
  511. out_mesh->mNumUVComponents[i] = 2;
  512. }
  513. // copy vertex colors
  514. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_COLOR_SETS; ++i) {
  515. const std::vector<aiColor4D>& colors = mesh.GetVertexColors(i);
  516. if(colors.empty()) {
  517. break;
  518. }
  519. out_mesh->mColors[i] = new aiColor4D[vertices.size()];
  520. std::copy(colors.begin(),colors.end(),out_mesh->mColors[i]);
  521. }
  522. if(!doc.Settings().readMaterials || mindices.empty()) {
  523. FBXImporter::LogError("no material assigned to mesh, setting default material");
  524. out_mesh->mMaterialIndex = GetDefaultMaterial();
  525. }
  526. else {
  527. ConvertMaterialForMesh(out_mesh,model,mesh,mindices[0]);
  528. }
  529. if(doc.Settings().readWeights && mesh.DeformerSkin() != NULL) {
  530. ConvertWeights(out_mesh, model, mesh, NO_MATERIAL_SEPARATION);
  531. }
  532. return static_cast<unsigned int>(meshes.size() - 1);
  533. }
  534. // ------------------------------------------------------------------------------------------------
  535. std::vector<unsigned int> ConvertMeshMultiMaterial(const MeshGeometry& mesh, const Model& model)
  536. {
  537. const std::vector<unsigned int>& mindices = mesh.GetMaterialIndices();
  538. ai_assert(mindices.size());
  539. std::set<unsigned int> had;
  540. std::vector<unsigned int> indices;
  541. BOOST_FOREACH(unsigned int index, mindices) {
  542. if(had.find(index) == had.end()) {
  543. indices.push_back(ConvertMeshMultiMaterial(mesh, model, index));
  544. had.insert(index);
  545. }
  546. }
  547. return indices;
  548. }
  549. // ------------------------------------------------------------------------------------------------
  550. unsigned int ConvertMeshMultiMaterial(const MeshGeometry& mesh, const Model& model, unsigned int index)
  551. {
  552. aiMesh* const out_mesh = SetupEmptyMesh(mesh, index);
  553. const std::vector<unsigned int>& mindices = mesh.GetMaterialIndices();
  554. const std::vector<aiVector3D>& vertices = mesh.GetVertices();
  555. const std::vector<unsigned int>& faces = mesh.GetFaceIndexCounts();
  556. const bool process_weights = doc.Settings().readWeights && mesh.DeformerSkin() != NULL;
  557. unsigned int count_faces = 0;
  558. unsigned int count_vertices = 0;
  559. // count faces
  560. for(std::vector<unsigned int>::const_iterator it = mindices.begin(),
  561. end = mindices.end(), itf = faces.begin(); it != end; ++it, ++itf)
  562. {
  563. if ((*it) != index) {
  564. continue;
  565. }
  566. ++count_faces;
  567. count_vertices += *itf;
  568. }
  569. ai_assert(count_faces);
  570. ai_assert(count_vertices);
  571. // mapping from output indices to DOM indexing, needed to resolve weights
  572. std::vector<unsigned int> reverseMapping;
  573. if (process_weights) {
  574. reverseMapping.resize(count_vertices);
  575. }
  576. // allocate output data arrays, but don't fill them yet
  577. out_mesh->mNumVertices = count_vertices;
  578. out_mesh->mVertices = new aiVector3D[count_vertices];
  579. out_mesh->mNumFaces = count_faces;
  580. aiFace* fac = out_mesh->mFaces = new aiFace[count_faces]();
  581. // allocate normals
  582. const std::vector<aiVector3D>& normals = mesh.GetNormals();
  583. if(normals.size()) {
  584. ai_assert(normals.size() == vertices.size());
  585. out_mesh->mNormals = new aiVector3D[vertices.size()];
  586. }
  587. // allocate tangents, binormals.
  588. const std::vector<aiVector3D>& tangents = mesh.GetTangents();
  589. const std::vector<aiVector3D>* binormals = &mesh.GetBinormals();
  590. if(tangents.size()) {
  591. std::vector<aiVector3D> tempBinormals;
  592. if (!binormals->size()) {
  593. if (normals.size()) {
  594. // XXX this computes the binormals for the entire mesh, not only
  595. // the part for which we need them.
  596. tempBinormals.resize(normals.size());
  597. for (unsigned int i = 0; i < tangents.size(); ++i) {
  598. tempBinormals[i] = normals[i] ^ tangents[i];
  599. }
  600. binormals = &tempBinormals;
  601. }
  602. else {
  603. binormals = NULL;
  604. }
  605. }
  606. if(binormals) {
  607. ai_assert(tangents.size() == vertices.size() && binormals->size() == vertices.size());
  608. out_mesh->mTangents = new aiVector3D[vertices.size()];
  609. out_mesh->mBitangents = new aiVector3D[vertices.size()];
  610. }
  611. }
  612. // allocate texture coords
  613. unsigned int num_uvs = 0;
  614. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i, ++num_uvs) {
  615. const std::vector<aiVector2D>& uvs = mesh.GetTextureCoords(i);
  616. if(uvs.empty()) {
  617. break;
  618. }
  619. out_mesh->mTextureCoords[i] = new aiVector3D[vertices.size()];
  620. out_mesh->mNumUVComponents[i] = 2;
  621. }
  622. // allocate vertex colors
  623. unsigned int num_vcs = 0;
  624. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_COLOR_SETS; ++i, ++num_vcs) {
  625. const std::vector<aiColor4D>& colors = mesh.GetVertexColors(i);
  626. if(colors.empty()) {
  627. break;
  628. }
  629. out_mesh->mColors[i] = new aiColor4D[vertices.size()];
  630. }
  631. unsigned int cursor = 0, in_cursor = 0;
  632. for(std::vector<unsigned int>::const_iterator it = mindices.begin(),
  633. end = mindices.end(), itf = faces.begin(); it != end; ++it, ++itf)
  634. {
  635. const unsigned int pcount = *itf;
  636. if ((*it) != index) {
  637. in_cursor += pcount;
  638. continue;
  639. }
  640. aiFace& f = *fac++;
  641. f.mNumIndices = pcount;
  642. f.mIndices = new unsigned int[pcount];
  643. switch(pcount)
  644. {
  645. case 1:
  646. out_mesh->mPrimitiveTypes |= aiPrimitiveType_POINT;
  647. break;
  648. case 2:
  649. out_mesh->mPrimitiveTypes |= aiPrimitiveType_LINE;
  650. break;
  651. case 3:
  652. out_mesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  653. break;
  654. default:
  655. out_mesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  656. break;
  657. }
  658. for (unsigned int i = 0; i < pcount; ++i, ++cursor, ++in_cursor) {
  659. f.mIndices[i] = cursor;
  660. if(reverseMapping.size()) {
  661. reverseMapping[cursor] = in_cursor;
  662. }
  663. out_mesh->mVertices[cursor] = vertices[in_cursor];
  664. if(out_mesh->mNormals) {
  665. out_mesh->mNormals[cursor] = normals[in_cursor];
  666. }
  667. if(out_mesh->mTangents) {
  668. out_mesh->mTangents[cursor] = tangents[in_cursor];
  669. out_mesh->mBitangents[cursor] = (*binormals)[in_cursor];
  670. }
  671. for (unsigned int i = 0; i < num_uvs; ++i) {
  672. const std::vector<aiVector2D>& uvs = mesh.GetTextureCoords(i);
  673. out_mesh->mTextureCoords[i][cursor] = aiVector3D(uvs[in_cursor].x,uvs[in_cursor].y, 0.0f);
  674. }
  675. for (unsigned int i = 0; i < num_vcs; ++i) {
  676. const std::vector<aiColor4D>& cols = mesh.GetVertexColors(i);
  677. out_mesh->mColors[i][cursor] = cols[in_cursor];
  678. }
  679. }
  680. }
  681. ConvertMaterialForMesh(out_mesh,model,mesh,index);
  682. if(process_weights) {
  683. ConvertWeights(out_mesh, model, mesh, index, &reverseMapping);
  684. }
  685. return static_cast<unsigned int>(meshes.size() - 1);
  686. }
  687. static const unsigned int NO_MATERIAL_SEPARATION = /* std::numeric_limits<unsigned int>::max() */
  688. static_cast<unsigned int>(-1);
  689. // ------------------------------------------------------------------------------------------------
  690. /** - if materialIndex == NO_MATERIAL_SEPARATION, materials are not taken into
  691. * account when determining which weights to include.
  692. * - outputVertStartIndices is only used when a material index is specified, it gives for
  693. * each output vertex the DOM index it maps to. */
  694. void ConvertWeights(aiMesh* out, const Model& model, const MeshGeometry& geo,
  695. unsigned int materialIndex = NO_MATERIAL_SEPARATION,
  696. std::vector<unsigned int>* outputVertStartIndices = NULL)
  697. {
  698. ai_assert(geo.DeformerSkin());
  699. std::vector<size_t> out_indices;
  700. std::vector<size_t> index_out_indices;
  701. std::vector<size_t> count_out_indices;
  702. const Skin& sk = *geo.DeformerSkin();
  703. std::vector<aiBone*> bones;
  704. bones.reserve(sk.Clusters().size());
  705. const bool no_mat_check = materialIndex == NO_MATERIAL_SEPARATION;
  706. ai_assert(no_mat_check || outputVertStartIndices);
  707. try {
  708. BOOST_FOREACH(const Cluster* cluster, sk.Clusters()) {
  709. ai_assert(cluster);
  710. const WeightIndexArray& indices = cluster->GetIndices();
  711. const WeightArray& weights = cluster->GetWeights();
  712. if(indices.empty()) {
  713. continue;
  714. }
  715. const MatIndexArray& mats = geo.GetMaterialIndices();
  716. bool ok = false;
  717. const size_t no_index_sentinel = std::numeric_limits<size_t>::max();
  718. count_out_indices.clear();
  719. index_out_indices.clear();
  720. out_indices.clear();
  721. // now check if *any* of these weights is contained in the output mesh,
  722. // taking notes so we don't need to do it twice.
  723. BOOST_FOREACH(WeightIndexArray::value_type index, indices) {
  724. unsigned int count;
  725. const unsigned int* const out_idx = geo.ToOutputVertexIndex(index, count);
  726. index_out_indices.push_back(no_index_sentinel);
  727. count_out_indices.push_back(0);
  728. for(unsigned int i = 0; i < count; ++i) {
  729. if (no_mat_check || mats[geo.FaceForVertexIndex(out_idx[i])] == materialIndex) {
  730. if (index_out_indices.back() == no_index_sentinel) {
  731. index_out_indices.back() = out_indices.size();
  732. }
  733. if (no_mat_check) {
  734. out_indices.push_back(out_idx[i]);
  735. }
  736. else {
  737. // this extra lookup is in O(logn), so the entire algorithm becomes O(nlogn)
  738. const std::vector<unsigned int>::iterator it = std::lower_bound(
  739. outputVertStartIndices->begin(),
  740. outputVertStartIndices->end(),
  741. out_idx[i]
  742. );
  743. out_indices.push_back(std::distance(outputVertStartIndices->begin(), it));
  744. }
  745. ++count_out_indices.back();
  746. ok = true;
  747. }
  748. }
  749. }
  750. // if we found at least one, generate the output bones
  751. // XXX this could be heavily simplified by collecting the bone
  752. // data in a single step.
  753. if (ok) {
  754. ConvertCluster(bones, *cluster, out_indices, index_out_indices, count_out_indices);
  755. }
  756. }
  757. }
  758. catch (std::exception&) {
  759. std::for_each(bones.begin(),bones.end(),Util::delete_fun<aiBone>());
  760. throw;
  761. }
  762. if(bones.empty()) {
  763. return;
  764. }
  765. out->mBones = new aiBone*[bones.size()]();
  766. out->mNumBones = static_cast<unsigned int>(bones.size());
  767. std::swap_ranges(bones.begin(),bones.end(),out->mBones);
  768. }
  769. // ------------------------------------------------------------------------------------------------
  770. void ConvertCluster(std::vector<aiBone*>& bones, const Cluster& cl,
  771. std::vector<size_t>& out_indices,
  772. std::vector<size_t>& index_out_indices,
  773. std::vector<size_t>& count_out_indices
  774. )
  775. {
  776. aiBone* const bone = new aiBone();
  777. bones.push_back(bone);
  778. bone->mName = FixNodeName(cl.TargetNode()->Name());
  779. bone->mOffsetMatrix = cl.TransformLink();
  780. bone->mOffsetMatrix.Inverse();
  781. bone->mNumWeights = static_cast<unsigned int>(out_indices.size());
  782. aiVertexWeight* cursor = bone->mWeights = new aiVertexWeight[out_indices.size()];
  783. const size_t no_index_sentinel = std::numeric_limits<size_t>::max();
  784. const WeightArray& weights = cl.GetWeights();
  785. const size_t c = index_out_indices.size();
  786. for (size_t i = 0; i < c; ++i) {
  787. const size_t index_index = index_out_indices[i];
  788. if (index_index == no_index_sentinel) {
  789. continue;
  790. }
  791. const size_t cc = count_out_indices[i];
  792. for (size_t j = 0; j < cc; ++j) {
  793. aiVertexWeight& out_weight = *cursor++;
  794. out_weight.mVertexId = static_cast<unsigned int>(out_indices[index_index + j]);
  795. out_weight.mWeight = weights[i];
  796. }
  797. }
  798. }
  799. // ------------------------------------------------------------------------------------------------
  800. void ConvertMaterialForMesh(aiMesh* out, const Model& model, const MeshGeometry& geo, unsigned int materialIndex)
  801. {
  802. // locate source materials for this mesh
  803. const std::vector<const Material*>& mats = model.GetMaterials();
  804. if (materialIndex >= mats.size()) {
  805. FBXImporter::LogError("material index out of bounds, setting default material");
  806. out->mMaterialIndex = GetDefaultMaterial();
  807. return;
  808. }
  809. const Material* const mat = mats[materialIndex];
  810. MaterialMap::const_iterator it = materials_converted.find(mat);
  811. if (it != materials_converted.end()) {
  812. out->mMaterialIndex = (*it).second;
  813. return;
  814. }
  815. out->mMaterialIndex = ConvertMaterial(*mat);
  816. materials_converted[mat] = out->mMaterialIndex;
  817. }
  818. // ------------------------------------------------------------------------------------------------
  819. unsigned int GetDefaultMaterial()
  820. {
  821. if (defaultMaterialIndex) {
  822. return defaultMaterialIndex - 1;
  823. }
  824. aiMaterial* out_mat = new aiMaterial();
  825. materials.push_back(out_mat);
  826. const aiColor3D diffuse = aiColor3D(0.8f,0.8f,0.8f);
  827. out_mat->AddProperty(&diffuse,1,AI_MATKEY_COLOR_DIFFUSE);
  828. aiString s;
  829. s.Set(AI_DEFAULT_MATERIAL_NAME);
  830. out_mat->AddProperty(&s,AI_MATKEY_NAME);
  831. defaultMaterialIndex = static_cast<unsigned int>(materials.size());
  832. return defaultMaterialIndex - 1;
  833. }
  834. // ------------------------------------------------------------------------------------------------
  835. // Material -> aiMaterial
  836. unsigned int ConvertMaterial(const Material& material)
  837. {
  838. const PropertyTable& props = material.Props();
  839. // generate empty output material
  840. aiMaterial* out_mat = new aiMaterial();
  841. materials_converted[&material] = static_cast<unsigned int>(materials.size());
  842. materials.push_back(out_mat);
  843. aiString str;
  844. // stip Material:: prefix
  845. std::string name = material.Name();
  846. if(name.substr(0,10) == "Material::") {
  847. name = name.substr(10);
  848. }
  849. // set material name if not empty - this could happen
  850. // and there should be no key for it in this case.
  851. if(name.length()) {
  852. str.Set(name);
  853. out_mat->AddProperty(&str,AI_MATKEY_NAME);
  854. }
  855. // shading stuff and colors
  856. SetShadingPropertiesCommon(out_mat,props);
  857. // texture assignments
  858. SetTextureProperties(out_mat,material.Textures());
  859. return static_cast<unsigned int>(materials.size() - 1);
  860. }
  861. // ------------------------------------------------------------------------------------------------
  862. void TrySetTextureProperties(aiMaterial* out_mat, const TextureMap& textures, const std::string& propName, aiTextureType target)
  863. {
  864. TextureMap::const_iterator it = textures.find(propName);
  865. if(it == textures.end()) {
  866. return;
  867. }
  868. const Texture* const tex = (*it).second;
  869. aiString path;
  870. path.Set(tex->RelativeFilename());
  871. out_mat->AddProperty(&path,_AI_MATKEY_TEXTURE_BASE,target,0);
  872. aiUVTransform uvTrafo;
  873. // XXX handle all kinds of UV transformations
  874. uvTrafo.mScaling = tex->UVScaling();
  875. uvTrafo.mTranslation = tex->UVTranslation();
  876. out_mat->AddProperty(&uvTrafo,1,_AI_MATKEY_UVTRANSFORM_BASE,target,0);
  877. const PropertyTable& props = tex->Props();
  878. int uvIndex = 0;
  879. bool ok;
  880. const std::string& uvSet = PropertyGet<std::string>(props,"UVSet",ok);
  881. if(ok) {
  882. // "default" is the name which usually appears in the FbxFileTexture template
  883. if(uvSet != "default" && uvSet.length()) {
  884. // this is a bit awkward - we need to find a mesh that uses this
  885. // material and scan its UV channels for the given UV name because
  886. // assimp references UV channels by index, not by name.
  887. // XXX: the case that UV channels may appear in different orders
  888. // in meshes is unhandled. A possible solution would be to sort
  889. // the UV channels alphabetically, but this would have the side
  890. // effect that the primary (first) UV channel would sometimes
  891. // be moved, causing trouble when users read only the first
  892. // UV channel and ignore UV channel assignments altogether.
  893. const unsigned int matIndex = static_cast<unsigned int>(std::distance(materials.begin(),
  894. std::find(materials.begin(),materials.end(),out_mat)
  895. ));
  896. uvIndex = -1;
  897. BOOST_FOREACH(const MeshMap::value_type& v,meshes_converted) {
  898. const MeshGeometry* const mesh = dynamic_cast<const MeshGeometry*> (v.first);
  899. if(!mesh) {
  900. continue;
  901. }
  902. const std::vector<unsigned int>& mats = mesh->GetMaterialIndices();
  903. if(std::find(mats.begin(),mats.end(),matIndex) == mats.end()) {
  904. continue;
  905. }
  906. int index = -1;
  907. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  908. if(mesh->GetTextureCoords(i).empty()) {
  909. break;
  910. }
  911. const std::string& name = mesh->GetTextureCoordChannelName(i);
  912. if(name == uvSet) {
  913. index = static_cast<int>(i);
  914. break;
  915. }
  916. }
  917. if(index == -1) {
  918. FBXImporter::LogWarn("did not find UV channel named " + uvSet + " in a mesh using this material");
  919. continue;
  920. }
  921. if(uvIndex == -1) {
  922. uvIndex = index;
  923. }
  924. else {
  925. FBXImporter::LogWarn("the UV channel named " + uvSet +
  926. " appears at different positions in meshes, results will be wrong");
  927. }
  928. }
  929. if(uvIndex == -1) {
  930. FBXImporter::LogWarn("failed to resolve UV channel " + uvSet + ", using first UV channel");
  931. uvIndex = 0;
  932. }
  933. }
  934. }
  935. out_mat->AddProperty(&uvIndex,1,_AI_MATKEY_UVWSRC_BASE,target,0);
  936. }
  937. // ------------------------------------------------------------------------------------------------
  938. void SetTextureProperties(aiMaterial* out_mat, const TextureMap& textures)
  939. {
  940. TrySetTextureProperties(out_mat, textures, "DiffuseColor", aiTextureType_DIFFUSE);
  941. TrySetTextureProperties(out_mat, textures, "AmbientColor", aiTextureType_AMBIENT);
  942. TrySetTextureProperties(out_mat, textures, "EmissiveColor", aiTextureType_EMISSIVE);
  943. TrySetTextureProperties(out_mat, textures, "SpecularColor", aiTextureType_SPECULAR);
  944. TrySetTextureProperties(out_mat, textures, "TransparentColor", aiTextureType_OPACITY);
  945. TrySetTextureProperties(out_mat, textures, "ReflectionColor", aiTextureType_REFLECTION);
  946. TrySetTextureProperties(out_mat, textures, "DisplacementColor", aiTextureType_DISPLACEMENT);
  947. TrySetTextureProperties(out_mat, textures, "NormalMap", aiTextureType_NORMALS);
  948. TrySetTextureProperties(out_mat, textures, "Bump", aiTextureType_HEIGHT);
  949. }
  950. // ------------------------------------------------------------------------------------------------
  951. aiColor3D GetColorPropertyFromMaterial(const PropertyTable& props,const std::string& baseName, bool& result)
  952. {
  953. result = true;
  954. bool ok;
  955. const aiVector3D& Diffuse = PropertyGet<aiVector3D>(props,baseName,ok);
  956. if(ok) {
  957. return aiColor3D(Diffuse.x,Diffuse.y,Diffuse.z);
  958. }
  959. else {
  960. aiVector3D DiffuseColor = PropertyGet<aiVector3D>(props,baseName + "Color",ok);
  961. if(ok) {
  962. float DiffuseFactor = PropertyGet<float>(props,baseName + "Factor",ok);
  963. if(ok) {
  964. DiffuseColor *= DiffuseFactor;
  965. }
  966. return aiColor3D(DiffuseColor.x,DiffuseColor.y,DiffuseColor.z);
  967. }
  968. }
  969. result = false;
  970. return aiColor3D(0.0f,0.0f,0.0f);
  971. }
  972. // ------------------------------------------------------------------------------------------------
  973. void SetShadingPropertiesCommon(aiMaterial* out_mat, const PropertyTable& props)
  974. {
  975. // set shading properties. There are various, redundant ways in which FBX materials
  976. // specify their shading settings (depending on shading models, prop
  977. // template etc.). No idea which one is right in a particular context.
  978. // Just try to make sense of it - there's no spec to verify this against,
  979. // so why should we.
  980. bool ok;
  981. const aiColor3D& Diffuse = GetColorPropertyFromMaterial(props,"Diffuse",ok);
  982. if(ok) {
  983. out_mat->AddProperty(&Diffuse,1,AI_MATKEY_COLOR_DIFFUSE);
  984. }
  985. const aiColor3D& Emissive = GetColorPropertyFromMaterial(props,"Emissive",ok);
  986. if(ok) {
  987. out_mat->AddProperty(&Emissive,1,AI_MATKEY_COLOR_EMISSIVE);
  988. }
  989. const aiColor3D& Ambient = GetColorPropertyFromMaterial(props,"Ambient",ok);
  990. if(ok) {
  991. out_mat->AddProperty(&Ambient,1,AI_MATKEY_COLOR_AMBIENT);
  992. }
  993. const aiColor3D& Specular = GetColorPropertyFromMaterial(props,"Specular",ok);
  994. if(ok) {
  995. out_mat->AddProperty(&Specular,1,AI_MATKEY_COLOR_SPECULAR);
  996. }
  997. const float Opacity = PropertyGet<float>(props,"Opacity",ok);
  998. if(ok) {
  999. out_mat->AddProperty(&Opacity,1,AI_MATKEY_OPACITY);
  1000. }
  1001. const float Reflectivity = PropertyGet<float>(props,"Reflectivity",ok);
  1002. if(ok) {
  1003. out_mat->AddProperty(&Reflectivity,1,AI_MATKEY_REFLECTIVITY);
  1004. }
  1005. const float Shininess = PropertyGet<float>(props,"Shininess",ok);
  1006. if(ok) {
  1007. out_mat->AddProperty(&Shininess,1,AI_MATKEY_SHININESS_STRENGTH);
  1008. }
  1009. const float ShininessExponent = PropertyGet<float>(props,"ShininessExponent",ok);
  1010. if(ok) {
  1011. out_mat->AddProperty(&ShininessExponent,1,AI_MATKEY_SHININESS);
  1012. }
  1013. }
  1014. // ------------------------------------------------------------------------------------------------
  1015. // convert animation data to aiAnimation et al
  1016. void ConvertAnimations()
  1017. {
  1018. const std::vector<const AnimationStack*>& animations = doc.AnimationStacks();
  1019. BOOST_FOREACH(const AnimationStack* stack, animations) {
  1020. ConvertAnimationStack(*stack);
  1021. }
  1022. }
  1023. // name -> prefix_stripped?
  1024. typedef std::map<std::string, bool> NodeNameMap;
  1025. NodeNameMap node_names;
  1026. // ------------------------------------------------------------------------------------------------
  1027. std::string FixNodeName(const std::string& name)
  1028. {
  1029. // strip Model:: prefix, avoiding ambiguities (i.e. don't strip if
  1030. // this causes ambiguities, well possible between empty identifiers,
  1031. // such as "Model::" and ""). Make sure the behaviour is consistent
  1032. // across multiple calls to FixNodeName().
  1033. if(name.substr(0,7) == "Model::") {
  1034. std::string temp = name.substr(7);
  1035. const NodeNameMap::const_iterator it = node_names.find(temp);
  1036. if (it != node_names.end()) {
  1037. if (!(*it).second) {
  1038. return FixNodeName(name + "_");
  1039. }
  1040. }
  1041. node_names[temp] = true;
  1042. return temp;
  1043. }
  1044. const NodeNameMap::const_iterator it = node_names.find(name);
  1045. if (it != node_names.end()) {
  1046. if ((*it).second) {
  1047. return FixNodeName(name + "_");
  1048. }
  1049. }
  1050. node_names[name] = false;
  1051. return name;
  1052. }
  1053. typedef std::map<const AnimationCurveNode*, const AnimationLayer*> LayerMap;
  1054. // XXX: better use multi_map ..
  1055. typedef std::map<std::string, std::vector<const AnimationCurveNode*> > NodeMap;
  1056. // ------------------------------------------------------------------------------------------------
  1057. void ConvertAnimationStack(const AnimationStack& st)
  1058. {
  1059. const AnimationLayerList& layers = st.Layers();
  1060. if(layers.empty()) {
  1061. return;
  1062. }
  1063. aiAnimation* const anim = new aiAnimation();
  1064. animations.push_back(anim);
  1065. // strip AnimationStack:: prefix
  1066. std::string name = st.Name();
  1067. if(name.substr(0,16) == "AnimationStack::") {
  1068. name = name.substr(16);
  1069. }
  1070. anim->mName.Set(name);
  1071. // need to find all nodes for which we need to generate node animations -
  1072. // it may happen that we need to merge multiple layers, though.
  1073. NodeMap node_map;
  1074. // reverse mapping from curves to layers, much faster than querying
  1075. // the FBX DOM for it.
  1076. LayerMap layer_map;
  1077. BOOST_FOREACH(const AnimationLayer* layer, layers) {
  1078. ai_assert(layer);
  1079. const AnimationCurveNodeList& nodes = layer->Nodes();
  1080. BOOST_FOREACH(const AnimationCurveNode* node, nodes) {
  1081. ai_assert(node);
  1082. const Model* const model = dynamic_cast<const Model*>(node->Target());
  1083. // this can happen - it could also be a NodeAttribute (i.e. for camera animations)
  1084. if(!model) {
  1085. continue;
  1086. }
  1087. const std::string& name = FixNodeName(model->Name());
  1088. node_map[name].push_back(node);
  1089. layer_map[node] = layer;
  1090. }
  1091. }
  1092. // generate node animations
  1093. std::vector<aiNodeAnim*> node_anims;
  1094. double min_time = 1e10;
  1095. double max_time = -1e10;
  1096. try {
  1097. NodeMap node_property_map;
  1098. BOOST_FOREACH(const NodeMap::value_type& kv, node_map) {
  1099. node_property_map.clear();
  1100. ai_assert(kv.second.size());
  1101. const AnimationCurveNode* curve_node;
  1102. BOOST_FOREACH(const AnimationCurveNode* node, kv.second) {
  1103. ai_assert(node);
  1104. if (node->TargetProperty().empty()) {
  1105. FBXImporter::LogWarn("target property for animation curve not set");
  1106. continue;
  1107. }
  1108. curve_node = node;
  1109. if (node->Curves().empty()) {
  1110. FBXImporter::LogWarn("no animation curves assigned to AnimationCurveNode");
  1111. continue;
  1112. }
  1113. node_property_map[node->TargetProperty()].push_back(node);
  1114. }
  1115. ai_assert(curve_node);
  1116. // check for all possible transformation components
  1117. NodeMap::const_iterator chain[TransformationComp_MAXIMUM];
  1118. bool has_any = false;
  1119. bool has_complex = false;
  1120. for (size_t i = 0; i < TransformationComp_MAXIMUM; ++i) {
  1121. const TransformationComp comp = static_cast<TransformationComp>(i);
  1122. chain[i] = node_property_map.find(NameTransformationCompProperty(comp));
  1123. if (chain[i] != node_property_map.end()) {
  1124. has_any = true;
  1125. if (comp != TransformationComp_Rotation && comp != TransformationComp_Scaling &&
  1126. comp != TransformationComp_Translation) {
  1127. has_complex = true;
  1128. }
  1129. }
  1130. }
  1131. if (!has_any) {
  1132. FBXImporter::LogWarn("ignoring node animation, did not find any transformation key frames");
  1133. continue;
  1134. }
  1135. ai_assert(curve_node->TargetAsModel());
  1136. // this needs to play nicely with GenerateTransformationNodeChain() which will
  1137. // be invoked _later_ (animations come first). If this node has only rotation,
  1138. // scaling and translation _and_ there are no animated other components either,
  1139. // we can use a single node and also a single node animation channel.
  1140. const Model& target = *curve_node->TargetAsModel();
  1141. if (!has_complex && !NeedsComplexTransformationChain(target)) {
  1142. aiNodeAnim* const nd = GenerateSimpleNodeAnim(kv.first, target, chain,
  1143. node_property_map.end(),
  1144. layer_map,
  1145. max_time,
  1146. min_time
  1147. );
  1148. ai_assert(nd);
  1149. node_anims.push_back(nd);
  1150. continue;
  1151. }
  1152. // otherwise, things get gruesome.
  1153. aiNodeAnim* const na = new aiNodeAnim();
  1154. // XXX todo
  1155. ai_assert(false);
  1156. }
  1157. }
  1158. catch(std::exception&) {
  1159. std::for_each(node_anims.begin(), node_anims.end(), Util::delete_fun<aiNodeAnim>());
  1160. throw;
  1161. }
  1162. if(node_anims.size()) {
  1163. anim->mChannels = new aiNodeAnim*[node_anims.size()]();
  1164. anim->mNumChannels = static_cast<unsigned int>(node_anims.size());
  1165. std::swap_ranges(node_anims.begin(),node_anims.end(),anim->mChannels);
  1166. }
  1167. else {
  1168. // empty animations would fail validation, so drop them
  1169. delete anim;
  1170. animations.pop_back();
  1171. FBXImporter::LogInfo("ignoring empty AnimationStack: " + name);
  1172. return;
  1173. }
  1174. // for some mysterious reason, mDuration is simply the maximum key -- the
  1175. // validator always assumes animations to start at zero.
  1176. anim->mDuration = max_time /*- min_time */;
  1177. anim->mTicksPerSecond = 1000.0;
  1178. }
  1179. // ------------------------------------------------------------------------------------------------
  1180. // generate node anim, extracting only Rotation, Scaling and Translation from the given chain
  1181. aiNodeAnim* GenerateSimpleNodeAnim(const std::string& name,
  1182. const Model& target,
  1183. NodeMap::const_iterator chain[TransformationComp_MAXIMUM],
  1184. NodeMap::const_iterator iter_end,
  1185. const LayerMap& layer_map,
  1186. double& max_time,
  1187. double& min_time)
  1188. {
  1189. ScopeGuard<aiNodeAnim> na(new aiNodeAnim());
  1190. na->mNodeName.Set(name);
  1191. const PropertyTable& props = target.Props();
  1192. // if a particular transformation is not given, grab it from
  1193. // the corresponding node to meet the semantics of aiNodeAnim,
  1194. // which requires all of rotation, scaling and translation
  1195. // to be set.
  1196. if(chain[TransformationComp_Scaling] != iter_end) {
  1197. ConvertScaleKeys(na, (*chain[TransformationComp_Scaling]).second,
  1198. layer_map,
  1199. max_time,
  1200. min_time);
  1201. }
  1202. else {
  1203. na->mScalingKeys = new aiVectorKey[1];
  1204. na->mNumScalingKeys = 1;
  1205. na->mScalingKeys[0].mTime = 0.;
  1206. na->mScalingKeys[0].mValue = PropertyGet(props,"Lcl Scaling",
  1207. aiVector3D(1.f,1.f,1.f));
  1208. }
  1209. if(chain[TransformationComp_Rotation] != iter_end) {
  1210. ConvertRotationKeys(na, (*chain[TransformationComp_Rotation]).second,
  1211. layer_map,
  1212. max_time,
  1213. min_time);
  1214. }
  1215. else {
  1216. na->mRotationKeys = new aiQuatKey[1];
  1217. na->mNumRotationKeys = 1;
  1218. na->mRotationKeys[0].mTime = 0.;
  1219. na->mRotationKeys[0].mValue = EulerToQuaternion(
  1220. PropertyGet(props,"Lcl Rotation",aiVector3D(0.f,0.f,0.f))
  1221. );
  1222. }
  1223. if(chain[TransformationComp_Translation] != iter_end) {
  1224. ConvertTranslationKeys(na, (*chain[TransformationComp_Translation]).second,
  1225. layer_map,
  1226. max_time,
  1227. min_time);
  1228. }
  1229. else {
  1230. na->mPositionKeys = new aiVectorKey[1];
  1231. na->mNumPositionKeys = 1;
  1232. na->mPositionKeys[0].mTime = 0.;
  1233. na->mPositionKeys[0].mValue = PropertyGet(props,"Lcl Translation",
  1234. aiVector3D(0.f,0.f,0.f));
  1235. }
  1236. return na.dismiss();
  1237. }
  1238. // key (time), value, mapto (component index)
  1239. typedef boost::tuple< const KeyTimeList*, const KeyValueList*, unsigned int > KeyFrameList;
  1240. typedef std::vector<KeyFrameList> KeyFrameListList;
  1241. // ------------------------------------------------------------------------------------------------
  1242. KeyFrameListList GetKeyframeList(const std::vector<const AnimationCurveNode*>& nodes)
  1243. {
  1244. KeyFrameListList inputs;
  1245. inputs.reserve(nodes.size()*3);
  1246. BOOST_FOREACH(const AnimationCurveNode* node, nodes) {
  1247. ai_assert(node);
  1248. const AnimationCurveMap& curves = node->Curves();
  1249. BOOST_FOREACH(const AnimationCurveMap::value_type& kv, curves) {
  1250. unsigned int mapto;
  1251. if (kv.first == "d|X") {
  1252. mapto = 0;
  1253. }
  1254. else if (kv.first == "d|Y") {
  1255. mapto = 1;
  1256. }
  1257. else if (kv.first == "d|Z") {
  1258. mapto = 2;
  1259. }
  1260. else {
  1261. FBXImporter::LogWarn("ignoring scale animation curve, did not recognize target component");
  1262. continue;
  1263. }
  1264. const AnimationCurve* const curve = kv.second;
  1265. ai_assert(curve->GetKeys().size() == curve->GetValues().size() && curve->GetKeys().size());
  1266. inputs.push_back(boost::make_tuple(&curve->GetKeys(), &curve->GetValues(), mapto));
  1267. }
  1268. }
  1269. return inputs; // pray for NRVO :-)
  1270. }
  1271. // ------------------------------------------------------------------------------------------------
  1272. KeyTimeList GetKeyTimeList(const KeyFrameListList& inputs)
  1273. {
  1274. ai_assert(inputs.size());
  1275. // reserve some space upfront - it is likely that the keyframe lists
  1276. // have matching time values, so max(of all keyframe lists) should
  1277. // be a good estimate.
  1278. KeyTimeList keys;
  1279. size_t estimate = 0;
  1280. BOOST_FOREACH(const KeyFrameList& kfl, inputs) {
  1281. estimate = std::max(estimate, kfl.get<0>()->size());
  1282. }
  1283. keys.reserve(estimate);
  1284. std::vector<unsigned int> next_pos;
  1285. next_pos.resize(inputs.size(),0);
  1286. const size_t count = inputs.size();
  1287. while(true) {
  1288. uint64_t min_tick = std::numeric_limits<uint64_t>::max();
  1289. for (size_t i = 0; i < count; ++i) {
  1290. const KeyFrameList& kfl = inputs[i];
  1291. if (kfl.get<0>()->size() > next_pos[i] && kfl.get<0>()->at(next_pos[i]) < min_tick) {
  1292. min_tick = kfl.get<0>()->at(next_pos[i]);
  1293. }
  1294. }
  1295. if (min_tick == std::numeric_limits<uint64_t>::max()) {
  1296. break;
  1297. }
  1298. keys.push_back(min_tick);
  1299. for (size_t i = 0; i < count; ++i) {
  1300. const KeyFrameList& kfl = inputs[i];
  1301. while(kfl.get<0>()->size() > next_pos[i] && kfl.get<0>()->at(next_pos[i]) == min_tick) {
  1302. ++next_pos[i];
  1303. }
  1304. }
  1305. }
  1306. return keys;
  1307. }
  1308. // ------------------------------------------------------------------------------------------------
  1309. void InterpolateKeys(aiVectorKey* valOut,const KeyTimeList& keys, const KeyFrameListList& inputs, const bool geom,
  1310. double& maxTime,
  1311. double& minTime)
  1312. {
  1313. ai_assert(keys.size());
  1314. ai_assert(valOut);
  1315. std::vector<unsigned int> next_pos;
  1316. const size_t count = inputs.size();
  1317. next_pos.resize(inputs.size(),0);
  1318. BOOST_FOREACH(KeyTimeList::value_type time, keys) {
  1319. float result[3] = {0.0f, 0.0f, 0.0f};
  1320. if(geom) {
  1321. result[0] = result[1] = result[2] = 1.0f;
  1322. }
  1323. for (size_t i = 0; i < count; ++i) {
  1324. const KeyFrameList& kfl = inputs[i];
  1325. const size_t ksize = kfl.get<0>()->size();
  1326. if (ksize > next_pos[i] && kfl.get<0>()->at(next_pos[i]) == time) {
  1327. ++next_pos[i];
  1328. }
  1329. const size_t id0 = next_pos[i]>0 ? next_pos[i]-1 : 0;
  1330. const size_t id1 = next_pos[i]==ksize ? ksize-1 : next_pos[i];
  1331. // use lerp for interpolation
  1332. const KeyValueList::value_type valueA = kfl.get<1>()->at(id0);
  1333. const KeyValueList::value_type valueB = kfl.get<1>()->at(id1);
  1334. const KeyTimeList::value_type timeA = kfl.get<0>()->at(id0);
  1335. const KeyTimeList::value_type timeB = kfl.get<0>()->at(id1);
  1336. // do the actual interpolation in double-precision arithmetics
  1337. // because it is a bit sensitive to rounding errors.
  1338. const double factor = timeB == timeA ? 0. : static_cast<double>((time - timeA) / (timeB - timeA));
  1339. const float interpValue = static_cast<float>(valueA + (valueB - valueA) * factor);
  1340. if(geom) {
  1341. result[kfl.get<2>()] *= interpValue;
  1342. }
  1343. else {
  1344. result[kfl.get<2>()] += interpValue;
  1345. }
  1346. }
  1347. // magic value to convert fbx times to milliseconds
  1348. valOut->mTime = static_cast<double>(time) / 46186158;
  1349. minTime = std::min(minTime, valOut->mTime);
  1350. maxTime = std::max(maxTime, valOut->mTime);
  1351. valOut->mValue.x = result[0];
  1352. valOut->mValue.y = result[1];
  1353. valOut->mValue.z = result[2];
  1354. ++valOut;
  1355. }
  1356. }
  1357. // ------------------------------------------------------------------------------------------------
  1358. void InterpolateKeys(aiQuatKey* valOut,const KeyTimeList& keys, const KeyFrameListList& inputs, const bool geom,
  1359. double& maxTime,
  1360. double& minTime)
  1361. {
  1362. ai_assert(keys.size());
  1363. ai_assert(valOut);
  1364. boost::scoped_array<aiVectorKey> temp(new aiVectorKey[keys.size()]);
  1365. InterpolateKeys(temp.get(),keys,inputs,geom,maxTime, minTime);
  1366. for (size_t i = 0, c = keys.size(); i < c; ++i) {
  1367. valOut[i].mTime = temp[i].mTime;
  1368. valOut[i].mValue = EulerToQuaternion(temp[i].mValue);
  1369. }
  1370. }
  1371. // ------------------------------------------------------------------------------------------------
  1372. // euler xyz -> quat
  1373. aiQuaternion EulerToQuaternion(const aiVector3D& rot)
  1374. {
  1375. aiMatrix4x4 m, mtemp;
  1376. if(fabs(rot.x) > 1e-6f) {
  1377. m *= aiMatrix4x4::RotationX(rot.x,mtemp);
  1378. }
  1379. if(fabs(rot.y) > 1e-6f) {
  1380. m *= aiMatrix4x4::RotationY(rot.y,mtemp);
  1381. }
  1382. if(fabs(rot.z) > 1e-6f) {
  1383. m *= aiMatrix4x4::RotationZ(rot.z,mtemp);
  1384. }
  1385. return aiQuaternion(aiMatrix3x3(m));
  1386. }
  1387. // ------------------------------------------------------------------------------------------------
  1388. void ConvertScaleKeys(aiNodeAnim* na, const std::vector<const AnimationCurveNode*>& nodes, const LayerMap& layers,
  1389. double& maxTime,
  1390. double& minTime)
  1391. {
  1392. ai_assert(nodes.size());
  1393. // XXX for now, assume scale should be blended geometrically (i.e. two
  1394. // layers should be multiplied with each other). There is a FBX
  1395. // property in the layer to specify the behaviour, though.
  1396. const KeyFrameListList& inputs = GetKeyframeList(nodes);
  1397. const KeyTimeList& keys = GetKeyTimeList(inputs);
  1398. na->mNumScalingKeys = static_cast<unsigned int>(keys.size());
  1399. na->mScalingKeys = new aiVectorKey[keys.size()];
  1400. InterpolateKeys(na->mScalingKeys, keys, inputs, true, maxTime, minTime);
  1401. }
  1402. // ------------------------------------------------------------------------------------------------
  1403. void ConvertTranslationKeys(aiNodeAnim* na, const std::vector<const AnimationCurveNode*>& nodes, const LayerMap& layers,
  1404. double& maxTime,
  1405. double& minTime)
  1406. {
  1407. ai_assert(nodes.size());
  1408. // XXX see notes in ConvertScaleKeys()
  1409. const KeyFrameListList& inputs = GetKeyframeList(nodes);
  1410. const KeyTimeList& keys = GetKeyTimeList(inputs);
  1411. na->mNumPositionKeys = static_cast<unsigned int>(keys.size());
  1412. na->mPositionKeys = new aiVectorKey[keys.size()];
  1413. InterpolateKeys(na->mPositionKeys, keys, inputs, false, maxTime, minTime);
  1414. }
  1415. // ------------------------------------------------------------------------------------------------
  1416. void ConvertRotationKeys(aiNodeAnim* na, const std::vector<const AnimationCurveNode*>& nodes, const LayerMap& layers,
  1417. double& maxTime,
  1418. double& minTime)
  1419. {
  1420. ai_assert(nodes.size());
  1421. // XXX see notes in ConvertScaleKeys()
  1422. const std::vector< KeyFrameList >& inputs = GetKeyframeList(nodes);
  1423. const KeyTimeList& keys = GetKeyTimeList(inputs);
  1424. na->mNumRotationKeys = static_cast<unsigned int>(keys.size());
  1425. na->mRotationKeys = new aiQuatKey[keys.size()];
  1426. InterpolateKeys(na->mRotationKeys, keys, inputs, false, maxTime, minTime);
  1427. }
  1428. // ------------------------------------------------------------------------------------------------
  1429. // copy generated meshes, animations, lights, cameras and textures to the output scene
  1430. void TransferDataToScene()
  1431. {
  1432. ai_assert(!out->mMeshes && !out->mNumMeshes);
  1433. // note: the trailing () ensures initialization with NULL - not
  1434. // many C++ users seem to know this, so pointing it out to avoid
  1435. // confusion why this code works.
  1436. out->mMeshes = new aiMesh*[meshes.size()]();
  1437. out->mNumMeshes = static_cast<unsigned int>(meshes.size());
  1438. std::swap_ranges(meshes.begin(),meshes.end(),out->mMeshes);
  1439. if(materials.size()) {
  1440. out->mMaterials = new aiMaterial*[materials.size()]();
  1441. out->mNumMaterials = static_cast<unsigned int>(materials.size());
  1442. std::swap_ranges(materials.begin(),materials.end(),out->mMaterials);
  1443. }
  1444. if(animations.size()) {
  1445. out->mAnimations = new aiAnimation*[animations.size()]();
  1446. out->mNumAnimations = static_cast<unsigned int>(animations.size());
  1447. std::swap_ranges(animations.begin(),animations.end(),out->mAnimations);
  1448. }
  1449. }
  1450. private:
  1451. // 0: not assigned yet, others: index is value - 1
  1452. unsigned int defaultMaterialIndex;
  1453. std::vector<aiMesh*> meshes;
  1454. std::vector<aiMaterial*> materials;
  1455. std::vector<aiAnimation*> animations;
  1456. typedef std::map<const Material*, unsigned int> MaterialMap;
  1457. MaterialMap materials_converted;
  1458. typedef std::map<const Geometry*, std::vector<unsigned int> > MeshMap;
  1459. MeshMap meshes_converted;
  1460. aiScene* const out;
  1461. const FBX::Document& doc;
  1462. };
  1463. //} // !anon
  1464. // ------------------------------------------------------------------------------------------------
  1465. void ConvertToAssimpScene(aiScene* out, const Document& doc)
  1466. {
  1467. Converter converter(out,doc);
  1468. }
  1469. } // !FBX
  1470. } // !Assimp
  1471. #endif