AssetImporter.cpp 109 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919
  1. //
  2. // Copyright (c) 2008-2020 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include <Urho3D/Core/Context.h>
  23. #include <Urho3D/Core/ProcessUtils.h>
  24. #include <Urho3D/Core/StringUtils.h>
  25. #include <Urho3D/Core/WorkQueue.h>
  26. #include <Urho3D/Graphics/AnimatedModel.h>
  27. #include <Urho3D/Graphics/Animation.h>
  28. #include <Urho3D/Graphics/DebugRenderer.h>
  29. #include <Urho3D/Graphics/Geometry.h>
  30. #include <Urho3D/Graphics/Graphics.h>
  31. #include <Urho3D/Graphics/IndexBuffer.h>
  32. #include <Urho3D/Graphics/Light.h>
  33. #include <Urho3D/Graphics/Material.h>
  34. #include <Urho3D/Graphics/Octree.h>
  35. #include <Urho3D/Graphics/VertexBuffer.h>
  36. #include <Urho3D/Graphics/Zone.h>
  37. #include <Urho3D/IO/File.h>
  38. #include <Urho3D/IO/FileSystem.h>
  39. #ifdef URHO3D_PHYSICS
  40. #include <Urho3D/Physics/PhysicsWorld.h>
  41. #endif
  42. #include <Urho3D/Resource/ResourceCache.h>
  43. #include <Urho3D/Resource/XMLFile.h>
  44. #include <Urho3D/Scene/Scene.h>
  45. #ifdef WIN32
  46. #include <windows.h>
  47. #endif
  48. #include <assimp/config.h>
  49. #include <assimp/cimport.h>
  50. #include <assimp/scene.h>
  51. #include <assimp/postprocess.h>
  52. #include <assimp/DefaultLogger.hpp>
  53. #include <Urho3D/DebugNew.h>
  54. using namespace Urho3D;
  55. struct OutModel
  56. {
  57. String outName_;
  58. aiNode* rootNode_{};
  59. HashSet<unsigned> meshIndices_;
  60. PODVector<aiMesh*> meshes_;
  61. PODVector<aiNode*> meshNodes_;
  62. PODVector<aiNode*> bones_;
  63. PODVector<aiNode*> pivotlessBones_;
  64. PODVector<aiAnimation*> animations_;
  65. PODVector<float> boneRadii_;
  66. PODVector<BoundingBox> boneHitboxes_;
  67. aiNode* rootBone_{};
  68. unsigned totalVertices_{};
  69. unsigned totalIndices_{};
  70. };
  71. struct OutScene
  72. {
  73. String outName_;
  74. aiNode* rootNode_{};
  75. Vector<OutModel> models_;
  76. PODVector<aiNode*> nodes_;
  77. PODVector<unsigned> nodeModelIndices_;
  78. };
  79. // FBX transform chain
  80. enum TransformationComp
  81. {
  82. TransformationComp_Translation = 0,
  83. TransformationComp_RotationOffset,
  84. TransformationComp_RotationPivot,
  85. TransformationComp_PreRotation,
  86. TransformationComp_Rotation,
  87. TransformationComp_PostRotation,
  88. TransformationComp_RotationPivotInverse,
  89. TransformationComp_ScalingOffset,
  90. TransformationComp_ScalingPivot,
  91. TransformationComp_Scaling,
  92. // Not checking these
  93. // They are typically flushed out in the fbxconverter, but there
  94. // might be cases where they're not, hence, leaving them.
  95. #ifdef EXT_TRANSFORMATION_CHECK
  96. TransformationComp_ScalingPivotInverse,
  97. TransformationComp_GeometricTranslation,
  98. TransformationComp_GeometricRotation,
  99. TransformationComp_GeometricScaling,
  100. #endif
  101. TransformationComp_MAXIMUM
  102. };
  103. const char *transformSuffix[TransformationComp_MAXIMUM] =
  104. {
  105. "Translation", // TransformationComp_Translation = 0,
  106. "RotationOffset", // TransformationComp_RotationOffset,
  107. "RotationPivot", // TransformationComp_RotationPivot,
  108. "PreRotation", // TransformationComp_PreRotation,
  109. "Rotation", // TransformationComp_Rotation,
  110. "PostRotation", // TransformationComp_PostRotation,
  111. "RotationPivotInverse", // TransformationComp_RotationPivotInverse,
  112. "ScalingOffset", // TransformationComp_ScalingOffset,
  113. "ScalingPivot", // TransformationComp_ScalingPivot,
  114. "Scaling", // TransformationComp_Scaling,
  115. #ifdef EXT_TRANSFORMATION_CHECK
  116. "ScalingPivotInverse", // TransformationComp_ScalingPivotInverse,
  117. "GeometricTranslation", // TransformationComp_GeometricTranslation,
  118. "GeometricRotation", // TransformationComp_GeometricRotation,
  119. "GeometricScaling", // TransformationComp_GeometricScaling,
  120. #endif
  121. };
  122. static const unsigned MAX_CHANNELS = 4;
  123. SharedPtr<Context> context_(new Context());
  124. const aiScene* scene_ = nullptr;
  125. aiNode* rootNode_ = nullptr;
  126. String inputName_;
  127. String resourcePath_;
  128. String outPath_;
  129. String outName_;
  130. bool useSubdirs_ = true;
  131. bool localIDs_ = false;
  132. bool saveBinary_ = false;
  133. bool saveJson_ = false;
  134. bool createZone_ = true;
  135. bool noAnimations_ = false;
  136. bool noHierarchy_ = false;
  137. bool noMaterials_ = false;
  138. bool noTextures_ = false;
  139. bool noMaterialDiffuseColor_ = false;
  140. bool noEmptyNodes_ = false;
  141. bool saveMaterialList_ = false;
  142. bool includeNonSkinningBones_ = false;
  143. bool verboseLog_ = false;
  144. bool emissiveAO_ = false;
  145. bool noOverwriteMaterial_ = false;
  146. bool noOverwriteTexture_ = false;
  147. bool noOverwriteNewerTexture_ = false;
  148. bool checkUniqueModel_ = true;
  149. bool moveToBindPose_ = false;
  150. unsigned maxBones_ = 64;
  151. Vector<String> nonSkinningBoneIncludes_;
  152. Vector<String> nonSkinningBoneExcludes_;
  153. HashSet<aiAnimation*> allAnimations_;
  154. PODVector<aiAnimation*> sceneAnimations_;
  155. float defaultTicksPerSecond_ = 4800.0f;
  156. // For subset animation import usage
  157. float importStartTime_ = 0.0f;
  158. float importEndTime_ = 0.0f;
  159. bool suppressFbxPivotNodes_ = true;
  160. int main(int argc, char** argv);
  161. void Run(const Vector<String>& arguments);
  162. void DumpNodes(aiNode* rootNode, unsigned level);
  163. void ExportModel(const String& outName, bool animationOnly);
  164. void ExportAnimation(const String& outName, bool animationOnly);
  165. void CollectMeshes(OutModel& model, aiNode* node);
  166. void CollectBones(OutModel& model, bool animationOnly = false);
  167. void CollectBonesFinal(PODVector<aiNode*>& dest, const HashSet<aiNode*>& necessary, aiNode* node);
  168. void MoveToBindPose(OutModel& model, aiNode* current);
  169. void CollectAnimations(OutModel* model = nullptr);
  170. void BuildBoneCollisionInfo(OutModel& model);
  171. void BuildAndSaveModel(OutModel& model);
  172. void BuildAndSaveAnimations(OutModel* model = nullptr);
  173. void ExportScene(const String& outName, bool asPrefab);
  174. void CollectSceneModels(OutScene& scene, aiNode* node);
  175. void CreateHierarchy(Scene* scene, aiNode* srcNode, HashMap<aiNode*, Node*>& nodeMapping);
  176. Node* CreateSceneNode(Scene* scene, aiNode* srcNode, HashMap<aiNode*, Node*>& nodeMapping);
  177. void BuildAndSaveScene(OutScene& scene, bool asPrefab);
  178. void ExportMaterials(HashSet<String>& usedTextures);
  179. void BuildAndSaveMaterial(aiMaterial* material, HashSet<String>& usedTextures);
  180. void CopyTextures(const HashSet<String>& usedTextures, const String& sourcePath);
  181. void CombineLods(const PODVector<float>& lodDistances, const Vector<String>& modelNames, const String& outName);
  182. void GetMeshesUnderNode(Vector<Pair<aiNode*, aiMesh*> >& dest, aiNode* node);
  183. unsigned GetMeshIndex(aiMesh* mesh);
  184. unsigned GetBoneIndex(OutModel& model, const String& boneName);
  185. aiBone* GetMeshBone(OutModel& model, const String& boneName);
  186. Matrix3x4 GetOffsetMatrix(OutModel& model, const String& boneName);
  187. void GetBlendData(OutModel& model, aiMesh* mesh, aiNode* meshNode, PODVector<unsigned>& boneMappings, Vector<PODVector<unsigned char> >&
  188. blendIndices, Vector<PODVector<float> >& blendWeights);
  189. String GetMeshMaterialName(aiMesh* mesh);
  190. String GetMaterialTextureName(const String& nameIn);
  191. String GenerateMaterialName(aiMaterial* material);
  192. String GenerateTextureName(unsigned texIndex);
  193. unsigned GetNumValidFaces(aiMesh* mesh);
  194. void WriteShortIndices(unsigned short*& dest, aiMesh* mesh, unsigned index, unsigned offset);
  195. void WriteLargeIndices(unsigned*& dest, aiMesh* mesh, unsigned index, unsigned offset);
  196. void WriteVertex(float*& dest, aiMesh* mesh, unsigned index, bool isSkinned, BoundingBox& box,
  197. const Matrix3x4& vertexTransform, const Matrix3& normalTransform, Vector<PODVector<unsigned char> >& blendIndices,
  198. Vector<PODVector<float> >& blendWeights);
  199. PODVector<VertexElement> GetVertexElements(aiMesh* mesh, bool isSkinned);
  200. aiNode* GetNode(const String& name, aiNode* rootNode, bool caseSensitive = true);
  201. aiMatrix4x4 GetDerivedTransform(aiNode* node, aiNode* rootNode, bool rootInclusive = true);
  202. aiMatrix4x4 GetDerivedTransform(aiMatrix4x4 transform, aiNode* node, aiNode* rootNode, bool rootInclusive = true);
  203. aiMatrix4x4 GetMeshBakingTransform(aiNode* meshNode, aiNode* modelRootNode);
  204. void GetPosRotScale(const aiMatrix4x4& transform, Vector3& pos, Quaternion& rot, Vector3& scale);
  205. String FromAIString(const aiString& str);
  206. Vector3 ToVector3(const aiVector3D& vec);
  207. Vector2 ToVector2(const aiVector2D& vec);
  208. Quaternion ToQuaternion(const aiQuaternion& quat);
  209. Matrix3x4 ToMatrix3x4(const aiMatrix4x4& mat);
  210. aiMatrix4x4 ToAIMatrix4x4(const Matrix3x4& mat);
  211. String SanitateAssetName(const String& name);
  212. unsigned GetPivotlessBoneIndex(OutModel& model, const String& boneName);
  213. void ExtrapolatePivotlessAnimation(OutModel* model);
  214. void CollectSceneNodesAsBones(OutModel &model, aiNode* rootNode);
  215. int main(int argc, char** argv)
  216. {
  217. Vector<String> arguments;
  218. #ifdef WIN32
  219. arguments = ParseArguments(GetCommandLineW());
  220. #else
  221. arguments = ParseArguments(argc, argv);
  222. #endif
  223. Run(arguments);
  224. return 0;
  225. }
  226. void Run(const Vector<String>& arguments)
  227. {
  228. if (arguments.Size() < 2)
  229. {
  230. ErrorExit(
  231. "Usage: AssetImporter <command> <input file> <output file> [options]\n"
  232. "See http://assimp.sourceforge.net/main_features_formats.html for input formats\n\n"
  233. "Commands:\n"
  234. "model Output a model\n"
  235. "anim Output animation(s)\n"
  236. "scene Output a scene\n"
  237. "node Output a node and its children (prefab)\n"
  238. "dump Dump scene node structure. No output file is generated\n"
  239. "lod Combine several Urho3D models as LOD levels of the output model\n"
  240. " Syntax: lod <dist0> <mdl0> <dist1 <mdl1> ... <output file>\n"
  241. "\n"
  242. "Options:\n"
  243. "-b Save scene in binary format, default format is XML\n"
  244. "-j Save scene in JSON format, default format is XML\n"
  245. "-h Generate hard instead of smooth normals if input has no normals\n"
  246. "-i Use local ID's for scene nodes\n"
  247. "-l Output a material list file for models\n"
  248. "-na Do not output animations\n"
  249. "-nm Do not output materials\n"
  250. "-nt Do not output material textures\n"
  251. "-nc Do not use material diffuse color value, instead output white\n"
  252. "-nh Do not save full node hierarchy (scene mode only)\n"
  253. "-ns Do not create subdirectories for resources\n"
  254. "-nz Do not create a zone and a directional light (scene mode only)\n"
  255. "-nf Do not fix infacing normals\n"
  256. "-ne Do not save empty nodes (scene mode only)\n"
  257. "-mb <x> Maximum number of bones per submesh. Default 64\n"
  258. "-p <path> Set path for scene resources. Default is output file path\n"
  259. "-r <name> Use the named scene node as root node\n"
  260. "-f <freq> Animation tick frequency to use if unspecified. Default 4800\n"
  261. "-o Optimize redundant submeshes. Loses scene hierarchy and animations\n"
  262. "-s <filter> Include non-skinning bones in the model's skeleton. Can be given a\n"
  263. " case-insensitive semicolon separated filter list. Bone is included\n"
  264. " if its name contains any of the filters. Prefix filter with minus\n"
  265. " sign to use as an exclude. For example -s \"Bip01;-Dummy;-Helper\"\n"
  266. "-t Generate tangents\n"
  267. "-v Enable verbose Assimp library logging\n"
  268. "-eao Interpret material emissive texture as ambient occlusion\n"
  269. "-cm Check and do not overwrite if material exists\n"
  270. "-ct Check and do not overwrite if texture exists\n"
  271. "-ctn Check and do not overwrite if texture has newer timestamp\n"
  272. "-am Export all meshes even if identical (scene mode only)\n"
  273. "-bp Move bones to bind pose before saving model\n"
  274. "-split <start> <end> (animation model only)\n"
  275. " Split animation, will only import from start frame to end frame\n"
  276. "-np Do not suppress $fbx pivot nodes (FBX files only)\n"
  277. );
  278. }
  279. context_->RegisterSubsystem(new FileSystem(context_));
  280. context_->RegisterSubsystem(new ResourceCache(context_));
  281. context_->RegisterSubsystem(new WorkQueue(context_));
  282. RegisterSceneLibrary(context_);
  283. RegisterGraphicsLibrary(context_);
  284. #ifdef URHO3D_PHYSICS
  285. RegisterPhysicsLibrary(context_);
  286. #endif
  287. String command = arguments[0].ToLower();
  288. String rootNodeName;
  289. unsigned flags =
  290. aiProcess_ConvertToLeftHanded |
  291. aiProcess_JoinIdenticalVertices |
  292. aiProcess_Triangulate |
  293. aiProcess_GenSmoothNormals |
  294. aiProcess_LimitBoneWeights |
  295. aiProcess_ImproveCacheLocality |
  296. aiProcess_RemoveRedundantMaterials |
  297. aiProcess_FixInfacingNormals |
  298. aiProcess_FindInvalidData |
  299. aiProcess_GenUVCoords |
  300. aiProcess_FindInstances |
  301. aiProcess_OptimizeMeshes;
  302. for (unsigned i = 2; i < arguments.Size(); ++i)
  303. {
  304. if (arguments[i].Length() > 1 && arguments[i][0] == '-')
  305. {
  306. String argument = arguments[i].Substring(1).ToLower();
  307. String value = i + 1 < arguments.Size() ? arguments[i + 1] : String::EMPTY;
  308. if (argument == "b")
  309. saveBinary_ = true;
  310. else if(argument == "j")
  311. saveJson_ = true;
  312. else if (argument == "h")
  313. {
  314. flags &= ~aiProcess_GenSmoothNormals;
  315. flags |= aiProcess_GenNormals;
  316. }
  317. else if (argument == "i")
  318. localIDs_ = true;
  319. else if (argument == "l")
  320. saveMaterialList_ = true;
  321. else if (argument == "t")
  322. flags |= aiProcess_CalcTangentSpace;
  323. else if (argument == "o")
  324. flags |= aiProcess_PreTransformVertices;
  325. else if (argument.Length() == 2 && argument[0] == 'n')
  326. {
  327. switch (tolower(argument[1]))
  328. {
  329. case 'a':
  330. noAnimations_ = true;
  331. break;
  332. case 'c':
  333. noMaterialDiffuseColor_ = true;
  334. break;
  335. case 'm':
  336. noMaterials_ = true;
  337. break;
  338. case 'h':
  339. noHierarchy_ = true;
  340. break;
  341. case 'e':
  342. noEmptyNodes_ = true;
  343. break;
  344. case 's':
  345. useSubdirs_ = false;
  346. break;
  347. case 't':
  348. noTextures_ = true;
  349. break;
  350. case 'z':
  351. createZone_ = false;
  352. break;
  353. case 'f':
  354. flags &= ~aiProcess_FixInfacingNormals;
  355. break;
  356. case 'p':
  357. suppressFbxPivotNodes_ = false;
  358. break;
  359. }
  360. }
  361. else if (argument == "mb" && !value.Empty())
  362. {
  363. maxBones_ = ToUInt(value);
  364. if (maxBones_ < 1)
  365. maxBones_ = 1;
  366. ++i;
  367. }
  368. else if (argument == "p" && !value.Empty())
  369. {
  370. resourcePath_ = AddTrailingSlash(value);
  371. ++i;
  372. }
  373. else if (argument == "r" && !value.Empty())
  374. {
  375. rootNodeName = value;
  376. ++i;
  377. }
  378. else if (argument == "f" && !value.Empty())
  379. {
  380. defaultTicksPerSecond_ = ToFloat(value);
  381. ++i;
  382. }
  383. else if (argument == "s")
  384. {
  385. includeNonSkinningBones_ = true;
  386. if (value.Length() && (value[0] != '-' || value.Length() > 3))
  387. {
  388. Vector<String> filters = value.Split(';');
  389. for (unsigned i = 0; i < filters.Size(); ++i)
  390. {
  391. if (filters[i][0] == '-')
  392. nonSkinningBoneExcludes_.Push(filters[i].Substring(1));
  393. else
  394. nonSkinningBoneIncludes_.Push(filters[i]);
  395. }
  396. }
  397. }
  398. else if (argument == "v")
  399. verboseLog_ = true;
  400. else if (argument == "eao")
  401. emissiveAO_ = true;
  402. else if (argument == "cm")
  403. noOverwriteMaterial_ = true;
  404. else if (argument == "ct")
  405. noOverwriteTexture_ = true;
  406. else if (argument == "ctn")
  407. noOverwriteNewerTexture_ = true;
  408. else if (argument == "am")
  409. checkUniqueModel_ = false;
  410. else if (argument == "bp")
  411. moveToBindPose_ = true;
  412. else if (argument == "split")
  413. {
  414. String value2 = i + 2 < arguments.Size() ? arguments[i + 2] : String::EMPTY;
  415. if (value.Length() && value2.Length() && (value[0] != '-') && (value2[0] != '-'))
  416. {
  417. importStartTime_ = ToFloat(value);
  418. importEndTime_ = ToFloat(value2);
  419. }
  420. }
  421. }
  422. }
  423. if (command == "model" || command == "scene" || command == "anim" || command == "node" || command == "dump")
  424. {
  425. String inFile = arguments[1];
  426. String outFile;
  427. if (arguments.Size() > 2 && arguments[2][0] != '-')
  428. outFile = GetInternalPath(arguments[2]);
  429. inputName_ = GetFileName(inFile);
  430. outName_ = outFile;
  431. outPath_ = GetPath(outFile);
  432. if (resourcePath_.Empty())
  433. {
  434. resourcePath_ = outPath_;
  435. // If output file already has the Models/ path (model mode), do not take it into the resource path
  436. if (command == "model")
  437. {
  438. if (resourcePath_.EndsWith("Models/", false))
  439. resourcePath_ = resourcePath_.Substring(0, resourcePath_.Length() - 7);
  440. }
  441. if (resourcePath_.Empty())
  442. resourcePath_ = "./";
  443. }
  444. resourcePath_ = AddTrailingSlash(resourcePath_);
  445. if (command != "dump" && outFile.Empty())
  446. ErrorExit("No output file defined");
  447. if (verboseLog_)
  448. Assimp::DefaultLogger::create("", Assimp::Logger::VERBOSE, aiDefaultLogStream_STDOUT);
  449. PrintLine("Reading file " + inFile);
  450. if (!inFile.EndsWith(".fbx", false))
  451. suppressFbxPivotNodes_ = false;
  452. // Only do this for the "model" command. "anim" command extrapolates animation from the original bone definition
  453. if (suppressFbxPivotNodes_ && command == "model")
  454. {
  455. PrintLine("Suppressing $fbx nodes");
  456. aiPropertyStore *aiprops = aiCreatePropertyStore();
  457. aiSetImportPropertyInteger(aiprops, AI_CONFIG_IMPORT_FBX_READ_ALL_GEOMETRY_LAYERS, 1); //default = true;
  458. aiSetImportPropertyInteger(aiprops, AI_CONFIG_IMPORT_FBX_READ_ALL_MATERIALS, 0); //default = false;
  459. aiSetImportPropertyInteger(aiprops, AI_CONFIG_IMPORT_FBX_READ_MATERIALS, 1); //default = true;
  460. aiSetImportPropertyInteger(aiprops, AI_CONFIG_IMPORT_FBX_READ_CAMERAS, 1); //default = true;
  461. aiSetImportPropertyInteger(aiprops, AI_CONFIG_IMPORT_FBX_READ_LIGHTS, 1); //default = true;
  462. aiSetImportPropertyInteger(aiprops, AI_CONFIG_IMPORT_FBX_READ_ANIMATIONS, 1); //default = true;
  463. aiSetImportPropertyInteger(aiprops, AI_CONFIG_IMPORT_FBX_STRICT_MODE, 0); //default = false;
  464. aiSetImportPropertyInteger(aiprops, AI_CONFIG_IMPORT_FBX_PRESERVE_PIVOTS, 0); //**false, default = true;
  465. aiSetImportPropertyInteger(aiprops, AI_CONFIG_IMPORT_FBX_OPTIMIZE_EMPTY_ANIMATION_CURVES, 1);//default = true;
  466. scene_ = aiImportFileExWithProperties(GetNativePath(inFile).CString(), flags, nullptr, aiprops);
  467. // prevent processing animation suppression, both cannot work simultaneously
  468. suppressFbxPivotNodes_ = false;
  469. }
  470. else
  471. scene_ = aiImportFile(GetNativePath(inFile).CString(), flags);
  472. if (!scene_)
  473. ErrorExit("Could not open or parse input file " + inFile + ": " + String(aiGetErrorString()));
  474. if (verboseLog_)
  475. Assimp::DefaultLogger::kill();
  476. rootNode_ = scene_->mRootNode;
  477. if (!rootNodeName.Empty())
  478. {
  479. rootNode_ = GetNode(rootNodeName, rootNode_, false);
  480. if (!rootNode_)
  481. ErrorExit("Could not find scene node " + rootNodeName);
  482. }
  483. if (command == "dump")
  484. {
  485. DumpNodes(rootNode_, 0);
  486. return;
  487. }
  488. if (command == "model")
  489. ExportModel(outFile, scene_->mFlags & AI_SCENE_FLAGS_INCOMPLETE);
  490. if (command == "anim")
  491. {
  492. noMaterials_ = true;
  493. ExportAnimation(outFile, scene_->mFlags & AI_SCENE_FLAGS_INCOMPLETE);
  494. }
  495. if (command == "scene" || command == "node")
  496. {
  497. bool asPrefab = command == "node";
  498. // Saving as prefab requires the hierarchy, especially the root node
  499. if (asPrefab)
  500. noHierarchy_ = false;
  501. ExportScene(outFile, asPrefab);
  502. }
  503. if (!noMaterials_)
  504. {
  505. HashSet<String> usedTextures;
  506. ExportMaterials(usedTextures);
  507. if (!noTextures_)
  508. CopyTextures(usedTextures, GetPath(inFile));
  509. }
  510. }
  511. else if (command == "lod")
  512. {
  513. PODVector<float> lodDistances;
  514. Vector<String> modelNames;
  515. String outFile;
  516. unsigned numLodArguments = 0;
  517. for (unsigned i = 1; i < arguments.Size(); ++i)
  518. {
  519. if (arguments[i][0] == '-')
  520. break;
  521. ++numLodArguments;
  522. }
  523. if (numLodArguments < 4)
  524. ErrorExit("Must define at least 2 LOD levels");
  525. if (!(numLodArguments & 1u))
  526. ErrorExit("No output file defined");
  527. for (unsigned i = 1; i < numLodArguments + 1; ++i)
  528. {
  529. if (i == numLodArguments)
  530. outFile = GetInternalPath(arguments[i]);
  531. else
  532. {
  533. if (i & 1u)
  534. lodDistances.Push(Max(ToFloat(arguments[i]), 0.0f));
  535. else
  536. modelNames.Push(GetInternalPath(arguments[i]));
  537. }
  538. }
  539. if (lodDistances[0] != 0.0f)
  540. {
  541. PrintLine("Warning: first LOD distance forced to 0");
  542. lodDistances[0] = 0.0f;
  543. }
  544. CombineLods(lodDistances, modelNames, outFile);
  545. }
  546. else
  547. ErrorExit("Unrecognized command " + command);
  548. }
  549. void DumpNodes(aiNode* rootNode, unsigned level)
  550. {
  551. if (!rootNode)
  552. return;
  553. String indent(' ', level * 2);
  554. Vector3 pos, scale;
  555. Quaternion rot;
  556. aiMatrix4x4 transform = GetDerivedTransform(rootNode, rootNode_);
  557. GetPosRotScale(transform, pos, rot, scale);
  558. PrintLine(indent + "Node " + FromAIString(rootNode->mName) + " pos " + String(pos));
  559. if (rootNode->mNumMeshes == 1)
  560. PrintLine(indent + " " + String(rootNode->mNumMeshes) + " geometry");
  561. if (rootNode->mNumMeshes > 1)
  562. PrintLine(indent + " " + String(rootNode->mNumMeshes) + " geometries");
  563. for (unsigned i = 0; i < rootNode->mNumChildren; ++i)
  564. DumpNodes(rootNode->mChildren[i], level + 1);
  565. }
  566. void ExportModel(const String& outName, bool animationOnly)
  567. {
  568. if (outName.Empty())
  569. ErrorExit("No output file defined");
  570. OutModel model;
  571. model.rootNode_ = rootNode_;
  572. model.outName_ = outName;
  573. CollectMeshes(model, model.rootNode_);
  574. CollectBones(model, animationOnly);
  575. BuildBoneCollisionInfo(model);
  576. BuildAndSaveModel(model);
  577. if (!noAnimations_)
  578. {
  579. CollectAnimations(&model);
  580. BuildAndSaveAnimations(&model);
  581. // Save scene-global animations
  582. CollectAnimations();
  583. BuildAndSaveAnimations();
  584. }
  585. }
  586. void ExportAnimation(const String& outName, bool animationOnly)
  587. {
  588. if (outName.Empty())
  589. ErrorExit("No output file defined");
  590. OutModel model;
  591. model.rootNode_ = rootNode_;
  592. model.outName_ = outName;
  593. CollectMeshes(model, model.rootNode_);
  594. CollectBones(model, animationOnly);
  595. BuildBoneCollisionInfo(model);
  596. // BuildAndSaveModel(model);
  597. if (!noAnimations_)
  598. {
  599. // Most fbx animation files contain only a skeleton and no skinned mesh.
  600. // Assume the scene node contains the model's bone definition and,
  601. // transfer the info to the model.
  602. if (suppressFbxPivotNodes_ && model.bones_.Size() == 0)
  603. CollectSceneNodesAsBones(model, rootNode_);
  604. CollectAnimations(&model);
  605. BuildAndSaveAnimations(&model);
  606. // Save scene-global animations
  607. CollectAnimations();
  608. BuildAndSaveAnimations();
  609. }
  610. }
  611. void CollectMeshes(OutModel& model, aiNode* node)
  612. {
  613. for (unsigned i = 0; i < node->mNumMeshes; ++i)
  614. {
  615. aiMesh* mesh = scene_->mMeshes[node->mMeshes[i]];
  616. for (unsigned j = 0; j < model.meshes_.Size(); ++j)
  617. {
  618. if (mesh == model.meshes_[j])
  619. {
  620. PrintLine("Warning: same mesh found multiple times");
  621. break;
  622. }
  623. }
  624. model.meshIndices_.Insert(node->mMeshes[i]);
  625. model.meshes_.Push(mesh);
  626. model.meshNodes_.Push(node);
  627. model.totalVertices_ += mesh->mNumVertices;
  628. model.totalIndices_ += GetNumValidFaces(mesh) * 3;
  629. }
  630. for (unsigned i = 0; i < node->mNumChildren; ++i)
  631. CollectMeshes(model, node->mChildren[i]);
  632. }
  633. void CollectBones(OutModel& model, bool animationOnly)
  634. {
  635. HashSet<aiNode*> necessary;
  636. HashSet<aiNode*> rootNodes;
  637. bool haveSkinnedMeshes = false;
  638. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  639. {
  640. if (model.meshes_[i]->HasBones())
  641. {
  642. haveSkinnedMeshes = true;
  643. break;
  644. }
  645. }
  646. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  647. {
  648. aiMesh* mesh = model.meshes_[i];
  649. aiNode* meshNode = model.meshNodes_[i];
  650. aiNode* meshParentNode = meshNode->mParent;
  651. aiNode* rootNode = nullptr;
  652. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  653. {
  654. aiBone* bone = mesh->mBones[j];
  655. String boneName(FromAIString(bone->mName));
  656. aiNode* boneNode = GetNode(boneName, scene_->mRootNode, true);
  657. if (!boneNode)
  658. ErrorExit("Could not find scene node for bone " + boneName);
  659. necessary.Insert(boneNode);
  660. rootNode = boneNode;
  661. for (;;)
  662. {
  663. boneNode = boneNode->mParent;
  664. if (!boneNode || ((boneNode == meshNode || boneNode == meshParentNode) && !animationOnly))
  665. break;
  666. rootNode = boneNode;
  667. necessary.Insert(boneNode);
  668. }
  669. if (rootNodes.Find(rootNode) == rootNodes.End())
  670. rootNodes.Insert(rootNode);
  671. }
  672. // When model is partially skinned, include the attachment nodes of the rigid meshes in the skeleton
  673. if (haveSkinnedMeshes && !mesh->mNumBones)
  674. {
  675. aiNode* boneNode = meshNode;
  676. necessary.Insert(boneNode);
  677. rootNode = boneNode;
  678. for (;;)
  679. {
  680. boneNode = boneNode->mParent;
  681. if (!boneNode || ((boneNode == meshNode || boneNode == meshParentNode) && !animationOnly))
  682. break;
  683. rootNode = boneNode;
  684. necessary.Insert(boneNode);
  685. }
  686. if (rootNodes.Find(rootNode) == rootNodes.End())
  687. rootNodes.Insert(rootNode);
  688. }
  689. }
  690. // If we find multiple root nodes, try to remedy by going back in the parent chain and finding a common parent
  691. if (rootNodes.Size() > 1)
  692. {
  693. for (HashSet<aiNode*>::Iterator i = rootNodes.Begin(); i != rootNodes.End(); ++i)
  694. {
  695. aiNode* commonParent = (*i);
  696. while (commonParent)
  697. {
  698. unsigned found = 0;
  699. for (HashSet<aiNode*>::Iterator j = rootNodes.Begin(); j != rootNodes.End(); ++j)
  700. {
  701. if (i == j)
  702. continue;
  703. aiNode* parent = *j;
  704. while (parent)
  705. {
  706. if (parent == commonParent)
  707. {
  708. ++found;
  709. break;
  710. }
  711. parent = parent->mParent;
  712. }
  713. }
  714. if (found >= rootNodes.Size() - 1)
  715. {
  716. PrintLine("Multiple roots initially found, using new root node " + FromAIString(commonParent->mName));
  717. rootNodes.Clear();
  718. rootNodes.Insert(commonParent);
  719. necessary.Insert(commonParent);
  720. break;
  721. }
  722. commonParent = commonParent->mParent;
  723. }
  724. if (rootNodes.Size() == 1)
  725. break; // Succeeded
  726. }
  727. if (rootNodes.Size() > 1)
  728. ErrorExit("Skeleton with multiple root nodes found, not supported");
  729. }
  730. if (rootNodes.Empty())
  731. return;
  732. model.rootBone_ = *rootNodes.Begin();
  733. // Move the model to bind pose now if requested
  734. if (moveToBindPose_)
  735. {
  736. PrintLine("Moving bones to bind pose");
  737. MoveToBindPose(model, model.rootBone_);
  738. }
  739. CollectBonesFinal(model.bones_, necessary, model.rootBone_);
  740. // Initialize the bone collision info
  741. model.boneRadii_.Resize(model.bones_.Size());
  742. model.boneHitboxes_.Resize(model.bones_.Size());
  743. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  744. {
  745. model.boneRadii_[i] = 0.0f;
  746. model.boneHitboxes_[i] = BoundingBox(0.0f, 0.0f);
  747. }
  748. }
  749. void MoveToBindPose(OutModel& model, aiNode* current)
  750. {
  751. String nodeName(FromAIString(current->mName));
  752. Matrix3x4 bindWorldTransform = GetOffsetMatrix(model, nodeName).Inverse();
  753. // Skip if we get an identity offset matrix (bone lookup failed)
  754. if (!bindWorldTransform.Equals(Matrix3x4::IDENTITY))
  755. {
  756. if (current->mParent && current != model.rootNode_)
  757. {
  758. aiMatrix4x4 parentWorldTransform = GetDerivedTransform(current->mParent, model.rootNode_, true);
  759. Matrix3x4 parentInverse = ToMatrix3x4(parentWorldTransform).Inverse();
  760. current->mTransformation = ToAIMatrix4x4(parentInverse * bindWorldTransform);
  761. }
  762. else
  763. current->mTransformation = ToAIMatrix4x4(bindWorldTransform);
  764. }
  765. for (unsigned i = 0; i < current->mNumChildren; ++i)
  766. MoveToBindPose(model, current->mChildren[i]);
  767. }
  768. void CollectBonesFinal(PODVector<aiNode*>& dest, const HashSet<aiNode*>& necessary, aiNode* node)
  769. {
  770. bool includeBone = necessary.Find(node) != necessary.End();
  771. String boneName = FromAIString(node->mName);
  772. // Check include/exclude filters for non-skinned bones
  773. if (!includeBone && includeNonSkinningBones_)
  774. {
  775. // If no includes specified, include by default but check for excludes
  776. if (nonSkinningBoneIncludes_.Empty())
  777. includeBone = true;
  778. // Check against includes/excludes
  779. for (unsigned i = 0; i < nonSkinningBoneIncludes_.Size(); ++i)
  780. {
  781. if (boneName.Contains(nonSkinningBoneIncludes_[i], false))
  782. {
  783. includeBone = true;
  784. break;
  785. }
  786. }
  787. for (unsigned i = 0; i < nonSkinningBoneExcludes_.Size(); ++i)
  788. {
  789. if (boneName.Contains(nonSkinningBoneExcludes_[i], false))
  790. {
  791. includeBone = false;
  792. break;
  793. }
  794. }
  795. if (includeBone)
  796. PrintLine("Including non-skinning bone " + boneName);
  797. }
  798. if (includeBone)
  799. dest.Push(node);
  800. for (unsigned i = 0; i < node->mNumChildren; ++i)
  801. CollectBonesFinal(dest, necessary, node->mChildren[i]);
  802. }
  803. void CollectAnimations(OutModel* model)
  804. {
  805. const aiScene* scene = scene_;
  806. for (unsigned i = 0; i < scene->mNumAnimations; ++i)
  807. {
  808. aiAnimation* anim = scene->mAnimations[i];
  809. if (allAnimations_.Contains(anim))
  810. continue;
  811. if (model)
  812. {
  813. bool modelBoneFound = false;
  814. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  815. {
  816. aiNodeAnim* channel = anim->mChannels[j];
  817. String channelName = FromAIString(channel->mNodeName);
  818. if (GetBoneIndex(*model, channelName) != M_MAX_UNSIGNED)
  819. {
  820. modelBoneFound = true;
  821. break;
  822. }
  823. }
  824. if (modelBoneFound)
  825. {
  826. model->animations_.Push(anim);
  827. allAnimations_.Insert(anim);
  828. }
  829. }
  830. else
  831. {
  832. sceneAnimations_.Push(anim);
  833. allAnimations_.Insert(anim);
  834. }
  835. }
  836. /// \todo Vertex morphs are ignored for now
  837. }
  838. void BuildBoneCollisionInfo(OutModel& model)
  839. {
  840. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  841. {
  842. aiMesh* mesh = model.meshes_[i];
  843. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  844. {
  845. aiBone* bone = mesh->mBones[j];
  846. String boneName = FromAIString(bone->mName);
  847. unsigned boneIndex = GetBoneIndex(model, boneName);
  848. if (boneIndex == M_MAX_UNSIGNED)
  849. continue;
  850. for (unsigned k = 0; k < bone->mNumWeights; ++k)
  851. {
  852. float weight = bone->mWeights[k].mWeight;
  853. // Require skinning weight to be sufficiently large before vertex contributes to bone hitbox
  854. if (weight > 0.33f)
  855. {
  856. aiVector3D vertexBoneSpace = bone->mOffsetMatrix * mesh->mVertices[bone->mWeights[k].mVertexId];
  857. Vector3 vertex = ToVector3(vertexBoneSpace);
  858. float radius = vertex.Length();
  859. if (radius > model.boneRadii_[boneIndex])
  860. model.boneRadii_[boneIndex] = radius;
  861. model.boneHitboxes_[boneIndex].Merge(vertex);
  862. }
  863. }
  864. }
  865. }
  866. }
  867. void BuildAndSaveModel(OutModel& model)
  868. {
  869. if (!model.rootNode_)
  870. {
  871. PrintLine("Null root node for model, skipping model save");
  872. return;
  873. }
  874. String rootNodeName = FromAIString(model.rootNode_->mName);
  875. if (!model.meshes_.Size())
  876. {
  877. PrintLine("No geometries found starting from node " + rootNodeName + ", skipping model save");
  878. return;
  879. }
  880. PrintLine("Writing model " + rootNodeName);
  881. SharedPtr<Model> outModel(new Model(context_));
  882. Vector<PODVector<unsigned> > allBoneMappings;
  883. BoundingBox box;
  884. unsigned numValidGeometries = 0;
  885. bool combineBuffers = true;
  886. // Check if buffers can be combined (same vertex elements, under 65535 vertices)
  887. PODVector<VertexElement> elements = GetVertexElements(model.meshes_[0], model.bones_.Size() > 0);
  888. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  889. {
  890. if (GetNumValidFaces(model.meshes_[i]))
  891. {
  892. ++numValidGeometries;
  893. if (i > 0 && GetVertexElements(model.meshes_[i], model.bones_.Size() > 0) != elements)
  894. combineBuffers = false;
  895. }
  896. }
  897. // Check if keeping separate buffers allows to avoid 32-bit indices
  898. if (combineBuffers && model.totalVertices_ > 65535)
  899. {
  900. bool allUnder65k = true;
  901. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  902. {
  903. if (GetNumValidFaces(model.meshes_[i]))
  904. {
  905. if (model.meshes_[i]->mNumVertices > 65535)
  906. allUnder65k = false;
  907. }
  908. }
  909. if (allUnder65k == true)
  910. combineBuffers = false;
  911. }
  912. SharedPtr<IndexBuffer> ib;
  913. SharedPtr<VertexBuffer> vb;
  914. Vector<SharedPtr<VertexBuffer> > vbVector;
  915. Vector<SharedPtr<IndexBuffer> > ibVector;
  916. unsigned startVertexOffset = 0;
  917. unsigned startIndexOffset = 0;
  918. unsigned destGeomIndex = 0;
  919. bool isSkinned = model.bones_.Size() > 0;
  920. outModel->SetNumGeometries(numValidGeometries);
  921. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  922. {
  923. aiMesh* mesh = model.meshes_[i];
  924. PODVector<VertexElement> elements = GetVertexElements(mesh, isSkinned);
  925. unsigned validFaces = GetNumValidFaces(mesh);
  926. if (!validFaces)
  927. continue;
  928. bool largeIndices;
  929. if (combineBuffers)
  930. largeIndices = model.totalIndices_ > 65535;
  931. else
  932. largeIndices = mesh->mNumVertices > 65535;
  933. // Create new buffers if necessary
  934. if (!combineBuffers || vbVector.Empty())
  935. {
  936. vb = new VertexBuffer(context_);
  937. ib = new IndexBuffer(context_);
  938. if (combineBuffers)
  939. {
  940. ib->SetSize(model.totalIndices_, largeIndices);
  941. vb->SetSize(model.totalVertices_, elements);
  942. }
  943. else
  944. {
  945. ib->SetSize(validFaces * 3, largeIndices);
  946. vb->SetSize(mesh->mNumVertices, elements);
  947. }
  948. vbVector.Push(vb);
  949. ibVector.Push(ib);
  950. startVertexOffset = 0;
  951. startIndexOffset = 0;
  952. }
  953. // Get the world transform of the mesh for baking into the vertices
  954. Matrix3x4 vertexTransform;
  955. Matrix3 normalTransform;
  956. Vector3 pos, scale;
  957. Quaternion rot;
  958. GetPosRotScale(GetMeshBakingTransform(model.meshNodes_[i], model.rootNode_), pos, rot, scale);
  959. vertexTransform = Matrix3x4(pos, rot, scale);
  960. normalTransform = rot.RotationMatrix();
  961. SharedPtr<Geometry> geom(new Geometry(context_));
  962. PrintLine("Writing geometry " + String(i) + " with " + String(mesh->mNumVertices) + " vertices " +
  963. String(validFaces * 3) + " indices");
  964. if (model.bones_.Size() > 0 && !mesh->HasBones())
  965. PrintLine("Warning: model has bones but geometry " + String(i) + " has no skinning information");
  966. unsigned char* vertexData = vb->GetShadowData();
  967. unsigned char* indexData = ib->GetShadowData();
  968. // Build the index data
  969. if (!largeIndices)
  970. {
  971. unsigned short* dest = (unsigned short*)indexData + startIndexOffset;
  972. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  973. WriteShortIndices(dest, mesh, j, startVertexOffset);
  974. }
  975. else
  976. {
  977. unsigned* dest = (unsigned*)indexData + startIndexOffset;
  978. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  979. WriteLargeIndices(dest, mesh, j, startVertexOffset);
  980. }
  981. // Build the vertex data
  982. // If there are bones, get blend data
  983. Vector<PODVector<unsigned char> > blendIndices;
  984. Vector<PODVector<float> > blendWeights;
  985. PODVector<unsigned> boneMappings;
  986. if (model.bones_.Size())
  987. GetBlendData(model, mesh, model.meshNodes_[i], boneMappings, blendIndices, blendWeights);
  988. auto* dest = (float*)((unsigned char*)vertexData + startVertexOffset * vb->GetVertexSize());
  989. for (unsigned j = 0; j < mesh->mNumVertices; ++j)
  990. WriteVertex(dest, mesh, j, isSkinned, box, vertexTransform, normalTransform, blendIndices, blendWeights);
  991. // Calculate the geometry center
  992. Vector3 center = Vector3::ZERO;
  993. if (validFaces)
  994. {
  995. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  996. {
  997. if (mesh->mFaces[j].mNumIndices == 3)
  998. {
  999. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[0]]);
  1000. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[1]]);
  1001. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[2]]);
  1002. }
  1003. }
  1004. center /= (float)validFaces * 3;
  1005. }
  1006. // Define the geometry
  1007. geom->SetIndexBuffer(ib);
  1008. geom->SetVertexBuffer(0, vb);
  1009. geom->SetDrawRange(TRIANGLE_LIST, startIndexOffset, validFaces * 3, true);
  1010. outModel->SetNumGeometryLodLevels(destGeomIndex, 1);
  1011. outModel->SetGeometry(destGeomIndex, 0, geom);
  1012. outModel->SetGeometryCenter(destGeomIndex, center);
  1013. if (model.bones_.Size() > maxBones_)
  1014. allBoneMappings.Push(boneMappings);
  1015. startVertexOffset += mesh->mNumVertices;
  1016. startIndexOffset += validFaces * 3;
  1017. ++destGeomIndex;
  1018. }
  1019. // Define the model buffers and bounding box
  1020. PODVector<unsigned> emptyMorphRange;
  1021. outModel->SetVertexBuffers(vbVector, emptyMorphRange, emptyMorphRange);
  1022. outModel->SetIndexBuffers(ibVector);
  1023. outModel->SetBoundingBox(box);
  1024. // Build skeleton if necessary
  1025. if (model.bones_.Size() && model.rootBone_)
  1026. {
  1027. PrintLine("Writing skeleton with " + String(model.bones_.Size()) + " bones, rootbone " +
  1028. FromAIString(model.rootBone_->mName));
  1029. Skeleton skeleton;
  1030. Vector<Bone>& bones = skeleton.GetModifiableBones();
  1031. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  1032. {
  1033. aiNode* boneNode = model.bones_[i];
  1034. String boneName(FromAIString(boneNode->mName));
  1035. Bone newBone;
  1036. newBone.name_ = boneName;
  1037. aiMatrix4x4 transform = boneNode->mTransformation;
  1038. // Make the root bone transform relative to the model's root node, if it is not already
  1039. // (in case there are nodes between that are not accounted for otherwise)
  1040. if (boneNode == model.rootBone_)
  1041. transform = GetDerivedTransform(boneNode, model.rootNode_, false);
  1042. GetPosRotScale(transform, newBone.initialPosition_, newBone.initialRotation_, newBone.initialScale_);
  1043. // Get offset information if exists
  1044. newBone.offsetMatrix_ = GetOffsetMatrix(model, boneName);
  1045. newBone.radius_ = model.boneRadii_[i];
  1046. newBone.boundingBox_ = model.boneHitboxes_[i];
  1047. newBone.collisionMask_ = BONECOLLISION_SPHERE | BONECOLLISION_BOX;
  1048. newBone.parentIndex_ = i;
  1049. bones.Push(newBone);
  1050. }
  1051. // Set the bone hierarchy
  1052. for (unsigned i = 1; i < model.bones_.Size(); ++i)
  1053. {
  1054. String parentName = FromAIString(model.bones_[i]->mParent->mName);
  1055. for (unsigned j = 0; j < bones.Size(); ++j)
  1056. {
  1057. if (bones[j].name_ == parentName)
  1058. {
  1059. bones[i].parentIndex_ = j;
  1060. break;
  1061. }
  1062. }
  1063. }
  1064. outModel->SetSkeleton(skeleton);
  1065. if (model.bones_.Size() > maxBones_)
  1066. outModel->SetGeometryBoneMappings(allBoneMappings);
  1067. }
  1068. File outFile(context_);
  1069. if (!outFile.Open(model.outName_, FILE_WRITE))
  1070. ErrorExit("Could not open output file " + model.outName_);
  1071. outModel->Save(outFile);
  1072. // If exporting materials, also save material list for use by the editor
  1073. if (!noMaterials_ && saveMaterialList_)
  1074. {
  1075. String materialListName = ReplaceExtension(model.outName_, ".txt");
  1076. File listFile(context_);
  1077. if (listFile.Open(materialListName, FILE_WRITE))
  1078. {
  1079. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  1080. listFile.WriteLine(GetMeshMaterialName(model.meshes_[i]));
  1081. }
  1082. else
  1083. PrintLine("Warning: could not write material list file " + materialListName);
  1084. }
  1085. }
  1086. void BuildAndSaveAnimations(OutModel* model)
  1087. {
  1088. // extrapolate anim
  1089. ExtrapolatePivotlessAnimation(model);
  1090. // build and save anim
  1091. const PODVector<aiAnimation*>& animations = model ? model->animations_ : sceneAnimations_;
  1092. for (unsigned i = 0; i < animations.Size(); ++i)
  1093. {
  1094. aiAnimation* anim = animations[i];
  1095. auto duration = (float)anim->mDuration;
  1096. String animName = FromAIString(anim->mName);
  1097. String animOutName;
  1098. float thisImportEndTime = importEndTime_;
  1099. float thisImportStartTime = importStartTime_;
  1100. // If no animation split specified, set the end time to duration
  1101. if (thisImportEndTime == 0.0f)
  1102. thisImportEndTime = duration;
  1103. if (animName.Empty())
  1104. animName = "Anim" + String(i + 1);
  1105. if (model)
  1106. animOutName = GetPath(model->outName_) + GetFileName(model->outName_) + "_" + SanitateAssetName(animName) + ".ani";
  1107. else
  1108. animOutName = outPath_ + GetFileName(outName_) + "_" + SanitateAssetName(animName) + ".ani";
  1109. auto ticksPerSecond = (float)anim->mTicksPerSecond;
  1110. // If ticks per second not specified, it's probably a .X file. In this case use the default tick rate
  1111. if (ticksPerSecond < M_EPSILON)
  1112. ticksPerSecond = defaultTicksPerSecond_;
  1113. float tickConversion = 1.0f / ticksPerSecond;
  1114. // Find out the start time of animation from each channel's first keyframe for adjusting the keyframe times
  1115. // to start from zero
  1116. float startTime = duration;
  1117. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  1118. {
  1119. aiNodeAnim* channel = anim->mChannels[j];
  1120. if (channel->mNumPositionKeys > 0)
  1121. startTime = Min(startTime, (float)channel->mPositionKeys[0].mTime);
  1122. if (channel->mNumRotationKeys > 0)
  1123. startTime = Min(startTime, (float)channel->mRotationKeys[0].mTime);
  1124. if (channel->mNumScalingKeys > 0)
  1125. startTime = Min(startTime, (float)channel->mScalingKeys[0].mTime);
  1126. }
  1127. if (startTime > thisImportStartTime)
  1128. thisImportStartTime = startTime;
  1129. duration = thisImportEndTime - thisImportStartTime;
  1130. SharedPtr<Animation> outAnim(new Animation(context_));
  1131. outAnim->SetAnimationName(animName);
  1132. outAnim->SetLength(duration * tickConversion);
  1133. PrintLine("Writing animation " + animName + " length " + String(outAnim->GetLength()));
  1134. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  1135. {
  1136. aiNodeAnim* channel = anim->mChannels[j];
  1137. String channelName = FromAIString(channel->mNodeName);
  1138. aiNode* boneNode = nullptr;
  1139. if (model)
  1140. {
  1141. unsigned boneIndex;
  1142. unsigned pos = channelName.Find("_$AssimpFbx$");
  1143. if (!suppressFbxPivotNodes_ || pos == String::NPOS)
  1144. {
  1145. boneIndex = GetBoneIndex(*model, channelName);
  1146. if (boneIndex == M_MAX_UNSIGNED)
  1147. {
  1148. PrintLine("Warning: skipping animation track " + channelName + " not found in model skeleton");
  1149. outAnim->RemoveTrack(channelName);
  1150. continue;
  1151. }
  1152. boneNode = model->bones_[boneIndex];
  1153. }
  1154. else
  1155. {
  1156. channelName = channelName.Substring(0, pos);
  1157. // every first $fbx animation channel for a bone will consolidate other $fbx animation to a single channel
  1158. // skip subsequent $fbx animation channel for the same bone
  1159. if (outAnim->GetTrack(channelName) != nullptr)
  1160. continue;
  1161. boneIndex = GetPivotlessBoneIndex(*model, channelName);
  1162. if (boneIndex == M_MAX_UNSIGNED)
  1163. {
  1164. PrintLine("Warning: skipping animation track " + channelName + " not found in model skeleton");
  1165. outAnim->RemoveTrack(channelName);
  1166. continue;
  1167. }
  1168. boneNode = model->pivotlessBones_[boneIndex];
  1169. }
  1170. }
  1171. else
  1172. {
  1173. boneNode = GetNode(channelName, scene_->mRootNode);
  1174. if (!boneNode)
  1175. {
  1176. PrintLine("Warning: skipping animation track " + channelName + " whose scene node was not found");
  1177. outAnim->RemoveTrack(channelName);
  1178. continue;
  1179. }
  1180. }
  1181. // To export single frame animation, check if first key frame is identical to bone transformation
  1182. aiVector3D bonePos, boneScale;
  1183. aiQuaternion boneRot;
  1184. boneNode->mTransformation.Decompose(boneScale, boneRot, bonePos);
  1185. bool posEqual = true;
  1186. bool scaleEqual = true;
  1187. bool rotEqual = true;
  1188. if (channel->mNumPositionKeys > 0 && !ToVector3(bonePos).Equals(ToVector3(channel->mPositionKeys[0].mValue)))
  1189. posEqual = false;
  1190. if (channel->mNumScalingKeys > 0 && !ToVector3(boneScale).Equals(ToVector3(channel->mScalingKeys[0].mValue)))
  1191. scaleEqual = false;
  1192. if (channel->mNumRotationKeys > 0 && !ToQuaternion(boneRot).Equals(ToQuaternion(channel->mRotationKeys[0].mValue)))
  1193. rotEqual = false;
  1194. AnimationTrack* track = outAnim->CreateTrack(channelName);
  1195. // Check which channels are used
  1196. track->channelMask_ = CHANNEL_NONE;
  1197. if (channel->mNumPositionKeys > 1 || !posEqual)
  1198. track->channelMask_ |= CHANNEL_POSITION;
  1199. if (channel->mNumRotationKeys > 1 || !rotEqual)
  1200. track->channelMask_ |= CHANNEL_ROTATION;
  1201. if (channel->mNumScalingKeys > 1 || !scaleEqual)
  1202. track->channelMask_ |= CHANNEL_SCALE;
  1203. // Check for redundant identity scale in all keyframes and remove in that case
  1204. if (track->channelMask_ & CHANNEL_SCALE)
  1205. {
  1206. bool redundantScale = true;
  1207. for (unsigned k = 0; k < channel->mNumScalingKeys; ++k)
  1208. {
  1209. float SCALE_EPSILON = 0.000001f;
  1210. Vector3 scaleVec = ToVector3(channel->mScalingKeys[k].mValue);
  1211. if (fabsf(scaleVec.x_ - 1.0f) >= SCALE_EPSILON || fabsf(scaleVec.y_ - 1.0f) >= SCALE_EPSILON ||
  1212. fabsf(scaleVec.z_ - 1.0f) >= SCALE_EPSILON)
  1213. {
  1214. redundantScale = false;
  1215. break;
  1216. }
  1217. }
  1218. if (redundantScale)
  1219. track->channelMask_ &= ~CHANNEL_SCALE;
  1220. }
  1221. if (!track->channelMask_)
  1222. {
  1223. PrintLine("Warning: skipping animation track " + channelName + " with no keyframes");
  1224. outAnim->RemoveTrack(channelName);
  1225. continue;
  1226. }
  1227. // Currently only same amount of keyframes is supported
  1228. // Note: should also check the times of individual keyframes for match
  1229. if ((channel->mNumPositionKeys > 1 && channel->mNumRotationKeys > 1 && channel->mNumPositionKeys != channel->mNumRotationKeys) ||
  1230. (channel->mNumPositionKeys > 1 && channel->mNumScalingKeys > 1 && channel->mNumPositionKeys != channel->mNumScalingKeys) ||
  1231. (channel->mNumRotationKeys > 1 && channel->mNumScalingKeys > 1 && channel->mNumRotationKeys != channel->mNumScalingKeys))
  1232. {
  1233. PrintLine("Warning: differing amounts of channel keyframes, skipping animation track " + channelName);
  1234. outAnim->RemoveTrack(channelName);
  1235. continue;
  1236. }
  1237. unsigned keyFrames = channel->mNumPositionKeys;
  1238. if (channel->mNumRotationKeys > keyFrames)
  1239. keyFrames = channel->mNumRotationKeys;
  1240. if (channel->mNumScalingKeys > keyFrames)
  1241. keyFrames = channel->mNumScalingKeys;
  1242. for (unsigned k = 0; k < keyFrames; ++k)
  1243. {
  1244. AnimationKeyFrame kf;
  1245. kf.time_ = 0.0f;
  1246. kf.position_ = Vector3::ZERO;
  1247. kf.rotation_ = Quaternion::IDENTITY;
  1248. kf.scale_ = Vector3::ONE;
  1249. // Get time for the keyframe. Adjust with animation's start time
  1250. if (track->channelMask_ & CHANNEL_POSITION && k < channel->mNumPositionKeys)
  1251. kf.time_ = ((float)channel->mPositionKeys[k].mTime - startTime);
  1252. else if (track->channelMask_ & CHANNEL_ROTATION && k < channel->mNumRotationKeys)
  1253. kf.time_ = ((float)channel->mRotationKeys[k].mTime - startTime);
  1254. else if (track->channelMask_ & CHANNEL_SCALE && k < channel->mNumScalingKeys)
  1255. kf.time_ = ((float)channel->mScalingKeys[k].mTime - startTime);
  1256. // Make sure time stays positive
  1257. kf.time_ = Max(kf.time_, 0.0f);
  1258. // Start with the bone's base transform
  1259. aiMatrix4x4 boneTransform = boneNode->mTransformation;
  1260. aiVector3D pos, scale;
  1261. aiQuaternion rot;
  1262. boneTransform.Decompose(scale, rot, pos);
  1263. // Then apply the active channels
  1264. if (track->channelMask_ & CHANNEL_POSITION && k < channel->mNumPositionKeys)
  1265. pos = channel->mPositionKeys[k].mValue;
  1266. if (track->channelMask_ & CHANNEL_ROTATION && k < channel->mNumRotationKeys)
  1267. rot = channel->mRotationKeys[k].mValue;
  1268. if (track->channelMask_ & CHANNEL_SCALE && k < channel->mNumScalingKeys)
  1269. scale = channel->mScalingKeys[k].mValue;
  1270. // If root bone, transform with nodes in between model root node (if any)
  1271. if (model && boneNode == model->rootBone_)
  1272. {
  1273. aiMatrix4x4 transMat, scaleMat, rotMat;
  1274. aiMatrix4x4::Translation(pos, transMat);
  1275. aiMatrix4x4::Scaling(scale, scaleMat);
  1276. rotMat = aiMatrix4x4(rot.GetMatrix());
  1277. aiMatrix4x4 tform = transMat * rotMat * scaleMat;
  1278. aiMatrix4x4 tformOld = tform;
  1279. tform = GetDerivedTransform(tform, boneNode, model->rootNode_, false);
  1280. // Do not decompose if did not actually change
  1281. if (tform != tformOld)
  1282. tform.Decompose(scale, rot, pos);
  1283. }
  1284. if (track->channelMask_ & CHANNEL_POSITION)
  1285. kf.position_ = ToVector3(pos);
  1286. if (track->channelMask_ & CHANNEL_ROTATION)
  1287. kf.rotation_ = ToQuaternion(rot);
  1288. if (track->channelMask_ & CHANNEL_SCALE)
  1289. kf.scale_ = ToVector3(scale);
  1290. if (kf.time_ >= thisImportStartTime && kf.time_ <= thisImportEndTime)
  1291. {
  1292. kf.time_ = (kf.time_ - thisImportStartTime) * tickConversion;
  1293. track->keyFrames_.Push(kf);
  1294. }
  1295. }
  1296. }
  1297. File outFile(context_);
  1298. if (!outFile.Open(animOutName, FILE_WRITE))
  1299. ErrorExit("Could not open output file " + animOutName);
  1300. outAnim->Save(outFile);
  1301. }
  1302. }
  1303. void ExportScene(const String& outName, bool asPrefab)
  1304. {
  1305. OutScene outScene;
  1306. outScene.outName_ = outName;
  1307. outScene.rootNode_ = rootNode_;
  1308. if (useSubdirs_)
  1309. context_->GetSubsystem<FileSystem>()->CreateDir(resourcePath_ + "Models");
  1310. CollectSceneModels(outScene, rootNode_);
  1311. // Save models, their material lists and animations
  1312. for (unsigned i = 0; i < outScene.models_.Size(); ++i)
  1313. BuildAndSaveModel(outScene.models_[i]);
  1314. // Save scene-global animations
  1315. if (!noAnimations_)
  1316. {
  1317. CollectAnimations();
  1318. BuildAndSaveAnimations();
  1319. }
  1320. // Save scene
  1321. BuildAndSaveScene(outScene, asPrefab);
  1322. }
  1323. void CollectSceneModels(OutScene& scene, aiNode* node)
  1324. {
  1325. Vector<Pair<aiNode*, aiMesh*> > meshes;
  1326. GetMeshesUnderNode(meshes, node);
  1327. if (meshes.Size())
  1328. {
  1329. OutModel model;
  1330. model.rootNode_ = node;
  1331. model.outName_ = resourcePath_ + (useSubdirs_ ? "Models/" : "") + SanitateAssetName(FromAIString(node->mName)) + ".mdl";
  1332. for (unsigned i = 0; i < meshes.Size(); ++i)
  1333. {
  1334. aiMesh* mesh = meshes[i].second_;
  1335. unsigned meshIndex = GetMeshIndex(mesh);
  1336. model.meshIndices_.Insert(meshIndex);
  1337. model.meshes_.Push(mesh);
  1338. model.meshNodes_.Push(meshes[i].first_);
  1339. model.totalVertices_ += mesh->mNumVertices;
  1340. model.totalIndices_ += GetNumValidFaces(mesh) * 3;
  1341. }
  1342. // Check if a model with identical mesh indices already exists. If yes, do not export twice
  1343. bool unique = true;
  1344. if (checkUniqueModel_)
  1345. {
  1346. for (unsigned i = 0; i < scene.models_.Size(); ++i)
  1347. {
  1348. if (scene.models_[i].meshIndices_ == model.meshIndices_)
  1349. {
  1350. PrintLine("Added node " + FromAIString(node->mName));
  1351. scene.nodes_.Push(node);
  1352. scene.nodeModelIndices_.Push(i);
  1353. unique = false;
  1354. break;
  1355. }
  1356. }
  1357. }
  1358. if (unique)
  1359. {
  1360. PrintLine("Added model " + model.outName_);
  1361. PrintLine("Added node " + FromAIString(node->mName));
  1362. CollectBones(model);
  1363. BuildBoneCollisionInfo(model);
  1364. if (!noAnimations_)
  1365. {
  1366. CollectAnimations(&model);
  1367. BuildAndSaveAnimations(&model);
  1368. }
  1369. scene.models_.Push(model);
  1370. scene.nodes_.Push(node);
  1371. scene.nodeModelIndices_.Push(scene.models_.Size() - 1);
  1372. }
  1373. }
  1374. for (unsigned i = 0; i < node->mNumChildren; ++i)
  1375. CollectSceneModels(scene, node->mChildren[i]);
  1376. }
  1377. void CreateHierarchy(Scene* scene, aiNode* srcNode, HashMap<aiNode*, Node*>& nodeMapping)
  1378. {
  1379. CreateSceneNode(scene, srcNode, nodeMapping);
  1380. for (unsigned i = 0; i < srcNode->mNumChildren; ++i)
  1381. CreateHierarchy(scene, srcNode->mChildren[i], nodeMapping);
  1382. }
  1383. Node* CreateSceneNode(Scene* scene, aiNode* srcNode, HashMap<aiNode*, Node*>& nodeMapping)
  1384. {
  1385. if (nodeMapping.Contains(srcNode))
  1386. return nodeMapping[srcNode];
  1387. // Flatten hierarchy if requested
  1388. if (noHierarchy_)
  1389. {
  1390. Node* outNode = scene->CreateChild(FromAIString(srcNode->mName), localIDs_ ? LOCAL : REPLICATED);
  1391. Vector3 pos, scale;
  1392. Quaternion rot;
  1393. GetPosRotScale(GetDerivedTransform(srcNode, rootNode_), pos, rot, scale);
  1394. outNode->SetTransform(pos, rot, scale);
  1395. nodeMapping[srcNode] = outNode;
  1396. return outNode;
  1397. }
  1398. if (srcNode == rootNode_ || !srcNode->mParent)
  1399. {
  1400. Node* outNode = scene->CreateChild(FromAIString(srcNode->mName), localIDs_ ? LOCAL : REPLICATED);
  1401. Vector3 pos, scale;
  1402. Quaternion rot;
  1403. GetPosRotScale(srcNode->mTransformation, pos, rot, scale);
  1404. outNode->SetTransform(pos, rot, scale);
  1405. nodeMapping[srcNode] = outNode;
  1406. return outNode;
  1407. }
  1408. else
  1409. {
  1410. // Ensure the existence of the parent chain as in the original file
  1411. if (!nodeMapping.Contains(srcNode->mParent))
  1412. CreateSceneNode(scene, srcNode->mParent, nodeMapping);
  1413. Node* parent = nodeMapping[srcNode->mParent];
  1414. Node* outNode = parent->CreateChild(FromAIString(srcNode->mName), localIDs_ ? LOCAL : REPLICATED);
  1415. Vector3 pos, scale;
  1416. Quaternion rot;
  1417. GetPosRotScale(srcNode->mTransformation, pos, rot, scale);
  1418. outNode->SetTransform(pos, rot, scale);
  1419. nodeMapping[srcNode] = outNode;
  1420. return outNode;
  1421. }
  1422. }
  1423. void BuildAndSaveScene(OutScene& scene, bool asPrefab)
  1424. {
  1425. if (!asPrefab)
  1426. PrintLine("Writing scene");
  1427. else
  1428. PrintLine("Writing node hierarchy");
  1429. SharedPtr<Scene> outScene(new Scene(context_));
  1430. if (!asPrefab)
  1431. {
  1432. #ifdef URHO3D_PHYSICS
  1433. /// \todo Make the physics properties configurable
  1434. outScene->CreateComponent<PhysicsWorld>();
  1435. #endif
  1436. /// \todo Make the octree properties configurable, or detect from the scene contents
  1437. outScene->CreateComponent<Octree>();
  1438. outScene->CreateComponent<DebugRenderer>();
  1439. if (createZone_)
  1440. {
  1441. Node* zoneNode = outScene->CreateChild("Zone", localIDs_ ? LOCAL : REPLICATED);
  1442. auto* zone = zoneNode->CreateComponent<Zone>();
  1443. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.f));
  1444. zone->SetAmbientColor(Color(0.25f, 0.25f, 0.25f));
  1445. // Create default light only if scene does not define them
  1446. if (!scene_->HasLights())
  1447. {
  1448. Node* lightNode = outScene->CreateChild("GlobalLight", localIDs_ ? LOCAL : REPLICATED);
  1449. auto* light = lightNode->CreateComponent<Light>();
  1450. light->SetLightType(LIGHT_DIRECTIONAL);
  1451. lightNode->SetRotation(Quaternion(60.0f, 30.0f, 0.0f));
  1452. }
  1453. }
  1454. }
  1455. auto* cache = context_->GetSubsystem<ResourceCache>();
  1456. HashMap<aiNode*, Node*> nodeMapping;
  1457. Node* outRootNode = nullptr;
  1458. if (asPrefab)
  1459. outRootNode = CreateSceneNode(outScene, rootNode_, nodeMapping);
  1460. else
  1461. {
  1462. // If not saving as a prefab, associate the root node with the scene first to prevent unnecessary creation of a root
  1463. // However do not do that if the root node does not have an identity matrix, or itself contains a model
  1464. // (models at the Urho scene root are not preferable)
  1465. if (ToMatrix3x4(rootNode_->mTransformation).Equals(Matrix3x4::IDENTITY) && !scene.nodes_.Contains(rootNode_))
  1466. nodeMapping[rootNode_] = outScene;
  1467. }
  1468. // If is allowed to export empty nodes, export the full Assimp node hierarchy first
  1469. if (!noHierarchy_ && !noEmptyNodes_)
  1470. CreateHierarchy(outScene, rootNode_, nodeMapping);
  1471. // Create geometry nodes
  1472. for (unsigned i = 0; i < scene.nodes_.Size(); ++i)
  1473. {
  1474. const OutModel& model = scene.models_[scene.nodeModelIndices_[i]];
  1475. Node* modelNode = CreateSceneNode(outScene, scene.nodes_[i], nodeMapping);
  1476. auto* staticModel =
  1477. static_cast<StaticModel*>(
  1478. model.bones_.Empty() ? modelNode->CreateComponent<StaticModel>() : modelNode->CreateComponent<AnimatedModel>());
  1479. // Create a dummy model so that the reference can be stored
  1480. String modelName = (useSubdirs_ ? "Models/" : "") + GetFileNameAndExtension(model.outName_);
  1481. if (!cache->Exists(modelName))
  1482. {
  1483. auto* dummyModel = new Model(context_);
  1484. dummyModel->SetName(modelName);
  1485. dummyModel->SetNumGeometries(model.meshes_.Size());
  1486. cache->AddManualResource(dummyModel);
  1487. }
  1488. staticModel->SetModel(cache->GetResource<Model>(modelName));
  1489. // Set materials if they are known
  1490. for (unsigned j = 0; j < model.meshes_.Size(); ++j)
  1491. {
  1492. String matName = GetMeshMaterialName(model.meshes_[j]);
  1493. // Create a dummy material so that the reference can be stored
  1494. if (!cache->Exists(matName))
  1495. {
  1496. auto* dummyMat = new Material(context_);
  1497. dummyMat->SetName(matName);
  1498. cache->AddManualResource(dummyMat);
  1499. }
  1500. staticModel->SetMaterial(j, cache->GetResource<Material>(matName));
  1501. }
  1502. }
  1503. // Create lights
  1504. if (!asPrefab)
  1505. {
  1506. for (unsigned i = 0; i < scene_->mNumLights; ++i)
  1507. {
  1508. aiLight* light = scene_->mLights[i];
  1509. aiNode* lightNode = GetNode(FromAIString(light->mName), rootNode_, true);
  1510. if (!lightNode)
  1511. continue;
  1512. Node* outNode = CreateSceneNode(outScene, lightNode, nodeMapping);
  1513. Vector3 lightAdjustPosition = ToVector3(light->mPosition);
  1514. Vector3 lightAdjustDirection = ToVector3(light->mDirection);
  1515. // If light is not aligned at the scene node, an adjustment node needs to be created
  1516. if (!lightAdjustPosition.Equals(Vector3::ZERO) || (light->mType != aiLightSource_POINT &&
  1517. !lightAdjustDirection.Equals(Vector3::FORWARD)))
  1518. {
  1519. outNode = outNode->CreateChild("LightAdjust");
  1520. outNode->SetPosition(lightAdjustPosition);
  1521. outNode->SetDirection(lightAdjustDirection);
  1522. }
  1523. auto* outLight = outNode->CreateComponent<Light>();
  1524. outLight->SetColor(Color(light->mColorDiffuse.r, light->mColorDiffuse.g, light->mColorDiffuse.b));
  1525. switch (light->mType)
  1526. {
  1527. case aiLightSource_DIRECTIONAL:
  1528. outLight->SetLightType(LIGHT_DIRECTIONAL);
  1529. break;
  1530. case aiLightSource_SPOT:
  1531. outLight->SetLightType(LIGHT_SPOT);
  1532. outLight->SetFov(light->mAngleOuterCone * 0.5f * M_RADTODEG);
  1533. break;
  1534. case aiLightSource_POINT:
  1535. outLight->SetLightType(LIGHT_POINT);
  1536. break;
  1537. default:
  1538. break;
  1539. }
  1540. // Calculate range from attenuation parameters so that light intensity has been reduced to 10% at that distance
  1541. if (light->mType != aiLightSource_DIRECTIONAL)
  1542. {
  1543. float a = light->mAttenuationQuadratic;
  1544. float b = light->mAttenuationLinear;
  1545. float c = -10.0f;
  1546. if (!Equals(a, 0.0f))
  1547. {
  1548. float root1 = (-b + sqrtf(b * b - 4.0f * a * c)) / (2.0f * a);
  1549. float root2 = (-b - sqrtf(b * b - 4.0f * a * c)) / (2.0f * a);
  1550. outLight->SetRange(Max(root1, root2));
  1551. }
  1552. else if (!Equals(b, 0.0f))
  1553. outLight->SetRange(-c / b);
  1554. }
  1555. }
  1556. }
  1557. File file(context_);
  1558. if (!file.Open(scene.outName_, FILE_WRITE))
  1559. ErrorExit("Could not open output file " + scene.outName_);
  1560. if (!asPrefab)
  1561. {
  1562. if (saveBinary_)
  1563. outScene->Save(file);
  1564. else if (saveJson_)
  1565. outScene->SaveJSON(file);
  1566. else
  1567. outScene->SaveXML(file);
  1568. }
  1569. else
  1570. {
  1571. if (saveBinary_)
  1572. outRootNode->Save(file);
  1573. else if (saveJson_)
  1574. outRootNode->SaveJSON(file);
  1575. else
  1576. outRootNode->SaveXML(file);
  1577. }
  1578. }
  1579. void ExportMaterials(HashSet<String>& usedTextures)
  1580. {
  1581. if (useSubdirs_)
  1582. context_->GetSubsystem<FileSystem>()->CreateDir(resourcePath_ + "Materials");
  1583. for (unsigned i = 0; i < scene_->mNumMaterials; ++i)
  1584. BuildAndSaveMaterial(scene_->mMaterials[i], usedTextures);
  1585. }
  1586. void BuildAndSaveMaterial(aiMaterial* material, HashSet<String>& usedTextures)
  1587. {
  1588. aiString matNameStr;
  1589. material->Get(AI_MATKEY_NAME, matNameStr);
  1590. String matName = SanitateAssetName(FromAIString(matNameStr));
  1591. if (matName.Trimmed().Empty())
  1592. matName = GenerateMaterialName(material);
  1593. // Do not actually create a material instance, but instead craft an xml file manually
  1594. XMLFile outMaterial(context_);
  1595. XMLElement materialElem = outMaterial.CreateRoot("material");
  1596. String diffuseTexName;
  1597. String normalTexName;
  1598. String specularTexName;
  1599. String lightmapTexName;
  1600. String emissiveTexName;
  1601. Color diffuseColor = Color::WHITE;
  1602. Color specularColor;
  1603. Color emissiveColor = Color::BLACK;
  1604. bool hasAlpha = false;
  1605. bool twoSided = false;
  1606. float specPower = 1.0f;
  1607. aiString stringVal;
  1608. float floatVal;
  1609. int intVal;
  1610. aiColor3D colorVal;
  1611. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_DIFFUSE, 0), stringVal) == AI_SUCCESS)
  1612. diffuseTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1613. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_NORMALS, 0), stringVal) == AI_SUCCESS)
  1614. normalTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1615. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_SPECULAR, 0), stringVal) == AI_SUCCESS)
  1616. specularTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1617. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_LIGHTMAP, 0), stringVal) == AI_SUCCESS)
  1618. lightmapTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1619. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_EMISSIVE, 0), stringVal) == AI_SUCCESS)
  1620. emissiveTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1621. if (!noMaterialDiffuseColor_)
  1622. {
  1623. if (material->Get(AI_MATKEY_COLOR_DIFFUSE, colorVal) == AI_SUCCESS)
  1624. diffuseColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1625. }
  1626. if (material->Get(AI_MATKEY_COLOR_SPECULAR, colorVal) == AI_SUCCESS)
  1627. specularColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1628. if (!emissiveAO_)
  1629. {
  1630. if (material->Get(AI_MATKEY_COLOR_EMISSIVE, colorVal) == AI_SUCCESS)
  1631. emissiveColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1632. }
  1633. if (material->Get(AI_MATKEY_OPACITY, floatVal) == AI_SUCCESS)
  1634. {
  1635. /// \hack New Assimp behavior - some materials may return 0 opacity, which is invisible.
  1636. /// Revert to full opacity in that case
  1637. if (floatVal < M_EPSILON)
  1638. floatVal = 1.0f;
  1639. if (floatVal < 1.0f)
  1640. hasAlpha = true;
  1641. diffuseColor.a_ = floatVal;
  1642. }
  1643. if (material->Get(AI_MATKEY_SHININESS, floatVal) == AI_SUCCESS)
  1644. specPower = floatVal;
  1645. if (material->Get(AI_MATKEY_TWOSIDED, intVal) == AI_SUCCESS)
  1646. twoSided = (intVal != 0);
  1647. String techniqueName = "Techniques/NoTexture";
  1648. if (!diffuseTexName.Empty())
  1649. {
  1650. techniqueName = "Techniques/Diff";
  1651. if (!normalTexName.Empty())
  1652. techniqueName += "Normal";
  1653. if (!specularTexName.Empty())
  1654. techniqueName += "Spec";
  1655. // For now lightmap does not coexist with normal & specular
  1656. if (normalTexName.Empty() && specularTexName.Empty() && !lightmapTexName.Empty())
  1657. techniqueName += "LightMap";
  1658. if (lightmapTexName.Empty() && !emissiveTexName.Empty())
  1659. techniqueName += emissiveAO_ ? "AO" : "Emissive";
  1660. }
  1661. if (hasAlpha)
  1662. techniqueName += "Alpha";
  1663. XMLElement techniqueElem = materialElem.CreateChild("technique");
  1664. techniqueElem.SetString("name", techniqueName + ".xml");
  1665. if (!diffuseTexName.Empty())
  1666. {
  1667. XMLElement diffuseElem = materialElem.CreateChild("texture");
  1668. diffuseElem.SetString("unit", "diffuse");
  1669. diffuseElem.SetString("name", GetMaterialTextureName(diffuseTexName));
  1670. usedTextures.Insert(diffuseTexName);
  1671. }
  1672. if (!normalTexName.Empty())
  1673. {
  1674. XMLElement normalElem = materialElem.CreateChild("texture");
  1675. normalElem.SetString("unit", "normal");
  1676. normalElem.SetString("name", GetMaterialTextureName(normalTexName));
  1677. usedTextures.Insert(normalTexName);
  1678. }
  1679. if (!specularTexName.Empty())
  1680. {
  1681. XMLElement specularElem = materialElem.CreateChild("texture");
  1682. specularElem.SetString("unit", "specular");
  1683. specularElem.SetString("name", GetMaterialTextureName(specularTexName));
  1684. usedTextures.Insert(specularTexName);
  1685. }
  1686. if (!lightmapTexName.Empty())
  1687. {
  1688. XMLElement lightmapElem = materialElem.CreateChild("texture");
  1689. lightmapElem.SetString("unit", "emissive");
  1690. lightmapElem.SetString("name", GetMaterialTextureName(lightmapTexName));
  1691. usedTextures.Insert(lightmapTexName);
  1692. }
  1693. if (!emissiveTexName.Empty())
  1694. {
  1695. XMLElement emissiveElem = materialElem.CreateChild("texture");
  1696. emissiveElem.SetString("unit", "emissive");
  1697. emissiveElem.SetString("name", GetMaterialTextureName(emissiveTexName));
  1698. usedTextures.Insert(emissiveTexName);
  1699. }
  1700. XMLElement diffuseColorElem = materialElem.CreateChild("parameter");
  1701. diffuseColorElem.SetString("name", "MatDiffColor");
  1702. diffuseColorElem.SetColor("value", diffuseColor);
  1703. XMLElement specularElem = materialElem.CreateChild("parameter");
  1704. specularElem.SetString("name", "MatSpecColor");
  1705. specularElem.SetVector4("value", Vector4(specularColor.r_, specularColor.g_, specularColor.b_, specPower));
  1706. XMLElement emissiveColorElem = materialElem.CreateChild("parameter");
  1707. emissiveColorElem.SetString("name", "MatEmissiveColor");
  1708. emissiveColorElem.SetColor("value", emissiveColor);
  1709. if (twoSided)
  1710. {
  1711. XMLElement cullElem = materialElem.CreateChild("cull");
  1712. XMLElement shadowCullElem = materialElem.CreateChild("shadowcull");
  1713. cullElem.SetString("value", "none");
  1714. shadowCullElem.SetString("value", "none");
  1715. }
  1716. auto* fileSystem = context_->GetSubsystem<FileSystem>();
  1717. String outFileName = resourcePath_ + (useSubdirs_ ? "Materials/" : "" ) + matName + ".xml";
  1718. if (noOverwriteMaterial_ && fileSystem->FileExists(outFileName))
  1719. {
  1720. PrintLine("Skipping save of existing material " + matName);
  1721. return;
  1722. }
  1723. PrintLine("Writing material " + matName);
  1724. File outFile(context_);
  1725. if (!outFile.Open(outFileName, FILE_WRITE))
  1726. ErrorExit("Could not open output file " + outFileName);
  1727. outMaterial.Save(outFile);
  1728. }
  1729. void CopyTextures(const HashSet<String>& usedTextures, const String& sourcePath)
  1730. {
  1731. auto* fileSystem = context_->GetSubsystem<FileSystem>();
  1732. if (useSubdirs_)
  1733. fileSystem->CreateDir(resourcePath_ + "Textures");
  1734. for (HashSet<String>::ConstIterator i = usedTextures.Begin(); i != usedTextures.End(); ++i)
  1735. {
  1736. // Handle assimp embedded textures
  1737. if (i->Length() && i->At(0) == '*')
  1738. {
  1739. unsigned texIndex = ToInt(i->Substring(1));
  1740. if (texIndex >= scene_->mNumTextures)
  1741. PrintLine("Skipping out of range texture index " + String(texIndex));
  1742. else
  1743. {
  1744. aiTexture* tex = scene_->mTextures[texIndex];
  1745. String fullDestName = resourcePath_ + GenerateTextureName(texIndex);
  1746. bool destExists = fileSystem->FileExists(fullDestName);
  1747. if (destExists && noOverwriteTexture_)
  1748. {
  1749. PrintLine("Skipping copy of existing embedded texture " + GetFileNameAndExtension(fullDestName));
  1750. continue;
  1751. }
  1752. // Encoded texture
  1753. if (!tex->mHeight)
  1754. {
  1755. PrintLine("Saving embedded texture " + GetFileNameAndExtension(fullDestName));
  1756. File dest(context_, fullDestName, FILE_WRITE);
  1757. dest.Write((const void*)tex->pcData, tex->mWidth);
  1758. }
  1759. // RGBA8 texture
  1760. else
  1761. {
  1762. PrintLine("Saving embedded RGBA texture " + GetFileNameAndExtension(fullDestName));
  1763. Image image(context_);
  1764. image.SetSize(tex->mWidth, tex->mHeight, 4);
  1765. memcpy(image.GetData(), (const void*)tex->pcData, (size_t)tex->mWidth * tex->mHeight * 4);
  1766. image.SavePNG(fullDestName);
  1767. }
  1768. }
  1769. }
  1770. else
  1771. {
  1772. String fullSourceName = sourcePath + *i;
  1773. String fullDestName = resourcePath_ + (useSubdirs_ ? "Textures/" : "") + *i;
  1774. if (!fileSystem->FileExists(fullSourceName))
  1775. {
  1776. PrintLine("Skipping copy of nonexisting material texture " + *i);
  1777. continue;
  1778. }
  1779. {
  1780. File test(context_, fullSourceName);
  1781. if (!test.GetSize())
  1782. {
  1783. PrintLine("Skipping copy of zero-size material texture " + *i);
  1784. continue;
  1785. }
  1786. }
  1787. bool destExists = fileSystem->FileExists(fullDestName);
  1788. if (destExists && noOverwriteTexture_)
  1789. {
  1790. PrintLine("Skipping copy of existing texture " + *i);
  1791. continue;
  1792. }
  1793. if (destExists && noOverwriteNewerTexture_ && fileSystem->GetLastModifiedTime(fullDestName) >
  1794. fileSystem->GetLastModifiedTime(fullSourceName))
  1795. {
  1796. PrintLine("Skipping copying of material texture " + *i + ", destination is newer");
  1797. continue;
  1798. }
  1799. PrintLine("Copying material texture " + *i);
  1800. fileSystem->Copy(fullSourceName, fullDestName);
  1801. }
  1802. }
  1803. }
  1804. void CombineLods(const PODVector<float>& lodDistances, const Vector<String>& modelNames, const String& outName)
  1805. {
  1806. // Load models
  1807. Vector<SharedPtr<Model> > srcModels;
  1808. for (unsigned i = 0; i < modelNames.Size(); ++i)
  1809. {
  1810. PrintLine("Reading LOD level " + String(i) + ": model " + modelNames[i] + " distance " + String(lodDistances[i]));
  1811. File srcFile(context_);
  1812. srcFile.Open(modelNames[i]);
  1813. SharedPtr<Model> srcModel(new Model(context_));
  1814. if (!srcModel->Load(srcFile))
  1815. ErrorExit("Could not load input model " + modelNames[i]);
  1816. srcModels.Push(srcModel);
  1817. }
  1818. // Check that none of the models already has LOD levels
  1819. for (unsigned i = 0; i < srcModels.Size(); ++i)
  1820. {
  1821. for (unsigned j = 0; j < srcModels[i]->GetNumGeometries(); ++j)
  1822. {
  1823. if (srcModels[i]->GetNumGeometryLodLevels(j) > 1)
  1824. ErrorExit(modelNames[i] + " already has multiple LOD levels defined");
  1825. }
  1826. }
  1827. // Check for number of geometries (need to have same amount for now)
  1828. for (unsigned i = 1; i < srcModels.Size(); ++i)
  1829. {
  1830. if (srcModels[i]->GetNumGeometries() != srcModels[0]->GetNumGeometries())
  1831. ErrorExit(modelNames[i] + " has different amount of geometries than " + modelNames[0]);
  1832. }
  1833. // If there are bones, check for compatibility (need to have exact match for now)
  1834. for (unsigned i = 1; i < srcModels.Size(); ++i)
  1835. {
  1836. if (srcModels[i]->GetSkeleton().GetNumBones() != srcModels[0]->GetSkeleton().GetNumBones())
  1837. ErrorExit(modelNames[i] + " has different amount of bones than " + modelNames[0]);
  1838. for (unsigned j = 0; j < srcModels[0]->GetSkeleton().GetNumBones(); ++j)
  1839. {
  1840. if (srcModels[i]->GetSkeleton().GetBone(j)->name_ != srcModels[0]->GetSkeleton().GetBone(j)->name_)
  1841. ErrorExit(modelNames[i] + " has different bones than " + modelNames[0]);
  1842. }
  1843. if (srcModels[i]->GetGeometryBoneMappings() != srcModels[0]->GetGeometryBoneMappings())
  1844. ErrorExit(modelNames[i] + " has different per-geometry bone mappings than " + modelNames[0]);
  1845. }
  1846. Vector<SharedPtr<VertexBuffer> > vbVector;
  1847. Vector<SharedPtr<IndexBuffer> > ibVector;
  1848. PODVector<unsigned> emptyMorphRange;
  1849. // Create the final model
  1850. SharedPtr<Model> outModel(new Model(context_));
  1851. outModel->SetNumGeometries(srcModels[0]->GetNumGeometries());
  1852. for (unsigned i = 0; i < srcModels[0]->GetNumGeometries(); ++i)
  1853. {
  1854. outModel->SetNumGeometryLodLevels(i, srcModels.Size());
  1855. for (unsigned j = 0; j < srcModels.Size(); ++j)
  1856. {
  1857. Geometry* geometry = srcModels[j]->GetGeometry(i, 0);
  1858. geometry->SetLodDistance(lodDistances[j]);
  1859. outModel->SetGeometry(i, j, geometry);
  1860. for (unsigned k = 0; k < geometry->GetNumVertexBuffers(); ++k)
  1861. {
  1862. SharedPtr<VertexBuffer> vb(geometry->GetVertexBuffer(k));
  1863. if (!vbVector.Contains(vb))
  1864. vbVector.Push(vb);
  1865. }
  1866. SharedPtr<IndexBuffer> ib(geometry->GetIndexBuffer());
  1867. if (!ibVector.Contains(ib))
  1868. ibVector.Push(ib);
  1869. }
  1870. }
  1871. outModel->SetVertexBuffers(vbVector, emptyMorphRange, emptyMorphRange);
  1872. outModel->SetIndexBuffers(ibVector);
  1873. outModel->SetSkeleton(srcModels[0]->GetSkeleton());
  1874. outModel->SetGeometryBoneMappings(srcModels[0]->GetGeometryBoneMappings());
  1875. outModel->SetBoundingBox(srcModels[0]->GetBoundingBox());
  1876. /// \todo Vertex morphs are ignored for now
  1877. // Save the final model
  1878. PrintLine("Writing output model");
  1879. File outFile(context_);
  1880. if (!outFile.Open(outName, FILE_WRITE))
  1881. ErrorExit("Could not open output file " + outName);
  1882. outModel->Save(outFile);
  1883. }
  1884. void GetMeshesUnderNode(Vector<Pair<aiNode*, aiMesh*> >& dest, aiNode* node)
  1885. {
  1886. for (unsigned i = 0; i < node->mNumMeshes; ++i)
  1887. dest.Push(MakePair(node, scene_->mMeshes[node->mMeshes[i]]));
  1888. }
  1889. unsigned GetMeshIndex(aiMesh* mesh)
  1890. {
  1891. for (unsigned i = 0; i < scene_->mNumMeshes; ++i)
  1892. {
  1893. if (scene_->mMeshes[i] == mesh)
  1894. return i;
  1895. }
  1896. return M_MAX_UNSIGNED;
  1897. }
  1898. unsigned GetBoneIndex(OutModel& model, const String& boneName)
  1899. {
  1900. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  1901. {
  1902. if (boneName == model.bones_[i]->mName.data)
  1903. return i;
  1904. }
  1905. return M_MAX_UNSIGNED;
  1906. }
  1907. aiBone* GetMeshBone(OutModel& model, const String& boneName)
  1908. {
  1909. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  1910. {
  1911. aiMesh* mesh = model.meshes_[i];
  1912. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  1913. {
  1914. aiBone* bone = mesh->mBones[j];
  1915. if (boneName == bone->mName.data)
  1916. return bone;
  1917. }
  1918. }
  1919. return nullptr;
  1920. }
  1921. Matrix3x4 GetOffsetMatrix(OutModel& model, const String& boneName)
  1922. {
  1923. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  1924. {
  1925. aiMesh* mesh = model.meshes_[i];
  1926. aiNode* node = model.meshNodes_[i];
  1927. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  1928. {
  1929. aiBone* bone = mesh->mBones[j];
  1930. if (boneName == bone->mName.data)
  1931. {
  1932. aiMatrix4x4 offset = bone->mOffsetMatrix;
  1933. aiMatrix4x4 nodeDerivedInverse = GetMeshBakingTransform(node, model.rootNode_);
  1934. nodeDerivedInverse.Inverse();
  1935. offset *= nodeDerivedInverse;
  1936. return ToMatrix3x4(offset);
  1937. }
  1938. }
  1939. }
  1940. // Fallback for rigid skinning for which actual offset matrix information doesn't exist
  1941. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  1942. {
  1943. aiMesh* mesh = model.meshes_[i];
  1944. aiNode* node = model.meshNodes_[i];
  1945. if (!mesh->HasBones() && boneName == node->mName.data)
  1946. {
  1947. aiMatrix4x4 nodeDerivedInverse = GetMeshBakingTransform(node, model.rootNode_);
  1948. nodeDerivedInverse.Inverse();
  1949. return ToMatrix3x4(nodeDerivedInverse);
  1950. }
  1951. }
  1952. return Matrix3x4::IDENTITY;
  1953. }
  1954. void GetBlendData(OutModel& model, aiMesh* mesh, aiNode* meshNode, PODVector<unsigned>& boneMappings, Vector<PODVector<unsigned char> >&
  1955. blendIndices, Vector<PODVector<float> >& blendWeights)
  1956. {
  1957. blendIndices.Resize(mesh->mNumVertices);
  1958. blendWeights.Resize(mesh->mNumVertices);
  1959. boneMappings.Clear();
  1960. // If model has more bones than can fit vertex shader parameters, write the per-geometry mappings
  1961. if (model.bones_.Size() > maxBones_)
  1962. {
  1963. if (mesh->mNumBones > maxBones_)
  1964. {
  1965. ErrorExit(
  1966. "Geometry (submesh) has over " + String(maxBones_) + " bone influences. Try splitting to more submeshes\n"
  1967. "that each stay at " + String(maxBones_) + " bones or below."
  1968. );
  1969. }
  1970. if (mesh->mNumBones > 0)
  1971. {
  1972. boneMappings.Resize(mesh->mNumBones);
  1973. for (unsigned i = 0; i < mesh->mNumBones; ++i)
  1974. {
  1975. aiBone* bone = mesh->mBones[i];
  1976. String boneName = FromAIString(bone->mName);
  1977. unsigned globalIndex = GetBoneIndex(model, boneName);
  1978. if (globalIndex == M_MAX_UNSIGNED)
  1979. ErrorExit("Bone " + boneName + " not found");
  1980. boneMappings[i] = globalIndex;
  1981. for (unsigned j = 0; j < bone->mNumWeights; ++j)
  1982. {
  1983. unsigned vertex = bone->mWeights[j].mVertexId;
  1984. blendIndices[vertex].Push(i);
  1985. blendWeights[vertex].Push(bone->mWeights[j].mWeight);
  1986. }
  1987. }
  1988. }
  1989. else
  1990. {
  1991. // If mesh does not have skinning information, implement rigid skinning so that it stays compatible with AnimatedModel
  1992. String boneName = FromAIString(meshNode->mName);
  1993. unsigned globalIndex = GetBoneIndex(model, boneName);
  1994. if (globalIndex == M_MAX_UNSIGNED)
  1995. PrintLine("Warning: bone " + boneName + " not found, skipping rigid skinning");
  1996. else
  1997. {
  1998. boneMappings.Push(globalIndex);
  1999. for (unsigned i = 0; i < mesh->mNumVertices; ++i)
  2000. {
  2001. blendIndices[i].Push(0);
  2002. blendWeights[i].Push(1.0f);
  2003. }
  2004. }
  2005. }
  2006. }
  2007. else
  2008. {
  2009. if (mesh->mNumBones > 0)
  2010. {
  2011. for (unsigned i = 0; i < mesh->mNumBones; ++i)
  2012. {
  2013. aiBone* bone = mesh->mBones[i];
  2014. String boneName = FromAIString(bone->mName);
  2015. unsigned globalIndex = GetBoneIndex(model, boneName);
  2016. if (globalIndex == M_MAX_UNSIGNED)
  2017. ErrorExit("Bone " + boneName + " not found");
  2018. for (unsigned j = 0; j < bone->mNumWeights; ++j)
  2019. {
  2020. unsigned vertex = bone->mWeights[j].mVertexId;
  2021. blendIndices[vertex].Push(globalIndex);
  2022. blendWeights[vertex].Push(bone->mWeights[j].mWeight);
  2023. }
  2024. }
  2025. }
  2026. else
  2027. {
  2028. String boneName = FromAIString(meshNode->mName);
  2029. unsigned globalIndex = GetBoneIndex(model, boneName);
  2030. if (globalIndex == M_MAX_UNSIGNED)
  2031. PrintLine("Warning: bone " + boneName + " not found, skipping rigid skinning");
  2032. else
  2033. {
  2034. for (unsigned i = 0; i < mesh->mNumVertices; ++i)
  2035. {
  2036. blendIndices[i].Push(globalIndex);
  2037. blendWeights[i].Push(1.0f);
  2038. }
  2039. }
  2040. }
  2041. }
  2042. // Normalize weights now if necessary, also remove too many influences
  2043. for (unsigned i = 0; i < blendWeights.Size(); ++i)
  2044. {
  2045. if (blendWeights[i].Size() > 4)
  2046. {
  2047. PrintLine("Warning: more than 4 bone influences in vertex " + String(i));
  2048. while (blendWeights[i].Size() > 4)
  2049. {
  2050. unsigned lowestIndex = 0;
  2051. float lowest = M_INFINITY;
  2052. for (unsigned j = 0; j < blendWeights[i].Size(); ++j)
  2053. {
  2054. if (blendWeights[i][j] < lowest)
  2055. {
  2056. lowest = blendWeights[i][j];
  2057. lowestIndex = j;
  2058. }
  2059. }
  2060. blendWeights[i].Erase(lowestIndex);
  2061. blendIndices[i].Erase(lowestIndex);
  2062. }
  2063. }
  2064. float sum = 0.0f;
  2065. for (unsigned j = 0; j < blendWeights[i].Size(); ++j)
  2066. sum += blendWeights[i][j];
  2067. if (sum != 1.0f && sum != 0.0f)
  2068. {
  2069. for (unsigned j = 0; j < blendWeights[i].Size(); ++j)
  2070. blendWeights[i][j] /= sum;
  2071. }
  2072. }
  2073. }
  2074. String GetMeshMaterialName(aiMesh* mesh)
  2075. {
  2076. aiMaterial* material = scene_->mMaterials[mesh->mMaterialIndex];
  2077. aiString matNameStr;
  2078. material->Get(AI_MATKEY_NAME, matNameStr);
  2079. String matName = SanitateAssetName(FromAIString(matNameStr));
  2080. if (matName.Trimmed().Empty())
  2081. matName = GenerateMaterialName(material);
  2082. return (useSubdirs_ ? "Materials/" : "") + matName + ".xml";
  2083. }
  2084. String GenerateMaterialName(aiMaterial* material)
  2085. {
  2086. for (unsigned i = 0; i < scene_->mNumMaterials; ++i)
  2087. {
  2088. if (scene_->mMaterials[i] == material)
  2089. return inputName_ + "_Material" + String(i);
  2090. }
  2091. // Should not go here
  2092. return String::EMPTY;
  2093. }
  2094. String GetMaterialTextureName(const String& nameIn)
  2095. {
  2096. // Detect assimp embedded texture
  2097. if (nameIn.Length() && nameIn[0] == '*')
  2098. return GenerateTextureName(ToInt(nameIn.Substring(1)));
  2099. else
  2100. return (useSubdirs_ ? "Textures/" : "") + nameIn;
  2101. }
  2102. String GenerateTextureName(unsigned texIndex)
  2103. {
  2104. if (texIndex < scene_->mNumTextures)
  2105. {
  2106. // If embedded texture contains encoded data, use the format hint for file extension. Else save RGBA8 data as PNG
  2107. aiTexture* tex = scene_->mTextures[texIndex];
  2108. if (!tex->mHeight)
  2109. return (useSubdirs_ ? "Textures/" : "") + inputName_ + "_Texture" + String(texIndex) + "." + tex->achFormatHint;
  2110. else
  2111. return (useSubdirs_ ? "Textures/" : "") + inputName_ + "_Texture" + String(texIndex) + ".png";
  2112. }
  2113. // Should not go here
  2114. return String::EMPTY;
  2115. }
  2116. unsigned GetNumValidFaces(aiMesh* mesh)
  2117. {
  2118. unsigned ret = 0;
  2119. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  2120. {
  2121. if (mesh->mFaces[j].mNumIndices == 3)
  2122. ++ret;
  2123. }
  2124. return ret;
  2125. }
  2126. void WriteShortIndices(unsigned short*& dest, aiMesh* mesh, unsigned index, unsigned offset)
  2127. {
  2128. if (mesh->mFaces[index].mNumIndices == 3)
  2129. {
  2130. *dest++ = mesh->mFaces[index].mIndices[0] + offset;
  2131. *dest++ = mesh->mFaces[index].mIndices[1] + offset;
  2132. *dest++ = mesh->mFaces[index].mIndices[2] + offset;
  2133. }
  2134. }
  2135. void WriteLargeIndices(unsigned*& dest, aiMesh* mesh, unsigned index, unsigned offset)
  2136. {
  2137. if (mesh->mFaces[index].mNumIndices == 3)
  2138. {
  2139. *dest++ = mesh->mFaces[index].mIndices[0] + offset;
  2140. *dest++ = mesh->mFaces[index].mIndices[1] + offset;
  2141. *dest++ = mesh->mFaces[index].mIndices[2] + offset;
  2142. }
  2143. }
  2144. void WriteVertex(float*& dest, aiMesh* mesh, unsigned index, bool isSkinned, BoundingBox& box,
  2145. const Matrix3x4& vertexTransform, const Matrix3& normalTransform, Vector<PODVector<unsigned char> >& blendIndices,
  2146. Vector<PODVector<float> >& blendWeights)
  2147. {
  2148. Vector3 vertex = vertexTransform * ToVector3(mesh->mVertices[index]);
  2149. box.Merge(vertex);
  2150. *dest++ = vertex.x_;
  2151. *dest++ = vertex.y_;
  2152. *dest++ = vertex.z_;
  2153. if (mesh->HasNormals())
  2154. {
  2155. Vector3 normal = normalTransform * ToVector3(mesh->mNormals[index]);
  2156. *dest++ = normal.x_;
  2157. *dest++ = normal.y_;
  2158. *dest++ = normal.z_;
  2159. }
  2160. for (unsigned i = 0; i < mesh->GetNumColorChannels() && i < MAX_CHANNELS; ++i)
  2161. {
  2162. *((unsigned*)dest) = Color(mesh->mColors[i][index].r, mesh->mColors[i][index].g, mesh->mColors[i][index].b,
  2163. mesh->mColors[i][index].a).ToUInt();
  2164. ++dest;
  2165. }
  2166. for (unsigned i = 0; i < mesh->GetNumUVChannels() && i < MAX_CHANNELS; ++i)
  2167. {
  2168. Vector3 texCoord = ToVector3(mesh->mTextureCoords[i][index]);
  2169. *dest++ = texCoord.x_;
  2170. *dest++ = texCoord.y_;
  2171. }
  2172. if (mesh->HasTangentsAndBitangents())
  2173. {
  2174. Vector3 tangent = normalTransform * ToVector3(mesh->mTangents[index]);
  2175. Vector3 normal = normalTransform * ToVector3(mesh->mNormals[index]);
  2176. Vector3 bitangent = normalTransform * ToVector3(mesh->mBitangents[index]);
  2177. // Check handedness
  2178. float w = 1.0f;
  2179. if ((tangent.CrossProduct(normal)).DotProduct(bitangent) < 0.5f)
  2180. w = -1.0f;
  2181. *dest++ = tangent.x_;
  2182. *dest++ = tangent.y_;
  2183. *dest++ = tangent.z_;
  2184. *dest++ = w;
  2185. }
  2186. if (isSkinned)
  2187. {
  2188. for (unsigned i = 0; i < 4; ++i)
  2189. {
  2190. if (i < blendWeights[index].Size())
  2191. *dest++ = blendWeights[index][i];
  2192. else
  2193. *dest++ = 0.0f;
  2194. }
  2195. auto* destBytes = (unsigned char*)dest;
  2196. ++dest;
  2197. for (unsigned i = 0; i < 4; ++i)
  2198. {
  2199. if (i < blendIndices[index].Size())
  2200. *destBytes++ = blendIndices[index][i];
  2201. else
  2202. *destBytes++ = 0;
  2203. }
  2204. }
  2205. }
  2206. PODVector<VertexElement> GetVertexElements(aiMesh* mesh, bool isSkinned)
  2207. {
  2208. PODVector<VertexElement> ret;
  2209. // Position must always be first and of type Vector3 for raycasts to work
  2210. ret.Push(VertexElement(TYPE_VECTOR3, SEM_POSITION));
  2211. if (mesh->HasNormals())
  2212. ret.Push(VertexElement(TYPE_VECTOR3, SEM_NORMAL));
  2213. for (unsigned i = 0; i < mesh->GetNumColorChannels() && i < MAX_CHANNELS; ++i)
  2214. ret.Push(VertexElement(TYPE_UBYTE4_NORM, SEM_COLOR, i));
  2215. /// \todo Assimp mesh structure can specify 3D UV-coords. How to determine the difference? For now always treated as 2D.
  2216. for (unsigned i = 0; i < mesh->GetNumUVChannels() && i < MAX_CHANNELS; ++i)
  2217. ret.Push(VertexElement(TYPE_VECTOR2, SEM_TEXCOORD, i));
  2218. if (mesh->HasTangentsAndBitangents())
  2219. ret.Push(VertexElement(TYPE_VECTOR4, SEM_TANGENT));
  2220. if (isSkinned)
  2221. {
  2222. ret.Push(VertexElement(TYPE_VECTOR4, SEM_BLENDWEIGHTS));
  2223. ret.Push(VertexElement(TYPE_UBYTE4, SEM_BLENDINDICES));
  2224. }
  2225. return ret;
  2226. }
  2227. aiNode* GetNode(const String& name, aiNode* rootNode, bool caseSensitive)
  2228. {
  2229. if (!rootNode)
  2230. return nullptr;
  2231. if (!name.Compare(rootNode->mName.data, caseSensitive))
  2232. return rootNode;
  2233. for (unsigned i = 0; i < rootNode->mNumChildren; ++i)
  2234. {
  2235. aiNode* found = GetNode(name, rootNode->mChildren[i], caseSensitive);
  2236. if (found)
  2237. return found;
  2238. }
  2239. return nullptr;
  2240. }
  2241. aiMatrix4x4 GetDerivedTransform(aiNode* node, aiNode* rootNode, bool rootInclusive)
  2242. {
  2243. return GetDerivedTransform(node->mTransformation, node, rootNode, rootInclusive);
  2244. }
  2245. aiMatrix4x4 GetDerivedTransform(aiMatrix4x4 transform, aiNode* node, aiNode* rootNode, bool rootInclusive)
  2246. {
  2247. // If basenode is defined, go only up to it in the parent chain
  2248. while (node && node != rootNode)
  2249. {
  2250. node = node->mParent;
  2251. if (!rootInclusive && node == rootNode)
  2252. break;
  2253. if (node)
  2254. transform = node->mTransformation * transform;
  2255. }
  2256. return transform;
  2257. }
  2258. aiMatrix4x4 GetMeshBakingTransform(aiNode* meshNode, aiNode* modelRootNode)
  2259. {
  2260. if (meshNode == modelRootNode)
  2261. return {};
  2262. else
  2263. return GetDerivedTransform(meshNode, modelRootNode);
  2264. }
  2265. void GetPosRotScale(const aiMatrix4x4& transform, Vector3& pos, Quaternion& rot, Vector3& scale)
  2266. {
  2267. aiVector3D aiPos;
  2268. aiQuaternion aiRot;
  2269. aiVector3D aiScale;
  2270. transform.Decompose(aiScale, aiRot, aiPos);
  2271. pos = ToVector3(aiPos);
  2272. rot = ToQuaternion(aiRot);
  2273. scale = ToVector3(aiScale);
  2274. }
  2275. String FromAIString(const aiString& str)
  2276. {
  2277. return String(str.data);
  2278. }
  2279. Vector3 ToVector3(const aiVector3D& vec)
  2280. {
  2281. return Vector3(vec.x, vec.y, vec.z);
  2282. }
  2283. Vector2 ToVector2(const aiVector2D& vec)
  2284. {
  2285. return Vector2(vec.x, vec.y);
  2286. }
  2287. Quaternion ToQuaternion(const aiQuaternion& quat)
  2288. {
  2289. return Quaternion(quat.w, quat.x, quat.y, quat.z);
  2290. }
  2291. Matrix3x4 ToMatrix3x4(const aiMatrix4x4& mat)
  2292. {
  2293. Matrix3x4 ret;
  2294. memcpy(&ret.m00_, &mat.a1, sizeof(Matrix3x4));
  2295. return ret;
  2296. }
  2297. aiMatrix4x4 ToAIMatrix4x4(const Matrix3x4& mat)
  2298. {
  2299. aiMatrix4x4 ret;
  2300. memcpy(&ret.a1, &mat.m00_, sizeof(Matrix3x4));
  2301. return ret;
  2302. }
  2303. String SanitateAssetName(const String& name)
  2304. {
  2305. String fixedName = name;
  2306. fixedName.Replace("<", "");
  2307. fixedName.Replace(">", "");
  2308. fixedName.Replace("?", "");
  2309. fixedName.Replace("*", "");
  2310. fixedName.Replace(":", "");
  2311. fixedName.Replace("\"", "");
  2312. fixedName.Replace("/", "");
  2313. fixedName.Replace("\\", "");
  2314. fixedName.Replace("|", "");
  2315. return fixedName;
  2316. }
  2317. unsigned GetPivotlessBoneIndex(OutModel& model, const String& boneName)
  2318. {
  2319. for (unsigned i = 0; i < model.pivotlessBones_.Size(); ++i)
  2320. {
  2321. if (boneName == model.pivotlessBones_[i]->mName.data)
  2322. return i;
  2323. }
  2324. return M_MAX_UNSIGNED;
  2325. }
  2326. void FillChainTransforms(OutModel &model, aiMatrix4x4 *chain, const String& mainBoneName)
  2327. {
  2328. for (unsigned j = 0; j < TransformationComp_MAXIMUM; ++j)
  2329. {
  2330. String transfBoneName = mainBoneName + "_$AssimpFbx$_" + String(transformSuffix[j]);
  2331. for (unsigned k = 0; k < model.bones_.Size(); ++k)
  2332. {
  2333. String boneName = String(model.bones_[k]->mName.data);
  2334. if (boneName == transfBoneName)
  2335. {
  2336. chain[j] = model.bones_[k]->mTransformation;
  2337. break;
  2338. }
  2339. }
  2340. }
  2341. }
  2342. void ExpandAnimatedChannelKeys(aiAnimation* anim, unsigned mainChannel, const int *channelIndices)
  2343. {
  2344. aiNodeAnim* channel = anim->mChannels[mainChannel];
  2345. unsigned int poskeyFrames = channel->mNumPositionKeys;
  2346. unsigned int rotkeyFrames = channel->mNumRotationKeys;
  2347. unsigned int scalekeyFrames = channel->mNumScalingKeys;
  2348. // Get max key frames
  2349. for (unsigned i = 0; i < TransformationComp_MAXIMUM; ++i)
  2350. {
  2351. if (channelIndices[i] != -1 && channelIndices[i] != mainChannel)
  2352. {
  2353. aiNodeAnim* channel2 = anim->mChannels[channelIndices[i]];
  2354. if (channel2->mNumPositionKeys > poskeyFrames)
  2355. poskeyFrames = channel2->mNumPositionKeys;
  2356. if (channel2->mNumRotationKeys > rotkeyFrames)
  2357. rotkeyFrames = channel2->mNumRotationKeys;
  2358. if (channel2->mNumScalingKeys > scalekeyFrames)
  2359. scalekeyFrames = channel2->mNumScalingKeys;
  2360. }
  2361. }
  2362. // Resize and init vector key array
  2363. if (poskeyFrames > channel->mNumPositionKeys)
  2364. {
  2365. auto* newKeys = new aiVectorKey[poskeyFrames];
  2366. for (unsigned i = 0; i < poskeyFrames; ++i)
  2367. {
  2368. if (i < channel->mNumPositionKeys )
  2369. newKeys[i] = aiVectorKey(channel->mPositionKeys[i].mTime, channel->mPositionKeys[i].mValue);
  2370. else
  2371. newKeys[i].mValue = aiVector3D(0.0f, 0.0f, 0.0f);
  2372. }
  2373. delete[] channel->mPositionKeys;
  2374. channel->mPositionKeys = newKeys;
  2375. channel->mNumPositionKeys = poskeyFrames;
  2376. }
  2377. if (rotkeyFrames > channel->mNumRotationKeys)
  2378. {
  2379. auto* newKeys = new aiQuatKey[rotkeyFrames];
  2380. for (unsigned i = 0; i < rotkeyFrames; ++i)
  2381. {
  2382. if (i < channel->mNumRotationKeys)
  2383. newKeys[i] = aiQuatKey(channel->mRotationKeys[i].mTime, channel->mRotationKeys[i].mValue);
  2384. else
  2385. newKeys[i].mValue = aiQuaternion();
  2386. }
  2387. delete[] channel->mRotationKeys;
  2388. channel->mRotationKeys = newKeys;
  2389. channel->mNumRotationKeys = rotkeyFrames;
  2390. }
  2391. if (scalekeyFrames > channel->mNumScalingKeys)
  2392. {
  2393. auto* newKeys = new aiVectorKey[scalekeyFrames];
  2394. for (unsigned i = 0; i < scalekeyFrames; ++i)
  2395. {
  2396. if ( i < channel->mNumScalingKeys)
  2397. newKeys[i] = aiVectorKey(channel->mScalingKeys[i].mTime, channel->mScalingKeys[i].mValue);
  2398. else
  2399. newKeys[i].mValue = aiVector3D(1.0f, 1.0f, 1.0f);
  2400. }
  2401. delete[] channel->mScalingKeys;
  2402. channel->mScalingKeys = newKeys;
  2403. channel->mNumScalingKeys = scalekeyFrames;
  2404. }
  2405. }
  2406. void InitAnimatedChainTransformIndices(aiAnimation* anim, unsigned mainChannel, const String& mainBoneName, int *channelIndices)
  2407. {
  2408. int numTransforms = 0;
  2409. for (unsigned j = 0; j < TransformationComp_MAXIMUM; ++j)
  2410. {
  2411. String transfBoneName = mainBoneName + "_$AssimpFbx$_" + String(transformSuffix[j]);
  2412. channelIndices[j] = -1;
  2413. for (unsigned k = 0; k < anim->mNumChannels; ++k)
  2414. {
  2415. aiNodeAnim* channel = anim->mChannels[k];
  2416. String channelName = FromAIString(channel->mNodeName);
  2417. if (channelName == transfBoneName)
  2418. {
  2419. ++numTransforms;
  2420. channelIndices[j] = k;
  2421. break;
  2422. }
  2423. }
  2424. }
  2425. // resize animated channel key size
  2426. if (numTransforms > 1)
  2427. ExpandAnimatedChannelKeys(anim, mainChannel, channelIndices);
  2428. }
  2429. void CreatePivotlessFbxBoneStruct(OutModel &model)
  2430. {
  2431. // Init
  2432. model.pivotlessBones_.Clear();
  2433. aiMatrix4x4 chains[TransformationComp_MAXIMUM];
  2434. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  2435. {
  2436. String mainBoneName = String(model.bones_[i]->mName.data);
  2437. // Skip $fbx nodes
  2438. if (mainBoneName.Find("$AssimpFbx$") != String::NPOS)
  2439. continue;
  2440. std::fill_n(chains, static_cast<unsigned int>(TransformationComp_MAXIMUM), aiMatrix4x4());
  2441. FillChainTransforms(model, &chains[0], mainBoneName);
  2442. // Calculate chained transform
  2443. aiMatrix4x4 finalTransform;
  2444. for (const auto& chain : chains)
  2445. finalTransform = finalTransform * chain;
  2446. // New bone node
  2447. auto*pnode = new aiNode;
  2448. pnode->mName = model.bones_[i]->mName;
  2449. pnode->mTransformation = finalTransform * model.bones_[i]->mTransformation;
  2450. model.pivotlessBones_.Push(pnode);
  2451. }
  2452. }
  2453. void ExtrapolatePivotlessAnimation(OutModel* model)
  2454. {
  2455. if (suppressFbxPivotNodes_ && model)
  2456. {
  2457. PrintLine("Suppressing $fbx nodes");
  2458. // Construct new bone structure from suppressed $fbx pivot nodes
  2459. CreatePivotlessFbxBoneStruct(*model);
  2460. // Extrapolate anim
  2461. const PODVector<aiAnimation *> &animations = model->animations_;
  2462. for (unsigned i = 0; i < animations.Size(); ++i)
  2463. {
  2464. aiAnimation* anim = animations[i];
  2465. Vector<String> mainBoneCompleteList;
  2466. mainBoneCompleteList.Clear();
  2467. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  2468. {
  2469. aiNodeAnim* channel = anim->mChannels[j];
  2470. String channelName = FromAIString(channel->mNodeName);
  2471. unsigned pos = channelName.Find("_$AssimpFbx$");
  2472. if (pos != String::NPOS)
  2473. {
  2474. // Every first $fbx animation channel for a bone will consolidate other $fbx animation to a single channel
  2475. // skip subsequent $fbx animation channel for the same bone
  2476. String mainBoneName = channelName.Substring(0, pos);
  2477. if (mainBoneCompleteList.Find(mainBoneName) != mainBoneCompleteList.End())
  2478. continue;
  2479. mainBoneCompleteList.Push(mainBoneName);
  2480. unsigned boneIdx = GetBoneIndex(*model, mainBoneName);
  2481. // This condition exists if a geometry, not a bone, has a key animation
  2482. if (boneIdx == M_MAX_UNSIGNED)
  2483. continue;
  2484. // Init chain indices and fill transforms
  2485. aiMatrix4x4 mainboneTransform = model->bones_[boneIdx]->mTransformation;
  2486. aiMatrix4x4 chain[TransformationComp_MAXIMUM];
  2487. int channelIndices[TransformationComp_MAXIMUM];
  2488. InitAnimatedChainTransformIndices(anim, j, mainBoneName, &channelIndices[0]);
  2489. std::fill_n(chain, static_cast<unsigned int>(TransformationComp_MAXIMUM), aiMatrix4x4());
  2490. FillChainTransforms(*model, &chain[0], mainBoneName);
  2491. unsigned keyFrames = channel->mNumPositionKeys;
  2492. if (channel->mNumRotationKeys > keyFrames)
  2493. keyFrames = channel->mNumRotationKeys;
  2494. if (channel->mNumScalingKeys > keyFrames)
  2495. keyFrames = channel->mNumScalingKeys;
  2496. for (unsigned k = 0; k < keyFrames; ++k)
  2497. {
  2498. double frameTime = 0.0;
  2499. aiMatrix4x4 finalTransform;
  2500. // Chain transform animated values
  2501. for (unsigned l = 0; l < TransformationComp_MAXIMUM; ++l)
  2502. {
  2503. // It's either the chain transform or animation channel transform
  2504. if (channelIndices[l] != -1)
  2505. {
  2506. aiMatrix4x4 animtform, tempMat;
  2507. aiNodeAnim* animchannel = anim->mChannels[channelIndices[l]];
  2508. if (k < animchannel->mNumPositionKeys)
  2509. {
  2510. aiMatrix4x4::Translation(animchannel->mPositionKeys[k].mValue, tempMat);
  2511. animtform = animtform * tempMat;
  2512. frameTime = Max(animchannel->mPositionKeys[k].mTime, frameTime);
  2513. }
  2514. if (k < animchannel->mNumRotationKeys)
  2515. {
  2516. tempMat = aiMatrix4x4(animchannel->mRotationKeys[k].mValue.GetMatrix());
  2517. animtform = animtform * tempMat;
  2518. frameTime = Max(animchannel->mRotationKeys[k].mTime, frameTime);
  2519. }
  2520. if (k < animchannel->mNumScalingKeys)
  2521. {
  2522. aiMatrix4x4::Scaling(animchannel->mScalingKeys[k].mValue, tempMat);
  2523. animtform = animtform * tempMat;
  2524. frameTime = Max(animchannel->mScalingKeys[k].mTime, frameTime);
  2525. }
  2526. finalTransform = finalTransform * animtform;
  2527. }
  2528. else
  2529. finalTransform = finalTransform * chain[l];
  2530. }
  2531. aiVector3D animPos, animScale;
  2532. aiQuaternion animRot;
  2533. finalTransform = finalTransform * mainboneTransform;
  2534. finalTransform.Decompose(animScale, animRot, animPos);
  2535. // New values
  2536. if (k < channel->mNumPositionKeys)
  2537. {
  2538. channel->mPositionKeys[k].mValue = animPos;
  2539. channel->mPositionKeys[k].mTime = frameTime;
  2540. }
  2541. if (k < channel->mNumRotationKeys)
  2542. {
  2543. channel->mRotationKeys[k].mValue = animRot;
  2544. channel->mRotationKeys[k].mTime = frameTime;
  2545. }
  2546. if (k < channel->mNumScalingKeys)
  2547. {
  2548. channel->mScalingKeys[k].mValue = animScale;
  2549. channel->mScalingKeys[k].mTime = frameTime;
  2550. }
  2551. }
  2552. }
  2553. }
  2554. }
  2555. }
  2556. }
  2557. void CollectSceneNodesAsBones(OutModel &model, aiNode* rootNode)
  2558. {
  2559. if (!rootNode)
  2560. return;
  2561. model.bones_.Push(rootNode);
  2562. for (unsigned i = 0; i < rootNode->mNumChildren; ++i)
  2563. {
  2564. CollectSceneNodesAsBones(model, rootNode->mChildren[i]);
  2565. }
  2566. }