FBXConverter.cpp 119 KB

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