FBXConverter.cpp 154 KB

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