AssetImporter.cpp 109 KB

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