FBXConverter.cpp 140 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2020, 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. #ifndef ASSIMP_BUILD_NO_FBX_IMPORTER
  37. #include "FBXConverter.h"
  38. #include "FBXDocument.h"
  39. #include "FBXImporter.h"
  40. #include "FBXMeshGeometry.h"
  41. #include "FBXParser.h"
  42. #include "FBXProperties.h"
  43. #include "FBXUtil.h"
  44. #include <assimp/MathFunctions.h>
  45. #include <assimp/StringComparison.h>
  46. #include <assimp/scene.h>
  47. #include <assimp/CreateAnimMesh.h>
  48. #include <assimp/StringUtils.h>
  49. #include <assimp/commonMetaData.h>
  50. #include <stdlib.h>
  51. #include <cstdint>
  52. #include <iomanip>
  53. #include <iostream>
  54. #include <iterator>
  55. #include <memory>
  56. #include <sstream>
  57. #include <tuple>
  58. #include <vector>
  59. namespace Assimp {
  60. namespace FBX {
  61. using namespace Util;
  62. #define MAGIC_NODE_TAG "_$AssimpFbx$"
  63. #define CONVERT_FBX_TIME(time) static_cast<double>(time) / 46186158000LL
  64. FBXConverter::FBXConverter(aiScene *out, const Document &doc, bool removeEmptyBones) :
  65. defaultMaterialIndex(),
  66. mMeshes(),
  67. lights(),
  68. cameras(),
  69. textures(),
  70. materials_converted(),
  71. textures_converted(),
  72. meshes_converted(),
  73. node_anim_chain_bits(),
  74. mNodeNames(),
  75. anim_fps(),
  76. mSceneOut(out),
  77. doc(doc),
  78. mRemoveEmptyBones(removeEmptyBones) {
  79. // animations need to be converted first since this will
  80. // populate the node_anim_chain_bits map, which is needed
  81. // to determine which nodes need to be generated.
  82. ConvertAnimations();
  83. // Embedded textures in FBX could be connected to nothing but to itself,
  84. // for instance Texture -> Video connection only but not to the main graph,
  85. // The idea here is to traverse all objects to find these Textures and convert them,
  86. // so later during material conversion it will find converted texture in the textures_converted array.
  87. if (doc.Settings().readTextures) {
  88. ConvertOrphanedEmbeddedTextures();
  89. }
  90. ConvertRootNode();
  91. if (doc.Settings().readAllMaterials) {
  92. // unfortunately this means we have to evaluate all objects
  93. for (const ObjectMap::value_type &v : doc.Objects()) {
  94. const Object *ob = v.second->Get();
  95. if (!ob) {
  96. continue;
  97. }
  98. const Material *mat = dynamic_cast<const Material *>(ob);
  99. if (mat) {
  100. if (materials_converted.find(mat) == materials_converted.end()) {
  101. ConvertMaterial(*mat, 0);
  102. }
  103. }
  104. }
  105. }
  106. ConvertGlobalSettings();
  107. TransferDataToScene();
  108. // if we didn't read any meshes set the AI_SCENE_FLAGS_INCOMPLETE
  109. // to make sure the scene passes assimp's validation. FBX files
  110. // need not contain geometry (i.e. camera animations, raw armatures).
  111. if (out->mNumMeshes == 0) {
  112. out->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  113. }
  114. }
  115. FBXConverter::~FBXConverter() {
  116. std::for_each(mMeshes.begin(), mMeshes.end(), Util::delete_fun<aiMesh>());
  117. std::for_each(materials.begin(), materials.end(), Util::delete_fun<aiMaterial>());
  118. std::for_each(animations.begin(), animations.end(), Util::delete_fun<aiAnimation>());
  119. std::for_each(lights.begin(), lights.end(), Util::delete_fun<aiLight>());
  120. std::for_each(cameras.begin(), cameras.end(), Util::delete_fun<aiCamera>());
  121. std::for_each(textures.begin(), textures.end(), Util::delete_fun<aiTexture>());
  122. }
  123. void FBXConverter::ConvertRootNode() {
  124. mSceneOut->mRootNode = new aiNode();
  125. std::string unique_name;
  126. GetUniqueName("RootNode", unique_name);
  127. mSceneOut->mRootNode->mName.Set(unique_name);
  128. // root has ID 0
  129. ConvertNodes(0L, mSceneOut->mRootNode, mSceneOut->mRootNode);
  130. }
  131. static std::string getAncestorBaseName(const aiNode *node) {
  132. const char *nodeName = nullptr;
  133. size_t length = 0;
  134. while (node && (!nodeName || length == 0)) {
  135. nodeName = node->mName.C_Str();
  136. length = node->mName.length;
  137. node = node->mParent;
  138. }
  139. if (!nodeName || length == 0) {
  140. return {};
  141. }
  142. // could be std::string_view if c++17 available
  143. return std::string(nodeName, length);
  144. }
  145. // Make unique name
  146. std::string FBXConverter::MakeUniqueNodeName(const Model *const model, const aiNode &parent) {
  147. std::string original_name = FixNodeName(model->Name());
  148. if (original_name.empty()) {
  149. original_name = getAncestorBaseName(&parent);
  150. }
  151. std::string unique_name;
  152. GetUniqueName(original_name, unique_name);
  153. return unique_name;
  154. }
  155. /// todo: pre-build node hierarchy
  156. /// todo: get bone from stack
  157. /// todo: make map of aiBone* to aiNode*
  158. /// then update convert clusters to the new format
  159. void FBXConverter::ConvertNodes(uint64_t id, aiNode *parent, aiNode *root_node) {
  160. const std::vector<const Connection *> &conns = doc.GetConnectionsByDestinationSequenced(id, "Model");
  161. std::vector<aiNode *> nodes;
  162. nodes.reserve(conns.size());
  163. std::vector<aiNode *> nodes_chain;
  164. std::vector<aiNode *> post_nodes_chain;
  165. try {
  166. for (const Connection *con : conns) {
  167. // ignore object-property links
  168. if (con->PropertyName().length()) {
  169. // really important we document why this is ignored.
  170. FBXImporter::LogInfo("ignoring property link - no docs on why this is ignored");
  171. continue; //?
  172. }
  173. // convert connection source object into Object base class
  174. const Object *const object = con->SourceObject();
  175. if (nullptr == object) {
  176. FBXImporter::LogError("failed to convert source object for Model link");
  177. continue;
  178. }
  179. // FBX Model::Cube, Model::Bone001, etc elements
  180. // This detects if we can cast the object into this model structure.
  181. const Model *const model = dynamic_cast<const Model *>(object);
  182. if (nullptr != model) {
  183. nodes_chain.clear();
  184. post_nodes_chain.clear();
  185. aiMatrix4x4 new_abs_transform = parent->mTransformation;
  186. std::string node_name = FixNodeName(model->Name());
  187. // even though there is only a single input node, the design of
  188. // assimp (or rather: the complicated transformation chain that
  189. // is employed by fbx) means that we may need multiple aiNode's
  190. // to represent a fbx node's transformation.
  191. // generate node transforms - this includes pivot data
  192. // if need_additional_node is true then you t
  193. const bool need_additional_node = GenerateTransformationNodeChain(*model, node_name, nodes_chain, post_nodes_chain);
  194. // assert that for the current node we must have at least a single transform
  195. ai_assert(nodes_chain.size());
  196. if (need_additional_node) {
  197. nodes_chain.push_back(new aiNode(node_name));
  198. }
  199. //setup metadata on newest node
  200. SetupNodeMetadata(*model, *nodes_chain.back());
  201. // link all nodes in a row
  202. aiNode *last_parent = parent;
  203. for (aiNode *child : nodes_chain) {
  204. ai_assert(child);
  205. if (last_parent != parent) {
  206. last_parent->mNumChildren = 1;
  207. last_parent->mChildren = new aiNode *[1];
  208. last_parent->mChildren[0] = child;
  209. }
  210. child->mParent = last_parent;
  211. last_parent = child;
  212. new_abs_transform *= child->mTransformation;
  213. }
  214. // attach geometry
  215. ConvertModel(*model, nodes_chain.back(), root_node, new_abs_transform);
  216. // check if there will be any child nodes
  217. const std::vector<const Connection *> &child_conns = doc.GetConnectionsByDestinationSequenced(model->ID(), "Model");
  218. // if so, link the geometric transform inverse nodes
  219. // before we attach any child nodes
  220. if (child_conns.size()) {
  221. for (aiNode *postnode : post_nodes_chain) {
  222. ai_assert(postnode);
  223. if (last_parent != parent) {
  224. last_parent->mNumChildren = 1;
  225. last_parent->mChildren = new aiNode *[1];
  226. last_parent->mChildren[0] = postnode;
  227. }
  228. postnode->mParent = last_parent;
  229. last_parent = postnode;
  230. new_abs_transform *= postnode->mTransformation;
  231. }
  232. } else {
  233. // free the nodes we allocated as we don't need them
  234. Util::delete_fun<aiNode> deleter;
  235. std::for_each(
  236. post_nodes_chain.begin(),
  237. post_nodes_chain.end(),
  238. deleter);
  239. }
  240. // recursion call - child nodes
  241. ConvertNodes(model->ID(), last_parent, root_node);
  242. if (doc.Settings().readLights) {
  243. ConvertLights(*model, node_name);
  244. }
  245. if (doc.Settings().readCameras) {
  246. ConvertCameras(*model, node_name);
  247. }
  248. nodes.push_back(nodes_chain.front());
  249. nodes_chain.clear();
  250. }
  251. }
  252. if (nodes.size()) {
  253. parent->mChildren = new aiNode *[nodes.size()]();
  254. parent->mNumChildren = static_cast<unsigned int>(nodes.size());
  255. std::swap_ranges(nodes.begin(), nodes.end(), parent->mChildren);
  256. } else {
  257. parent->mNumChildren = 0;
  258. parent->mChildren = nullptr;
  259. }
  260. } catch (std::exception &) {
  261. Util::delete_fun<aiNode> deleter;
  262. std::for_each(nodes.begin(), nodes.end(), deleter);
  263. std::for_each(nodes_chain.begin(), nodes_chain.end(), deleter);
  264. std::for_each(post_nodes_chain.begin(), post_nodes_chain.end(), deleter);
  265. }
  266. }
  267. void FBXConverter::ConvertLights(const Model &model, const std::string &orig_name) {
  268. const std::vector<const NodeAttribute *> &node_attrs = model.GetAttributes();
  269. for (const NodeAttribute *attr : node_attrs) {
  270. const Light *const light = dynamic_cast<const Light *>(attr);
  271. if (light) {
  272. ConvertLight(*light, orig_name);
  273. }
  274. }
  275. }
  276. void FBXConverter::ConvertCameras(const Model &model, const std::string &orig_name) {
  277. const std::vector<const NodeAttribute *> &node_attrs = model.GetAttributes();
  278. for (const NodeAttribute *attr : node_attrs) {
  279. const Camera *const cam = dynamic_cast<const Camera *>(attr);
  280. if (cam) {
  281. ConvertCamera(*cam, orig_name);
  282. }
  283. }
  284. }
  285. void FBXConverter::ConvertLight(const Light &light, const std::string &orig_name) {
  286. lights.push_back(new aiLight());
  287. aiLight *const out_light = lights.back();
  288. out_light->mName.Set(orig_name);
  289. const float intensity = light.Intensity() / 100.0f;
  290. const aiVector3D &col = light.Color();
  291. out_light->mColorDiffuse = aiColor3D(col.x, col.y, col.z);
  292. out_light->mColorDiffuse.r *= intensity;
  293. out_light->mColorDiffuse.g *= intensity;
  294. out_light->mColorDiffuse.b *= intensity;
  295. out_light->mColorSpecular = out_light->mColorDiffuse;
  296. //lights are defined along negative y direction
  297. out_light->mPosition = aiVector3D(0.0f);
  298. out_light->mDirection = aiVector3D(0.0f, -1.0f, 0.0f);
  299. out_light->mUp = aiVector3D(0.0f, 0.0f, -1.0f);
  300. switch (light.LightType()) {
  301. case Light::Type_Point:
  302. out_light->mType = aiLightSource_POINT;
  303. break;
  304. case Light::Type_Directional:
  305. out_light->mType = aiLightSource_DIRECTIONAL;
  306. break;
  307. case Light::Type_Spot:
  308. out_light->mType = aiLightSource_SPOT;
  309. out_light->mAngleOuterCone = AI_DEG_TO_RAD(light.OuterAngle());
  310. out_light->mAngleInnerCone = AI_DEG_TO_RAD(light.InnerAngle());
  311. break;
  312. case Light::Type_Area:
  313. FBXImporter::LogWarn("cannot represent area light, set to UNDEFINED");
  314. out_light->mType = aiLightSource_UNDEFINED;
  315. break;
  316. case Light::Type_Volume:
  317. FBXImporter::LogWarn("cannot represent volume light, set to UNDEFINED");
  318. out_light->mType = aiLightSource_UNDEFINED;
  319. break;
  320. default:
  321. ai_assert(false);
  322. }
  323. float decay = light.DecayStart();
  324. switch (light.DecayType()) {
  325. case Light::Decay_None:
  326. out_light->mAttenuationConstant = decay;
  327. out_light->mAttenuationLinear = 0.0f;
  328. out_light->mAttenuationQuadratic = 0.0f;
  329. break;
  330. case Light::Decay_Linear:
  331. out_light->mAttenuationConstant = 0.0f;
  332. out_light->mAttenuationLinear = 2.0f / decay;
  333. out_light->mAttenuationQuadratic = 0.0f;
  334. break;
  335. case Light::Decay_Quadratic:
  336. out_light->mAttenuationConstant = 0.0f;
  337. out_light->mAttenuationLinear = 0.0f;
  338. out_light->mAttenuationQuadratic = 2.0f / (decay * decay);
  339. break;
  340. case Light::Decay_Cubic:
  341. FBXImporter::LogWarn("cannot represent cubic attenuation, set to Quadratic");
  342. out_light->mAttenuationQuadratic = 1.0f;
  343. break;
  344. default:
  345. ai_assert(false);
  346. break;
  347. }
  348. }
  349. void FBXConverter::ConvertCamera(const Camera &cam, const std::string &orig_name) {
  350. cameras.push_back(new aiCamera());
  351. aiCamera *const out_camera = cameras.back();
  352. out_camera->mName.Set(orig_name);
  353. out_camera->mAspect = cam.AspectWidth() / cam.AspectHeight();
  354. out_camera->mPosition = aiVector3D(0.0f);
  355. out_camera->mLookAt = aiVector3D(1.0f, 0.0f, 0.0f);
  356. out_camera->mUp = aiVector3D(0.0f, 1.0f, 0.0f);
  357. out_camera->mHorizontalFOV = AI_DEG_TO_RAD(cam.FieldOfView());
  358. out_camera->mClipPlaneNear = cam.NearPlane();
  359. out_camera->mClipPlaneFar = cam.FarPlane();
  360. out_camera->mHorizontalFOV = AI_DEG_TO_RAD(cam.FieldOfView());
  361. out_camera->mClipPlaneNear = cam.NearPlane();
  362. out_camera->mClipPlaneFar = cam.FarPlane();
  363. }
  364. void FBXConverter::GetUniqueName(const std::string &name, std::string &uniqueName) {
  365. uniqueName = name;
  366. auto it_pair = mNodeNames.insert({ name, 0 }); // duplicate node name instance count
  367. unsigned int &i = it_pair.first->second;
  368. while (!it_pair.second) {
  369. i++;
  370. std::ostringstream ext;
  371. ext << name << std::setfill('0') << std::setw(3) << i;
  372. uniqueName = ext.str();
  373. it_pair = mNodeNames.insert({ uniqueName, 0 });
  374. }
  375. }
  376. const char *FBXConverter::NameTransformationComp(TransformationComp comp) {
  377. switch (comp) {
  378. case TransformationComp_Translation:
  379. return "Translation";
  380. case TransformationComp_RotationOffset:
  381. return "RotationOffset";
  382. case TransformationComp_RotationPivot:
  383. return "RotationPivot";
  384. case TransformationComp_PreRotation:
  385. return "PreRotation";
  386. case TransformationComp_Rotation:
  387. return "Rotation";
  388. case TransformationComp_PostRotation:
  389. return "PostRotation";
  390. case TransformationComp_RotationPivotInverse:
  391. return "RotationPivotInverse";
  392. case TransformationComp_ScalingOffset:
  393. return "ScalingOffset";
  394. case TransformationComp_ScalingPivot:
  395. return "ScalingPivot";
  396. case TransformationComp_Scaling:
  397. return "Scaling";
  398. case TransformationComp_ScalingPivotInverse:
  399. return "ScalingPivotInverse";
  400. case TransformationComp_GeometricScaling:
  401. return "GeometricScaling";
  402. case TransformationComp_GeometricRotation:
  403. return "GeometricRotation";
  404. case TransformationComp_GeometricTranslation:
  405. return "GeometricTranslation";
  406. case TransformationComp_GeometricScalingInverse:
  407. return "GeometricScalingInverse";
  408. case TransformationComp_GeometricRotationInverse:
  409. return "GeometricRotationInverse";
  410. case TransformationComp_GeometricTranslationInverse:
  411. return "GeometricTranslationInverse";
  412. case TransformationComp_MAXIMUM: // this is to silence compiler warnings
  413. default:
  414. break;
  415. }
  416. ai_assert(false);
  417. return nullptr;
  418. }
  419. const char *FBXConverter::NameTransformationCompProperty(TransformationComp comp) {
  420. switch (comp) {
  421. case TransformationComp_Translation:
  422. return "Lcl Translation";
  423. case TransformationComp_RotationOffset:
  424. return "RotationOffset";
  425. case TransformationComp_RotationPivot:
  426. return "RotationPivot";
  427. case TransformationComp_PreRotation:
  428. return "PreRotation";
  429. case TransformationComp_Rotation:
  430. return "Lcl Rotation";
  431. case TransformationComp_PostRotation:
  432. return "PostRotation";
  433. case TransformationComp_RotationPivotInverse:
  434. return "RotationPivotInverse";
  435. case TransformationComp_ScalingOffset:
  436. return "ScalingOffset";
  437. case TransformationComp_ScalingPivot:
  438. return "ScalingPivot";
  439. case TransformationComp_Scaling:
  440. return "Lcl Scaling";
  441. case TransformationComp_ScalingPivotInverse:
  442. return "ScalingPivotInverse";
  443. case TransformationComp_GeometricScaling:
  444. return "GeometricScaling";
  445. case TransformationComp_GeometricRotation:
  446. return "GeometricRotation";
  447. case TransformationComp_GeometricTranslation:
  448. return "GeometricTranslation";
  449. case TransformationComp_GeometricScalingInverse:
  450. return "GeometricScalingInverse";
  451. case TransformationComp_GeometricRotationInverse:
  452. return "GeometricRotationInverse";
  453. case TransformationComp_GeometricTranslationInverse:
  454. return "GeometricTranslationInverse";
  455. case TransformationComp_MAXIMUM: // this is to silence compiler warnings
  456. break;
  457. }
  458. ai_assert(false);
  459. return nullptr;
  460. }
  461. aiVector3D FBXConverter::TransformationCompDefaultValue(TransformationComp comp) {
  462. // XXX a neat way to solve the never-ending special cases for scaling
  463. // would be to do everything in log space!
  464. return comp == TransformationComp_Scaling ? aiVector3D(1.f, 1.f, 1.f) : aiVector3D();
  465. }
  466. void FBXConverter::GetRotationMatrix(Model::RotOrder mode, const aiVector3D &rotation, aiMatrix4x4 &out) {
  467. if (mode == Model::RotOrder_SphericXYZ) {
  468. FBXImporter::LogError("Unsupported RotationMode: SphericXYZ");
  469. out = aiMatrix4x4();
  470. return;
  471. }
  472. const float angle_epsilon = Math::getEpsilon<float>();
  473. out = aiMatrix4x4();
  474. bool is_id[3] = { true, true, true };
  475. aiMatrix4x4 temp[3];
  476. if (std::fabs(rotation.z) > angle_epsilon) {
  477. aiMatrix4x4::RotationZ(AI_DEG_TO_RAD(rotation.z), temp[2]);
  478. is_id[2] = false;
  479. }
  480. if (std::fabs(rotation.y) > angle_epsilon) {
  481. aiMatrix4x4::RotationY(AI_DEG_TO_RAD(rotation.y), temp[1]);
  482. is_id[1] = false;
  483. }
  484. if (std::fabs(rotation.x) > angle_epsilon) {
  485. aiMatrix4x4::RotationX(AI_DEG_TO_RAD(rotation.x), temp[0]);
  486. is_id[0] = false;
  487. }
  488. int order[3] = { -1, -1, -1 };
  489. // note: rotation order is inverted since we're left multiplying as is usual in assimp
  490. switch (mode) {
  491. case Model::RotOrder_EulerXYZ:
  492. order[0] = 2;
  493. order[1] = 1;
  494. order[2] = 0;
  495. break;
  496. case Model::RotOrder_EulerXZY:
  497. order[0] = 1;
  498. order[1] = 2;
  499. order[2] = 0;
  500. break;
  501. case Model::RotOrder_EulerYZX:
  502. order[0] = 0;
  503. order[1] = 2;
  504. order[2] = 1;
  505. break;
  506. case Model::RotOrder_EulerYXZ:
  507. order[0] = 2;
  508. order[1] = 0;
  509. order[2] = 1;
  510. break;
  511. case Model::RotOrder_EulerZXY:
  512. order[0] = 1;
  513. order[1] = 0;
  514. order[2] = 2;
  515. break;
  516. case Model::RotOrder_EulerZYX:
  517. order[0] = 0;
  518. order[1] = 1;
  519. order[2] = 2;
  520. break;
  521. default:
  522. ai_assert(false);
  523. break;
  524. }
  525. ai_assert(order[0] >= 0);
  526. ai_assert(order[0] <= 2);
  527. ai_assert(order[1] >= 0);
  528. ai_assert(order[1] <= 2);
  529. ai_assert(order[2] >= 0);
  530. ai_assert(order[2] <= 2);
  531. if (!is_id[order[0]]) {
  532. out = temp[order[0]];
  533. }
  534. if (!is_id[order[1]]) {
  535. out = out * temp[order[1]];
  536. }
  537. if (!is_id[order[2]]) {
  538. out = out * temp[order[2]];
  539. }
  540. }
  541. bool FBXConverter::NeedsComplexTransformationChain(const Model &model) {
  542. const PropertyTable &props = model.Props();
  543. bool ok;
  544. const float zero_epsilon = 1e-6f;
  545. const aiVector3D all_ones(1.0f, 1.0f, 1.0f);
  546. for (size_t i = 0; i < TransformationComp_MAXIMUM; ++i) {
  547. const TransformationComp comp = static_cast<TransformationComp>(i);
  548. if (comp == TransformationComp_Rotation || comp == TransformationComp_Scaling || comp == TransformationComp_Translation ||
  549. comp == TransformationComp_PreRotation || comp == TransformationComp_PostRotation) {
  550. continue;
  551. }
  552. bool scale_compare = (comp == TransformationComp_GeometricScaling || comp == TransformationComp_Scaling);
  553. const aiVector3D &v = PropertyGet<aiVector3D>(props, NameTransformationCompProperty(comp), ok);
  554. if (ok && scale_compare) {
  555. if ((v - all_ones).SquareLength() > zero_epsilon) {
  556. return true;
  557. }
  558. } else if (ok) {
  559. if (v.SquareLength() > zero_epsilon) {
  560. return true;
  561. }
  562. }
  563. }
  564. return false;
  565. }
  566. std::string FBXConverter::NameTransformationChainNode(const std::string &name, TransformationComp comp) {
  567. return name + std::string(MAGIC_NODE_TAG) + "_" + NameTransformationComp(comp);
  568. }
  569. bool FBXConverter::GenerateTransformationNodeChain(const Model &model, const std::string &name, std::vector<aiNode *> &output_nodes,
  570. std::vector<aiNode *> &post_output_nodes) {
  571. const PropertyTable &props = model.Props();
  572. const Model::RotOrder rot = model.RotationOrder();
  573. bool ok;
  574. aiMatrix4x4 chain[TransformationComp_MAXIMUM];
  575. ai_assert(TransformationComp_MAXIMUM < 32);
  576. std::uint32_t chainBits = 0;
  577. // A node won't need a node chain if it only has these.
  578. const std::uint32_t chainMaskSimple = (1 << TransformationComp_Translation) + (1 << TransformationComp_Scaling) + (1 << TransformationComp_Rotation);
  579. // A node will need a node chain if it has any of these.
  580. const std::uint32_t chainMaskComplex = ((1 << (TransformationComp_MAXIMUM)) - 1) - chainMaskSimple;
  581. std::fill_n(chain, static_cast<unsigned int>(TransformationComp_MAXIMUM), aiMatrix4x4());
  582. // generate transformation matrices for all the different transformation components
  583. const float zero_epsilon = Math::getEpsilon<float>();
  584. const aiVector3D all_ones(1.0f, 1.0f, 1.0f);
  585. const aiVector3D &PreRotation = PropertyGet<aiVector3D>(props, "PreRotation", ok);
  586. if (ok && PreRotation.SquareLength() > zero_epsilon) {
  587. chainBits = chainBits | (1 << TransformationComp_PreRotation);
  588. GetRotationMatrix(Model::RotOrder::RotOrder_EulerXYZ, PreRotation, chain[TransformationComp_PreRotation]);
  589. }
  590. const aiVector3D &PostRotation = PropertyGet<aiVector3D>(props, "PostRotation", ok);
  591. if (ok && PostRotation.SquareLength() > zero_epsilon) {
  592. chainBits = chainBits | (1 << TransformationComp_PostRotation);
  593. GetRotationMatrix(Model::RotOrder::RotOrder_EulerXYZ, PostRotation, chain[TransformationComp_PostRotation]);
  594. }
  595. const aiVector3D &RotationPivot = PropertyGet<aiVector3D>(props, "RotationPivot", ok);
  596. if (ok && RotationPivot.SquareLength() > zero_epsilon) {
  597. chainBits = chainBits | (1 << TransformationComp_RotationPivot) | (1 << TransformationComp_RotationPivotInverse);
  598. aiMatrix4x4::Translation(RotationPivot, chain[TransformationComp_RotationPivot]);
  599. aiMatrix4x4::Translation(-RotationPivot, chain[TransformationComp_RotationPivotInverse]);
  600. }
  601. const aiVector3D &RotationOffset = PropertyGet<aiVector3D>(props, "RotationOffset", ok);
  602. if (ok && RotationOffset.SquareLength() > zero_epsilon) {
  603. chainBits = chainBits | (1 << TransformationComp_RotationOffset);
  604. aiMatrix4x4::Translation(RotationOffset, chain[TransformationComp_RotationOffset]);
  605. }
  606. const aiVector3D &ScalingOffset = PropertyGet<aiVector3D>(props, "ScalingOffset", ok);
  607. if (ok && ScalingOffset.SquareLength() > zero_epsilon) {
  608. chainBits = chainBits | (1 << TransformationComp_ScalingOffset);
  609. aiMatrix4x4::Translation(ScalingOffset, chain[TransformationComp_ScalingOffset]);
  610. }
  611. const aiVector3D &ScalingPivot = PropertyGet<aiVector3D>(props, "ScalingPivot", ok);
  612. if (ok && ScalingPivot.SquareLength() > zero_epsilon) {
  613. chainBits = chainBits | (1 << TransformationComp_ScalingPivot) | (1 << TransformationComp_ScalingPivotInverse);
  614. aiMatrix4x4::Translation(ScalingPivot, chain[TransformationComp_ScalingPivot]);
  615. aiMatrix4x4::Translation(-ScalingPivot, chain[TransformationComp_ScalingPivotInverse]);
  616. }
  617. const aiVector3D &Translation = PropertyGet<aiVector3D>(props, "Lcl Translation", ok);
  618. if (ok && Translation.SquareLength() > zero_epsilon) {
  619. chainBits = chainBits | (1 << TransformationComp_Translation);
  620. aiMatrix4x4::Translation(Translation, chain[TransformationComp_Translation]);
  621. }
  622. const aiVector3D &Scaling = PropertyGet<aiVector3D>(props, "Lcl Scaling", ok);
  623. if (ok && (Scaling - all_ones).SquareLength() > zero_epsilon) {
  624. chainBits = chainBits | (1 << TransformationComp_Scaling);
  625. aiMatrix4x4::Scaling(Scaling, chain[TransformationComp_Scaling]);
  626. }
  627. const aiVector3D &Rotation = PropertyGet<aiVector3D>(props, "Lcl Rotation", ok);
  628. if (ok && Rotation.SquareLength() > zero_epsilon) {
  629. chainBits = chainBits | (1 << TransformationComp_Rotation);
  630. GetRotationMatrix(rot, Rotation, chain[TransformationComp_Rotation]);
  631. }
  632. const aiVector3D &GeometricScaling = PropertyGet<aiVector3D>(props, "GeometricScaling", ok);
  633. if (ok && (GeometricScaling - all_ones).SquareLength() > zero_epsilon) {
  634. chainBits = chainBits | (1 << TransformationComp_GeometricScaling);
  635. aiMatrix4x4::Scaling(GeometricScaling, chain[TransformationComp_GeometricScaling]);
  636. aiVector3D GeometricScalingInverse = GeometricScaling;
  637. bool canscale = true;
  638. for (unsigned int i = 0; i < 3; ++i) {
  639. if (std::fabs(GeometricScalingInverse[i]) > zero_epsilon) {
  640. GeometricScalingInverse[i] = 1.0f / GeometricScaling[i];
  641. } else {
  642. FBXImporter::LogError("cannot invert geometric scaling matrix with a 0.0 scale component");
  643. canscale = false;
  644. break;
  645. }
  646. }
  647. if (canscale) {
  648. chainBits = chainBits | (1 << TransformationComp_GeometricScalingInverse);
  649. aiMatrix4x4::Scaling(GeometricScalingInverse, chain[TransformationComp_GeometricScalingInverse]);
  650. }
  651. }
  652. const aiVector3D &GeometricRotation = PropertyGet<aiVector3D>(props, "GeometricRotation", ok);
  653. if (ok && GeometricRotation.SquareLength() > zero_epsilon) {
  654. chainBits = chainBits | (1 << TransformationComp_GeometricRotation) | (1 << TransformationComp_GeometricRotationInverse);
  655. GetRotationMatrix(rot, GeometricRotation, chain[TransformationComp_GeometricRotation]);
  656. GetRotationMatrix(rot, GeometricRotation, chain[TransformationComp_GeometricRotationInverse]);
  657. chain[TransformationComp_GeometricRotationInverse].Inverse();
  658. }
  659. const aiVector3D &GeometricTranslation = PropertyGet<aiVector3D>(props, "GeometricTranslation", ok);
  660. if (ok && GeometricTranslation.SquareLength() > zero_epsilon) {
  661. chainBits = chainBits | (1 << TransformationComp_GeometricTranslation) | (1 << TransformationComp_GeometricTranslationInverse);
  662. aiMatrix4x4::Translation(GeometricTranslation, chain[TransformationComp_GeometricTranslation]);
  663. aiMatrix4x4::Translation(-GeometricTranslation, chain[TransformationComp_GeometricTranslationInverse]);
  664. }
  665. // is_complex needs to be consistent with NeedsComplexTransformationChain()
  666. // or the interplay between this code and the animation converter would
  667. // not be guaranteed.
  668. //ai_assert(NeedsComplexTransformationChain(model) == ((chainBits & chainMaskComplex) != 0));
  669. // now, if we have more than just Translation, Scaling and Rotation,
  670. // we need to generate a full node chain to accommodate for assimp's
  671. // lack to express pivots and offsets.
  672. if ((chainBits & chainMaskComplex) && doc.Settings().preservePivots) {
  673. FBXImporter::LogInfo("generating full transformation chain for node: " + name);
  674. // query the anim_chain_bits dictionary to find out which chain elements
  675. // have associated node animation channels. These can not be dropped
  676. // even if they have identity transform in bind pose.
  677. NodeAnimBitMap::const_iterator it = node_anim_chain_bits.find(name);
  678. const unsigned int anim_chain_bitmask = (it == node_anim_chain_bits.end() ? 0 : (*it).second);
  679. unsigned int bit = 0x1;
  680. for (size_t i = 0; i < TransformationComp_MAXIMUM; ++i, bit <<= 1) {
  681. const TransformationComp comp = static_cast<TransformationComp>(i);
  682. if ((chainBits & bit) == 0 && (anim_chain_bitmask & bit) == 0) {
  683. continue;
  684. }
  685. if (comp == TransformationComp_PostRotation) {
  686. chain[i] = chain[i].Inverse();
  687. }
  688. aiNode *nd = new aiNode();
  689. nd->mName.Set(NameTransformationChainNode(name, comp));
  690. nd->mTransformation = chain[i];
  691. // geometric inverses go in a post-node chain
  692. if (comp == TransformationComp_GeometricScalingInverse ||
  693. comp == TransformationComp_GeometricRotationInverse ||
  694. comp == TransformationComp_GeometricTranslationInverse) {
  695. post_output_nodes.push_back(nd);
  696. } else {
  697. output_nodes.push_back(nd);
  698. }
  699. }
  700. ai_assert(output_nodes.size());
  701. return true;
  702. }
  703. // else, we can just multiply the matrices together
  704. aiNode *nd = new aiNode();
  705. output_nodes.push_back(nd);
  706. // name passed to the method is already unique
  707. nd->mName.Set(name);
  708. // for (const auto &transform : chain) {
  709. // skip inverse chain for no preservePivots
  710. for (unsigned int i = TransformationComp_Translation; i < TransformationComp_MAXIMUM; i++) {
  711. nd->mTransformation = nd->mTransformation * chain[i];
  712. }
  713. return false;
  714. }
  715. void FBXConverter::SetupNodeMetadata(const Model &model, aiNode &nd) {
  716. const PropertyTable &props = model.Props();
  717. DirectPropertyMap unparsedProperties = props.GetUnparsedProperties();
  718. // create metadata on node
  719. const std::size_t numStaticMetaData = 2;
  720. aiMetadata *data = aiMetadata::Alloc(static_cast<unsigned int>(unparsedProperties.size() + numStaticMetaData));
  721. nd.mMetaData = data;
  722. int index = 0;
  723. // find user defined properties (3ds Max)
  724. data->Set(index++, "UserProperties", aiString(PropertyGet<std::string>(props, "UDP3DSMAX", "")));
  725. // preserve the info that a node was marked as Null node in the original file.
  726. data->Set(index++, "IsNull", model.IsNull() ? true : false);
  727. // add unparsed properties to the node's metadata
  728. for (const DirectPropertyMap::value_type &prop : unparsedProperties) {
  729. // Interpret the property as a concrete type
  730. if (const TypedProperty<bool> *interpretedBool = prop.second->As<TypedProperty<bool>>()) {
  731. data->Set(index++, prop.first, interpretedBool->Value());
  732. } else if (const TypedProperty<int> *interpretedInt = prop.second->As<TypedProperty<int>>()) {
  733. data->Set(index++, prop.first, interpretedInt->Value());
  734. } else if (const TypedProperty<uint64_t> *interpretedUint64 = prop.second->As<TypedProperty<uint64_t>>()) {
  735. data->Set(index++, prop.first, interpretedUint64->Value());
  736. } else if (const TypedProperty<float> *interpretedFloat = prop.second->As<TypedProperty<float>>()) {
  737. data->Set(index++, prop.first, interpretedFloat->Value());
  738. } else if (const TypedProperty<std::string> *interpretedString = prop.second->As<TypedProperty<std::string>>()) {
  739. data->Set(index++, prop.first, aiString(interpretedString->Value()));
  740. } else if (const TypedProperty<aiVector3D> *interpretedVec3 = prop.second->As<TypedProperty<aiVector3D>>()) {
  741. data->Set(index++, prop.first, interpretedVec3->Value());
  742. } else {
  743. ai_assert(false);
  744. }
  745. }
  746. }
  747. void FBXConverter::ConvertModel(const Model &model, aiNode *parent, aiNode *root_node,
  748. const aiMatrix4x4 &absolute_transform) {
  749. const std::vector<const Geometry *> &geos = model.GetGeometry();
  750. std::vector<unsigned int> meshes;
  751. meshes.reserve(geos.size());
  752. for (const Geometry *geo : geos) {
  753. const MeshGeometry *const mesh = dynamic_cast<const MeshGeometry *>(geo);
  754. const LineGeometry *const line = dynamic_cast<const LineGeometry *>(geo);
  755. if (mesh) {
  756. const std::vector<unsigned int> &indices = ConvertMesh(*mesh, model, parent, root_node,
  757. absolute_transform);
  758. std::copy(indices.begin(), indices.end(), std::back_inserter(meshes));
  759. } else if (line) {
  760. const std::vector<unsigned int> &indices = ConvertLine(*line, root_node);
  761. std::copy(indices.begin(), indices.end(), std::back_inserter(meshes));
  762. } else {
  763. FBXImporter::LogWarn("ignoring unrecognized geometry: " + geo->Name());
  764. }
  765. }
  766. if (meshes.size()) {
  767. parent->mMeshes = new unsigned int[meshes.size()]();
  768. parent->mNumMeshes = static_cast<unsigned int>(meshes.size());
  769. std::swap_ranges(meshes.begin(), meshes.end(), parent->mMeshes);
  770. }
  771. }
  772. std::vector<unsigned int>
  773. FBXConverter::ConvertMesh(const MeshGeometry &mesh, const Model &model, aiNode *parent, aiNode *root_node,
  774. const aiMatrix4x4 &absolute_transform) {
  775. std::vector<unsigned int> temp;
  776. MeshMap::const_iterator it = meshes_converted.find(&mesh);
  777. if (it != meshes_converted.end()) {
  778. std::copy((*it).second.begin(), (*it).second.end(), std::back_inserter(temp));
  779. return temp;
  780. }
  781. const std::vector<aiVector3D> &vertices = mesh.GetVertices();
  782. const std::vector<unsigned int> &faces = mesh.GetFaceIndexCounts();
  783. if (vertices.empty() || faces.empty()) {
  784. FBXImporter::LogWarn("ignoring empty geometry: " + mesh.Name());
  785. return temp;
  786. }
  787. // one material per mesh maps easily to aiMesh. Multiple material
  788. // meshes need to be split.
  789. const MatIndexArray &mindices = mesh.GetMaterialIndices();
  790. if (doc.Settings().readMaterials && !mindices.empty()) {
  791. const MatIndexArray::value_type base = mindices[0];
  792. for (MatIndexArray::value_type index : mindices) {
  793. if (index != base) {
  794. return ConvertMeshMultiMaterial(mesh, model, parent, root_node, absolute_transform);
  795. }
  796. }
  797. }
  798. // faster code-path, just copy the data
  799. temp.push_back(ConvertMeshSingleMaterial(mesh, model, absolute_transform, parent, root_node));
  800. return temp;
  801. }
  802. std::vector<unsigned int> FBXConverter::ConvertLine(const LineGeometry &line, aiNode *root_node) {
  803. std::vector<unsigned int> temp;
  804. const std::vector<aiVector3D> &vertices = line.GetVertices();
  805. const std::vector<int> &indices = line.GetIndices();
  806. if (vertices.empty() || indices.empty()) {
  807. FBXImporter::LogWarn("ignoring empty line: " + line.Name());
  808. return temp;
  809. }
  810. aiMesh *const out_mesh = SetupEmptyMesh(line, root_node);
  811. out_mesh->mPrimitiveTypes |= aiPrimitiveType_LINE;
  812. // copy vertices
  813. out_mesh->mNumVertices = static_cast<unsigned int>(vertices.size());
  814. out_mesh->mVertices = new aiVector3D[out_mesh->mNumVertices];
  815. std::copy(vertices.begin(), vertices.end(), out_mesh->mVertices);
  816. //Number of line segments (faces) is "Number of Points - Number of Endpoints"
  817. //N.B.: Endpoints in FbxLine are denoted by negative indices.
  818. //If such an Index is encountered, add 1 and multiply by -1 to get the real index.
  819. unsigned int epcount = 0;
  820. for (unsigned i = 0; i < indices.size(); i++) {
  821. if (indices[i] < 0) {
  822. epcount++;
  823. }
  824. }
  825. unsigned int pcount = static_cast<unsigned int>(indices.size());
  826. unsigned int scount = out_mesh->mNumFaces = pcount - epcount;
  827. aiFace *fac = out_mesh->mFaces = new aiFace[scount]();
  828. for (unsigned int i = 0; i < pcount; ++i) {
  829. if (indices[i] < 0) continue;
  830. aiFace &f = *fac++;
  831. f.mNumIndices = 2; //2 == aiPrimitiveType_LINE
  832. f.mIndices = new unsigned int[2];
  833. f.mIndices[0] = indices[i];
  834. int segid = indices[(i + 1 == pcount ? 0 : i + 1)]; //If we have reached he last point, wrap around
  835. f.mIndices[1] = (segid < 0 ? (segid + 1) * -1 : segid); //Convert EndPoint Index to normal Index
  836. }
  837. temp.push_back(static_cast<unsigned int>(mMeshes.size() - 1));
  838. return temp;
  839. }
  840. aiMesh *FBXConverter::SetupEmptyMesh(const Geometry &mesh, aiNode *parent) {
  841. aiMesh *const out_mesh = new aiMesh();
  842. mMeshes.push_back(out_mesh);
  843. meshes_converted[&mesh].push_back(static_cast<unsigned int>(mMeshes.size() - 1));
  844. // set name
  845. std::string name = mesh.Name();
  846. if (name.substr(0, 10) == "Geometry::") {
  847. name = name.substr(10);
  848. }
  849. if (name.length()) {
  850. out_mesh->mName.Set(name);
  851. } else {
  852. out_mesh->mName = parent->mName;
  853. }
  854. return out_mesh;
  855. }
  856. unsigned int FBXConverter::ConvertMeshSingleMaterial(const MeshGeometry &mesh, const Model &model,
  857. const aiMatrix4x4 &absolute_transform, aiNode *parent,
  858. aiNode *) {
  859. const MatIndexArray &mindices = mesh.GetMaterialIndices();
  860. aiMesh *const out_mesh = SetupEmptyMesh(mesh, parent);
  861. const std::vector<aiVector3D> &vertices = mesh.GetVertices();
  862. const std::vector<unsigned int> &faces = mesh.GetFaceIndexCounts();
  863. // copy vertices
  864. out_mesh->mNumVertices = static_cast<unsigned int>(vertices.size());
  865. out_mesh->mVertices = new aiVector3D[vertices.size()];
  866. std::copy(vertices.begin(), vertices.end(), out_mesh->mVertices);
  867. // generate dummy faces
  868. out_mesh->mNumFaces = static_cast<unsigned int>(faces.size());
  869. aiFace *fac = out_mesh->mFaces = new aiFace[faces.size()]();
  870. unsigned int cursor = 0;
  871. for (unsigned int pcount : faces) {
  872. aiFace &f = *fac++;
  873. f.mNumIndices = pcount;
  874. f.mIndices = new unsigned int[pcount];
  875. switch (pcount) {
  876. case 1:
  877. out_mesh->mPrimitiveTypes |= aiPrimitiveType_POINT;
  878. break;
  879. case 2:
  880. out_mesh->mPrimitiveTypes |= aiPrimitiveType_LINE;
  881. break;
  882. case 3:
  883. out_mesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  884. break;
  885. default:
  886. out_mesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  887. break;
  888. }
  889. for (unsigned int i = 0; i < pcount; ++i) {
  890. f.mIndices[i] = cursor++;
  891. }
  892. }
  893. // copy normals
  894. const std::vector<aiVector3D> &normals = mesh.GetNormals();
  895. if (normals.size()) {
  896. ai_assert(normals.size() == vertices.size());
  897. out_mesh->mNormals = new aiVector3D[vertices.size()];
  898. std::copy(normals.begin(), normals.end(), out_mesh->mNormals);
  899. }
  900. // copy tangents - assimp requires both tangents and bitangents (binormals)
  901. // to be present, or neither of them. Compute binormals from normals
  902. // and tangents if needed.
  903. const std::vector<aiVector3D> &tangents = mesh.GetTangents();
  904. const std::vector<aiVector3D> *binormals = &mesh.GetBinormals();
  905. if (tangents.size()) {
  906. std::vector<aiVector3D> tempBinormals;
  907. if (!binormals->size()) {
  908. if (normals.size()) {
  909. tempBinormals.resize(normals.size());
  910. for (unsigned int i = 0; i < tangents.size(); ++i) {
  911. tempBinormals[i] = normals[i] ^ tangents[i];
  912. }
  913. binormals = &tempBinormals;
  914. } else {
  915. binormals = nullptr;
  916. }
  917. }
  918. if (binormals) {
  919. ai_assert(tangents.size() == vertices.size());
  920. ai_assert(binormals->size() == vertices.size());
  921. out_mesh->mTangents = new aiVector3D[vertices.size()];
  922. std::copy(tangents.begin(), tangents.end(), out_mesh->mTangents);
  923. out_mesh->mBitangents = new aiVector3D[vertices.size()];
  924. std::copy(binormals->begin(), binormals->end(), out_mesh->mBitangents);
  925. }
  926. }
  927. // copy texture coords
  928. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  929. const std::vector<aiVector2D> &uvs = mesh.GetTextureCoords(i);
  930. if (uvs.empty()) {
  931. break;
  932. }
  933. aiVector3D *out_uv = out_mesh->mTextureCoords[i] = new aiVector3D[vertices.size()];
  934. for (const aiVector2D &v : uvs) {
  935. *out_uv++ = aiVector3D(v.x, v.y, 0.0f);
  936. }
  937. out_mesh->mNumUVComponents[i] = 2;
  938. }
  939. // copy vertex colors
  940. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_COLOR_SETS; ++i) {
  941. const std::vector<aiColor4D> &colors = mesh.GetVertexColors(i);
  942. if (colors.empty()) {
  943. break;
  944. }
  945. out_mesh->mColors[i] = new aiColor4D[vertices.size()];
  946. std::copy(colors.begin(), colors.end(), out_mesh->mColors[i]);
  947. }
  948. if (!doc.Settings().readMaterials || mindices.empty()) {
  949. FBXImporter::LogError("no material assigned to mesh, setting default material");
  950. out_mesh->mMaterialIndex = GetDefaultMaterial();
  951. } else {
  952. ConvertMaterialForMesh(out_mesh, model, mesh, mindices[0]);
  953. }
  954. if (doc.Settings().readWeights && mesh.DeformerSkin() != nullptr) {
  955. ConvertWeights(out_mesh, mesh, absolute_transform, parent, NO_MATERIAL_SEPARATION, nullptr);
  956. }
  957. std::vector<aiAnimMesh *> animMeshes;
  958. for (const BlendShape *blendShape : mesh.GetBlendShapes()) {
  959. for (const BlendShapeChannel *blendShapeChannel : blendShape->BlendShapeChannels()) {
  960. const std::vector<const ShapeGeometry *> &shapeGeometries = blendShapeChannel->GetShapeGeometries();
  961. for (size_t i = 0; i < shapeGeometries.size(); i++) {
  962. aiAnimMesh *animMesh = aiCreateAnimMesh(out_mesh);
  963. const ShapeGeometry *shapeGeometry = shapeGeometries.at(i);
  964. const std::vector<aiVector3D> &curVertices = shapeGeometry->GetVertices();
  965. const std::vector<aiVector3D> &curNormals = shapeGeometry->GetNormals();
  966. const std::vector<unsigned int> &curIndices = shapeGeometry->GetIndices();
  967. animMesh->mName.Set(FixAnimMeshName(shapeGeometry->Name()));
  968. for (size_t j = 0; j < curIndices.size(); j++) {
  969. const unsigned int curIndex = curIndices.at(j);
  970. aiVector3D vertex = curVertices.at(j);
  971. aiVector3D normal = curNormals.at(j);
  972. unsigned int count = 0;
  973. const unsigned int *outIndices = mesh.ToOutputVertexIndex(curIndex, count);
  974. for (unsigned int k = 0; k < count; k++) {
  975. unsigned int index = outIndices[k];
  976. animMesh->mVertices[index] += vertex;
  977. if (animMesh->mNormals != nullptr) {
  978. animMesh->mNormals[index] += normal;
  979. animMesh->mNormals[index].NormalizeSafe();
  980. }
  981. }
  982. }
  983. animMesh->mWeight = shapeGeometries.size() > 1 ? blendShapeChannel->DeformPercent() / 100.0f : 1.0f;
  984. animMeshes.push_back(animMesh);
  985. }
  986. }
  987. }
  988. const size_t numAnimMeshes = animMeshes.size();
  989. if (numAnimMeshes > 0) {
  990. out_mesh->mNumAnimMeshes = static_cast<unsigned int>(numAnimMeshes);
  991. out_mesh->mAnimMeshes = new aiAnimMesh *[numAnimMeshes];
  992. for (size_t i = 0; i < numAnimMeshes; i++) {
  993. out_mesh->mAnimMeshes[i] = animMeshes.at(i);
  994. }
  995. }
  996. return static_cast<unsigned int>(mMeshes.size() - 1);
  997. }
  998. std::vector<unsigned int>
  999. FBXConverter::ConvertMeshMultiMaterial(const MeshGeometry &mesh, const Model &model, aiNode *parent,
  1000. aiNode *root_node,
  1001. const aiMatrix4x4 &absolute_transform) {
  1002. const MatIndexArray &mindices = mesh.GetMaterialIndices();
  1003. ai_assert(mindices.size());
  1004. std::set<MatIndexArray::value_type> had;
  1005. std::vector<unsigned int> indices;
  1006. for (MatIndexArray::value_type index : mindices) {
  1007. if (had.find(index) == had.end()) {
  1008. indices.push_back(ConvertMeshMultiMaterial(mesh, model, index, parent, root_node, absolute_transform));
  1009. had.insert(index);
  1010. }
  1011. }
  1012. return indices;
  1013. }
  1014. unsigned int FBXConverter::ConvertMeshMultiMaterial(const MeshGeometry &mesh, const Model &model,
  1015. MatIndexArray::value_type index,
  1016. aiNode *parent, aiNode *,
  1017. const aiMatrix4x4 &absolute_transform) {
  1018. aiMesh *const out_mesh = SetupEmptyMesh(mesh, parent);
  1019. const MatIndexArray &mindices = mesh.GetMaterialIndices();
  1020. const std::vector<aiVector3D> &vertices = mesh.GetVertices();
  1021. const std::vector<unsigned int> &faces = mesh.GetFaceIndexCounts();
  1022. const bool process_weights = doc.Settings().readWeights && mesh.DeformerSkin() != nullptr;
  1023. unsigned int count_faces = 0;
  1024. unsigned int count_vertices = 0;
  1025. // count faces
  1026. std::vector<unsigned int>::const_iterator itf = faces.begin();
  1027. for (MatIndexArray::const_iterator it = mindices.begin(),
  1028. end = mindices.end();
  1029. it != end; ++it, ++itf) {
  1030. if ((*it) != index) {
  1031. continue;
  1032. }
  1033. ++count_faces;
  1034. count_vertices += *itf;
  1035. }
  1036. ai_assert(count_faces);
  1037. ai_assert(count_vertices);
  1038. // mapping from output indices to DOM indexing, needed to resolve weights or blendshapes
  1039. std::vector<unsigned int> reverseMapping;
  1040. std::map<unsigned int, unsigned int> translateIndexMap;
  1041. if (process_weights || mesh.GetBlendShapes().size() > 0) {
  1042. reverseMapping.resize(count_vertices);
  1043. }
  1044. // allocate output data arrays, but don't fill them yet
  1045. out_mesh->mNumVertices = count_vertices;
  1046. out_mesh->mVertices = new aiVector3D[count_vertices];
  1047. out_mesh->mNumFaces = count_faces;
  1048. aiFace *fac = out_mesh->mFaces = new aiFace[count_faces]();
  1049. // allocate normals
  1050. const std::vector<aiVector3D> &normals = mesh.GetNormals();
  1051. if (normals.size()) {
  1052. ai_assert(normals.size() == vertices.size());
  1053. out_mesh->mNormals = new aiVector3D[vertices.size()];
  1054. }
  1055. // allocate tangents, binormals.
  1056. const std::vector<aiVector3D> &tangents = mesh.GetTangents();
  1057. const std::vector<aiVector3D> *binormals = &mesh.GetBinormals();
  1058. std::vector<aiVector3D> tempBinormals;
  1059. if (tangents.size()) {
  1060. if (!binormals->size()) {
  1061. if (normals.size()) {
  1062. // XXX this computes the binormals for the entire mesh, not only
  1063. // the part for which we need them.
  1064. tempBinormals.resize(normals.size());
  1065. for (unsigned int i = 0; i < tangents.size(); ++i) {
  1066. tempBinormals[i] = normals[i] ^ tangents[i];
  1067. }
  1068. binormals = &tempBinormals;
  1069. } else {
  1070. binormals = nullptr;
  1071. }
  1072. }
  1073. if (binormals) {
  1074. ai_assert(tangents.size() == vertices.size() && binormals->size() == vertices.size());
  1075. out_mesh->mTangents = new aiVector3D[vertices.size()];
  1076. out_mesh->mBitangents = new aiVector3D[vertices.size()];
  1077. }
  1078. }
  1079. // allocate texture coords
  1080. unsigned int num_uvs = 0;
  1081. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i, ++num_uvs) {
  1082. const std::vector<aiVector2D> &uvs = mesh.GetTextureCoords(i);
  1083. if (uvs.empty()) {
  1084. break;
  1085. }
  1086. out_mesh->mTextureCoords[i] = new aiVector3D[vertices.size()];
  1087. out_mesh->mNumUVComponents[i] = 2;
  1088. }
  1089. // allocate vertex colors
  1090. unsigned int num_vcs = 0;
  1091. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_COLOR_SETS; ++i, ++num_vcs) {
  1092. const std::vector<aiColor4D> &colors = mesh.GetVertexColors(i);
  1093. if (colors.empty()) {
  1094. break;
  1095. }
  1096. out_mesh->mColors[i] = new aiColor4D[vertices.size()];
  1097. }
  1098. unsigned int cursor = 0, in_cursor = 0;
  1099. itf = faces.begin();
  1100. for (MatIndexArray::const_iterator it = mindices.begin(), end = mindices.end(); it != end; ++it, ++itf) {
  1101. const unsigned int pcount = *itf;
  1102. if ((*it) != index) {
  1103. in_cursor += pcount;
  1104. continue;
  1105. }
  1106. aiFace &f = *fac++;
  1107. f.mNumIndices = pcount;
  1108. f.mIndices = new unsigned int[pcount];
  1109. switch (pcount) {
  1110. case 1:
  1111. out_mesh->mPrimitiveTypes |= aiPrimitiveType_POINT;
  1112. break;
  1113. case 2:
  1114. out_mesh->mPrimitiveTypes |= aiPrimitiveType_LINE;
  1115. break;
  1116. case 3:
  1117. out_mesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  1118. break;
  1119. default:
  1120. out_mesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  1121. break;
  1122. }
  1123. for (unsigned int i = 0; i < pcount; ++i, ++cursor, ++in_cursor) {
  1124. f.mIndices[i] = cursor;
  1125. if (reverseMapping.size()) {
  1126. reverseMapping[cursor] = in_cursor;
  1127. translateIndexMap[in_cursor] = cursor;
  1128. }
  1129. out_mesh->mVertices[cursor] = vertices[in_cursor];
  1130. if (out_mesh->mNormals) {
  1131. out_mesh->mNormals[cursor] = normals[in_cursor];
  1132. }
  1133. if (out_mesh->mTangents) {
  1134. out_mesh->mTangents[cursor] = tangents[in_cursor];
  1135. out_mesh->mBitangents[cursor] = (*binormals)[in_cursor];
  1136. }
  1137. for (unsigned int j = 0; j < num_uvs; ++j) {
  1138. const std::vector<aiVector2D> &uvs = mesh.GetTextureCoords(j);
  1139. out_mesh->mTextureCoords[j][cursor] = aiVector3D(uvs[in_cursor].x, uvs[in_cursor].y, 0.0f);
  1140. }
  1141. for (unsigned int j = 0; j < num_vcs; ++j) {
  1142. const std::vector<aiColor4D> &cols = mesh.GetVertexColors(j);
  1143. out_mesh->mColors[j][cursor] = cols[in_cursor];
  1144. }
  1145. }
  1146. }
  1147. ConvertMaterialForMesh(out_mesh, model, mesh, index);
  1148. if (process_weights) {
  1149. ConvertWeights(out_mesh, mesh, absolute_transform, parent, index, &reverseMapping);
  1150. }
  1151. std::vector<aiAnimMesh *> animMeshes;
  1152. for (const BlendShape *blendShape : mesh.GetBlendShapes()) {
  1153. for (const BlendShapeChannel *blendShapeChannel : blendShape->BlendShapeChannels()) {
  1154. const std::vector<const ShapeGeometry *> &shapeGeometries = blendShapeChannel->GetShapeGeometries();
  1155. for (size_t i = 0; i < shapeGeometries.size(); i++) {
  1156. aiAnimMesh *animMesh = aiCreateAnimMesh(out_mesh);
  1157. const ShapeGeometry *shapeGeometry = shapeGeometries.at(i);
  1158. const std::vector<aiVector3D> &curVertices = shapeGeometry->GetVertices();
  1159. const std::vector<aiVector3D> &curNormals = shapeGeometry->GetNormals();
  1160. const std::vector<unsigned int> &curIndices = shapeGeometry->GetIndices();
  1161. animMesh->mName.Set(FixAnimMeshName(shapeGeometry->Name()));
  1162. for (size_t j = 0; j < curIndices.size(); j++) {
  1163. unsigned int curIndex = curIndices.at(j);
  1164. aiVector3D vertex = curVertices.at(j);
  1165. aiVector3D normal = curNormals.at(j);
  1166. unsigned int count = 0;
  1167. const unsigned int *outIndices = mesh.ToOutputVertexIndex(curIndex, count);
  1168. for (unsigned int k = 0; k < count; k++) {
  1169. unsigned int outIndex = outIndices[k];
  1170. if (translateIndexMap.find(outIndex) == translateIndexMap.end())
  1171. continue;
  1172. unsigned int transIndex = translateIndexMap[outIndex];
  1173. animMesh->mVertices[transIndex] += vertex;
  1174. if (animMesh->mNormals != nullptr) {
  1175. animMesh->mNormals[transIndex] += normal;
  1176. animMesh->mNormals[transIndex].NormalizeSafe();
  1177. }
  1178. }
  1179. }
  1180. animMesh->mWeight = shapeGeometries.size() > 1 ? blendShapeChannel->DeformPercent() / 100.0f : 1.0f;
  1181. animMeshes.push_back(animMesh);
  1182. }
  1183. }
  1184. }
  1185. const size_t numAnimMeshes = animMeshes.size();
  1186. if (numAnimMeshes > 0) {
  1187. out_mesh->mNumAnimMeshes = static_cast<unsigned int>(numAnimMeshes);
  1188. out_mesh->mAnimMeshes = new aiAnimMesh *[numAnimMeshes];
  1189. for (size_t i = 0; i < numAnimMeshes; i++) {
  1190. out_mesh->mAnimMeshes[i] = animMeshes.at(i);
  1191. }
  1192. }
  1193. return static_cast<unsigned int>(mMeshes.size() - 1);
  1194. }
  1195. void FBXConverter::ConvertWeights(aiMesh *out, const MeshGeometry &geo,
  1196. const aiMatrix4x4 &absolute_transform,
  1197. aiNode *parent, unsigned int materialIndex,
  1198. std::vector<unsigned int> *outputVertStartIndices) {
  1199. ai_assert(geo.DeformerSkin());
  1200. std::vector<size_t> out_indices;
  1201. std::vector<size_t> index_out_indices;
  1202. std::vector<size_t> count_out_indices;
  1203. const Skin &sk = *geo.DeformerSkin();
  1204. std::vector<aiBone *> bones;
  1205. const bool no_mat_check = materialIndex == NO_MATERIAL_SEPARATION;
  1206. ai_assert(no_mat_check || outputVertStartIndices);
  1207. try {
  1208. // iterate over the sub deformers
  1209. for (const Cluster *cluster : sk.Clusters()) {
  1210. ai_assert(cluster);
  1211. const WeightIndexArray &indices = cluster->GetIndices();
  1212. const MatIndexArray &mats = geo.GetMaterialIndices();
  1213. const size_t no_index_sentinel = std::numeric_limits<size_t>::max();
  1214. count_out_indices.clear();
  1215. index_out_indices.clear();
  1216. out_indices.clear();
  1217. // now check if *any* of these weights is contained in the output mesh,
  1218. // taking notes so we don't need to do it twice.
  1219. for (WeightIndexArray::value_type index : indices) {
  1220. unsigned int count = 0;
  1221. const unsigned int *const out_idx = geo.ToOutputVertexIndex(index, count);
  1222. // ToOutputVertexIndex only returns nullptr if index is out of bounds
  1223. // which should never happen
  1224. ai_assert(out_idx != nullptr);
  1225. index_out_indices.push_back(no_index_sentinel);
  1226. count_out_indices.push_back(0);
  1227. for (unsigned int i = 0; i < count; ++i) {
  1228. if (no_mat_check || static_cast<size_t>(mats[geo.FaceForVertexIndex(out_idx[i])]) == materialIndex) {
  1229. if (index_out_indices.back() == no_index_sentinel) {
  1230. index_out_indices.back() = out_indices.size();
  1231. }
  1232. if (no_mat_check) {
  1233. out_indices.push_back(out_idx[i]);
  1234. } else {
  1235. // this extra lookup is in O(logn), so the entire algorithm becomes O(nlogn)
  1236. const std::vector<unsigned int>::iterator it = std::lower_bound(
  1237. outputVertStartIndices->begin(),
  1238. outputVertStartIndices->end(),
  1239. out_idx[i]);
  1240. out_indices.push_back(std::distance(outputVertStartIndices->begin(), it));
  1241. }
  1242. ++count_out_indices.back();
  1243. }
  1244. }
  1245. }
  1246. // if we found at least one, generate the output bones
  1247. // XXX this could be heavily simplified by collecting the bone
  1248. // data in a single step.
  1249. ConvertCluster(bones, cluster, out_indices, index_out_indices,
  1250. count_out_indices, absolute_transform, parent);
  1251. }
  1252. bone_map.clear();
  1253. } catch (std::exception &) {
  1254. std::for_each(bones.begin(), bones.end(), Util::delete_fun<aiBone>());
  1255. throw;
  1256. }
  1257. if (bones.empty()) {
  1258. out->mBones = nullptr;
  1259. out->mNumBones = 0;
  1260. return;
  1261. } else {
  1262. out->mBones = new aiBone *[bones.size()]();
  1263. out->mNumBones = static_cast<unsigned int>(bones.size());
  1264. std::swap_ranges(bones.begin(), bones.end(), out->mBones);
  1265. }
  1266. }
  1267. const aiNode *GetNodeByName(aiNode *current_node) {
  1268. aiNode *iter = current_node;
  1269. //printf("Child count: %d", iter->mNumChildren);
  1270. return iter;
  1271. }
  1272. void FBXConverter::ConvertCluster(std::vector<aiBone *> &local_mesh_bones, const Cluster *cl,
  1273. std::vector<size_t> &out_indices, std::vector<size_t> &index_out_indices,
  1274. std::vector<size_t> &count_out_indices, const aiMatrix4x4 &absolute_transform,
  1275. aiNode *) {
  1276. ai_assert(cl); // make sure cluster valid
  1277. std::string deformer_name = cl->TargetNode()->Name();
  1278. aiString bone_name = aiString(FixNodeName(deformer_name));
  1279. aiBone *bone = nullptr;
  1280. if (bone_map.count(deformer_name)) {
  1281. ASSIMP_LOG_VERBOSE_DEBUG_F("retrieved bone from lookup ", bone_name.C_Str(), ". Deformer:", deformer_name);
  1282. bone = bone_map[deformer_name];
  1283. } else {
  1284. ASSIMP_LOG_VERBOSE_DEBUG_F("created new bone ", bone_name.C_Str(), ". Deformer: ", deformer_name);
  1285. bone = new aiBone();
  1286. bone->mName = bone_name;
  1287. // store local transform link for post processing
  1288. bone->mOffsetMatrix = cl->TransformLink();
  1289. bone->mOffsetMatrix.Inverse();
  1290. aiMatrix4x4 matrix = (aiMatrix4x4)absolute_transform;
  1291. bone->mOffsetMatrix = bone->mOffsetMatrix * matrix; // * mesh_offset
  1292. //
  1293. // Now calculate the aiVertexWeights
  1294. //
  1295. aiVertexWeight *cursor = nullptr;
  1296. bone->mNumWeights = static_cast<unsigned int>(out_indices.size());
  1297. cursor = bone->mWeights = new aiVertexWeight[out_indices.size()];
  1298. const size_t no_index_sentinel = std::numeric_limits<size_t>::max();
  1299. const WeightArray &weights = cl->GetWeights();
  1300. const size_t c = index_out_indices.size();
  1301. for (size_t i = 0; i < c; ++i) {
  1302. const size_t index_index = index_out_indices[i];
  1303. if (index_index == no_index_sentinel) {
  1304. continue;
  1305. }
  1306. const size_t cc = count_out_indices[i];
  1307. for (size_t j = 0; j < cc; ++j) {
  1308. // cursor runs from first element relative to the start
  1309. // or relative to the start of the next indexes.
  1310. aiVertexWeight &out_weight = *cursor++;
  1311. out_weight.mVertexId = static_cast<unsigned int>(out_indices[index_index + j]);
  1312. out_weight.mWeight = weights[i];
  1313. }
  1314. }
  1315. bone_map.insert(std::pair<const std::string, aiBone *>(deformer_name, bone));
  1316. }
  1317. ASSIMP_LOG_DEBUG_F("bone research: Indicies size: ", out_indices.size());
  1318. // lookup must be populated in case something goes wrong
  1319. // this also allocates bones to mesh instance outside
  1320. local_mesh_bones.push_back(bone);
  1321. }
  1322. void FBXConverter::ConvertMaterialForMesh(aiMesh *out, const Model &model, const MeshGeometry &geo,
  1323. MatIndexArray::value_type materialIndex) {
  1324. // locate source materials for this mesh
  1325. const std::vector<const Material *> &mats = model.GetMaterials();
  1326. if (static_cast<unsigned int>(materialIndex) >= mats.size() || materialIndex < 0) {
  1327. FBXImporter::LogError("material index out of bounds, setting default material");
  1328. out->mMaterialIndex = GetDefaultMaterial();
  1329. return;
  1330. }
  1331. const Material *const mat = mats[materialIndex];
  1332. MaterialMap::const_iterator it = materials_converted.find(mat);
  1333. if (it != materials_converted.end()) {
  1334. out->mMaterialIndex = (*it).second;
  1335. return;
  1336. }
  1337. out->mMaterialIndex = ConvertMaterial(*mat, &geo);
  1338. materials_converted[mat] = out->mMaterialIndex;
  1339. }
  1340. unsigned int FBXConverter::GetDefaultMaterial() {
  1341. if (defaultMaterialIndex) {
  1342. return defaultMaterialIndex - 1;
  1343. }
  1344. aiMaterial *out_mat = new aiMaterial();
  1345. materials.push_back(out_mat);
  1346. const aiColor3D diffuse = aiColor3D(0.8f, 0.8f, 0.8f);
  1347. out_mat->AddProperty(&diffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  1348. aiString s;
  1349. s.Set(AI_DEFAULT_MATERIAL_NAME);
  1350. out_mat->AddProperty(&s, AI_MATKEY_NAME);
  1351. defaultMaterialIndex = static_cast<unsigned int>(materials.size());
  1352. return defaultMaterialIndex - 1;
  1353. }
  1354. unsigned int FBXConverter::ConvertMaterial(const Material &material, const MeshGeometry *const mesh) {
  1355. const PropertyTable &props = material.Props();
  1356. // generate empty output material
  1357. aiMaterial *out_mat = new aiMaterial();
  1358. materials_converted[&material] = static_cast<unsigned int>(materials.size());
  1359. materials.push_back(out_mat);
  1360. aiString str;
  1361. // strip Material:: prefix
  1362. std::string name = material.Name();
  1363. if (name.substr(0, 10) == "Material::") {
  1364. name = name.substr(10);
  1365. }
  1366. // set material name if not empty - this could happen
  1367. // and there should be no key for it in this case.
  1368. if (name.length()) {
  1369. str.Set(name);
  1370. out_mat->AddProperty(&str, AI_MATKEY_NAME);
  1371. }
  1372. // Set the shading mode as best we can: The FBX specification only mentions Lambert and Phong, and only Phong is mentioned in Assimp's aiShadingMode enum.
  1373. if (material.GetShadingModel() == "phong") {
  1374. aiShadingMode shadingMode = aiShadingMode_Phong;
  1375. out_mat->AddProperty<aiShadingMode>(&shadingMode, 1, AI_MATKEY_SHADING_MODEL);
  1376. }
  1377. // shading stuff and colors
  1378. SetShadingPropertiesCommon(out_mat, props);
  1379. SetShadingPropertiesRaw(out_mat, props, material.Textures(), mesh);
  1380. // texture assignments
  1381. SetTextureProperties(out_mat, material.Textures(), mesh);
  1382. SetTextureProperties(out_mat, material.LayeredTextures(), mesh);
  1383. return static_cast<unsigned int>(materials.size() - 1);
  1384. }
  1385. unsigned int FBXConverter::ConvertVideo(const Video &video) {
  1386. // generate empty output texture
  1387. aiTexture *out_tex = new aiTexture();
  1388. textures.push_back(out_tex);
  1389. // assuming the texture is compressed
  1390. out_tex->mWidth = static_cast<unsigned int>(video.ContentLength()); // total data size
  1391. out_tex->mHeight = 0; // fixed to 0
  1392. // steal the data from the Video to avoid an additional copy
  1393. out_tex->pcData = reinterpret_cast<aiTexel *>(const_cast<Video &>(video).RelinquishContent());
  1394. // try to extract a hint from the file extension
  1395. const std::string &filename = video.RelativeFilename().empty() ? video.FileName() : video.RelativeFilename();
  1396. std::string ext = BaseImporter::GetExtension(filename);
  1397. if (ext == "jpeg") {
  1398. ext = "jpg";
  1399. }
  1400. if (ext.size() <= 3) {
  1401. memcpy(out_tex->achFormatHint, ext.c_str(), ext.size());
  1402. }
  1403. out_tex->mFilename.Set(filename.c_str());
  1404. return static_cast<unsigned int>(textures.size() - 1);
  1405. }
  1406. aiString FBXConverter::GetTexturePath(const Texture *tex) {
  1407. aiString path;
  1408. path.Set(tex->RelativeFilename());
  1409. const Video *media = tex->Media();
  1410. if (media != nullptr) {
  1411. bool textureReady = false; //tells if our texture is ready (if it was loaded or if it was found)
  1412. unsigned int index=0;
  1413. VideoMap::const_iterator it = textures_converted.find(*media);
  1414. if (it != textures_converted.end()) {
  1415. index = (*it).second;
  1416. textureReady = true;
  1417. } else {
  1418. if (media->ContentLength() > 0) {
  1419. index = ConvertVideo(*media);
  1420. textures_converted[*media] = index;
  1421. textureReady = true;
  1422. }
  1423. }
  1424. // setup texture reference string (copied from ColladaLoader::FindFilenameForEffectTexture), if the texture is ready
  1425. if (doc.Settings().useLegacyEmbeddedTextureNaming) {
  1426. if (textureReady) {
  1427. // TODO: check the possibility of using the flag "AI_CONFIG_IMPORT_FBX_EMBEDDED_TEXTURES_LEGACY_NAMING"
  1428. // In FBX files textures are now stored internally by Assimp with their filename included
  1429. // Now Assimp can lookup through the loaded textures after all data is processed
  1430. // We need to load all textures before referencing them, as FBX file format order may reference a texture before loading it
  1431. // This may occur on this case too, it has to be studied
  1432. path.data[0] = '*';
  1433. path.length = 1 + ASSIMP_itoa10(path.data + 1, MAXLEN - 1, index);
  1434. }
  1435. }
  1436. }
  1437. return path;
  1438. }
  1439. void FBXConverter::TrySetTextureProperties(aiMaterial *out_mat, const TextureMap &_textures,
  1440. const std::string &propName,
  1441. aiTextureType target, const MeshGeometry *const mesh) {
  1442. TextureMap::const_iterator it = _textures.find(propName);
  1443. if (it == _textures.end()) {
  1444. return;
  1445. }
  1446. const Texture *const tex = (*it).second;
  1447. if (tex != nullptr) {
  1448. aiString path = GetTexturePath(tex);
  1449. out_mat->AddProperty(&path, _AI_MATKEY_TEXTURE_BASE, target, 0);
  1450. aiUVTransform uvTrafo;
  1451. // XXX handle all kinds of UV transformations
  1452. uvTrafo.mScaling = tex->UVScaling();
  1453. uvTrafo.mTranslation = tex->UVTranslation();
  1454. out_mat->AddProperty(&uvTrafo, 1, _AI_MATKEY_UVTRANSFORM_BASE, target, 0);
  1455. const PropertyTable &props = tex->Props();
  1456. int uvIndex = 0;
  1457. bool ok;
  1458. const std::string &uvSet = PropertyGet<std::string>(props, "UVSet", ok);
  1459. if (ok) {
  1460. // "default" is the name which usually appears in the FbxFileTexture template
  1461. if (uvSet != "default" && uvSet.length()) {
  1462. // this is a bit awkward - we need to find a mesh that uses this
  1463. // material and scan its UV channels for the given UV name because
  1464. // assimp references UV channels by index, not by name.
  1465. // XXX: the case that UV channels may appear in different orders
  1466. // in meshes is unhandled. A possible solution would be to sort
  1467. // the UV channels alphabetically, but this would have the side
  1468. // effect that the primary (first) UV channel would sometimes
  1469. // be moved, causing trouble when users read only the first
  1470. // UV channel and ignore UV channel assignments altogether.
  1471. const unsigned int matIndex = static_cast<unsigned int>(std::distance(materials.begin(),
  1472. std::find(materials.begin(), materials.end(), out_mat)));
  1473. uvIndex = -1;
  1474. if (!mesh) {
  1475. for (const MeshMap::value_type &v : meshes_converted) {
  1476. const MeshGeometry *const meshGeom = dynamic_cast<const MeshGeometry *>(v.first);
  1477. if (!meshGeom) {
  1478. continue;
  1479. }
  1480. const MatIndexArray &mats = meshGeom->GetMaterialIndices();
  1481. MatIndexArray::const_iterator curIt = std::find(mats.begin(), mats.end(), (int) matIndex);
  1482. if (curIt == mats.end()) {
  1483. continue;
  1484. }
  1485. int index = -1;
  1486. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  1487. if (meshGeom->GetTextureCoords(i).empty()) {
  1488. break;
  1489. }
  1490. const std::string &name = meshGeom->GetTextureCoordChannelName(i);
  1491. if (name == uvSet) {
  1492. index = static_cast<int>(i);
  1493. break;
  1494. }
  1495. }
  1496. if (index == -1) {
  1497. FBXImporter::LogWarn("did not find UV channel named " + uvSet + " in a mesh using this material");
  1498. continue;
  1499. }
  1500. if (uvIndex == -1) {
  1501. uvIndex = index;
  1502. } else {
  1503. FBXImporter::LogWarn("the UV channel named " + uvSet +
  1504. " appears at different positions in meshes, results will be wrong");
  1505. }
  1506. }
  1507. } else {
  1508. int index = -1;
  1509. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  1510. if (mesh->GetTextureCoords(i).empty()) {
  1511. break;
  1512. }
  1513. const std::string &name = mesh->GetTextureCoordChannelName(i);
  1514. if (name == uvSet) {
  1515. index = static_cast<int>(i);
  1516. break;
  1517. }
  1518. }
  1519. if (index == -1) {
  1520. FBXImporter::LogWarn("did not find UV channel named " + uvSet + " in a mesh using this material");
  1521. }
  1522. if (uvIndex == -1) {
  1523. uvIndex = index;
  1524. }
  1525. }
  1526. if (uvIndex == -1) {
  1527. FBXImporter::LogWarn("failed to resolve UV channel " + uvSet + ", using first UV channel");
  1528. uvIndex = 0;
  1529. }
  1530. }
  1531. }
  1532. out_mat->AddProperty(&uvIndex, 1, _AI_MATKEY_UVWSRC_BASE, target, 0);
  1533. }
  1534. }
  1535. void FBXConverter::TrySetTextureProperties(aiMaterial *out_mat, const LayeredTextureMap &layeredTextures,
  1536. const std::string &propName,
  1537. aiTextureType target, const MeshGeometry *const mesh) {
  1538. LayeredTextureMap::const_iterator it = layeredTextures.find(propName);
  1539. if (it == layeredTextures.end()) {
  1540. return;
  1541. }
  1542. int texCount = (*it).second->textureCount();
  1543. // Set the blend mode for layered textures
  1544. int blendmode = (*it).second->GetBlendMode();
  1545. out_mat->AddProperty(&blendmode, 1, _AI_MATKEY_TEXOP_BASE, target, 0);
  1546. for (int texIndex = 0; texIndex < texCount; texIndex++) {
  1547. const Texture *const tex = (*it).second->getTexture(texIndex);
  1548. aiString path = GetTexturePath(tex);
  1549. out_mat->AddProperty(&path, _AI_MATKEY_TEXTURE_BASE, target, texIndex);
  1550. aiUVTransform uvTrafo;
  1551. // XXX handle all kinds of UV transformations
  1552. uvTrafo.mScaling = tex->UVScaling();
  1553. uvTrafo.mTranslation = tex->UVTranslation();
  1554. out_mat->AddProperty(&uvTrafo, 1, _AI_MATKEY_UVTRANSFORM_BASE, target, texIndex);
  1555. const PropertyTable &props = tex->Props();
  1556. int uvIndex = 0;
  1557. bool ok;
  1558. const std::string &uvSet = PropertyGet<std::string>(props, "UVSet", ok);
  1559. if (ok) {
  1560. // "default" is the name which usually appears in the FbxFileTexture template
  1561. if (uvSet != "default" && uvSet.length()) {
  1562. // this is a bit awkward - we need to find a mesh that uses this
  1563. // material and scan its UV channels for the given UV name because
  1564. // assimp references UV channels by index, not by name.
  1565. // XXX: the case that UV channels may appear in different orders
  1566. // in meshes is unhandled. A possible solution would be to sort
  1567. // the UV channels alphabetically, but this would have the side
  1568. // effect that the primary (first) UV channel would sometimes
  1569. // be moved, causing trouble when users read only the first
  1570. // UV channel and ignore UV channel assignments altogether.
  1571. const unsigned int matIndex = static_cast<unsigned int>(std::distance(materials.begin(),
  1572. std::find(materials.begin(), materials.end(), out_mat)));
  1573. uvIndex = -1;
  1574. if (!mesh) {
  1575. for (const MeshMap::value_type &v : meshes_converted) {
  1576. const MeshGeometry *const meshGeom = dynamic_cast<const MeshGeometry *>(v.first);
  1577. if (!meshGeom) {
  1578. continue;
  1579. }
  1580. const MatIndexArray &mats = meshGeom->GetMaterialIndices();
  1581. MatIndexArray::const_iterator curIt = std::find(mats.begin(), mats.end(), (int) matIndex);
  1582. if ( curIt == mats.end()) {
  1583. continue;
  1584. }
  1585. int index = -1;
  1586. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  1587. if (meshGeom->GetTextureCoords(i).empty()) {
  1588. break;
  1589. }
  1590. const std::string &name = meshGeom->GetTextureCoordChannelName(i);
  1591. if (name == uvSet) {
  1592. index = static_cast<int>(i);
  1593. break;
  1594. }
  1595. }
  1596. if (index == -1) {
  1597. FBXImporter::LogWarn("did not find UV channel named " + uvSet + " in a mesh using this material");
  1598. continue;
  1599. }
  1600. if (uvIndex == -1) {
  1601. uvIndex = index;
  1602. } else {
  1603. FBXImporter::LogWarn("the UV channel named " + uvSet +
  1604. " appears at different positions in meshes, results will be wrong");
  1605. }
  1606. }
  1607. } else {
  1608. int index = -1;
  1609. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  1610. if (mesh->GetTextureCoords(i).empty()) {
  1611. break;
  1612. }
  1613. const std::string &name = mesh->GetTextureCoordChannelName(i);
  1614. if (name == uvSet) {
  1615. index = static_cast<int>(i);
  1616. break;
  1617. }
  1618. }
  1619. if (index == -1) {
  1620. FBXImporter::LogWarn("did not find UV channel named " + uvSet + " in a mesh using this material");
  1621. }
  1622. if (uvIndex == -1) {
  1623. uvIndex = index;
  1624. }
  1625. }
  1626. if (uvIndex == -1) {
  1627. FBXImporter::LogWarn("failed to resolve UV channel " + uvSet + ", using first UV channel");
  1628. uvIndex = 0;
  1629. }
  1630. }
  1631. }
  1632. out_mat->AddProperty(&uvIndex, 1, _AI_MATKEY_UVWSRC_BASE, target, texIndex);
  1633. }
  1634. }
  1635. void FBXConverter::SetTextureProperties(aiMaterial *out_mat, const TextureMap &_textures, const MeshGeometry *const mesh) {
  1636. TrySetTextureProperties(out_mat, _textures, "DiffuseColor", aiTextureType_DIFFUSE, mesh);
  1637. TrySetTextureProperties(out_mat, _textures, "AmbientColor", aiTextureType_AMBIENT, mesh);
  1638. TrySetTextureProperties(out_mat, _textures, "EmissiveColor", aiTextureType_EMISSIVE, mesh);
  1639. TrySetTextureProperties(out_mat, _textures, "SpecularColor", aiTextureType_SPECULAR, mesh);
  1640. TrySetTextureProperties(out_mat, _textures, "SpecularFactor", aiTextureType_SPECULAR, mesh);
  1641. TrySetTextureProperties(out_mat, _textures, "TransparentColor", aiTextureType_OPACITY, mesh);
  1642. TrySetTextureProperties(out_mat, _textures, "ReflectionColor", aiTextureType_REFLECTION, mesh);
  1643. TrySetTextureProperties(out_mat, _textures, "DisplacementColor", aiTextureType_DISPLACEMENT, mesh);
  1644. TrySetTextureProperties(out_mat, _textures, "NormalMap", aiTextureType_NORMALS, mesh);
  1645. TrySetTextureProperties(out_mat, _textures, "Bump", aiTextureType_HEIGHT, mesh);
  1646. TrySetTextureProperties(out_mat, _textures, "ShininessExponent", aiTextureType_SHININESS, mesh);
  1647. TrySetTextureProperties(out_mat, _textures, "TransparencyFactor", aiTextureType_OPACITY, mesh);
  1648. TrySetTextureProperties(out_mat, _textures, "EmissiveFactor", aiTextureType_EMISSIVE, mesh);
  1649. //Maya counterparts
  1650. TrySetTextureProperties(out_mat, _textures, "Maya|DiffuseTexture", aiTextureType_DIFFUSE, mesh);
  1651. TrySetTextureProperties(out_mat, _textures, "Maya|NormalTexture", aiTextureType_NORMALS, mesh);
  1652. TrySetTextureProperties(out_mat, _textures, "Maya|SpecularTexture", aiTextureType_SPECULAR, mesh);
  1653. TrySetTextureProperties(out_mat, _textures, "Maya|FalloffTexture", aiTextureType_OPACITY, mesh);
  1654. TrySetTextureProperties(out_mat, _textures, "Maya|ReflectionMapTexture", aiTextureType_REFLECTION, mesh);
  1655. // Maya PBR
  1656. TrySetTextureProperties(out_mat, _textures, "Maya|baseColor|file", aiTextureType_BASE_COLOR, mesh);
  1657. TrySetTextureProperties(out_mat, _textures, "Maya|normalCamera|file", aiTextureType_NORMAL_CAMERA, mesh);
  1658. TrySetTextureProperties(out_mat, _textures, "Maya|emissionColor|file", aiTextureType_EMISSION_COLOR, mesh);
  1659. TrySetTextureProperties(out_mat, _textures, "Maya|metalness|file", aiTextureType_METALNESS, mesh);
  1660. TrySetTextureProperties(out_mat, _textures, "Maya|diffuseRoughness|file", aiTextureType_DIFFUSE_ROUGHNESS, mesh);
  1661. // Maya stingray
  1662. TrySetTextureProperties(out_mat, _textures, "Maya|TEX_color_map|file", aiTextureType_BASE_COLOR, mesh);
  1663. TrySetTextureProperties(out_mat, _textures, "Maya|TEX_normal_map|file", aiTextureType_NORMAL_CAMERA, mesh);
  1664. TrySetTextureProperties(out_mat, _textures, "Maya|TEX_emissive_map|file", aiTextureType_EMISSION_COLOR, mesh);
  1665. TrySetTextureProperties(out_mat, _textures, "Maya|TEX_metallic_map|file", aiTextureType_METALNESS, mesh);
  1666. TrySetTextureProperties(out_mat, _textures, "Maya|TEX_roughness_map|file", aiTextureType_DIFFUSE_ROUGHNESS, mesh);
  1667. TrySetTextureProperties(out_mat, _textures, "Maya|TEX_ao_map|file", aiTextureType_AMBIENT_OCCLUSION, mesh);
  1668. // 3DSMax PBR
  1669. TrySetTextureProperties(out_mat, _textures, "3dsMax|Parameters|base_color_map", aiTextureType_BASE_COLOR, mesh);
  1670. TrySetTextureProperties(out_mat, _textures, "3dsMax|Parameters|bump_map", aiTextureType_NORMAL_CAMERA, mesh);
  1671. TrySetTextureProperties(out_mat, _textures, "3dsMax|Parameters|emission_map", aiTextureType_EMISSION_COLOR, mesh);
  1672. TrySetTextureProperties(out_mat, _textures, "3dsMax|Parameters|metalness_map", aiTextureType_METALNESS, mesh);
  1673. TrySetTextureProperties(out_mat, _textures, "3dsMax|Parameters|roughness_map", aiTextureType_DIFFUSE_ROUGHNESS, mesh);
  1674. }
  1675. void FBXConverter::SetTextureProperties(aiMaterial *out_mat, const LayeredTextureMap &layeredTextures, const MeshGeometry *const mesh) {
  1676. TrySetTextureProperties(out_mat, layeredTextures, "DiffuseColor", aiTextureType_DIFFUSE, mesh);
  1677. TrySetTextureProperties(out_mat, layeredTextures, "AmbientColor", aiTextureType_AMBIENT, mesh);
  1678. TrySetTextureProperties(out_mat, layeredTextures, "EmissiveColor", aiTextureType_EMISSIVE, mesh);
  1679. TrySetTextureProperties(out_mat, layeredTextures, "SpecularColor", aiTextureType_SPECULAR, mesh);
  1680. TrySetTextureProperties(out_mat, layeredTextures, "SpecularFactor", aiTextureType_SPECULAR, mesh);
  1681. TrySetTextureProperties(out_mat, layeredTextures, "TransparentColor", aiTextureType_OPACITY, mesh);
  1682. TrySetTextureProperties(out_mat, layeredTextures, "ReflectionColor", aiTextureType_REFLECTION, mesh);
  1683. TrySetTextureProperties(out_mat, layeredTextures, "DisplacementColor", aiTextureType_DISPLACEMENT, mesh);
  1684. TrySetTextureProperties(out_mat, layeredTextures, "NormalMap", aiTextureType_NORMALS, mesh);
  1685. TrySetTextureProperties(out_mat, layeredTextures, "Bump", aiTextureType_HEIGHT, mesh);
  1686. TrySetTextureProperties(out_mat, layeredTextures, "ShininessExponent", aiTextureType_SHININESS, mesh);
  1687. TrySetTextureProperties(out_mat, layeredTextures, "EmissiveFactor", aiTextureType_EMISSIVE, mesh);
  1688. TrySetTextureProperties(out_mat, layeredTextures, "TransparencyFactor", aiTextureType_OPACITY, mesh);
  1689. }
  1690. aiColor3D FBXConverter::GetColorPropertyFactored(const PropertyTable &props, const std::string &colorName,
  1691. const std::string &factorName, bool &result, bool useTemplate) {
  1692. result = true;
  1693. bool ok;
  1694. aiVector3D BaseColor = PropertyGet<aiVector3D>(props, colorName, ok, useTemplate);
  1695. if (!ok) {
  1696. result = false;
  1697. return aiColor3D(0.0f, 0.0f, 0.0f);
  1698. }
  1699. // if no factor name, return the colour as is
  1700. if (factorName.empty()) {
  1701. return aiColor3D(BaseColor.x, BaseColor.y, BaseColor.z);
  1702. }
  1703. // otherwise it should be multiplied by the factor, if found.
  1704. float factor = PropertyGet<float>(props, factorName, ok, useTemplate);
  1705. if (ok) {
  1706. BaseColor *= factor;
  1707. }
  1708. return aiColor3D(BaseColor.x, BaseColor.y, BaseColor.z);
  1709. }
  1710. aiColor3D FBXConverter::GetColorPropertyFromMaterial(const PropertyTable &props, const std::string &baseName,
  1711. bool &result) {
  1712. return GetColorPropertyFactored(props, baseName + "Color", baseName + "Factor", result, true);
  1713. }
  1714. aiColor3D FBXConverter::GetColorProperty(const PropertyTable &props, const std::string &colorName,
  1715. bool &result, bool useTemplate) {
  1716. result = true;
  1717. bool ok;
  1718. const aiVector3D &ColorVec = PropertyGet<aiVector3D>(props, colorName, ok, useTemplate);
  1719. if (!ok) {
  1720. result = false;
  1721. return aiColor3D(0.0f, 0.0f, 0.0f);
  1722. }
  1723. return aiColor3D(ColorVec.x, ColorVec.y, ColorVec.z);
  1724. }
  1725. void FBXConverter::SetShadingPropertiesCommon(aiMaterial *out_mat, const PropertyTable &props) {
  1726. // Set shading properties.
  1727. // Modern FBX Files have two separate systems for defining these,
  1728. // with only the more comprehensive one described in the property template.
  1729. // Likely the other values are a legacy system,
  1730. // which is still always exported by the official FBX SDK.
  1731. //
  1732. // Blender's FBX import and export mostly ignore this legacy system,
  1733. // and as we only support recent versions of FBX anyway, we can do the same.
  1734. bool ok;
  1735. const aiColor3D &Diffuse = GetColorPropertyFromMaterial(props, "Diffuse", ok);
  1736. if (ok) {
  1737. out_mat->AddProperty(&Diffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  1738. }
  1739. const aiColor3D &Emissive = GetColorPropertyFromMaterial(props, "Emissive", ok);
  1740. if (ok) {
  1741. out_mat->AddProperty(&Emissive, 1, AI_MATKEY_COLOR_EMISSIVE);
  1742. }
  1743. const aiColor3D &Ambient = GetColorPropertyFromMaterial(props, "Ambient", ok);
  1744. if (ok) {
  1745. out_mat->AddProperty(&Ambient, 1, AI_MATKEY_COLOR_AMBIENT);
  1746. }
  1747. // we store specular factor as SHININESS_STRENGTH, so just get the color
  1748. const aiColor3D &Specular = GetColorProperty(props, "SpecularColor", ok, true);
  1749. if (ok) {
  1750. out_mat->AddProperty(&Specular, 1, AI_MATKEY_COLOR_SPECULAR);
  1751. }
  1752. // and also try to get SHININESS_STRENGTH
  1753. const float SpecularFactor = PropertyGet<float>(props, "SpecularFactor", ok, true);
  1754. if (ok) {
  1755. out_mat->AddProperty(&SpecularFactor, 1, AI_MATKEY_SHININESS_STRENGTH);
  1756. }
  1757. // and the specular exponent
  1758. const float ShininessExponent = PropertyGet<float>(props, "ShininessExponent", ok);
  1759. if (ok) {
  1760. out_mat->AddProperty(&ShininessExponent, 1, AI_MATKEY_SHININESS);
  1761. }
  1762. // TransparentColor / TransparencyFactor... gee thanks FBX :rolleyes:
  1763. const aiColor3D &Transparent = GetColorPropertyFactored(props, "TransparentColor", "TransparencyFactor", ok);
  1764. float CalculatedOpacity = 1.0f;
  1765. if (ok) {
  1766. out_mat->AddProperty(&Transparent, 1, AI_MATKEY_COLOR_TRANSPARENT);
  1767. // as calculated by FBX SDK 2017:
  1768. CalculatedOpacity = 1.0f - ((Transparent.r + Transparent.g + Transparent.b) / 3.0f);
  1769. }
  1770. // try to get the transparency factor
  1771. const float TransparencyFactor = PropertyGet<float>(props, "TransparencyFactor", ok);
  1772. if (ok) {
  1773. out_mat->AddProperty(&TransparencyFactor, 1, AI_MATKEY_TRANSPARENCYFACTOR);
  1774. }
  1775. // use of TransparencyFactor is inconsistent.
  1776. // Maya always stores it as 1.0,
  1777. // so we can't use it to set AI_MATKEY_OPACITY.
  1778. // Blender is more sensible and stores it as the alpha value.
  1779. // However both the FBX SDK and Blender always write an additional
  1780. // legacy "Opacity" field, so we can try to use that.
  1781. //
  1782. // If we can't find it,
  1783. // we can fall back to the value which the FBX SDK calculates
  1784. // from transparency colour (RGB) and factor (F) as
  1785. // 1.0 - F*((R+G+B)/3).
  1786. //
  1787. // There's no consistent way to interpret this opacity value,
  1788. // so it's up to clients to do the correct thing.
  1789. const float Opacity = PropertyGet<float>(props, "Opacity", ok);
  1790. if (ok) {
  1791. out_mat->AddProperty(&Opacity, 1, AI_MATKEY_OPACITY);
  1792. } else if (CalculatedOpacity != 1.0) {
  1793. out_mat->AddProperty(&CalculatedOpacity, 1, AI_MATKEY_OPACITY);
  1794. }
  1795. // reflection color and factor are stored separately
  1796. const aiColor3D &Reflection = GetColorProperty(props, "ReflectionColor", ok, true);
  1797. if (ok) {
  1798. out_mat->AddProperty(&Reflection, 1, AI_MATKEY_COLOR_REFLECTIVE);
  1799. }
  1800. float ReflectionFactor = PropertyGet<float>(props, "ReflectionFactor", ok, true);
  1801. if (ok) {
  1802. out_mat->AddProperty(&ReflectionFactor, 1, AI_MATKEY_REFLECTIVITY);
  1803. }
  1804. const float BumpFactor = PropertyGet<float>(props, "BumpFactor", ok);
  1805. if (ok) {
  1806. out_mat->AddProperty(&BumpFactor, 1, AI_MATKEY_BUMPSCALING);
  1807. }
  1808. const float DispFactor = PropertyGet<float>(props, "DisplacementFactor", ok);
  1809. if (ok) {
  1810. out_mat->AddProperty(&DispFactor, 1, "$mat.displacementscaling", 0, 0);
  1811. }
  1812. }
  1813. void FBXConverter::SetShadingPropertiesRaw(aiMaterial *out_mat, const PropertyTable &props, const TextureMap &_textures, const MeshGeometry *const mesh) {
  1814. // Add all the unparsed properties with a "$raw." prefix
  1815. const std::string prefix = "$raw.";
  1816. for (const DirectPropertyMap::value_type &prop : props.GetUnparsedProperties()) {
  1817. std::string name = prefix + prop.first;
  1818. if (const TypedProperty<aiVector3D> *interpretedVec3 = prop.second->As<TypedProperty<aiVector3D>>()) {
  1819. out_mat->AddProperty(&interpretedVec3->Value(), 1, name.c_str(), 0, 0);
  1820. } else if (const TypedProperty<aiColor3D> *interpretedCol3 = prop.second->As<TypedProperty<aiColor3D>>()) {
  1821. out_mat->AddProperty(&interpretedCol3->Value(), 1, name.c_str(), 0, 0);
  1822. } else if (const TypedProperty<aiColor4D> *interpretedCol4 = prop.second->As<TypedProperty<aiColor4D>>()) {
  1823. out_mat->AddProperty(&interpretedCol4->Value(), 1, name.c_str(), 0, 0);
  1824. } else if (const TypedProperty<float> *interpretedFloat = prop.second->As<TypedProperty<float>>()) {
  1825. out_mat->AddProperty(&interpretedFloat->Value(), 1, name.c_str(), 0, 0);
  1826. } else if (const TypedProperty<int> *interpretedInt = prop.second->As<TypedProperty<int>>()) {
  1827. out_mat->AddProperty(&interpretedInt->Value(), 1, name.c_str(), 0, 0);
  1828. } else if (const TypedProperty<bool> *interpretedBool = prop.second->As<TypedProperty<bool>>()) {
  1829. int value = interpretedBool->Value() ? 1 : 0;
  1830. out_mat->AddProperty(&value, 1, name.c_str(), 0, 0);
  1831. } else if (const TypedProperty<std::string> *interpretedString = prop.second->As<TypedProperty<std::string>>()) {
  1832. const aiString value = aiString(interpretedString->Value());
  1833. out_mat->AddProperty(&value, name.c_str(), 0, 0);
  1834. }
  1835. }
  1836. // Add the textures' properties
  1837. for (TextureMap::const_iterator it = _textures.begin(); it != _textures.end(); ++it) {
  1838. std::string name = prefix + it->first;
  1839. const Texture *const tex = it->second;
  1840. if (tex != nullptr) {
  1841. aiString path;
  1842. path.Set(tex->RelativeFilename());
  1843. const Video *media = tex->Media();
  1844. if (media != nullptr && media->ContentLength() > 0) {
  1845. unsigned int index;
  1846. VideoMap::const_iterator videoIt = textures_converted.find(*media);
  1847. if (videoIt != textures_converted.end()) {
  1848. index = videoIt->second;
  1849. } else {
  1850. index = ConvertVideo(*media);
  1851. textures_converted[*media] = index;
  1852. }
  1853. // setup texture reference string (copied from ColladaLoader::FindFilenameForEffectTexture)
  1854. path.data[0] = '*';
  1855. path.length = 1 + ASSIMP_itoa10(path.data + 1, MAXLEN - 1, index);
  1856. }
  1857. out_mat->AddProperty(&path, (name + "|file").c_str(), aiTextureType_UNKNOWN, 0);
  1858. aiUVTransform uvTrafo;
  1859. // XXX handle all kinds of UV transformations
  1860. uvTrafo.mScaling = tex->UVScaling();
  1861. uvTrafo.mTranslation = tex->UVTranslation();
  1862. out_mat->AddProperty(&uvTrafo, 1, (name + "|uvtrafo").c_str(), aiTextureType_UNKNOWN, 0);
  1863. int uvIndex = 0;
  1864. bool uvFound = false;
  1865. const std::string &uvSet = PropertyGet<std::string>(tex->Props(), "UVSet", uvFound);
  1866. if (uvFound) {
  1867. // "default" is the name which usually appears in the FbxFileTexture template
  1868. if (uvSet != "default" && uvSet.length()) {
  1869. // this is a bit awkward - we need to find a mesh that uses this
  1870. // material and scan its UV channels for the given UV name because
  1871. // assimp references UV channels by index, not by name.
  1872. // XXX: the case that UV channels may appear in different orders
  1873. // in meshes is unhandled. A possible solution would be to sort
  1874. // the UV channels alphabetically, but this would have the side
  1875. // effect that the primary (first) UV channel would sometimes
  1876. // be moved, causing trouble when users read only the first
  1877. // UV channel and ignore UV channel assignments altogether.
  1878. std::vector<aiMaterial *>::iterator materialIt = std::find(materials.begin(), materials.end(), out_mat);
  1879. const unsigned int matIndex = static_cast<unsigned int>(std::distance(materials.begin(), materialIt));
  1880. uvIndex = -1;
  1881. if (!mesh) {
  1882. for (const MeshMap::value_type &v : meshes_converted) {
  1883. const MeshGeometry *const meshGeom = dynamic_cast<const MeshGeometry *>(v.first);
  1884. if (!meshGeom) {
  1885. continue;
  1886. }
  1887. const MatIndexArray &mats = meshGeom->GetMaterialIndices();
  1888. if (std::find(mats.begin(), mats.end(), (int)matIndex) == mats.end()) {
  1889. continue;
  1890. }
  1891. int index = -1;
  1892. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  1893. if (meshGeom->GetTextureCoords(i).empty()) {
  1894. break;
  1895. }
  1896. const std::string &curName = meshGeom->GetTextureCoordChannelName(i);
  1897. if (curName == uvSet) {
  1898. index = static_cast<int>(i);
  1899. break;
  1900. }
  1901. }
  1902. if (index == -1) {
  1903. FBXImporter::LogWarn("did not find UV channel named " + uvSet + " in a mesh using this material");
  1904. continue;
  1905. }
  1906. if (uvIndex == -1) {
  1907. uvIndex = index;
  1908. } else {
  1909. FBXImporter::LogWarn("the UV channel named " + uvSet + " appears at different positions in meshes, results will be wrong");
  1910. }
  1911. }
  1912. } else {
  1913. int index = -1;
  1914. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  1915. if (mesh->GetTextureCoords(i).empty()) {
  1916. break;
  1917. }
  1918. const std::string &curName = mesh->GetTextureCoordChannelName(i);
  1919. if (curName == uvSet) {
  1920. index = static_cast<int>(i);
  1921. break;
  1922. }
  1923. }
  1924. if (index == -1) {
  1925. FBXImporter::LogWarn("did not find UV channel named " + uvSet + " in a mesh using this material");
  1926. }
  1927. if (uvIndex == -1) {
  1928. uvIndex = index;
  1929. }
  1930. }
  1931. if (uvIndex == -1) {
  1932. FBXImporter::LogWarn("failed to resolve UV channel " + uvSet + ", using first UV channel");
  1933. uvIndex = 0;
  1934. }
  1935. }
  1936. }
  1937. out_mat->AddProperty(&uvIndex, 1, (name + "|uvwsrc").c_str(), aiTextureType_UNKNOWN, 0);
  1938. }
  1939. }
  1940. }
  1941. double FBXConverter::FrameRateToDouble(FileGlobalSettings::FrameRate fp, double customFPSVal) {
  1942. switch (fp) {
  1943. case FileGlobalSettings::FrameRate_DEFAULT:
  1944. return 1.0;
  1945. case FileGlobalSettings::FrameRate_120:
  1946. return 120.0;
  1947. case FileGlobalSettings::FrameRate_100:
  1948. return 100.0;
  1949. case FileGlobalSettings::FrameRate_60:
  1950. return 60.0;
  1951. case FileGlobalSettings::FrameRate_50:
  1952. return 50.0;
  1953. case FileGlobalSettings::FrameRate_48:
  1954. return 48.0;
  1955. case FileGlobalSettings::FrameRate_30:
  1956. case FileGlobalSettings::FrameRate_30_DROP:
  1957. return 30.0;
  1958. case FileGlobalSettings::FrameRate_NTSC_DROP_FRAME:
  1959. case FileGlobalSettings::FrameRate_NTSC_FULL_FRAME:
  1960. return 29.9700262;
  1961. case FileGlobalSettings::FrameRate_PAL:
  1962. return 25.0;
  1963. case FileGlobalSettings::FrameRate_CINEMA:
  1964. return 24.0;
  1965. case FileGlobalSettings::FrameRate_1000:
  1966. return 1000.0;
  1967. case FileGlobalSettings::FrameRate_CINEMA_ND:
  1968. return 23.976;
  1969. case FileGlobalSettings::FrameRate_CUSTOM:
  1970. return customFPSVal;
  1971. case FileGlobalSettings::FrameRate_MAX: // this is to silence compiler warnings
  1972. break;
  1973. }
  1974. ai_assert(false);
  1975. return -1.0f;
  1976. }
  1977. void FBXConverter::ConvertAnimations() {
  1978. // first of all determine framerate
  1979. const FileGlobalSettings::FrameRate fps = doc.GlobalSettings().TimeMode();
  1980. const float custom = doc.GlobalSettings().CustomFrameRate();
  1981. anim_fps = FrameRateToDouble(fps, custom);
  1982. const std::vector<const AnimationStack *> &curAnimations = doc.AnimationStacks();
  1983. for (const AnimationStack *stack : curAnimations) {
  1984. ConvertAnimationStack(*stack);
  1985. }
  1986. }
  1987. std::string FBXConverter::FixNodeName(const std::string &name) {
  1988. // strip Model:: prefix, avoiding ambiguities (i.e. don't strip if
  1989. // this causes ambiguities, well possible between empty identifiers,
  1990. // such as "Model::" and ""). Make sure the behaviour is consistent
  1991. // across multiple calls to FixNodeName().
  1992. if (name.substr(0, 7) == "Model::") {
  1993. std::string temp = name.substr(7);
  1994. return temp;
  1995. }
  1996. return name;
  1997. }
  1998. std::string FBXConverter::FixAnimMeshName(const std::string &name) {
  1999. if (name.length()) {
  2000. size_t indexOf = name.find_first_of("::");
  2001. if (indexOf != std::string::npos && indexOf < name.size() - 2) {
  2002. return name.substr(indexOf + 2);
  2003. }
  2004. }
  2005. return name.length() ? name : "AnimMesh";
  2006. }
  2007. void FBXConverter::ConvertAnimationStack(const AnimationStack &st) {
  2008. const AnimationLayerList &layers = st.Layers();
  2009. if (layers.empty()) {
  2010. return;
  2011. }
  2012. aiAnimation *const anim = new aiAnimation();
  2013. animations.push_back(anim);
  2014. // strip AnimationStack:: prefix
  2015. std::string name = st.Name();
  2016. if (name.substr(0, 16) == "AnimationStack::") {
  2017. name = name.substr(16);
  2018. } else if (name.substr(0, 11) == "AnimStack::") {
  2019. name = name.substr(11);
  2020. }
  2021. anim->mName.Set(name);
  2022. // need to find all nodes for which we need to generate node animations -
  2023. // it may happen that we need to merge multiple layers, though.
  2024. NodeMap node_map;
  2025. // reverse mapping from curves to layers, much faster than querying
  2026. // the FBX DOM for it.
  2027. LayerMap layer_map;
  2028. const char *prop_whitelist[] = {
  2029. "Lcl Scaling",
  2030. "Lcl Rotation",
  2031. "Lcl Translation",
  2032. "DeformPercent"
  2033. };
  2034. std::map<std::string, morphAnimData *> morphAnimDatas;
  2035. for (const AnimationLayer *layer : layers) {
  2036. ai_assert(layer);
  2037. const AnimationCurveNodeList &nodes = layer->Nodes(prop_whitelist, 4);
  2038. for (const AnimationCurveNode *node : nodes) {
  2039. ai_assert(node);
  2040. const Model *const model = dynamic_cast<const Model *>(node->Target());
  2041. if (model) {
  2042. const std::string &curName = FixNodeName(model->Name());
  2043. node_map[curName].push_back(node);
  2044. layer_map[node] = layer;
  2045. continue;
  2046. }
  2047. const BlendShapeChannel *const bsc = dynamic_cast<const BlendShapeChannel *>(node->Target());
  2048. if (bsc) {
  2049. ProcessMorphAnimDatas(&morphAnimDatas, bsc, node);
  2050. }
  2051. }
  2052. }
  2053. // generate node animations
  2054. std::vector<aiNodeAnim *> node_anims;
  2055. double min_time = 1e10;
  2056. double max_time = -1e10;
  2057. int64_t start_time = st.LocalStart();
  2058. int64_t stop_time = st.LocalStop();
  2059. bool has_local_startstop = start_time != 0 || stop_time != 0;
  2060. if (!has_local_startstop) {
  2061. // no time range given, so accept every keyframe and use the actual min/max time
  2062. // the numbers are INT64_MIN/MAX, the 20000 is for safety because GenerateNodeAnimations uses an epsilon of 10000
  2063. start_time = -9223372036854775807ll + 20000;
  2064. stop_time = 9223372036854775807ll - 20000;
  2065. }
  2066. try {
  2067. for (const NodeMap::value_type &kv : node_map) {
  2068. GenerateNodeAnimations(node_anims,
  2069. kv.first,
  2070. kv.second,
  2071. layer_map,
  2072. start_time, stop_time,
  2073. max_time,
  2074. min_time);
  2075. }
  2076. } catch (std::exception &) {
  2077. std::for_each(node_anims.begin(), node_anims.end(), Util::delete_fun<aiNodeAnim>());
  2078. throw;
  2079. }
  2080. if (node_anims.size() || morphAnimDatas.size()) {
  2081. if (node_anims.size()) {
  2082. anim->mChannels = new aiNodeAnim *[node_anims.size()]();
  2083. anim->mNumChannels = static_cast<unsigned int>(node_anims.size());
  2084. std::swap_ranges(node_anims.begin(), node_anims.end(), anim->mChannels);
  2085. }
  2086. if (morphAnimDatas.size()) {
  2087. unsigned int numMorphMeshChannels = static_cast<unsigned int>(morphAnimDatas.size());
  2088. anim->mMorphMeshChannels = new aiMeshMorphAnim *[numMorphMeshChannels];
  2089. anim->mNumMorphMeshChannels = numMorphMeshChannels;
  2090. unsigned int i = 0;
  2091. for (auto morphAnimIt : morphAnimDatas) {
  2092. morphAnimData *animData = morphAnimIt.second;
  2093. unsigned int numKeys = static_cast<unsigned int>(animData->size());
  2094. aiMeshMorphAnim *meshMorphAnim = new aiMeshMorphAnim();
  2095. meshMorphAnim->mName.Set(morphAnimIt.first);
  2096. meshMorphAnim->mNumKeys = numKeys;
  2097. meshMorphAnim->mKeys = new aiMeshMorphKey[numKeys];
  2098. unsigned int j = 0;
  2099. for (auto animIt : *animData) {
  2100. morphKeyData *keyData = animIt.second;
  2101. unsigned int numValuesAndWeights = static_cast<unsigned int>(keyData->values.size());
  2102. meshMorphAnim->mKeys[j].mNumValuesAndWeights = numValuesAndWeights;
  2103. meshMorphAnim->mKeys[j].mValues = new unsigned int[numValuesAndWeights];
  2104. meshMorphAnim->mKeys[j].mWeights = new double[numValuesAndWeights];
  2105. meshMorphAnim->mKeys[j].mTime = CONVERT_FBX_TIME(animIt.first) * anim_fps;
  2106. for (unsigned int k = 0; k < numValuesAndWeights; k++) {
  2107. meshMorphAnim->mKeys[j].mValues[k] = keyData->values.at(k);
  2108. meshMorphAnim->mKeys[j].mWeights[k] = keyData->weights.at(k);
  2109. }
  2110. j++;
  2111. }
  2112. anim->mMorphMeshChannels[i++] = meshMorphAnim;
  2113. }
  2114. }
  2115. } else {
  2116. // empty animations would fail validation, so drop them
  2117. delete anim;
  2118. animations.pop_back();
  2119. FBXImporter::LogInfo("ignoring empty AnimationStack (using IK?): " + name);
  2120. return;
  2121. }
  2122. double start_time_fps = has_local_startstop ? (CONVERT_FBX_TIME(start_time) * anim_fps) : min_time;
  2123. double stop_time_fps = has_local_startstop ? (CONVERT_FBX_TIME(stop_time) * anim_fps) : max_time;
  2124. // adjust relative timing for animation
  2125. for (unsigned int c = 0; c < anim->mNumChannels; c++) {
  2126. aiNodeAnim *channel = anim->mChannels[c];
  2127. for (uint32_t i = 0; i < channel->mNumPositionKeys; i++) {
  2128. channel->mPositionKeys[i].mTime -= start_time_fps;
  2129. }
  2130. for (uint32_t i = 0; i < channel->mNumRotationKeys; i++) {
  2131. channel->mRotationKeys[i].mTime -= start_time_fps;
  2132. }
  2133. for (uint32_t i = 0; i < channel->mNumScalingKeys; i++) {
  2134. channel->mScalingKeys[i].mTime -= start_time_fps;
  2135. }
  2136. }
  2137. for (unsigned int c = 0; c < anim->mNumMorphMeshChannels; c++) {
  2138. aiMeshMorphAnim *channel = anim->mMorphMeshChannels[c];
  2139. for (uint32_t i = 0; i < channel->mNumKeys; i++) {
  2140. channel->mKeys[i].mTime -= start_time_fps;
  2141. }
  2142. }
  2143. // for some mysterious reason, mDuration is simply the maximum key -- the
  2144. // validator always assumes animations to start at zero.
  2145. anim->mDuration = stop_time_fps - start_time_fps;
  2146. anim->mTicksPerSecond = anim_fps;
  2147. }
  2148. // ------------------------------------------------------------------------------------------------
  2149. void FBXConverter::ProcessMorphAnimDatas(std::map<std::string, morphAnimData *> *morphAnimDatas, const BlendShapeChannel *bsc, const AnimationCurveNode *node) {
  2150. std::vector<const Connection *> bscConnections = doc.GetConnectionsBySourceSequenced(bsc->ID(), "Deformer");
  2151. for (const Connection *bscConnection : bscConnections) {
  2152. auto bs = dynamic_cast<const BlendShape *>(bscConnection->DestinationObject());
  2153. if (bs) {
  2154. auto channelIt = std::find(bs->BlendShapeChannels().begin(), bs->BlendShapeChannels().end(), bsc);
  2155. if (channelIt != bs->BlendShapeChannels().end()) {
  2156. auto channelIndex = static_cast<unsigned int>(std::distance(bs->BlendShapeChannels().begin(), channelIt));
  2157. std::vector<const Connection *> bsConnections = doc.GetConnectionsBySourceSequenced(bs->ID(), "Geometry");
  2158. for (const Connection *bsConnection : bsConnections) {
  2159. auto geo = dynamic_cast<const Geometry *>(bsConnection->DestinationObject());
  2160. if (geo) {
  2161. std::vector<const Connection *> geoConnections = doc.GetConnectionsBySourceSequenced(geo->ID(), "Model");
  2162. for (const Connection *geoConnection : geoConnections) {
  2163. auto model = dynamic_cast<const Model *>(geoConnection->DestinationObject());
  2164. if (model) {
  2165. auto geoIt = std::find(model->GetGeometry().begin(), model->GetGeometry().end(), geo);
  2166. auto geoIndex = static_cast<unsigned int>(std::distance(model->GetGeometry().begin(), geoIt));
  2167. auto name = aiString(FixNodeName(model->Name() + "*"));
  2168. name.length = 1 + ASSIMP_itoa10(name.data + name.length, MAXLEN - 1, geoIndex);
  2169. morphAnimData *animData;
  2170. auto animIt = morphAnimDatas->find(name.C_Str());
  2171. if (animIt == morphAnimDatas->end()) {
  2172. animData = new morphAnimData();
  2173. morphAnimDatas->insert(std::make_pair(name.C_Str(), animData));
  2174. } else {
  2175. animData = animIt->second;
  2176. }
  2177. for (std::pair<std::string, const AnimationCurve *> curvesIt : node->Curves()) {
  2178. if (curvesIt.first == "d|DeformPercent") {
  2179. const AnimationCurve *animationCurve = curvesIt.second;
  2180. const KeyTimeList &keys = animationCurve->GetKeys();
  2181. const KeyValueList &values = animationCurve->GetValues();
  2182. unsigned int k = 0;
  2183. for (auto key : keys) {
  2184. morphKeyData *keyData;
  2185. auto keyIt = animData->find(key);
  2186. if (keyIt == animData->end()) {
  2187. keyData = new morphKeyData();
  2188. animData->insert(std::make_pair(key, keyData));
  2189. } else {
  2190. keyData = keyIt->second;
  2191. }
  2192. keyData->values.push_back(channelIndex);
  2193. keyData->weights.push_back(values.at(k) / 100.0f);
  2194. k++;
  2195. }
  2196. }
  2197. }
  2198. }
  2199. }
  2200. }
  2201. }
  2202. }
  2203. }
  2204. }
  2205. }
  2206. // ------------------------------------------------------------------------------------------------
  2207. #ifdef ASSIMP_BUILD_DEBUG
  2208. // ------------------------------------------------------------------------------------------------
  2209. // sanity check whether the input is ok
  2210. static void validateAnimCurveNodes(const std::vector<const AnimationCurveNode *> &curves,
  2211. bool strictMode) {
  2212. const Object *target(nullptr);
  2213. for (const AnimationCurveNode *node : curves) {
  2214. if (!target) {
  2215. target = node->Target();
  2216. }
  2217. if (node->Target() != target) {
  2218. FBXImporter::LogWarn("Node target is nullptr type.");
  2219. }
  2220. if (strictMode) {
  2221. ai_assert(node->Target() == target);
  2222. }
  2223. }
  2224. }
  2225. #endif // ASSIMP_BUILD_DEBUG
  2226. // ------------------------------------------------------------------------------------------------
  2227. void FBXConverter::GenerateNodeAnimations(std::vector<aiNodeAnim *> &node_anims,
  2228. const std::string &fixed_name,
  2229. const std::vector<const AnimationCurveNode *> &curves,
  2230. const LayerMap &layer_map,
  2231. int64_t start, int64_t stop,
  2232. double &max_time,
  2233. double &min_time) {
  2234. NodeMap node_property_map;
  2235. ai_assert(curves.size());
  2236. #ifdef ASSIMP_BUILD_DEBUG
  2237. validateAnimCurveNodes(curves, doc.Settings().strictMode);
  2238. #endif
  2239. const AnimationCurveNode *curve_node = nullptr;
  2240. for (const AnimationCurveNode *node : curves) {
  2241. ai_assert(node);
  2242. if (node->TargetProperty().empty()) {
  2243. FBXImporter::LogWarn("target property for animation curve not set: " + node->Name());
  2244. continue;
  2245. }
  2246. curve_node = node;
  2247. if (node->Curves().empty()) {
  2248. FBXImporter::LogWarn("no animation curves assigned to AnimationCurveNode: " + node->Name());
  2249. continue;
  2250. }
  2251. node_property_map[node->TargetProperty()].push_back(node);
  2252. }
  2253. ai_assert(curve_node);
  2254. ai_assert(curve_node->TargetAsModel());
  2255. const Model &target = *curve_node->TargetAsModel();
  2256. // check for all possible transformation components
  2257. NodeMap::const_iterator chain[TransformationComp_MAXIMUM];
  2258. bool has_any = false;
  2259. bool has_complex = false;
  2260. for (size_t i = 0; i < TransformationComp_MAXIMUM; ++i) {
  2261. const TransformationComp comp = static_cast<TransformationComp>(i);
  2262. // inverse pivots don't exist in the input, we just generate them
  2263. if (comp == TransformationComp_RotationPivotInverse || comp == TransformationComp_ScalingPivotInverse) {
  2264. chain[i] = node_property_map.end();
  2265. continue;
  2266. }
  2267. chain[i] = node_property_map.find(NameTransformationCompProperty(comp));
  2268. if (chain[i] != node_property_map.end()) {
  2269. // check if this curves contains redundant information by looking
  2270. // up the corresponding node's transformation chain.
  2271. if (doc.Settings().optimizeEmptyAnimationCurves &&
  2272. IsRedundantAnimationData(target, comp, (chain[i]->second))) {
  2273. FBXImporter::LogVerboseDebug("dropping redundant animation channel for node " + target.Name());
  2274. continue;
  2275. }
  2276. has_any = true;
  2277. if (comp != TransformationComp_Rotation && comp != TransformationComp_Scaling && comp != TransformationComp_Translation) {
  2278. has_complex = true;
  2279. }
  2280. }
  2281. }
  2282. if (!has_any) {
  2283. FBXImporter::LogWarn("ignoring node animation, did not find any transformation key frames");
  2284. return;
  2285. }
  2286. // this needs to play nicely with GenerateTransformationNodeChain() which will
  2287. // be invoked _later_ (animations come first). If this node has only rotation,
  2288. // scaling and translation _and_ there are no animated other components either,
  2289. // we can use a single node and also a single node animation channel.
  2290. if( !has_complex && !NeedsComplexTransformationChain(target)) {
  2291. aiNodeAnim* const nd = GenerateSimpleNodeAnim(fixed_name, target, chain,
  2292. node_property_map.end(),
  2293. start, stop,
  2294. max_time,
  2295. min_time
  2296. );
  2297. ai_assert(nd);
  2298. if (nd->mNumPositionKeys == 0 && nd->mNumRotationKeys == 0 && nd->mNumScalingKeys == 0) {
  2299. delete nd;
  2300. } else {
  2301. node_anims.push_back(nd);
  2302. }
  2303. return;
  2304. }
  2305. // otherwise, things get gruesome and we need separate animation channels
  2306. // for each part of the transformation chain. Remember which channels
  2307. // we generated and pass this information to the node conversion
  2308. // code to avoid nodes that have identity transform, but non-identity
  2309. // animations, being dropped.
  2310. unsigned int flags = 0, bit = 0x1;
  2311. for (size_t i = 0; i < TransformationComp_MAXIMUM; ++i, bit <<= 1) {
  2312. const TransformationComp comp = static_cast<TransformationComp>(i);
  2313. if (chain[i] != node_property_map.end()) {
  2314. flags |= bit;
  2315. ai_assert(comp != TransformationComp_RotationPivotInverse);
  2316. ai_assert(comp != TransformationComp_ScalingPivotInverse);
  2317. const std::string &chain_name = NameTransformationChainNode(fixed_name, comp);
  2318. aiNodeAnim *na = nullptr;
  2319. switch (comp) {
  2320. case TransformationComp_Rotation:
  2321. case TransformationComp_PreRotation:
  2322. case TransformationComp_PostRotation:
  2323. case TransformationComp_GeometricRotation:
  2324. na = GenerateRotationNodeAnim(chain_name,
  2325. target,
  2326. (*chain[i]).second,
  2327. layer_map,
  2328. start, stop,
  2329. max_time,
  2330. min_time);
  2331. break;
  2332. case TransformationComp_RotationOffset:
  2333. case TransformationComp_RotationPivot:
  2334. case TransformationComp_ScalingOffset:
  2335. case TransformationComp_ScalingPivot:
  2336. case TransformationComp_Translation:
  2337. case TransformationComp_GeometricTranslation:
  2338. na = GenerateTranslationNodeAnim(chain_name,
  2339. target,
  2340. (*chain[i]).second,
  2341. layer_map,
  2342. start, stop,
  2343. max_time,
  2344. min_time);
  2345. // pivoting requires us to generate an implicit inverse channel to undo the pivot translation
  2346. if (comp == TransformationComp_RotationPivot) {
  2347. const std::string &invName = NameTransformationChainNode(fixed_name,
  2348. TransformationComp_RotationPivotInverse);
  2349. aiNodeAnim *const inv = GenerateTranslationNodeAnim(invName,
  2350. target,
  2351. (*chain[i]).second,
  2352. layer_map,
  2353. start, stop,
  2354. max_time,
  2355. min_time,
  2356. true);
  2357. ai_assert(inv);
  2358. if (inv->mNumPositionKeys == 0 && inv->mNumRotationKeys == 0 && inv->mNumScalingKeys == 0) {
  2359. delete inv;
  2360. } else {
  2361. node_anims.push_back(inv);
  2362. }
  2363. ai_assert(TransformationComp_RotationPivotInverse > i);
  2364. flags |= bit << (TransformationComp_RotationPivotInverse - i);
  2365. } else if (comp == TransformationComp_ScalingPivot) {
  2366. const std::string &invName = NameTransformationChainNode(fixed_name,
  2367. TransformationComp_ScalingPivotInverse);
  2368. aiNodeAnim *const inv = GenerateTranslationNodeAnim(invName,
  2369. target,
  2370. (*chain[i]).second,
  2371. layer_map,
  2372. start, stop,
  2373. max_time,
  2374. min_time,
  2375. true);
  2376. ai_assert(inv);
  2377. if (inv->mNumPositionKeys == 0 && inv->mNumRotationKeys == 0 && inv->mNumScalingKeys == 0) {
  2378. delete inv;
  2379. } else {
  2380. node_anims.push_back(inv);
  2381. }
  2382. ai_assert(TransformationComp_RotationPivotInverse > i);
  2383. flags |= bit << (TransformationComp_RotationPivotInverse - i);
  2384. }
  2385. break;
  2386. case TransformationComp_Scaling:
  2387. case TransformationComp_GeometricScaling:
  2388. na = GenerateScalingNodeAnim(chain_name,
  2389. target,
  2390. (*chain[i]).second,
  2391. layer_map,
  2392. start, stop,
  2393. max_time,
  2394. min_time);
  2395. break;
  2396. default:
  2397. ai_assert(false);
  2398. }
  2399. ai_assert(na);
  2400. if (na->mNumPositionKeys == 0 && na->mNumRotationKeys == 0 && na->mNumScalingKeys == 0) {
  2401. delete na;
  2402. } else {
  2403. node_anims.push_back(na);
  2404. }
  2405. continue;
  2406. }
  2407. }
  2408. node_anim_chain_bits[fixed_name] = flags;
  2409. }
  2410. bool FBXConverter::IsRedundantAnimationData(const Model &target,
  2411. TransformationComp comp,
  2412. const std::vector<const AnimationCurveNode *> &curves) {
  2413. ai_assert(curves.size());
  2414. // look for animation nodes with
  2415. // * sub channels for all relevant components set
  2416. // * one key/value pair per component
  2417. // * combined values match up the corresponding value in the bind pose node transformation
  2418. // only such nodes are 'redundant' for this function.
  2419. if (curves.size() > 1) {
  2420. return false;
  2421. }
  2422. const AnimationCurveNode &nd = *curves.front();
  2423. const AnimationCurveMap &sub_curves = nd.Curves();
  2424. const AnimationCurveMap::const_iterator dx = sub_curves.find("d|X");
  2425. const AnimationCurveMap::const_iterator dy = sub_curves.find("d|Y");
  2426. const AnimationCurveMap::const_iterator dz = sub_curves.find("d|Z");
  2427. if (dx == sub_curves.end() || dy == sub_curves.end() || dz == sub_curves.end()) {
  2428. return false;
  2429. }
  2430. const KeyValueList &vx = (*dx).second->GetValues();
  2431. const KeyValueList &vy = (*dy).second->GetValues();
  2432. const KeyValueList &vz = (*dz).second->GetValues();
  2433. if (vx.size() != 1 || vy.size() != 1 || vz.size() != 1) {
  2434. return false;
  2435. }
  2436. const aiVector3D dyn_val = aiVector3D(vx[0], vy[0], vz[0]);
  2437. const aiVector3D &static_val = PropertyGet<aiVector3D>(target.Props(),
  2438. NameTransformationCompProperty(comp),
  2439. TransformationCompDefaultValue(comp));
  2440. const float epsilon = Math::getEpsilon<float>();
  2441. return (dyn_val - static_val).SquareLength() < epsilon;
  2442. }
  2443. aiNodeAnim *FBXConverter::GenerateRotationNodeAnim(const std::string &name,
  2444. const Model &target,
  2445. const std::vector<const AnimationCurveNode *> &curves,
  2446. const LayerMap &layer_map,
  2447. int64_t start, int64_t stop,
  2448. double &max_time,
  2449. double &min_time) {
  2450. std::unique_ptr<aiNodeAnim> na(new aiNodeAnim());
  2451. na->mNodeName.Set(name);
  2452. ConvertRotationKeys(na.get(), curves, layer_map, start, stop, max_time, min_time, target.RotationOrder());
  2453. // dummy scaling key
  2454. na->mScalingKeys = new aiVectorKey[1];
  2455. na->mNumScalingKeys = 1;
  2456. na->mScalingKeys[0].mTime = 0.;
  2457. na->mScalingKeys[0].mValue = aiVector3D(1.0f, 1.0f, 1.0f);
  2458. // dummy position key
  2459. na->mPositionKeys = new aiVectorKey[1];
  2460. na->mNumPositionKeys = 1;
  2461. na->mPositionKeys[0].mTime = 0.;
  2462. na->mPositionKeys[0].mValue = aiVector3D();
  2463. return na.release();
  2464. }
  2465. aiNodeAnim *FBXConverter::GenerateScalingNodeAnim(const std::string &name,
  2466. const Model & /*target*/,
  2467. const std::vector<const AnimationCurveNode *> &curves,
  2468. const LayerMap &layer_map,
  2469. int64_t start, int64_t stop,
  2470. double &max_time,
  2471. double &min_time) {
  2472. std::unique_ptr<aiNodeAnim> na(new aiNodeAnim());
  2473. na->mNodeName.Set(name);
  2474. ConvertScaleKeys(na.get(), curves, layer_map, start, stop, max_time, min_time);
  2475. // dummy rotation key
  2476. na->mRotationKeys = new aiQuatKey[1];
  2477. na->mNumRotationKeys = 1;
  2478. na->mRotationKeys[0].mTime = 0.;
  2479. na->mRotationKeys[0].mValue = aiQuaternion();
  2480. // dummy position key
  2481. na->mPositionKeys = new aiVectorKey[1];
  2482. na->mNumPositionKeys = 1;
  2483. na->mPositionKeys[0].mTime = 0.;
  2484. na->mPositionKeys[0].mValue = aiVector3D();
  2485. return na.release();
  2486. }
  2487. aiNodeAnim *FBXConverter::GenerateTranslationNodeAnim(const std::string &name,
  2488. const Model & /*target*/,
  2489. const std::vector<const AnimationCurveNode *> &curves,
  2490. const LayerMap &layer_map,
  2491. int64_t start, int64_t stop,
  2492. double &max_time,
  2493. double &min_time,
  2494. bool inverse) {
  2495. std::unique_ptr<aiNodeAnim> na(new aiNodeAnim());
  2496. na->mNodeName.Set(name);
  2497. ConvertTranslationKeys(na.get(), curves, layer_map, start, stop, max_time, min_time);
  2498. if (inverse) {
  2499. for (unsigned int i = 0; i < na->mNumPositionKeys; ++i) {
  2500. na->mPositionKeys[i].mValue *= -1.0f;
  2501. }
  2502. }
  2503. // dummy scaling key
  2504. na->mScalingKeys = new aiVectorKey[1];
  2505. na->mNumScalingKeys = 1;
  2506. na->mScalingKeys[0].mTime = 0.;
  2507. na->mScalingKeys[0].mValue = aiVector3D(1.0f, 1.0f, 1.0f);
  2508. // dummy rotation key
  2509. na->mRotationKeys = new aiQuatKey[1];
  2510. na->mNumRotationKeys = 1;
  2511. na->mRotationKeys[0].mTime = 0.;
  2512. na->mRotationKeys[0].mValue = aiQuaternion();
  2513. return na.release();
  2514. }
  2515. aiNodeAnim* FBXConverter::GenerateSimpleNodeAnim(const std::string& name,
  2516. const Model& target,
  2517. NodeMap::const_iterator chain[TransformationComp_MAXIMUM],
  2518. NodeMap::const_iterator iterEnd,
  2519. int64_t start, int64_t stop,
  2520. double& maxTime,
  2521. double& minTime)
  2522. {
  2523. std::unique_ptr<aiNodeAnim> na(new aiNodeAnim());
  2524. na->mNodeName.Set(name);
  2525. const PropertyTable &props = target.Props();
  2526. // collect unique times and keyframe lists
  2527. KeyFrameListList keyframeLists[TransformationComp_MAXIMUM];
  2528. KeyTimeList keytimes;
  2529. for (size_t i = 0; i < TransformationComp_MAXIMUM; ++i) {
  2530. if (chain[i] == iterEnd)
  2531. continue;
  2532. keyframeLists[i] = GetKeyframeList((*chain[i]).second, start, stop);
  2533. for (KeyFrameListList::const_iterator it = keyframeLists[i].begin(); it != keyframeLists[i].end(); ++it) {
  2534. const KeyTimeList& times = *std::get<0>(*it);
  2535. keytimes.insert(keytimes.end(), times.begin(), times.end());
  2536. }
  2537. // remove duplicates
  2538. std::sort(keytimes.begin(), keytimes.end());
  2539. auto last = std::unique(keytimes.begin(), keytimes.end());
  2540. keytimes.erase(last, keytimes.end());
  2541. }
  2542. const Model::RotOrder rotOrder = target.RotationOrder();
  2543. const size_t keyCount = keytimes.size();
  2544. aiVector3D defTranslate = PropertyGet(props, "Lcl Translation", aiVector3D(0.f, 0.f, 0.f));
  2545. aiVector3D defRotation = PropertyGet(props, "Lcl Rotation", aiVector3D(0.f, 0.f, 0.f));
  2546. aiVector3D defScale = PropertyGet(props, "Lcl Scaling", aiVector3D(1.f, 1.f, 1.f));
  2547. aiQuaternion defQuat = EulerToQuaternion(defRotation, rotOrder);
  2548. aiVectorKey* outTranslations = new aiVectorKey[keyCount];
  2549. aiQuatKey* outRotations = new aiQuatKey[keyCount];
  2550. aiVectorKey* outScales = new aiVectorKey[keyCount];
  2551. if (keyframeLists[TransformationComp_Translation].size() > 0) {
  2552. InterpolateKeys(outTranslations, keytimes, keyframeLists[TransformationComp_Translation], defTranslate, maxTime, minTime);
  2553. } else {
  2554. for (size_t i = 0; i < keyCount; ++i) {
  2555. outTranslations[i].mTime = CONVERT_FBX_TIME(keytimes[i]) * anim_fps;
  2556. outTranslations[i].mValue = defTranslate;
  2557. }
  2558. }
  2559. if (keyframeLists[TransformationComp_Rotation].size() > 0) {
  2560. InterpolateKeys(outRotations, keytimes, keyframeLists[TransformationComp_Rotation], defRotation, maxTime, minTime, rotOrder);
  2561. } else {
  2562. for (size_t i = 0; i < keyCount; ++i) {
  2563. outRotations[i].mTime = CONVERT_FBX_TIME(keytimes[i]) * anim_fps;
  2564. outRotations[i].mValue = defQuat;
  2565. }
  2566. }
  2567. if (keyframeLists[TransformationComp_Scaling].size() > 0) {
  2568. InterpolateKeys(outScales, keytimes, keyframeLists[TransformationComp_Scaling], defScale, maxTime, minTime);
  2569. } else {
  2570. for (size_t i = 0; i < keyCount; ++i) {
  2571. outScales[i].mTime = CONVERT_FBX_TIME(keytimes[i]) * anim_fps;
  2572. outScales[i].mValue = defScale;
  2573. }
  2574. }
  2575. bool ok = false;
  2576. const float zero_epsilon = 1e-6f;
  2577. const aiVector3D& preRotation = PropertyGet<aiVector3D>(props, "PreRotation", ok);
  2578. if (ok && preRotation.SquareLength() > zero_epsilon) {
  2579. const aiQuaternion preQuat = EulerToQuaternion(preRotation, Model::RotOrder_EulerXYZ);
  2580. for (size_t i = 0; i < keyCount; ++i) {
  2581. outRotations[i].mValue = preQuat * outRotations[i].mValue;
  2582. }
  2583. }
  2584. const aiVector3D& postRotation = PropertyGet<aiVector3D>(props, "PostRotation", ok);
  2585. if (ok && postRotation.SquareLength() > zero_epsilon) {
  2586. const aiQuaternion postQuat = EulerToQuaternion(postRotation, Model::RotOrder_EulerXYZ);
  2587. for (size_t i = 0; i < keyCount; ++i) {
  2588. outRotations[i].mValue = outRotations[i].mValue * postQuat;
  2589. }
  2590. }
  2591. // convert TRS to SRT
  2592. for (size_t i = 0; i < keyCount; ++i) {
  2593. aiQuaternion& r = outRotations[i].mValue;
  2594. aiVector3D& s = outScales[i].mValue;
  2595. aiVector3D& t = outTranslations[i].mValue;
  2596. aiMatrix4x4 mat, temp;
  2597. aiMatrix4x4::Translation(t, mat);
  2598. mat *= aiMatrix4x4(r.GetMatrix());
  2599. mat *= aiMatrix4x4::Scaling(s, temp);
  2600. mat.Decompose(s, r, t);
  2601. }
  2602. na->mNumScalingKeys = static_cast<unsigned int>(keyCount);
  2603. na->mNumRotationKeys = na->mNumScalingKeys;
  2604. na->mNumPositionKeys = na->mNumScalingKeys;
  2605. na->mScalingKeys = outScales;
  2606. na->mRotationKeys = outRotations;
  2607. na->mPositionKeys = outTranslations;
  2608. return na.release();
  2609. }
  2610. FBXConverter::KeyFrameListList FBXConverter::GetKeyframeList(const std::vector<const AnimationCurveNode *> &nodes, int64_t start, int64_t stop) {
  2611. KeyFrameListList inputs;
  2612. inputs.reserve(nodes.size() * 3);
  2613. //give some breathing room for rounding errors
  2614. int64_t adj_start = start - 10000;
  2615. int64_t adj_stop = stop + 10000;
  2616. for (const AnimationCurveNode *node : nodes) {
  2617. ai_assert(node);
  2618. const AnimationCurveMap &curves = node->Curves();
  2619. for (const AnimationCurveMap::value_type &kv : curves) {
  2620. unsigned int mapto;
  2621. if (kv.first == "d|X") {
  2622. mapto = 0;
  2623. } else if (kv.first == "d|Y") {
  2624. mapto = 1;
  2625. } else if (kv.first == "d|Z") {
  2626. mapto = 2;
  2627. } else {
  2628. FBXImporter::LogWarn("ignoring scale animation curve, did not recognize target component");
  2629. continue;
  2630. }
  2631. const AnimationCurve *const curve = kv.second;
  2632. ai_assert(curve->GetKeys().size() == curve->GetValues().size() && curve->GetKeys().size());
  2633. //get values within the start/stop time window
  2634. std::shared_ptr<KeyTimeList> Keys(new KeyTimeList());
  2635. std::shared_ptr<KeyValueList> Values(new KeyValueList());
  2636. const size_t count = curve->GetKeys().size();
  2637. Keys->reserve(count);
  2638. Values->reserve(count);
  2639. for (size_t n = 0; n < count; n++) {
  2640. int64_t k = curve->GetKeys().at(n);
  2641. if (k >= adj_start && k <= adj_stop) {
  2642. Keys->push_back(k);
  2643. Values->push_back(curve->GetValues().at(n));
  2644. }
  2645. }
  2646. inputs.push_back(std::make_tuple(Keys, Values, mapto));
  2647. }
  2648. }
  2649. return inputs; // pray for NRVO :-)
  2650. }
  2651. KeyTimeList FBXConverter::GetKeyTimeList(const KeyFrameListList &inputs) {
  2652. ai_assert(!inputs.empty());
  2653. // reserve some space upfront - it is likely that the key-frame lists
  2654. // have matching time values, so max(of all key-frame lists) should
  2655. // be a good estimate.
  2656. KeyTimeList keys;
  2657. size_t estimate = 0;
  2658. for (const KeyFrameList &kfl : inputs) {
  2659. estimate = std::max(estimate, std::get<0>(kfl)->size());
  2660. }
  2661. keys.reserve(estimate);
  2662. std::vector<unsigned int> next_pos;
  2663. next_pos.resize(inputs.size(), 0);
  2664. const size_t count = inputs.size();
  2665. while (true) {
  2666. int64_t min_tick = std::numeric_limits<int64_t>::max();
  2667. for (size_t i = 0; i < count; ++i) {
  2668. const KeyFrameList &kfl = inputs[i];
  2669. if (std::get<0>(kfl)->size() > next_pos[i] && std::get<0>(kfl)->at(next_pos[i]) < min_tick) {
  2670. min_tick = std::get<0>(kfl)->at(next_pos[i]);
  2671. }
  2672. }
  2673. if (min_tick == std::numeric_limits<int64_t>::max()) {
  2674. break;
  2675. }
  2676. keys.push_back(min_tick);
  2677. for (size_t i = 0; i < count; ++i) {
  2678. const KeyFrameList &kfl = inputs[i];
  2679. while (std::get<0>(kfl)->size() > next_pos[i] && std::get<0>(kfl)->at(next_pos[i]) == min_tick) {
  2680. ++next_pos[i];
  2681. }
  2682. }
  2683. }
  2684. return keys;
  2685. }
  2686. void FBXConverter::InterpolateKeys(aiVectorKey *valOut, const KeyTimeList &keys, const KeyFrameListList &inputs,
  2687. const aiVector3D &def_value,
  2688. double &max_time,
  2689. double &min_time) {
  2690. ai_assert(!keys.empty());
  2691. ai_assert(nullptr != valOut);
  2692. std::vector<unsigned int> next_pos;
  2693. const size_t count(inputs.size());
  2694. next_pos.resize(inputs.size(), 0);
  2695. for (KeyTimeList::value_type time : keys) {
  2696. ai_real result[3] = { def_value.x, def_value.y, def_value.z };
  2697. for (size_t i = 0; i < count; ++i) {
  2698. const KeyFrameList &kfl = inputs[i];
  2699. const size_t ksize = std::get<0>(kfl)->size();
  2700. if (ksize == 0) {
  2701. continue;
  2702. }
  2703. if (ksize > next_pos[i] && std::get<0>(kfl)->at(next_pos[i]) == time) {
  2704. ++next_pos[i];
  2705. }
  2706. const size_t id0 = next_pos[i] > 0 ? next_pos[i] - 1 : 0;
  2707. const size_t id1 = next_pos[i] == ksize ? ksize - 1 : next_pos[i];
  2708. // use lerp for interpolation
  2709. const KeyValueList::value_type valueA = std::get<1>(kfl)->at(id0);
  2710. const KeyValueList::value_type valueB = std::get<1>(kfl)->at(id1);
  2711. const KeyTimeList::value_type timeA = std::get<0>(kfl)->at(id0);
  2712. const KeyTimeList::value_type timeB = std::get<0>(kfl)->at(id1);
  2713. const ai_real factor = timeB == timeA ? ai_real(0.) : static_cast<ai_real>((time - timeA)) / (timeB - timeA);
  2714. const ai_real interpValue = static_cast<ai_real>(valueA + (valueB - valueA) * factor);
  2715. result[std::get<2>(kfl)] = interpValue;
  2716. }
  2717. // magic value to convert fbx times to seconds
  2718. valOut->mTime = CONVERT_FBX_TIME(time) * anim_fps;
  2719. min_time = std::min(min_time, valOut->mTime);
  2720. max_time = std::max(max_time, valOut->mTime);
  2721. valOut->mValue.x = result[0];
  2722. valOut->mValue.y = result[1];
  2723. valOut->mValue.z = result[2];
  2724. ++valOut;
  2725. }
  2726. }
  2727. void FBXConverter::InterpolateKeys(aiQuatKey *valOut, const KeyTimeList &keys, const KeyFrameListList &inputs,
  2728. const aiVector3D &def_value,
  2729. double &maxTime,
  2730. double &minTime,
  2731. Model::RotOrder order) {
  2732. ai_assert(!keys.empty());
  2733. ai_assert(nullptr != valOut);
  2734. std::unique_ptr<aiVectorKey[]> temp(new aiVectorKey[keys.size()]);
  2735. InterpolateKeys(temp.get(), keys, inputs, def_value, maxTime, minTime);
  2736. aiMatrix4x4 m;
  2737. aiQuaternion lastq;
  2738. for (size_t i = 0, c = keys.size(); i < c; ++i) {
  2739. valOut[i].mTime = temp[i].mTime;
  2740. GetRotationMatrix(order, temp[i].mValue, m);
  2741. aiQuaternion quat = aiQuaternion(aiMatrix3x3(m));
  2742. // take shortest path by checking the inner product
  2743. // http://www.3dkingdoms.com/weekly/weekly.php?a=36
  2744. if (quat.x * lastq.x + quat.y * lastq.y + quat.z * lastq.z + quat.w * lastq.w < 0) {
  2745. quat.Conjugate();
  2746. quat.w = -quat.w;
  2747. }
  2748. lastq = quat;
  2749. valOut[i].mValue = quat;
  2750. }
  2751. }
  2752. aiQuaternion FBXConverter::EulerToQuaternion(const aiVector3D &rot, Model::RotOrder order) {
  2753. aiMatrix4x4 m;
  2754. GetRotationMatrix(order, rot, m);
  2755. return aiQuaternion(aiMatrix3x3(m));
  2756. }
  2757. void FBXConverter::ConvertScaleKeys(aiNodeAnim *na, const std::vector<const AnimationCurveNode *> &nodes, const LayerMap & /*layers*/,
  2758. int64_t start, int64_t stop,
  2759. double &maxTime,
  2760. double &minTime) {
  2761. ai_assert(nodes.size());
  2762. // XXX for now, assume scale should be blended geometrically (i.e. two
  2763. // layers should be multiplied with each other). There is a FBX
  2764. // property in the layer to specify the behaviour, though.
  2765. const KeyFrameListList &inputs = GetKeyframeList(nodes, start, stop);
  2766. const KeyTimeList &keys = GetKeyTimeList(inputs);
  2767. na->mNumScalingKeys = static_cast<unsigned int>(keys.size());
  2768. na->mScalingKeys = new aiVectorKey[keys.size()];
  2769. if (keys.size() > 0) {
  2770. InterpolateKeys(na->mScalingKeys, keys, inputs, aiVector3D(1.0f, 1.0f, 1.0f), maxTime, minTime);
  2771. }
  2772. }
  2773. void FBXConverter::ConvertTranslationKeys(aiNodeAnim *na, const std::vector<const AnimationCurveNode *> &nodes,
  2774. const LayerMap & /*layers*/,
  2775. int64_t start, int64_t stop,
  2776. double &maxTime,
  2777. double &minTime) {
  2778. ai_assert(nodes.size());
  2779. // XXX see notes in ConvertScaleKeys()
  2780. const KeyFrameListList &inputs = GetKeyframeList(nodes, start, stop);
  2781. const KeyTimeList &keys = GetKeyTimeList(inputs);
  2782. na->mNumPositionKeys = static_cast<unsigned int>(keys.size());
  2783. na->mPositionKeys = new aiVectorKey[keys.size()];
  2784. if (keys.size() > 0)
  2785. InterpolateKeys(na->mPositionKeys, keys, inputs, aiVector3D(0.0f, 0.0f, 0.0f), maxTime, minTime);
  2786. }
  2787. void FBXConverter::ConvertRotationKeys(aiNodeAnim *na, const std::vector<const AnimationCurveNode *> &nodes,
  2788. const LayerMap & /*layers*/,
  2789. int64_t start, int64_t stop,
  2790. double &maxTime,
  2791. double &minTime,
  2792. Model::RotOrder order) {
  2793. ai_assert(nodes.size());
  2794. // XXX see notes in ConvertScaleKeys()
  2795. const std::vector<KeyFrameList> &inputs = GetKeyframeList(nodes, start, stop);
  2796. const KeyTimeList &keys = GetKeyTimeList(inputs);
  2797. na->mNumRotationKeys = static_cast<unsigned int>(keys.size());
  2798. na->mRotationKeys = new aiQuatKey[keys.size()];
  2799. if (!keys.empty()) {
  2800. InterpolateKeys(na->mRotationKeys, keys, inputs, aiVector3D(0.0f, 0.0f, 0.0f), maxTime, minTime, order);
  2801. }
  2802. }
  2803. void FBXConverter::ConvertGlobalSettings() {
  2804. if (nullptr == mSceneOut) {
  2805. return;
  2806. }
  2807. const bool hasGenerator = !doc.Creator().empty();
  2808. mSceneOut->mMetaData = aiMetadata::Alloc(16 + (hasGenerator ? 1 : 0));
  2809. mSceneOut->mMetaData->Set(0, "UpAxis", doc.GlobalSettings().UpAxis());
  2810. mSceneOut->mMetaData->Set(1, "UpAxisSign", doc.GlobalSettings().UpAxisSign());
  2811. mSceneOut->mMetaData->Set(2, "FrontAxis", doc.GlobalSettings().FrontAxis());
  2812. mSceneOut->mMetaData->Set(3, "FrontAxisSign", doc.GlobalSettings().FrontAxisSign());
  2813. mSceneOut->mMetaData->Set(4, "CoordAxis", doc.GlobalSettings().CoordAxis());
  2814. mSceneOut->mMetaData->Set(5, "CoordAxisSign", doc.GlobalSettings().CoordAxisSign());
  2815. mSceneOut->mMetaData->Set(6, "OriginalUpAxis", doc.GlobalSettings().OriginalUpAxis());
  2816. mSceneOut->mMetaData->Set(7, "OriginalUpAxisSign", doc.GlobalSettings().OriginalUpAxisSign());
  2817. //const double unitScaleFactor = (double)doc.GlobalSettings().UnitScaleFactor();
  2818. mSceneOut->mMetaData->Set(8, "UnitScaleFactor", doc.GlobalSettings().UnitScaleFactor());
  2819. mSceneOut->mMetaData->Set(9, "OriginalUnitScaleFactor", doc.GlobalSettings().OriginalUnitScaleFactor());
  2820. mSceneOut->mMetaData->Set(10, "AmbientColor", doc.GlobalSettings().AmbientColor());
  2821. mSceneOut->mMetaData->Set(11, "FrameRate", (int)doc.GlobalSettings().TimeMode());
  2822. mSceneOut->mMetaData->Set(12, "TimeSpanStart", doc.GlobalSettings().TimeSpanStart());
  2823. mSceneOut->mMetaData->Set(13, "TimeSpanStop", doc.GlobalSettings().TimeSpanStop());
  2824. mSceneOut->mMetaData->Set(14, "CustomFrameRate", doc.GlobalSettings().CustomFrameRate());
  2825. mSceneOut->mMetaData->Set(15, AI_METADATA_SOURCE_FORMAT_VERSION, aiString(to_string(doc.FBXVersion())));
  2826. if (hasGenerator) {
  2827. mSceneOut->mMetaData->Set(16, AI_METADATA_SOURCE_GENERATOR, aiString(doc.Creator()));
  2828. }
  2829. }
  2830. void FBXConverter::TransferDataToScene() {
  2831. ai_assert(!mSceneOut->mMeshes);
  2832. ai_assert(!mSceneOut->mNumMeshes);
  2833. // note: the trailing () ensures initialization with nullptr - not
  2834. // many C++ users seem to know this, so pointing it out to avoid
  2835. // confusion why this code works.
  2836. if (mMeshes.size()) {
  2837. mSceneOut->mMeshes = new aiMesh *[mMeshes.size()]();
  2838. mSceneOut->mNumMeshes = static_cast<unsigned int>(mMeshes.size());
  2839. std::swap_ranges(mMeshes.begin(), mMeshes.end(), mSceneOut->mMeshes);
  2840. }
  2841. if (materials.size()) {
  2842. mSceneOut->mMaterials = new aiMaterial *[materials.size()]();
  2843. mSceneOut->mNumMaterials = static_cast<unsigned int>(materials.size());
  2844. std::swap_ranges(materials.begin(), materials.end(), mSceneOut->mMaterials);
  2845. }
  2846. if (animations.size()) {
  2847. mSceneOut->mAnimations = new aiAnimation *[animations.size()]();
  2848. mSceneOut->mNumAnimations = static_cast<unsigned int>(animations.size());
  2849. std::swap_ranges(animations.begin(), animations.end(), mSceneOut->mAnimations);
  2850. }
  2851. if (lights.size()) {
  2852. mSceneOut->mLights = new aiLight *[lights.size()]();
  2853. mSceneOut->mNumLights = static_cast<unsigned int>(lights.size());
  2854. std::swap_ranges(lights.begin(), lights.end(), mSceneOut->mLights);
  2855. }
  2856. if (cameras.size()) {
  2857. mSceneOut->mCameras = new aiCamera *[cameras.size()]();
  2858. mSceneOut->mNumCameras = static_cast<unsigned int>(cameras.size());
  2859. std::swap_ranges(cameras.begin(), cameras.end(), mSceneOut->mCameras);
  2860. }
  2861. if (textures.size()) {
  2862. mSceneOut->mTextures = new aiTexture *[textures.size()]();
  2863. mSceneOut->mNumTextures = static_cast<unsigned int>(textures.size());
  2864. std::swap_ranges(textures.begin(), textures.end(), mSceneOut->mTextures);
  2865. }
  2866. }
  2867. void FBXConverter::ConvertOrphanedEmbeddedTextures() {
  2868. // in C++14 it could be:
  2869. // for (auto&& [id, object] : objects)
  2870. for (auto &&id_and_object : doc.Objects()) {
  2871. auto &&id = std::get<0>(id_and_object);
  2872. auto &&object = std::get<1>(id_and_object);
  2873. // If an object doesn't have parent
  2874. if (doc.ConnectionsBySource().count(id) == 0) {
  2875. const Texture *realTexture = nullptr;
  2876. try {
  2877. const auto &element = object->GetElement();
  2878. const Token &key = element.KeyToken();
  2879. const char *obtype = key.begin();
  2880. const size_t length = static_cast<size_t>(key.end() - key.begin());
  2881. if (strncmp(obtype, "Texture", length) == 0) {
  2882. const Texture *texture = static_cast<const Texture *>(object->Get());
  2883. if (texture->Media() && texture->Media()->ContentLength() > 0) {
  2884. realTexture = texture;
  2885. }
  2886. }
  2887. } catch (...) {
  2888. // do nothing
  2889. }
  2890. if (realTexture) {
  2891. const Video *media = realTexture->Media();
  2892. unsigned int index = ConvertVideo(*media);
  2893. textures_converted[*media] = index;
  2894. }
  2895. }
  2896. }
  2897. }
  2898. // ------------------------------------------------------------------------------------------------
  2899. void ConvertToAssimpScene(aiScene *out, const Document &doc, bool removeEmptyBones) {
  2900. FBXConverter converter(out, doc, removeEmptyBones);
  2901. }
  2902. } // namespace FBX
  2903. } // namespace Assimp
  2904. #endif