FBXConverter.cpp 150 KB

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