AssetImporter.cpp 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178
  1. //
  2. // Copyright (c) 2008-2014 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 "AnimatedModel.h"
  23. #include "Animation.h"
  24. #include "Context.h"
  25. #include "DebugRenderer.h"
  26. #include "File.h"
  27. #include "FileSystem.h"
  28. #include "Geometry.h"
  29. #include "Graphics.h"
  30. #include "IndexBuffer.h"
  31. #include "Light.h"
  32. #include "Material.h"
  33. #include "Model.h"
  34. #include "Octree.h"
  35. #ifdef URHO3D_PHYSICS
  36. #include "PhysicsWorld.h"
  37. #endif
  38. #include "ProcessUtils.h"
  39. #include "Quaternion.h"
  40. #include "ResourceCache.h"
  41. #include "Scene.h"
  42. #include "StringUtils.h"
  43. #include "Vector3.h"
  44. #include "VertexBuffer.h"
  45. #include "WorkQueue.h"
  46. #include "XMLFile.h"
  47. #include "Zone.h"
  48. #include "Sort.h"
  49. #ifdef WIN32
  50. #include <windows.h>
  51. #endif
  52. #include <assimp/cimport.h>
  53. #include <assimp/scene.h>
  54. #include <assimp/postprocess.h>
  55. #include <assimp/DefaultLogger.hpp>
  56. #include <cstring>
  57. #include "DebugNew.h"
  58. using namespace Urho3D;
  59. struct OutModel
  60. {
  61. OutModel() :
  62. rootBone_(0),
  63. totalVertices_(0),
  64. totalIndices_(0)
  65. {
  66. }
  67. String outName_;
  68. aiNode* rootNode_;
  69. HashSet<unsigned> meshIndices_;
  70. PODVector<aiMesh*> meshes_;
  71. PODVector<aiNode*> meshNodes_;
  72. PODVector<aiNode*> bones_;
  73. PODVector<aiAnimation*> animations_;
  74. PODVector<float> boneRadii_;
  75. PODVector<BoundingBox> boneHitboxes_;
  76. aiNode* rootBone_;
  77. unsigned totalVertices_;
  78. unsigned totalIndices_;
  79. };
  80. struct OutScene
  81. {
  82. String outName_;
  83. aiNode* rootNode_;
  84. Vector<OutModel> models_;
  85. PODVector<aiNode*> nodes_;
  86. PODVector<unsigned> nodeModelIndices_;
  87. };
  88. SharedPtr<Context> context_(new Context());
  89. const aiScene* scene_ = 0;
  90. aiNode* rootNode_ = 0;
  91. String inputName_;
  92. String resourcePath_;
  93. String outPath_;
  94. bool useSubdirs_ = true;
  95. bool localIDs_ = false;
  96. bool saveBinary_ = false;
  97. bool createZone_ = true;
  98. bool noAnimations_ = false;
  99. bool noHierarchy_ = false;
  100. bool noMaterials_ = false;
  101. bool noTextures_ = false;
  102. bool noMaterialDiffuseColor_ = false;
  103. bool saveMaterialList_ = false;
  104. bool includeNonSkinningBones_ = false;
  105. bool verboseLog_ = false;
  106. bool emissiveAO_ = false;
  107. bool noOverwriteMaterial_ = false;
  108. bool noOverwriteTexture_ = false;
  109. bool noOverwriteNewerTexture_ = false;
  110. bool checkUniqueModel_ = true;
  111. Vector<String> nonSkinningBoneIncludes_;
  112. Vector<String> nonSkinningBoneExcludes_;
  113. HashSet<aiAnimation*> allAnimations_;
  114. PODVector<aiAnimation*> sceneAnimations_;
  115. float defaultTicksPerSecond_ = 4800.0f;
  116. int main(int argc, char** argv);
  117. void Run(const Vector<String>& arguments);
  118. void DumpNodes(aiNode* rootNode, unsigned level);
  119. void ExportModel(const String& outName, bool animationOnly);
  120. void CollectMeshes(OutModel& model, aiNode* node);
  121. void CollectBones(OutModel& model, bool animationOnly = false);
  122. void CollectBonesFinal(PODVector<aiNode*>& dest, const HashSet<aiNode*>& necessary, aiNode* node);
  123. void CollectAnimations(OutModel* model = 0);
  124. void BuildBoneCollisionInfo(OutModel& model);
  125. void BuildAndSaveModel(OutModel& model);
  126. void BuildAndSaveAnimations(OutModel* model = 0);
  127. void ExportScene(const String& outName, bool asPrefab);
  128. void CollectSceneModels(OutScene& scene, aiNode* node);
  129. Node* CreateSceneNode(Scene* scene, aiNode* srcNode, HashMap<aiNode*, WeakPtr<Node> >& nodeMapping);
  130. void BuildAndSaveScene(OutScene& scene, bool asPrefab);
  131. void ExportMaterials(HashSet<String>& usedTextures);
  132. void BuildAndSaveMaterial(aiMaterial* material, HashSet<String>& usedTextures);
  133. void CopyTextures(const HashSet<String>& usedTextures, const String& sourcePath);
  134. void CombineLods(const PODVector<float>& lodDistances, const Vector<String>& modelNames, const String& outName);
  135. void GetMeshesUnderNode(Vector<Pair<aiNode*, aiMesh*> >& meshes, aiNode* node);
  136. unsigned GetMeshIndex(aiMesh* mesh);
  137. unsigned GetBoneIndex(OutModel& model, const String& boneName);
  138. aiBone* GetMeshBone(OutModel& model, const String& boneName);
  139. Matrix3x4 GetOffsetMatrix(OutModel& model, const String& boneName);
  140. void GetBlendData(OutModel& model, aiMesh* mesh, PODVector<unsigned>& boneMappings, Vector<PODVector<unsigned char> >&
  141. blendIndices, Vector<PODVector<float> >& blendWeights);
  142. String GetMeshMaterialName(aiMesh* mesh);
  143. String GetMaterialTextureName(const String& nameIn);
  144. String GenerateMaterialName(aiMaterial* material);
  145. String GenerateTextureName(unsigned texIndex);
  146. unsigned GetNumValidFaces(aiMesh* mesh);
  147. void WriteShortIndices(unsigned short*& dest, aiMesh* mesh, unsigned index, unsigned offset);
  148. void WriteLargeIndices(unsigned*& dest, aiMesh* mesh, unsigned index, unsigned offset);
  149. void WriteVertex(float*& dest, aiMesh* mesh, unsigned index, unsigned elementMask, BoundingBox& box,
  150. const Matrix3x4& vertexTransform, const Matrix3& normalTransform, Vector<PODVector<unsigned char> >& blendIndices,
  151. Vector<PODVector<float> >& blendWeights);
  152. unsigned GetElementMask(aiMesh* mesh);
  153. aiNode* GetNode(const String& name, aiNode* rootNode, bool caseSensitive = true);
  154. aiMatrix4x4 GetDerivedTransform(aiNode* node, aiNode* rootNode, bool rootInclusive = true);
  155. aiMatrix4x4 GetDerivedTransform(aiMatrix4x4 transform, aiNode* node, aiNode* rootNode, bool rootInclusive = true);
  156. aiMatrix4x4 GetMeshBakingTransform(aiNode* meshNode, aiNode* modelRootNode);
  157. void GetPosRotScale(const aiMatrix4x4& transform, Vector3& pos, Quaternion& rot, Vector3& scale);
  158. String FromAIString(const aiString& str);
  159. Vector3 ToVector3(const aiVector3D& vec);
  160. Vector2 ToVector2(const aiVector2D& vec);
  161. Quaternion ToQuaternion(const aiQuaternion& quat);
  162. Matrix3x4 ToMatrix3x4(const aiMatrix4x4& mat);
  163. String SanitateAssetName(const String& name);
  164. int main(int argc, char** argv)
  165. {
  166. Vector<String> arguments;
  167. #ifdef WIN32
  168. arguments = ParseArguments(GetCommandLineW());
  169. #else
  170. arguments = ParseArguments(argc, argv);
  171. #endif
  172. Run(arguments);
  173. return 0;
  174. }
  175. void Run(const Vector<String>& arguments)
  176. {
  177. if (arguments.Size() < 2)
  178. {
  179. ErrorExit(
  180. "Usage: AssetImporter <command> <input file> <output file> [options]\n"
  181. "See http://assimp.sourceforge.net/main_features_formats.html for input formats\n\n"
  182. "Commands:\n"
  183. "model Output a model\n"
  184. "scene Output a scene\n"
  185. "node Output a node and its children (prefab)\n"
  186. "dump Dump scene node structure. No output file is generated\n"
  187. "lod Combine several Urho3D models as LOD levels of the output model\n"
  188. " Syntax: lod <dist0> <mdl0> <dist1 <mdl1> ... <output file>\n"
  189. "\n"
  190. "Options:\n"
  191. "-b Save scene in binary format, default format is XML\n"
  192. "-h Generate hard instead of smooth normals if input file has no normals\n"
  193. "-i Use local ID's for scene nodes\n"
  194. "-l Output a material list file for models\n"
  195. "-na Do not output animations\n"
  196. "-nm Do not output materials\n"
  197. "-nt Do not output material textures\n"
  198. "-nc Do not use material diffuse color value, instead output white\n"
  199. "-nh Do not save full node hierarchy (scene mode only)\n"
  200. "-ns Do not create subdirectories for resources\n"
  201. "-nz Do not create a zone and a directional light (scene mode only)\n"
  202. "-nf Do not fix infacing normals\n"
  203. "-p <path> Set path for scene resources. Default is output file path\n"
  204. "-r <name> Use the named scene node as root node\n"
  205. "-f <freq> Animation tick frequency to use if unspecified. Default 4800\n"
  206. "-o Optimize redundant submeshes. Loses scene hierarchy and animations\n"
  207. "-s <filter> Include non-skinning bones in the model's skeleton. Can be given a\n"
  208. " case-insensitive semicolon separated filter list. Bone is included\n"
  209. " if its name contains any of the filters. Prefix filter with minus\n"
  210. " sign to use as an exclude. For example -s \"Bip01;-Dummy;-Helper\"\n"
  211. "-t Generate tangents\n"
  212. "-v Enable verbose Assimp library logging\n"
  213. "-eao Interpret material emissive texture as ambient occlusion\n"
  214. "-cm Check and do not overwrite if material exists\n"
  215. "-ct Check and do not overwrite if texture exists\n"
  216. "-ctn Check and do not overwrite if texture has newer timestamp\n"
  217. "-am Export all meshes even if identical (scene mode only)\n"
  218. );
  219. }
  220. context_->RegisterSubsystem(new FileSystem(context_));
  221. context_->RegisterSubsystem(new ResourceCache(context_));
  222. context_->RegisterSubsystem(new WorkQueue(context_));
  223. RegisterSceneLibrary(context_);
  224. RegisterGraphicsLibrary(context_);
  225. #ifdef URHO3D_PHYSICS
  226. RegisterPhysicsLibrary(context_);
  227. #endif
  228. String command = arguments[0].ToLower();
  229. String rootNodeName;
  230. unsigned flags =
  231. aiProcess_ConvertToLeftHanded |
  232. aiProcess_JoinIdenticalVertices |
  233. aiProcess_Triangulate |
  234. aiProcess_GenSmoothNormals |
  235. aiProcess_LimitBoneWeights |
  236. aiProcess_ImproveCacheLocality |
  237. aiProcess_RemoveRedundantMaterials |
  238. aiProcess_FixInfacingNormals |
  239. aiProcess_FindInvalidData |
  240. aiProcess_GenUVCoords |
  241. aiProcess_FindInstances |
  242. aiProcess_OptimizeMeshes;
  243. for (unsigned i = 2; i < arguments.Size(); ++i)
  244. {
  245. if (arguments[i].Length() > 1 && arguments[i][0] == '-')
  246. {
  247. String argument = arguments[i].Substring(1).ToLower();
  248. String value = i + 1 < arguments.Size() ? arguments[i + 1] : String::EMPTY;
  249. if (argument == "b")
  250. saveBinary_ = true;
  251. else if (argument == "h")
  252. {
  253. flags &= ~aiProcess_GenSmoothNormals;
  254. flags |= aiProcess_GenNormals;
  255. }
  256. else if (argument == "i")
  257. localIDs_ = true;
  258. else if (argument == "l")
  259. saveMaterialList_ = true;
  260. else if (argument == "t")
  261. flags |= aiProcess_CalcTangentSpace;
  262. else if (argument == "o")
  263. flags |= aiProcess_PreTransformVertices;
  264. else if (argument.Length() == 2 && argument[0] == 'n')
  265. {
  266. switch (tolower(argument[1]))
  267. {
  268. case 'a':
  269. noAnimations_ = true;
  270. break;
  271. case 'c':
  272. noMaterialDiffuseColor_ = true;
  273. break;
  274. case 'm':
  275. noMaterials_ = true;
  276. break;
  277. case 'h':
  278. noHierarchy_ = true;
  279. break;
  280. case 's':
  281. useSubdirs_ = false;
  282. break;
  283. case 't':
  284. noTextures_ = true;
  285. break;
  286. case 'z':
  287. createZone_ = false;
  288. break;
  289. case 'f':
  290. flags &= ~aiProcess_FixInfacingNormals;
  291. break;
  292. }
  293. }
  294. else if (argument == "p" && !value.Empty())
  295. {
  296. resourcePath_ = AddTrailingSlash(value);
  297. ++i;
  298. }
  299. else if (argument == "r" && !value.Empty())
  300. {
  301. rootNodeName = value;
  302. ++i;
  303. }
  304. else if (argument == "f" && !value.Empty())
  305. {
  306. defaultTicksPerSecond_ = ToFloat(value);
  307. ++i;
  308. }
  309. else if (argument == "s")
  310. {
  311. includeNonSkinningBones_ = true;
  312. if (value.Length() && (value[0] != '-' || value.Length() > 3))
  313. {
  314. Vector<String> filters = value.Split(';');
  315. for (unsigned i = 0; i < filters.Size(); ++i)
  316. {
  317. if (filters[i][0] == '-')
  318. nonSkinningBoneExcludes_.Push(filters[i].Substring(1));
  319. else
  320. nonSkinningBoneIncludes_.Push(filters[i]);
  321. }
  322. }
  323. }
  324. else if (argument == "v")
  325. verboseLog_ = true;
  326. else if (argument == "eao")
  327. emissiveAO_ = true;
  328. else if (argument == "cm")
  329. noOverwriteMaterial_ = true;
  330. else if (argument == "ct")
  331. noOverwriteTexture_ = true;
  332. else if (argument == "ctn")
  333. noOverwriteNewerTexture_ = true;
  334. else if (argument == "am")
  335. checkUniqueModel_ = false;
  336. }
  337. }
  338. if (command == "model" || command == "scene" || command == "node" || command == "dump")
  339. {
  340. String inFile = arguments[1];
  341. String outFile;
  342. if (arguments.Size() > 2 && arguments[2][0] != '-')
  343. outFile = GetInternalPath(arguments[2]);
  344. inputName_ = GetFileName(inFile);
  345. outPath_ = GetPath(outFile);
  346. if (resourcePath_.Empty())
  347. {
  348. resourcePath_ = outPath_;
  349. // If output file already has the Models/ path (model mode), do not take it into the resource path
  350. if (command == "model")
  351. {
  352. if (resourcePath_.EndsWith("Models/", false))
  353. resourcePath_ = resourcePath_.Substring(0, resourcePath_.Length() - 7);
  354. }
  355. if (resourcePath_.Empty())
  356. resourcePath_ = "./";
  357. }
  358. resourcePath_ = AddTrailingSlash(resourcePath_);
  359. if (command != "dump" && outFile.Empty())
  360. ErrorExit("No output file defined");
  361. if (verboseLog_)
  362. Assimp::DefaultLogger::create("", Assimp::Logger::VERBOSE, aiDefaultLogStream_STDOUT);
  363. PrintLine("Reading file " + inFile);
  364. scene_ = aiImportFile(GetNativePath(inFile).CString(), flags);
  365. if (!scene_)
  366. ErrorExit("Could not open or parse input file " + inFile);
  367. if (verboseLog_)
  368. Assimp::DefaultLogger::kill();
  369. rootNode_ = scene_->mRootNode;
  370. if (!rootNodeName.Empty())
  371. {
  372. rootNode_ = GetNode(rootNodeName, rootNode_, false);
  373. if (!rootNode_)
  374. ErrorExit("Could not find scene node " + rootNodeName);
  375. }
  376. if (command == "dump")
  377. {
  378. DumpNodes(rootNode_, 0);
  379. return;
  380. }
  381. if (command == "model")
  382. ExportModel(outFile, scene_->mFlags & AI_SCENE_FLAGS_INCOMPLETE);
  383. if (command == "scene" || command == "node")
  384. {
  385. bool asPrefab = command == "node";
  386. // Saving as prefab requires the hierarchy, especially the root node
  387. if (asPrefab)
  388. noHierarchy_ = false;
  389. ExportScene(outFile, asPrefab);
  390. }
  391. if (!noMaterials_)
  392. {
  393. HashSet<String> usedTextures;
  394. ExportMaterials(usedTextures);
  395. if (!noTextures_)
  396. CopyTextures(usedTextures, GetPath(inFile));
  397. }
  398. }
  399. else if (command == "lod")
  400. {
  401. PODVector<float> lodDistances;
  402. Vector<String> modelNames;
  403. String outFile;
  404. unsigned numLodArguments = 0;
  405. for (unsigned i = 1; i < arguments.Size(); ++i)
  406. {
  407. if (arguments[i][0] == '-')
  408. break;
  409. ++numLodArguments;
  410. }
  411. if (numLodArguments < 4)
  412. ErrorExit("Must define at least 2 LOD levels");
  413. if (!(numLodArguments & 1))
  414. ErrorExit("No output file defined");
  415. for (unsigned i = 1; i < numLodArguments + 1; ++i)
  416. {
  417. if (i == numLodArguments)
  418. outFile = GetInternalPath(arguments[i]);
  419. else
  420. {
  421. if (i & 1)
  422. lodDistances.Push(Max(ToFloat(arguments[i]), 0.0f));
  423. else
  424. modelNames.Push(GetInternalPath(arguments[i]));
  425. }
  426. }
  427. if (lodDistances[0] != 0.0f)
  428. {
  429. PrintLine("Warning: first LOD distance forced to 0");
  430. lodDistances[0] = 0.0f;
  431. }
  432. CombineLods(lodDistances, modelNames, outFile);
  433. }
  434. else
  435. ErrorExit("Unrecognized command " + command);
  436. }
  437. void DumpNodes(aiNode* rootNode, unsigned level)
  438. {
  439. if (!rootNode)
  440. return;
  441. String indent(' ', level * 2);
  442. Vector3 pos, scale;
  443. Quaternion rot;
  444. aiMatrix4x4 transform = GetDerivedTransform(rootNode, rootNode_);
  445. GetPosRotScale(transform, pos, rot, scale);
  446. PrintLine(indent + "Node " + FromAIString(rootNode->mName) + " pos " + String(pos));
  447. if (rootNode->mNumMeshes == 1)
  448. PrintLine(indent + " " + String(rootNode->mNumMeshes) + " geometry");
  449. if (rootNode->mNumMeshes > 1)
  450. PrintLine(indent + " " + String(rootNode->mNumMeshes) + " geometries");
  451. for (unsigned i = 0; i < rootNode->mNumChildren; ++i)
  452. DumpNodes(rootNode->mChildren[i], level + 1);
  453. }
  454. void ExportModel(const String& outName, bool animationOnly)
  455. {
  456. if (outName.Empty())
  457. ErrorExit("No output file defined");
  458. OutModel model;
  459. model.rootNode_ = rootNode_;
  460. model.outName_ = outName;
  461. CollectMeshes(model, model.rootNode_);
  462. CollectBones(model, animationOnly);
  463. BuildBoneCollisionInfo(model);
  464. BuildAndSaveModel(model);
  465. if (!noAnimations_)
  466. {
  467. CollectAnimations(&model);
  468. BuildAndSaveAnimations(&model);
  469. // Save scene-global animations
  470. CollectAnimations();
  471. BuildAndSaveAnimations();
  472. }
  473. }
  474. void CollectMeshes(OutModel& model, aiNode* node)
  475. {
  476. for (unsigned i = 0; i < node->mNumMeshes; ++i)
  477. {
  478. aiMesh* mesh = scene_->mMeshes[node->mMeshes[i]];
  479. for (unsigned j = 0; j < model.meshes_.Size(); ++j)
  480. {
  481. if (mesh == model.meshes_[j])
  482. {
  483. PrintLine("Warning: same mesh found multiple times");
  484. break;
  485. }
  486. }
  487. model.meshIndices_.Insert(node->mMeshes[i]);
  488. model.meshes_.Push(mesh);
  489. model.meshNodes_.Push(node);
  490. model.totalVertices_ += mesh->mNumVertices;
  491. model.totalIndices_ += GetNumValidFaces(mesh) * 3;
  492. }
  493. for (unsigned i = 0; i < node->mNumChildren; ++i)
  494. CollectMeshes(model, node->mChildren[i]);
  495. }
  496. void CollectBones(OutModel& model, bool animationOnly)
  497. {
  498. HashSet<aiNode*> necessary;
  499. HashSet<aiNode*> rootNodes;
  500. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  501. {
  502. aiMesh* mesh = model.meshes_[i];
  503. aiNode* meshNode = model.meshNodes_[i];
  504. aiNode* meshParentNode = meshNode->mParent;
  505. aiNode* rootNode = 0;
  506. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  507. {
  508. aiBone* bone = mesh->mBones[j];
  509. String boneName(FromAIString(bone->mName));
  510. aiNode* boneNode = GetNode(boneName, scene_->mRootNode, true);
  511. if (!boneNode)
  512. ErrorExit("Could not find scene node for bone " + boneName);
  513. necessary.Insert(boneNode);
  514. rootNode = boneNode;
  515. for (;;)
  516. {
  517. boneNode = boneNode->mParent;
  518. if (!boneNode || ((boneNode == meshNode || boneNode == meshParentNode) && !animationOnly))
  519. break;
  520. rootNode = boneNode;
  521. necessary.Insert(boneNode);
  522. }
  523. if (rootNodes.Find(rootNode) == rootNodes.End())
  524. rootNodes.Insert(rootNode);
  525. }
  526. }
  527. // If we find multiple root nodes, try to remedy by using their parent instead
  528. if (rootNodes.Size() > 1)
  529. {
  530. aiNode* commonParent = (*rootNodes.Begin())->mParent;
  531. for (HashSet<aiNode*>::Iterator i = rootNodes.Begin(); i != rootNodes.End(); ++i)
  532. {
  533. if (*i != commonParent)
  534. {
  535. if (!commonParent || (*i)->mParent != commonParent)
  536. ErrorExit("Skeleton with multiple root nodes found, not supported");
  537. }
  538. }
  539. rootNodes.Clear();
  540. rootNodes.Insert(commonParent);
  541. necessary.Insert(commonParent);
  542. }
  543. if (rootNodes.Empty())
  544. return;
  545. model.rootBone_ = *rootNodes.Begin();
  546. CollectBonesFinal(model.bones_, necessary, model.rootBone_);
  547. // Initialize the bone collision info
  548. model.boneRadii_.Resize(model.bones_.Size());
  549. model.boneHitboxes_.Resize(model.bones_.Size());
  550. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  551. {
  552. model.boneRadii_[i] = 0.0f;
  553. model.boneHitboxes_[i] = BoundingBox(0.0f, 0.0f);
  554. }
  555. }
  556. void CollectBonesFinal(PODVector<aiNode*>& dest, const HashSet<aiNode*>& necessary, aiNode* node)
  557. {
  558. bool includeBone = necessary.Find(node) != necessary.End();
  559. String boneName = FromAIString(node->mName);
  560. // Check include/exclude filters for non-skinned bones
  561. if (!includeBone && includeNonSkinningBones_)
  562. {
  563. // If no includes specified, include by default but check for excludes
  564. if (nonSkinningBoneIncludes_.Empty())
  565. includeBone = true;
  566. // Check against includes/excludes
  567. for (unsigned i = 0; i < nonSkinningBoneIncludes_.Size(); ++i)
  568. {
  569. if (boneName.Contains(nonSkinningBoneIncludes_[i], false))
  570. {
  571. includeBone = true;
  572. break;
  573. }
  574. }
  575. for (unsigned i = 0; i < nonSkinningBoneExcludes_.Size(); ++i)
  576. {
  577. if (boneName.Contains(nonSkinningBoneExcludes_[i], false))
  578. {
  579. includeBone = false;
  580. break;
  581. }
  582. }
  583. if (includeBone)
  584. PrintLine("Including non-skinning bone " + boneName);
  585. }
  586. if (includeBone)
  587. dest.Push(node);
  588. for (unsigned i = 0; i < node->mNumChildren; ++i)
  589. CollectBonesFinal(dest, necessary, node->mChildren[i]);
  590. }
  591. void CollectAnimations(OutModel* model)
  592. {
  593. const aiScene* scene = scene_;
  594. for (unsigned i = 0; i < scene->mNumAnimations; ++i)
  595. {
  596. aiAnimation* anim = scene->mAnimations[i];
  597. if (allAnimations_.Contains(anim))
  598. continue;
  599. if (model)
  600. {
  601. bool modelBoneFound = false;
  602. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  603. {
  604. aiNodeAnim* channel = anim->mChannels[j];
  605. String channelName = FromAIString(channel->mNodeName);
  606. if (GetBoneIndex(*model, channelName) != M_MAX_UNSIGNED)
  607. {
  608. modelBoneFound = true;
  609. break;
  610. }
  611. }
  612. if (modelBoneFound)
  613. {
  614. model->animations_.Push(anim);
  615. allAnimations_.Insert(anim);
  616. }
  617. }
  618. else
  619. {
  620. sceneAnimations_.Push(anim);
  621. allAnimations_.Insert(anim);
  622. }
  623. }
  624. /// \todo Vertex morphs are ignored for now
  625. }
  626. void BuildBoneCollisionInfo(OutModel& model)
  627. {
  628. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  629. {
  630. aiMesh* mesh = model.meshes_[i];
  631. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  632. {
  633. aiBone* bone = mesh->mBones[j];
  634. String boneName = FromAIString(bone->mName);
  635. unsigned boneIndex = GetBoneIndex(model, boneName);
  636. if (boneIndex == M_MAX_UNSIGNED)
  637. continue;
  638. for (unsigned k = 0; k < bone->mNumWeights; ++k)
  639. {
  640. float weight = bone->mWeights[k].mWeight;
  641. // Require skinning weight to be sufficiently large before vertex contributes to bone hitbox
  642. if (weight > 0.33f)
  643. {
  644. aiVector3D vertexBoneSpace = bone->mOffsetMatrix * mesh->mVertices[bone->mWeights[k].mVertexId];
  645. Vector3 vertex = ToVector3(vertexBoneSpace);
  646. float radius = vertex.Length();
  647. if (radius > model.boneRadii_[boneIndex])
  648. model.boneRadii_[boneIndex] = radius;
  649. model.boneHitboxes_[boneIndex].Merge(vertex);
  650. }
  651. }
  652. }
  653. }
  654. }
  655. void BuildAndSaveModel(OutModel& model)
  656. {
  657. if (!model.rootNode_)
  658. ErrorExit("Null root node for model");
  659. String rootNodeName = FromAIString(model.rootNode_->mName);
  660. if (!model.meshes_.Size())
  661. ErrorExit("No geometries found starting from node " + rootNodeName);
  662. PrintLine("Writing model " + rootNodeName);
  663. SharedPtr<Model> outModel(new Model(context_));
  664. Vector<PODVector<unsigned> > allBoneMappings;
  665. BoundingBox box;
  666. unsigned numValidGeometries = 0;
  667. bool combineBuffers = true;
  668. // Check if buffers can be combined (same vertex element mask, under 65535 vertices)
  669. unsigned elementMask = GetElementMask(model.meshes_[0]);
  670. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  671. {
  672. if (GetNumValidFaces(model.meshes_[i]))
  673. {
  674. ++numValidGeometries;
  675. if (i > 0 && GetElementMask(model.meshes_[i]) != elementMask)
  676. combineBuffers = false;
  677. }
  678. }
  679. // Check if keeping separate buffers allows to avoid 32-bit indices
  680. if (combineBuffers && model.totalVertices_ > 65535)
  681. {
  682. bool allUnder65k = true;
  683. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  684. {
  685. if (GetNumValidFaces(model.meshes_[i]))
  686. {
  687. if (model.meshes_[i]->mNumVertices > 65535)
  688. allUnder65k = false;
  689. }
  690. }
  691. if (allUnder65k == true)
  692. combineBuffers = false;
  693. }
  694. SharedPtr<IndexBuffer> ib;
  695. SharedPtr<VertexBuffer> vb;
  696. Vector<SharedPtr<VertexBuffer> > vbVector;
  697. Vector<SharedPtr<IndexBuffer> > ibVector;
  698. unsigned startVertexOffset = 0;
  699. unsigned startIndexOffset = 0;
  700. unsigned destGeomIndex = 0;
  701. outModel->SetNumGeometries(numValidGeometries);
  702. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  703. {
  704. aiMesh* mesh = model.meshes_[i];
  705. unsigned elementMask = GetElementMask(mesh);
  706. unsigned validFaces = GetNumValidFaces(mesh);
  707. if (!validFaces)
  708. continue;
  709. bool largeIndices;
  710. if (combineBuffers)
  711. largeIndices = model.totalIndices_ > 65535;
  712. else
  713. largeIndices = mesh->mNumVertices > 65535;
  714. // Create new buffers if necessary
  715. if (!combineBuffers || vbVector.Empty())
  716. {
  717. vb = new VertexBuffer(context_);
  718. ib = new IndexBuffer(context_);
  719. if (combineBuffers)
  720. {
  721. ib->SetSize(model.totalIndices_, largeIndices);
  722. vb->SetSize(model.totalVertices_, elementMask);
  723. }
  724. else
  725. {
  726. ib->SetSize(validFaces * 3, largeIndices);
  727. vb->SetSize(mesh->mNumVertices, elementMask);
  728. }
  729. vbVector.Push(vb);
  730. ibVector.Push(ib);
  731. startVertexOffset = 0;
  732. startIndexOffset = 0;
  733. }
  734. // Get the world transform of the mesh for baking into the vertices
  735. Matrix3x4 vertexTransform;
  736. Matrix3 normalTransform;
  737. Vector3 pos, scale;
  738. Quaternion rot;
  739. GetPosRotScale(GetMeshBakingTransform(model.meshNodes_[i], model.rootNode_), pos, rot, scale);
  740. vertexTransform = Matrix3x4(pos, rot, scale);
  741. normalTransform = rot.RotationMatrix();
  742. SharedPtr<Geometry> geom(new Geometry(context_));
  743. PrintLine("Writing geometry " + String(i) + " with " + String(mesh->mNumVertices) + " vertices " +
  744. String(validFaces * 3) + " indices");
  745. unsigned char* vertexData = vb->GetShadowData();
  746. unsigned char* indexData = ib->GetShadowData();
  747. // Build the index data
  748. if (!largeIndices)
  749. {
  750. unsigned short* dest = (unsigned short*)indexData + startIndexOffset;
  751. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  752. WriteShortIndices(dest, mesh, j, startVertexOffset);
  753. }
  754. else
  755. {
  756. unsigned* dest = (unsigned*)indexData + startIndexOffset;
  757. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  758. WriteLargeIndices(dest, mesh, j, startVertexOffset);
  759. }
  760. // Build the vertex data
  761. // If there are bones, get blend data
  762. Vector<PODVector<unsigned char> > blendIndices;
  763. Vector<PODVector<float> > blendWeights;
  764. PODVector<unsigned> boneMappings;
  765. if (model.bones_.Size())
  766. GetBlendData(model, mesh, boneMappings, blendIndices, blendWeights);
  767. float* dest = (float*)((unsigned char*)vertexData + startVertexOffset * vb->GetVertexSize());
  768. for (unsigned j = 0; j < mesh->mNumVertices; ++j)
  769. WriteVertex(dest, mesh, j, elementMask, box, vertexTransform, normalTransform, blendIndices, blendWeights);
  770. // Calculate the geometry center
  771. Vector3 center = Vector3::ZERO;
  772. if (validFaces)
  773. {
  774. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  775. {
  776. if (mesh->mFaces[j].mNumIndices == 3)
  777. {
  778. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[0]]);
  779. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[1]]);
  780. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[2]]);
  781. }
  782. }
  783. center /= (float)validFaces * 3;
  784. }
  785. // Define the geometry
  786. geom->SetIndexBuffer(ib);
  787. geom->SetVertexBuffer(0, vb);
  788. geom->SetDrawRange(TRIANGLE_LIST, startIndexOffset, validFaces * 3, true);
  789. outModel->SetNumGeometryLodLevels(destGeomIndex, 1);
  790. outModel->SetGeometry(destGeomIndex, 0, geom);
  791. outModel->SetGeometryCenter(destGeomIndex, center);
  792. if (model.bones_.Size() > MAX_SKIN_MATRICES)
  793. allBoneMappings.Push(boneMappings);
  794. startVertexOffset += mesh->mNumVertices;
  795. startIndexOffset += validFaces * 3;
  796. ++destGeomIndex;
  797. }
  798. // Define the model buffers and bounding box
  799. PODVector<unsigned> emptyMorphRange;
  800. outModel->SetVertexBuffers(vbVector, emptyMorphRange, emptyMorphRange);
  801. outModel->SetIndexBuffers(ibVector);
  802. outModel->SetBoundingBox(box);
  803. // Build skeleton if necessary
  804. if (model.bones_.Size() && model.rootBone_)
  805. {
  806. PrintLine("Writing skeleton with " + String(model.bones_.Size()) + " bones, rootbone " +
  807. FromAIString(model.rootBone_->mName));
  808. Skeleton skeleton;
  809. Vector<Bone>& bones = skeleton.GetModifiableBones();
  810. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  811. {
  812. aiNode* boneNode = model.bones_[i];
  813. String boneName(FromAIString(boneNode->mName));
  814. Bone newBone;
  815. newBone.name_ = boneName;
  816. aiMatrix4x4 transform = boneNode->mTransformation;
  817. // Make the root bone transform relative to the model's root node, if it is not already
  818. if (boneNode == model.rootBone_)
  819. transform = GetDerivedTransform(boneNode, model.rootNode_);
  820. GetPosRotScale(transform, newBone.initialPosition_, newBone.initialRotation_, newBone.initialScale_);
  821. // Get offset information if exists
  822. newBone.offsetMatrix_ = GetOffsetMatrix(model, boneName);
  823. newBone.radius_ = model.boneRadii_[i];
  824. newBone.boundingBox_ = model.boneHitboxes_[i];
  825. newBone.collisionMask_ = BONECOLLISION_SPHERE | BONECOLLISION_BOX;
  826. newBone.parentIndex_ = i;
  827. bones.Push(newBone);
  828. }
  829. // Set the bone hierarchy
  830. for (unsigned i = 1; i < model.bones_.Size(); ++i)
  831. {
  832. String parentName = FromAIString(model.bones_[i]->mParent->mName);
  833. for (unsigned j = 0; j < bones.Size(); ++j)
  834. {
  835. if (bones[j].name_ == parentName)
  836. {
  837. bones[i].parentIndex_ = j;
  838. break;
  839. }
  840. }
  841. }
  842. outModel->SetSkeleton(skeleton);
  843. if (model.bones_.Size() > MAX_SKIN_MATRICES)
  844. outModel->SetGeometryBoneMappings(allBoneMappings);
  845. }
  846. File outFile(context_);
  847. if (!outFile.Open(model.outName_, FILE_WRITE))
  848. ErrorExit("Could not open output file " + model.outName_);
  849. outModel->Save(outFile);
  850. // If exporting materials, also save material list for use by the editor
  851. if (!noMaterials_ && saveMaterialList_)
  852. {
  853. String materialListName = ReplaceExtension(model.outName_, ".txt");
  854. File listFile(context_);
  855. if (listFile.Open(materialListName, FILE_WRITE))
  856. {
  857. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  858. listFile.WriteLine(GetMeshMaterialName(model.meshes_[i]));
  859. }
  860. else
  861. PrintLine("Warning: could not write material list file " + materialListName);
  862. }
  863. }
  864. void BuildAndSaveAnimations(OutModel* model)
  865. {
  866. const PODVector<aiAnimation*>& animations = model ? model->animations_ : sceneAnimations_;
  867. for (unsigned i = 0; i < animations.Size(); ++i)
  868. {
  869. aiAnimation* anim = animations[i];
  870. float duration = (float)anim->mDuration;
  871. String animName = FromAIString(anim->mName);
  872. String animOutName;
  873. if (animName.Empty())
  874. animName = "Anim" + String(i + 1);
  875. if (model)
  876. animOutName = GetPath(model->outName_) + GetFileName(model->outName_) + "_" + SanitateAssetName(animName) + ".ani";
  877. else
  878. animOutName = outPath_ + SanitateAssetName(animName) + ".ani";
  879. float ticksPerSecond = (float)anim->mTicksPerSecond;
  880. // If ticks per second not specified, it's probably a .X file. In this case use the default tick rate
  881. if (ticksPerSecond < M_EPSILON)
  882. ticksPerSecond = defaultTicksPerSecond_;
  883. float tickConversion = 1.0f / ticksPerSecond;
  884. // Find out the start time of animation from each channel's first keyframe for adjusting the keyframe times
  885. // to start from zero
  886. float startTime = duration;
  887. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  888. {
  889. aiNodeAnim* channel = anim->mChannels[j];
  890. if (channel->mNumPositionKeys > 0)
  891. startTime = Min(startTime, (float)channel->mPositionKeys[0].mTime);
  892. if (channel->mNumRotationKeys > 0)
  893. startTime = Min(startTime, (float)channel->mRotationKeys[0].mTime);
  894. if (channel->mScalingKeys > 0)
  895. startTime = Min(startTime, (float)channel->mScalingKeys[0].mTime);
  896. }
  897. duration -= startTime;
  898. SharedPtr<Animation> outAnim(new Animation(context_));
  899. outAnim->SetAnimationName(animName);
  900. outAnim->SetLength(duration * tickConversion);
  901. PrintLine("Writing animation " + animName + " length " + String(outAnim->GetLength()));
  902. Vector<AnimationTrack> tracks;
  903. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  904. {
  905. aiNodeAnim* channel = anim->mChannels[j];
  906. String channelName = FromAIString(channel->mNodeName);
  907. aiNode* boneNode = 0;
  908. bool isRootBone = false;
  909. if (model)
  910. {
  911. unsigned boneIndex = GetBoneIndex(*model, channelName);
  912. if (boneIndex == M_MAX_UNSIGNED)
  913. {
  914. PrintLine("Warning: skipping animation track " + channelName + " not found in model skeleton");
  915. continue;
  916. }
  917. boneNode = model->bones_[boneIndex];
  918. isRootBone = boneIndex == 0;
  919. }
  920. else
  921. {
  922. boneNode = GetNode(channelName, scene_->mRootNode);
  923. if (!boneNode)
  924. {
  925. PrintLine("Warning: skipping animation track " + channelName + " whose scene node was not found");
  926. continue;
  927. }
  928. }
  929. AnimationTrack track;
  930. track.name_ = channelName;
  931. track.nameHash_ = channelName;
  932. // Check which channels are used
  933. track.channelMask_ = 0;
  934. if (channel->mNumPositionKeys > 1)
  935. track.channelMask_ |= CHANNEL_POSITION;
  936. if (channel->mNumRotationKeys > 1)
  937. track.channelMask_ |= CHANNEL_ROTATION;
  938. if (channel->mNumScalingKeys > 1)
  939. track.channelMask_ |= CHANNEL_SCALE;
  940. // Check for redundant identity scale in all keyframes and remove in that case
  941. if (track.channelMask_ & CHANNEL_SCALE)
  942. {
  943. bool redundantScale = true;
  944. for (unsigned k = 0; k < channel->mNumScalingKeys; ++k)
  945. {
  946. float SCALE_EPSILON = 0.000001f;
  947. Vector3 scaleVec = ToVector3(channel->mScalingKeys[k].mValue);
  948. if (fabsf(scaleVec.x_ - 1.0f) >= SCALE_EPSILON || fabsf(scaleVec.y_ - 1.0f) >= SCALE_EPSILON ||
  949. fabsf(scaleVec.z_ - 1.0f) >= SCALE_EPSILON)
  950. {
  951. redundantScale = false;
  952. break;
  953. }
  954. }
  955. if (redundantScale)
  956. track.channelMask_ &= ~CHANNEL_SCALE;
  957. }
  958. if (!track.channelMask_)
  959. PrintLine("Warning: skipping animation track " + channelName + " with no keyframes");
  960. // Currently only same amount of keyframes is supported
  961. // Note: should also check the times of individual keyframes for match
  962. if ((channel->mNumPositionKeys > 1 && channel->mNumRotationKeys > 1 && channel->mNumPositionKeys != channel->mNumRotationKeys) ||
  963. (channel->mNumPositionKeys > 1 && channel->mNumScalingKeys > 1 && channel->mNumPositionKeys != channel->mNumScalingKeys) ||
  964. (channel->mNumRotationKeys > 1 && channel->mNumScalingKeys > 1 && channel->mNumRotationKeys != channel->mNumScalingKeys))
  965. {
  966. PrintLine("Warning: differing amounts of channel keyframes, skipping animation track " + channelName);
  967. continue;
  968. }
  969. unsigned keyFrames = channel->mNumPositionKeys;
  970. if (channel->mNumRotationKeys > keyFrames)
  971. keyFrames = channel->mNumRotationKeys;
  972. if (channel->mNumScalingKeys > keyFrames)
  973. keyFrames = channel->mNumScalingKeys;
  974. for (unsigned k = 0; k < keyFrames; ++k)
  975. {
  976. AnimationKeyFrame kf;
  977. kf.time_ = 0.0f;
  978. kf.position_ = Vector3::ZERO;
  979. kf.rotation_ = Quaternion::IDENTITY;
  980. kf.scale_ = Vector3::ONE;
  981. // Get time for the keyframe. Adjust with animation's start time
  982. if (track.channelMask_ & CHANNEL_POSITION && k < channel->mNumPositionKeys)
  983. kf.time_ = ((float)channel->mPositionKeys[k].mTime - startTime) * tickConversion;
  984. else if (track.channelMask_ & CHANNEL_ROTATION && k < channel->mNumRotationKeys)
  985. kf.time_ = ((float)channel->mRotationKeys[k].mTime - startTime) * tickConversion;
  986. else if (track.channelMask_ & CHANNEL_SCALE && k < channel->mNumScalingKeys)
  987. kf.time_ = ((float)channel->mScalingKeys[k].mTime - startTime) * tickConversion;
  988. // Make sure time stays positive
  989. kf.time_ = Max(kf.time_, 0.0f);
  990. // Start with the bone's base transform
  991. aiMatrix4x4 boneTransform = boneNode->mTransformation;
  992. aiVector3D pos, scale;
  993. aiQuaternion rot;
  994. boneTransform.Decompose(scale, rot, pos);
  995. // Then apply the active channels
  996. if (track.channelMask_ & CHANNEL_POSITION && k < channel->mNumPositionKeys)
  997. pos = channel->mPositionKeys[k].mValue;
  998. if (track.channelMask_ & CHANNEL_ROTATION && k < channel->mNumRotationKeys)
  999. rot = channel->mRotationKeys[k].mValue;
  1000. if (track.channelMask_ & CHANNEL_SCALE && k < channel->mNumScalingKeys)
  1001. scale = channel->mScalingKeys[k].mValue;
  1002. // If root bone, transform with the model root node transform
  1003. if (model && isRootBone)
  1004. {
  1005. aiMatrix4x4 transMat, scaleMat, rotMat;
  1006. aiMatrix4x4::Translation(pos, transMat);
  1007. aiMatrix4x4::Scaling(scale, scaleMat);
  1008. rotMat = aiMatrix4x4(rot.GetMatrix());
  1009. aiMatrix4x4 tform = transMat * rotMat * scaleMat;
  1010. tform = GetDerivedTransform(tform, boneNode, model->rootNode_);
  1011. tform.Decompose(scale, rot, pos);
  1012. }
  1013. if (track.channelMask_ & CHANNEL_POSITION)
  1014. kf.position_ = ToVector3(pos);
  1015. if (track.channelMask_ & CHANNEL_ROTATION)
  1016. kf.rotation_ = ToQuaternion(rot);
  1017. if (track.channelMask_ & CHANNEL_SCALE)
  1018. kf.scale_ = ToVector3(scale);
  1019. track.keyFrames_.Push(kf);
  1020. }
  1021. tracks.Push(track);
  1022. }
  1023. outAnim->SetTracks(tracks);
  1024. File outFile(context_);
  1025. if (!outFile.Open(animOutName, FILE_WRITE))
  1026. ErrorExit("Could not open output file " + animOutName);
  1027. outAnim->Save(outFile);
  1028. }
  1029. }
  1030. void ExportScene(const String& outName, bool asPrefab)
  1031. {
  1032. OutScene outScene;
  1033. outScene.outName_ = outName;
  1034. outScene.rootNode_ = rootNode_;
  1035. if (useSubdirs_)
  1036. context_->GetSubsystem<FileSystem>()->CreateDir(resourcePath_ + "Models");
  1037. CollectSceneModels(outScene, rootNode_);
  1038. // Save models, their material lists and animations
  1039. for (unsigned i = 0; i < outScene.models_.Size(); ++i)
  1040. BuildAndSaveModel(outScene.models_[i]);
  1041. // Save scene-global animations
  1042. if (!noAnimations_)
  1043. {
  1044. CollectAnimations();
  1045. BuildAndSaveAnimations();
  1046. }
  1047. // Save scene
  1048. BuildAndSaveScene(outScene, asPrefab);
  1049. }
  1050. void CollectSceneModels(OutScene& scene, aiNode* node)
  1051. {
  1052. Vector<Pair<aiNode*, aiMesh*> > meshes;
  1053. GetMeshesUnderNode(meshes, node);
  1054. if (meshes.Size())
  1055. {
  1056. OutModel model;
  1057. model.rootNode_ = node;
  1058. model.outName_ = resourcePath_ + (useSubdirs_ ? "Models/" : "") + SanitateAssetName(FromAIString(node->mName)) + ".mdl";
  1059. for (unsigned i = 0; i < meshes.Size(); ++i)
  1060. {
  1061. aiMesh* mesh = meshes[i].second_;
  1062. unsigned meshIndex = GetMeshIndex(mesh);
  1063. model.meshIndices_.Insert(meshIndex);
  1064. model.meshes_.Push(mesh);
  1065. model.meshNodes_.Push(meshes[i].first_);
  1066. model.totalVertices_ += mesh->mNumVertices;
  1067. model.totalIndices_ += GetNumValidFaces(mesh) * 3;
  1068. }
  1069. // Check if a model with identical mesh indices already exists. If yes, do not export twice
  1070. bool unique = true;
  1071. if (checkUniqueModel_)
  1072. {
  1073. for (unsigned i = 0; i < scene.models_.Size(); ++i)
  1074. {
  1075. if (scene.models_[i].meshIndices_ == model.meshIndices_)
  1076. {
  1077. PrintLine("Added node " + FromAIString(node->mName));
  1078. scene.nodes_.Push(node);
  1079. scene.nodeModelIndices_.Push(i);
  1080. unique = false;
  1081. break;
  1082. }
  1083. }
  1084. }
  1085. if (unique)
  1086. {
  1087. PrintLine("Added model " + model.outName_);
  1088. PrintLine("Added node " + FromAIString(node->mName));
  1089. CollectBones(model);
  1090. BuildBoneCollisionInfo(model);
  1091. if (!noAnimations_)
  1092. {
  1093. CollectAnimations(&model);
  1094. BuildAndSaveAnimations(&model);
  1095. }
  1096. scene.models_.Push(model);
  1097. scene.nodes_.Push(node);
  1098. scene.nodeModelIndices_.Push(scene.models_.Size() - 1);
  1099. }
  1100. }
  1101. for (unsigned i = 0; i < node->mNumChildren; ++i)
  1102. CollectSceneModels(scene, node->mChildren[i]);
  1103. }
  1104. Node* CreateSceneNode(Scene* scene, aiNode* srcNode, HashMap<aiNode*, Node*>& nodeMapping)
  1105. {
  1106. if (nodeMapping.Contains(srcNode))
  1107. return nodeMapping[srcNode];
  1108. // Flatten hierarchy if requested
  1109. if (noHierarchy_)
  1110. {
  1111. Node* outNode = scene->CreateChild(FromAIString(srcNode->mName), localIDs_ ? LOCAL : REPLICATED);
  1112. Vector3 pos, scale;
  1113. Quaternion rot;
  1114. GetPosRotScale(GetDerivedTransform(srcNode, rootNode_), pos, rot, scale);
  1115. outNode->SetTransform(pos, rot, scale);
  1116. nodeMapping[srcNode] = outNode;
  1117. return outNode;
  1118. }
  1119. if (srcNode == rootNode_ || !srcNode->mParent)
  1120. {
  1121. Node* outNode = scene->CreateChild(FromAIString(srcNode->mName), localIDs_ ? LOCAL : REPLICATED);
  1122. Vector3 pos, scale;
  1123. Quaternion rot;
  1124. GetPosRotScale(srcNode->mTransformation, pos, rot, scale);
  1125. outNode->SetTransform(pos, rot, scale);
  1126. nodeMapping[srcNode] = outNode;
  1127. return outNode;
  1128. }
  1129. else
  1130. {
  1131. // Ensure the existence of the parent chain as in the original file
  1132. if (!nodeMapping.Contains(srcNode->mParent))
  1133. CreateSceneNode(scene, srcNode->mParent, nodeMapping);
  1134. Node* parent = nodeMapping[srcNode->mParent];
  1135. Node* outNode = parent->CreateChild(FromAIString(srcNode->mName), localIDs_ ? LOCAL : REPLICATED);
  1136. Vector3 pos, scale;
  1137. Quaternion rot;
  1138. GetPosRotScale(srcNode->mTransformation, pos, rot, scale);
  1139. outNode->SetTransform(pos, rot, scale);
  1140. nodeMapping[srcNode] = outNode;
  1141. return outNode;
  1142. }
  1143. }
  1144. void BuildAndSaveScene(OutScene& scene, bool asPrefab)
  1145. {
  1146. if (!asPrefab)
  1147. PrintLine("Writing scene");
  1148. else
  1149. PrintLine("Writing node hierarchy");
  1150. SharedPtr<Scene> outScene(new Scene(context_));
  1151. if (!asPrefab)
  1152. {
  1153. #ifdef URHO3D_PHYSICS
  1154. /// \todo Make the physics properties configurable
  1155. outScene->CreateComponent<PhysicsWorld>();
  1156. #endif
  1157. /// \todo Make the octree properties configurable, or detect from the scene contents
  1158. outScene->CreateComponent<Octree>();
  1159. outScene->CreateComponent<DebugRenderer>();
  1160. if (createZone_)
  1161. {
  1162. Node* zoneNode = outScene->CreateChild("Zone", localIDs_ ? LOCAL : REPLICATED);
  1163. Zone* zone = zoneNode->CreateComponent<Zone>();
  1164. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.f));
  1165. zone->SetAmbientColor(Color(0.25f, 0.25f, 0.25f));
  1166. // Create default light only if scene does not define them
  1167. if (!scene_->HasLights())
  1168. {
  1169. Node* lightNode = outScene->CreateChild("GlobalLight", localIDs_ ? LOCAL : REPLICATED);
  1170. Light* light = lightNode->CreateComponent<Light>();
  1171. light->SetLightType(LIGHT_DIRECTIONAL);
  1172. lightNode->SetRotation(Quaternion(60.0f, 30.0f, 0.0f));
  1173. }
  1174. }
  1175. }
  1176. ResourceCache* cache = context_->GetSubsystem<ResourceCache>();
  1177. HashMap<aiNode*, Node*> nodeMapping;
  1178. Node* outRootNode = 0;
  1179. if (asPrefab || !noHierarchy_)
  1180. outRootNode = CreateSceneNode(outScene, rootNode_, nodeMapping);
  1181. // Create geometry nodes
  1182. for (unsigned i = 0; i < scene.nodes_.Size(); ++i)
  1183. {
  1184. const OutModel& model = scene.models_[scene.nodeModelIndices_[i]];
  1185. Node* modelNode = CreateSceneNode(outScene, scene.nodes_[i], nodeMapping);
  1186. StaticModel* staticModel = model.bones_.Empty() ? modelNode->CreateComponent<StaticModel>() : modelNode->CreateComponent<AnimatedModel>();
  1187. // Create a dummy model so that the reference can be stored
  1188. String modelName = (useSubdirs_ ? "Models/" : "") + GetFileNameAndExtension(model.outName_);
  1189. if (!cache->Exists(modelName))
  1190. {
  1191. Model* dummyModel = new Model(context_);
  1192. dummyModel->SetName(modelName);
  1193. dummyModel->SetNumGeometries(model.meshes_.Size());
  1194. cache->AddManualResource(dummyModel);
  1195. }
  1196. staticModel->SetModel(cache->GetResource<Model>(modelName));
  1197. // Set materials if they are known
  1198. for (unsigned j = 0; j < model.meshes_.Size(); ++j)
  1199. {
  1200. String matName = GetMeshMaterialName(model.meshes_[j]);
  1201. // Create a dummy material so that the reference can be stored
  1202. if (!cache->Exists(matName))
  1203. {
  1204. Material* dummyMat = new Material(context_);
  1205. dummyMat->SetName(matName);
  1206. cache->AddManualResource(dummyMat);
  1207. }
  1208. staticModel->SetMaterial(j, cache->GetResource<Material>(matName));
  1209. }
  1210. }
  1211. // Create lights
  1212. if (!asPrefab)
  1213. {
  1214. for (unsigned i = 0; i < scene_->mNumLights; ++i)
  1215. {
  1216. aiLight* light = scene_->mLights[i];
  1217. aiNode* lightNode = GetNode(FromAIString(light->mName), rootNode_, true);
  1218. if (!lightNode)
  1219. continue;
  1220. Node* outNode = CreateSceneNode(outScene, lightNode, nodeMapping);
  1221. Vector3 lightAdjustPosition = ToVector3(light->mPosition);
  1222. Vector3 lightAdjustDirection = ToVector3(light->mDirection);
  1223. // If light is not aligned at the scene node, an adjustment node needs to be created
  1224. if (!lightAdjustPosition.Equals(Vector3::ZERO) || (light->mType != aiLightSource_POINT &&
  1225. !lightAdjustDirection.Equals(Vector3::FORWARD)))
  1226. {
  1227. outNode = outNode->CreateChild("LightAdjust");
  1228. outNode->SetPosition(lightAdjustPosition);
  1229. outNode->SetDirection(lightAdjustDirection);
  1230. }
  1231. Light* outLight = outNode->CreateComponent<Light>();
  1232. outLight->SetColor(Color(light->mColorDiffuse.r, light->mColorDiffuse.g, light->mColorDiffuse.b));
  1233. switch (light->mType)
  1234. {
  1235. case aiLightSource_DIRECTIONAL:
  1236. outLight->SetLightType(LIGHT_DIRECTIONAL);
  1237. break;
  1238. case aiLightSource_SPOT:
  1239. outLight->SetLightType(LIGHT_SPOT);
  1240. outLight->SetFov(light->mAngleOuterCone * M_RADTODEG);
  1241. break;
  1242. case aiLightSource_POINT:
  1243. outLight->SetLightType(LIGHT_POINT);
  1244. break;
  1245. default:
  1246. break;
  1247. }
  1248. // Calculate range from attenuation parameters so that light intensity has been reduced to 10% at that distance
  1249. if (light->mType != aiLightSource_DIRECTIONAL)
  1250. {
  1251. float a = light->mAttenuationQuadratic;
  1252. float b = light->mAttenuationLinear;
  1253. float c = -10.0f;
  1254. if (!Equals(a, 0.0f))
  1255. {
  1256. float root1 = (-b + sqrtf(b * b - 4.0f * a * c)) / (2.0f * a);
  1257. float root2 = (-b - sqrtf(b * b - 4.0f * a * c)) / (2.0f * a);
  1258. outLight->SetRange(Max(root1, root2));
  1259. }
  1260. else if (!Equals(b, 0.0f))
  1261. outLight->SetRange(-c / b);
  1262. }
  1263. }
  1264. }
  1265. File file(context_);
  1266. if (!file.Open(scene.outName_, FILE_WRITE))
  1267. ErrorExit("Could not open output file " + scene.outName_);
  1268. if (!asPrefab)
  1269. {
  1270. if (!saveBinary_)
  1271. outScene->SaveXML(file);
  1272. else
  1273. outScene->Save(file);
  1274. }
  1275. else
  1276. {
  1277. if (!saveBinary_)
  1278. outRootNode->SaveXML(file);
  1279. else
  1280. outRootNode->Save(file);
  1281. }
  1282. }
  1283. void ExportMaterials(HashSet<String>& usedTextures)
  1284. {
  1285. if (useSubdirs_)
  1286. context_->GetSubsystem<FileSystem>()->CreateDir(resourcePath_ + "Materials");
  1287. for (unsigned i = 0; i < scene_->mNumMaterials; ++i)
  1288. BuildAndSaveMaterial(scene_->mMaterials[i], usedTextures);
  1289. }
  1290. void BuildAndSaveMaterial(aiMaterial* material, HashSet<String>& usedTextures)
  1291. {
  1292. aiString matNameStr;
  1293. material->Get(AI_MATKEY_NAME, matNameStr);
  1294. String matName = SanitateAssetName(FromAIString(matNameStr));
  1295. if (matName.Trimmed().Empty())
  1296. matName = GenerateMaterialName(material);
  1297. // Do not actually create a material instance, but instead craft an xml file manually
  1298. XMLFile outMaterial(context_);
  1299. XMLElement materialElem = outMaterial.CreateRoot("material");
  1300. String diffuseTexName;
  1301. String normalTexName;
  1302. String specularTexName;
  1303. String lightmapTexName;
  1304. String emissiveTexName;
  1305. Color diffuseColor = Color::WHITE;
  1306. Color specularColor;
  1307. Color emissiveColor = Color::BLACK;
  1308. bool hasAlpha = false;
  1309. bool twoSided = false;
  1310. float specPower = 1.0f;
  1311. aiString stringVal;
  1312. float floatVal;
  1313. int intVal;
  1314. aiColor3D colorVal;
  1315. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_DIFFUSE, 0), stringVal) == AI_SUCCESS)
  1316. diffuseTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1317. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_NORMALS, 0), stringVal) == AI_SUCCESS)
  1318. normalTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1319. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_SPECULAR, 0), stringVal) == AI_SUCCESS)
  1320. specularTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1321. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_LIGHTMAP, 0), stringVal) == AI_SUCCESS)
  1322. specularTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1323. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_EMISSIVE, 0), stringVal) == AI_SUCCESS)
  1324. emissiveTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1325. if (!noMaterialDiffuseColor_)
  1326. {
  1327. if (material->Get(AI_MATKEY_COLOR_DIFFUSE, colorVal) == AI_SUCCESS)
  1328. diffuseColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1329. }
  1330. if (material->Get(AI_MATKEY_COLOR_SPECULAR, colorVal) == AI_SUCCESS)
  1331. specularColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1332. if (!emissiveAO_)
  1333. {
  1334. if (material->Get(AI_MATKEY_COLOR_EMISSIVE, colorVal) == AI_SUCCESS)
  1335. emissiveColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1336. }
  1337. if (material->Get(AI_MATKEY_OPACITY, floatVal) == AI_SUCCESS)
  1338. {
  1339. if (floatVal < 1.0f)
  1340. hasAlpha = true;
  1341. diffuseColor.a_ = floatVal;
  1342. }
  1343. if (material->Get(AI_MATKEY_SHININESS, floatVal) == AI_SUCCESS)
  1344. specPower = floatVal;
  1345. if (material->Get(AI_MATKEY_TWOSIDED, intVal) == AI_SUCCESS)
  1346. twoSided = (intVal != 0);
  1347. String techniqueName = "Techniques/NoTexture";
  1348. if (!diffuseTexName.Empty())
  1349. {
  1350. techniqueName = "Techniques/Diff";
  1351. if (!normalTexName.Empty())
  1352. techniqueName += "Normal";
  1353. if (!specularTexName.Empty())
  1354. techniqueName += "Spec";
  1355. // For now lightmap does not coexist with normal & specular
  1356. if (normalTexName.Empty() && specularTexName.Empty() && !lightmapTexName.Empty())
  1357. techniqueName += "LightMap";
  1358. if (lightmapTexName.Empty() && !emissiveTexName.Empty())
  1359. techniqueName += emissiveAO_ ? "AO" : "Emissive";
  1360. }
  1361. if (hasAlpha)
  1362. techniqueName += "Alpha";
  1363. XMLElement techniqueElem = materialElem.CreateChild("technique");
  1364. techniqueElem.SetString("name", techniqueName + ".xml");
  1365. if (!diffuseTexName.Empty())
  1366. {
  1367. XMLElement diffuseElem = materialElem.CreateChild("texture");
  1368. diffuseElem.SetString("unit", "diffuse");
  1369. diffuseElem.SetString("name", GetMaterialTextureName(diffuseTexName));
  1370. usedTextures.Insert(diffuseTexName);
  1371. }
  1372. if (!normalTexName.Empty())
  1373. {
  1374. XMLElement normalElem = materialElem.CreateChild("texture");
  1375. normalElem.SetString("unit", "normal");
  1376. normalElem.SetString("name", GetMaterialTextureName(normalTexName));
  1377. usedTextures.Insert(normalTexName);
  1378. }
  1379. if (!specularTexName.Empty())
  1380. {
  1381. XMLElement specularElem = materialElem.CreateChild("texture");
  1382. specularElem.SetString("unit", "specular");
  1383. specularElem.SetString("name", GetMaterialTextureName(specularTexName));
  1384. usedTextures.Insert(specularTexName);
  1385. }
  1386. if (!lightmapTexName.Empty())
  1387. {
  1388. XMLElement lightmapElem = materialElem.CreateChild("texture");
  1389. lightmapElem.SetString("unit", "emissive");
  1390. lightmapElem.SetString("name", GetMaterialTextureName(lightmapTexName));
  1391. usedTextures.Insert(lightmapTexName);
  1392. }
  1393. if (!emissiveTexName.Empty())
  1394. {
  1395. XMLElement emissiveElem = materialElem.CreateChild("texture");
  1396. emissiveElem.SetString("unit", "emissive");
  1397. emissiveElem.SetString("name", GetMaterialTextureName(emissiveTexName));
  1398. usedTextures.Insert(emissiveTexName);
  1399. }
  1400. XMLElement diffuseColorElem = materialElem.CreateChild("parameter");
  1401. diffuseColorElem.SetString("name", "MatDiffColor");
  1402. diffuseColorElem.SetColor("value", diffuseColor);
  1403. XMLElement specularElem = materialElem.CreateChild("parameter");
  1404. specularElem.SetString("name", "MatSpecColor");
  1405. specularElem.SetVector4("value", Vector4(specularColor.r_, specularColor.g_, specularColor.b_, specPower));
  1406. XMLElement emissiveColorElem = materialElem.CreateChild("parameter");
  1407. emissiveColorElem.SetString("name", "MatEmissiveColor");
  1408. emissiveColorElem.SetColor("value", emissiveColor);
  1409. if (twoSided)
  1410. {
  1411. XMLElement cullElem = materialElem.CreateChild("cull");
  1412. XMLElement shadowCullElem = materialElem.CreateChild("shadowcull");
  1413. cullElem.SetString("value", "none");
  1414. shadowCullElem.SetString("value", "none");
  1415. }
  1416. FileSystem* fileSystem = context_->GetSubsystem<FileSystem>();
  1417. String outFileName = resourcePath_ + (useSubdirs_ ? "Materials/" : "" ) + matName + ".xml";
  1418. if (noOverwriteMaterial_ && fileSystem->FileExists(outFileName))
  1419. {
  1420. PrintLine("Skipping save of existing material " + matName);
  1421. return;
  1422. }
  1423. PrintLine("Writing material " + matName);
  1424. File outFile(context_);
  1425. if (!outFile.Open(outFileName, FILE_WRITE))
  1426. ErrorExit("Could not open output file " + outFileName);
  1427. outMaterial.Save(outFile);
  1428. }
  1429. void CopyTextures(const HashSet<String>& usedTextures, const String& sourcePath)
  1430. {
  1431. FileSystem* fileSystem = context_->GetSubsystem<FileSystem>();
  1432. if (useSubdirs_)
  1433. fileSystem->CreateDir(resourcePath_ + "Textures");
  1434. for (HashSet<String>::ConstIterator i = usedTextures.Begin(); i != usedTextures.End(); ++i)
  1435. {
  1436. // Handle assimp embedded textures
  1437. if (i->Length() && i->At(0) == '*')
  1438. {
  1439. unsigned texIndex = ToInt(i->Substring(1));
  1440. if (texIndex >= scene_->mNumTextures)
  1441. PrintLine("Skipping out of range texture index " + String(texIndex));
  1442. else
  1443. {
  1444. aiTexture* tex = scene_->mTextures[texIndex];
  1445. String fullDestName = resourcePath_ + GenerateTextureName(texIndex);
  1446. bool destExists = fileSystem->FileExists(fullDestName);
  1447. if (destExists && noOverwriteTexture_)
  1448. {
  1449. PrintLine("Skipping copy of existing embedded texture " + GetFileNameAndExtension(fullDestName));
  1450. continue;
  1451. }
  1452. // Encoded texture
  1453. if (!tex->mHeight)
  1454. {
  1455. PrintLine("Saving embedded texture " + GetFileNameAndExtension(fullDestName));
  1456. File dest(context_, fullDestName, FILE_WRITE);
  1457. dest.Write((const void*)tex->pcData, tex->mWidth);
  1458. }
  1459. // RGBA8 texture
  1460. else
  1461. {
  1462. PrintLine("Saving embedded RGBA texture " + GetFileNameAndExtension(fullDestName));
  1463. Image image(context_);
  1464. image.SetSize(tex->mWidth, tex->mHeight, 4);
  1465. memcpy(image.GetData(), (const void*)tex->pcData, tex->mWidth * tex->mHeight * 4);
  1466. image.SavePNG(fullDestName);
  1467. }
  1468. }
  1469. }
  1470. else
  1471. {
  1472. String fullSourceName = sourcePath + *i;
  1473. String fullDestName = resourcePath_ + (useSubdirs_ ? "Textures/" : "") + *i;
  1474. if (!fileSystem->FileExists(fullSourceName))
  1475. {
  1476. PrintLine("Skipping copy of nonexisting material texture " + *i);
  1477. continue;
  1478. }
  1479. {
  1480. File test(context_, fullSourceName);
  1481. if (!test.GetSize())
  1482. {
  1483. PrintLine("Skipping copy of zero-size material texture " + *i);
  1484. continue;
  1485. }
  1486. }
  1487. bool destExists = fileSystem->FileExists(fullDestName);
  1488. if (destExists && noOverwriteTexture_)
  1489. {
  1490. PrintLine("Skipping copy of existing texture " + *i);
  1491. continue;
  1492. }
  1493. if (destExists && noOverwriteNewerTexture_ && fileSystem->GetLastModifiedTime(fullDestName) >
  1494. fileSystem->GetLastModifiedTime(fullSourceName))
  1495. {
  1496. PrintLine("Skipping copying of material texture " + *i + ", destination is newer");
  1497. continue;
  1498. }
  1499. PrintLine("Copying material texture " + *i);
  1500. fileSystem->Copy(fullSourceName, fullDestName);
  1501. }
  1502. }
  1503. }
  1504. void CombineLods(const PODVector<float>& lodDistances, const Vector<String>& modelNames, const String& outName)
  1505. {
  1506. // Load models
  1507. Vector<SharedPtr<Model> > srcModels;
  1508. for (unsigned i = 0; i < modelNames.Size(); ++i)
  1509. {
  1510. PrintLine("Reading LOD level " + String(i) + ": model " + modelNames[i] + " distance " + String(lodDistances[i]));
  1511. File srcFile(context_);
  1512. srcFile.Open(modelNames[i]);
  1513. SharedPtr<Model> srcModel(new Model(context_));
  1514. if (!srcModel->Load(srcFile))
  1515. ErrorExit("Could not load input model " + modelNames[i]);
  1516. srcModels.Push(srcModel);
  1517. }
  1518. // Check that none of the models already has LOD levels
  1519. for (unsigned i = 0; i < srcModels.Size(); ++i)
  1520. {
  1521. for (unsigned j = 0; j < srcModels[i]->GetNumGeometries(); ++j)
  1522. {
  1523. if (srcModels[i]->GetNumGeometryLodLevels(j) > 1)
  1524. ErrorExit(modelNames[i] + " already has multiple LOD levels defined");
  1525. }
  1526. }
  1527. // Check for number of geometries (need to have same amount for now)
  1528. for (unsigned i = 1; i < srcModels.Size(); ++i)
  1529. {
  1530. if (srcModels[i]->GetNumGeometries() != srcModels[0]->GetNumGeometries())
  1531. ErrorExit(modelNames[i] + " has different amount of geometries than " + modelNames[0]);
  1532. }
  1533. // If there are bones, check for compatibility (need to have exact match for now)
  1534. for (unsigned i = 1; i < srcModels.Size(); ++i)
  1535. {
  1536. if (srcModels[i]->GetSkeleton().GetNumBones() != srcModels[0]->GetSkeleton().GetNumBones())
  1537. ErrorExit(modelNames[i] + " has different amount of bones than " + modelNames[0]);
  1538. for (unsigned j = 0; j < srcModels[0]->GetSkeleton().GetNumBones(); ++j)
  1539. {
  1540. if (srcModels[i]->GetSkeleton().GetBone(j)->name_ != srcModels[0]->GetSkeleton().GetBone(j)->name_)
  1541. ErrorExit(modelNames[i] + " has different bones than " + modelNames[0]);
  1542. }
  1543. if (srcModels[i]->GetGeometryBoneMappings() != srcModels[0]->GetGeometryBoneMappings())
  1544. ErrorExit(modelNames[i] + " has different per-geometry bone mappings than " + modelNames[0]);
  1545. }
  1546. Vector<SharedPtr<VertexBuffer> > vbVector;
  1547. Vector<SharedPtr<IndexBuffer> > ibVector;
  1548. PODVector<unsigned> emptyMorphRange;
  1549. // Create the final model
  1550. SharedPtr<Model> outModel(new Model(context_));
  1551. outModel->SetNumGeometries(srcModels[0]->GetNumGeometries());
  1552. for (unsigned i = 0; i < srcModels[0]->GetNumGeometries(); ++i)
  1553. {
  1554. outModel->SetNumGeometryLodLevels(i, srcModels.Size());
  1555. for (unsigned j = 0; j < srcModels.Size(); ++j)
  1556. {
  1557. Geometry* geometry = srcModels[j]->GetGeometry(i, 0);
  1558. geometry->SetLodDistance(lodDistances[j]);
  1559. outModel->SetGeometry(i, j, geometry);
  1560. for (unsigned k = 0; k < geometry->GetNumVertexBuffers(); ++k)
  1561. {
  1562. SharedPtr<VertexBuffer> vb(geometry->GetVertexBuffer(k));
  1563. if (!vbVector.Contains(vb))
  1564. vbVector.Push(vb);
  1565. }
  1566. SharedPtr<IndexBuffer> ib(geometry->GetIndexBuffer());
  1567. if (!ibVector.Contains(ib))
  1568. ibVector.Push(ib);
  1569. }
  1570. }
  1571. outModel->SetVertexBuffers(vbVector, emptyMorphRange, emptyMorphRange);
  1572. outModel->SetIndexBuffers(ibVector);
  1573. outModel->SetSkeleton(srcModels[0]->GetSkeleton());
  1574. outModel->SetGeometryBoneMappings(srcModels[0]->GetGeometryBoneMappings());
  1575. outModel->SetBoundingBox(srcModels[0]->GetBoundingBox());
  1576. /// \todo Vertex morphs are ignored for now
  1577. // Save the final model
  1578. PrintLine("Writing output model");
  1579. File outFile(context_);
  1580. if (!outFile.Open(outName, FILE_WRITE))
  1581. ErrorExit("Could not open output file " + outName);
  1582. outModel->Save(outFile);
  1583. }
  1584. void GetMeshesUnderNode(Vector<Pair<aiNode*, aiMesh*> >& dest, aiNode* node)
  1585. {
  1586. for (unsigned i = 0; i < node->mNumMeshes; ++i)
  1587. dest.Push(MakePair(node, scene_->mMeshes[node->mMeshes[i]]));
  1588. }
  1589. unsigned GetMeshIndex(aiMesh* mesh)
  1590. {
  1591. for (unsigned i = 0; i < scene_->mNumMeshes; ++i)
  1592. {
  1593. if (scene_->mMeshes[i] == mesh)
  1594. return i;
  1595. }
  1596. return M_MAX_UNSIGNED;
  1597. }
  1598. unsigned GetBoneIndex(OutModel& model, const String& boneName)
  1599. {
  1600. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  1601. {
  1602. if (boneName == model.bones_[i]->mName.data)
  1603. return i;
  1604. }
  1605. return M_MAX_UNSIGNED;
  1606. }
  1607. aiBone* GetMeshBone(OutModel& model, const String& boneName)
  1608. {
  1609. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  1610. {
  1611. aiMesh* mesh = model.meshes_[i];
  1612. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  1613. {
  1614. aiBone* bone = mesh->mBones[j];
  1615. if (boneName == bone->mName.data)
  1616. return bone;
  1617. }
  1618. }
  1619. return 0;
  1620. }
  1621. Matrix3x4 GetOffsetMatrix(OutModel& model, const String& boneName)
  1622. {
  1623. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  1624. {
  1625. aiMesh* mesh = model.meshes_[i];
  1626. aiNode* node = model.meshNodes_[i];
  1627. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  1628. {
  1629. aiBone* bone = mesh->mBones[j];
  1630. if (boneName == bone->mName.data)
  1631. {
  1632. aiMatrix4x4 offset = bone->mOffsetMatrix;
  1633. aiMatrix4x4 nodeDerivedInverse = GetMeshBakingTransform(node, model.rootNode_);
  1634. nodeDerivedInverse.Inverse();
  1635. offset *= nodeDerivedInverse;
  1636. return ToMatrix3x4(offset);
  1637. }
  1638. }
  1639. }
  1640. return Matrix3x4::IDENTITY;
  1641. }
  1642. void GetBlendData(OutModel& model, aiMesh* mesh, PODVector<unsigned>& boneMappings, Vector<PODVector<unsigned char> >&
  1643. blendIndices, Vector<PODVector<float> >& blendWeights)
  1644. {
  1645. blendIndices.Resize(mesh->mNumVertices);
  1646. blendWeights.Resize(mesh->mNumVertices);
  1647. boneMappings.Clear();
  1648. // If model has more bones than can fit vertex shader parameters, write the per-geometry mappings
  1649. if (model.bones_.Size() > MAX_SKIN_MATRICES)
  1650. {
  1651. if (mesh->mNumBones > MAX_SKIN_MATRICES)
  1652. ErrorExit("Geometry has too many bone influences");
  1653. boneMappings.Resize(mesh->mNumBones);
  1654. for (unsigned i = 0; i < mesh->mNumBones; ++i)
  1655. {
  1656. aiBone* bone = mesh->mBones[i];
  1657. String boneName = FromAIString(bone->mName);
  1658. unsigned globalIndex = GetBoneIndex(model, boneName);
  1659. if (globalIndex == M_MAX_UNSIGNED)
  1660. ErrorExit("Bone " + boneName + " not found");
  1661. boneMappings[i] = globalIndex;
  1662. for (unsigned j = 0; j < bone->mNumWeights; ++j)
  1663. {
  1664. unsigned vertex = bone->mWeights[j].mVertexId;
  1665. blendIndices[vertex].Push(i);
  1666. blendWeights[vertex].Push(bone->mWeights[j].mWeight);
  1667. if (blendWeights[vertex].Size() > 4)
  1668. ErrorExit("More than 4 bone influences on vertex");
  1669. }
  1670. }
  1671. }
  1672. else
  1673. {
  1674. for (unsigned i = 0; i < mesh->mNumBones; ++i)
  1675. {
  1676. aiBone* bone = mesh->mBones[i];
  1677. String boneName = FromAIString(bone->mName);
  1678. unsigned globalIndex = GetBoneIndex(model, boneName);
  1679. if (globalIndex == M_MAX_UNSIGNED)
  1680. ErrorExit("Bone " + boneName + " not found");
  1681. for (unsigned j = 0; j < bone->mNumWeights; ++j)
  1682. {
  1683. unsigned vertex = bone->mWeights[j].mVertexId;
  1684. blendIndices[vertex].Push(globalIndex);
  1685. blendWeights[vertex].Push(bone->mWeights[j].mWeight);
  1686. if (blendWeights[vertex].Size() > 4)
  1687. ErrorExit("More than 4 bone influences on vertex");
  1688. }
  1689. }
  1690. }
  1691. }
  1692. String GetMeshMaterialName(aiMesh* mesh)
  1693. {
  1694. aiMaterial* material = scene_->mMaterials[mesh->mMaterialIndex];
  1695. aiString matNameStr;
  1696. material->Get(AI_MATKEY_NAME, matNameStr);
  1697. String matName = SanitateAssetName(FromAIString(matNameStr));
  1698. if (matName.Trimmed().Empty())
  1699. matName = GenerateMaterialName(material);
  1700. return (useSubdirs_ ? "Materials/" : "") + matName + ".xml";
  1701. }
  1702. String GenerateMaterialName(aiMaterial* material)
  1703. {
  1704. for (unsigned i = 0; i < scene_->mNumMaterials; ++i)
  1705. {
  1706. if (scene_->mMaterials[i] == material)
  1707. return inputName_ + "_Material" + String(i);
  1708. }
  1709. // Should not go here
  1710. return String::EMPTY;
  1711. }
  1712. String GetMaterialTextureName(const String& nameIn)
  1713. {
  1714. // Detect assimp embedded texture
  1715. if (nameIn.Length() && nameIn[0] == '*')
  1716. return GenerateTextureName(ToInt(nameIn.Substring(1)));
  1717. else
  1718. return (useSubdirs_ ? "Textures/" : "") + nameIn;
  1719. }
  1720. String GenerateTextureName(unsigned texIndex)
  1721. {
  1722. if (texIndex < scene_->mNumTextures)
  1723. {
  1724. // If embedded texture contains encoded data, use the format hint for file extension. Else save RGBA8 data as PNG
  1725. aiTexture* tex = scene_->mTextures[texIndex];
  1726. if (!tex->mHeight)
  1727. return (useSubdirs_ ? "Textures/" : "") + inputName_ + "_Texture" + String(texIndex) + "." + tex->achFormatHint;
  1728. else
  1729. return (useSubdirs_ ? "Textures/" : "") + inputName_ + "_Texture" + String(texIndex) + ".png";
  1730. }
  1731. // Should not go here
  1732. return String::EMPTY;
  1733. }
  1734. unsigned GetNumValidFaces(aiMesh* mesh)
  1735. {
  1736. unsigned ret = 0;
  1737. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  1738. {
  1739. if (mesh->mFaces[j].mNumIndices == 3)
  1740. ++ret;
  1741. }
  1742. return ret;
  1743. }
  1744. void WriteShortIndices(unsigned short*& dest, aiMesh* mesh, unsigned index, unsigned offset)
  1745. {
  1746. if (mesh->mFaces[index].mNumIndices == 3)
  1747. {
  1748. *dest++ = mesh->mFaces[index].mIndices[0] + offset;
  1749. *dest++ = mesh->mFaces[index].mIndices[1] + offset;
  1750. *dest++ = mesh->mFaces[index].mIndices[2] + offset;
  1751. }
  1752. }
  1753. void WriteLargeIndices(unsigned*& dest, aiMesh* mesh, unsigned index, unsigned offset)
  1754. {
  1755. if (mesh->mFaces[index].mNumIndices == 3)
  1756. {
  1757. *dest++ = mesh->mFaces[index].mIndices[0] + offset;
  1758. *dest++ = mesh->mFaces[index].mIndices[1] + offset;
  1759. *dest++ = mesh->mFaces[index].mIndices[2] + offset;
  1760. }
  1761. }
  1762. void WriteVertex(float*& dest, aiMesh* mesh, unsigned index, unsigned elementMask, BoundingBox& box,
  1763. const Matrix3x4& vertexTransform, const Matrix3& normalTransform, Vector<PODVector<unsigned char> >& blendIndices,
  1764. Vector<PODVector<float> >& blendWeights)
  1765. {
  1766. Vector3 vertex = vertexTransform * ToVector3(mesh->mVertices[index]);
  1767. box.Merge(vertex);
  1768. *dest++ = vertex.x_;
  1769. *dest++ = vertex.y_;
  1770. *dest++ = vertex.z_;
  1771. if (elementMask & MASK_NORMAL)
  1772. {
  1773. Vector3 normal = normalTransform * ToVector3(mesh->mNormals[index]);
  1774. *dest++ = normal.x_;
  1775. *dest++ = normal.y_;
  1776. *dest++ = normal.z_;
  1777. }
  1778. if (elementMask & MASK_COLOR)
  1779. {
  1780. *((unsigned*)dest) = Color(mesh->mColors[0][index].r, mesh->mColors[0][index].g, mesh->mColors[0][index].b,
  1781. mesh->mColors[0][index].a).ToUInt();
  1782. ++dest;
  1783. }
  1784. if (elementMask & MASK_TEXCOORD1)
  1785. {
  1786. Vector3 texCoord = ToVector3(mesh->mTextureCoords[0][index]);
  1787. *dest++ = texCoord.x_;
  1788. *dest++ = texCoord.y_;
  1789. }
  1790. if (elementMask & MASK_TEXCOORD2)
  1791. {
  1792. Vector3 texCoord = ToVector3(mesh->mTextureCoords[1][index]);
  1793. *dest++ = texCoord.x_;
  1794. *dest++ = texCoord.y_;
  1795. }
  1796. if (elementMask & MASK_TANGENT)
  1797. {
  1798. Vector3 tangent = normalTransform * ToVector3(mesh->mTangents[index]);
  1799. Vector3 normal = normalTransform * ToVector3(mesh->mNormals[index]);
  1800. Vector3 bitangent = normalTransform * ToVector3(mesh->mBitangents[index]);
  1801. // Check handedness
  1802. float w = 1.0f;
  1803. if ((tangent.CrossProduct(normal)).DotProduct(bitangent) < 0.5f)
  1804. w = -1.0f;
  1805. *dest++ = tangent.x_;
  1806. *dest++ = tangent.y_;
  1807. *dest++ = tangent.z_;
  1808. *dest++ = w;
  1809. }
  1810. if (elementMask & MASK_BLENDWEIGHTS)
  1811. {
  1812. for (unsigned i = 0; i < 4; ++i)
  1813. {
  1814. if (i < blendWeights[index].Size())
  1815. *dest++ = blendWeights[index][i];
  1816. else
  1817. *dest++ = 0.0f;
  1818. }
  1819. }
  1820. if (elementMask & MASK_BLENDINDICES)
  1821. {
  1822. unsigned char* destBytes = (unsigned char*)dest;
  1823. ++dest;
  1824. for (unsigned i = 0; i < 4; ++i)
  1825. {
  1826. if (i < blendIndices[index].Size())
  1827. *destBytes++ = blendIndices[index][i];
  1828. else
  1829. *destBytes++ = 0;
  1830. }
  1831. }
  1832. }
  1833. unsigned GetElementMask(aiMesh* mesh)
  1834. {
  1835. unsigned elementMask = MASK_POSITION;
  1836. if (mesh->HasNormals())
  1837. elementMask |= MASK_NORMAL;
  1838. if (mesh->HasTangentsAndBitangents())
  1839. elementMask |= MASK_TANGENT;
  1840. if (mesh->GetNumColorChannels() > 0)
  1841. elementMask |= MASK_COLOR;
  1842. if (mesh->GetNumUVChannels() > 0)
  1843. elementMask |= MASK_TEXCOORD1;
  1844. if (mesh->GetNumUVChannels() > 1)
  1845. elementMask |= MASK_TEXCOORD2;
  1846. if (mesh->HasBones())
  1847. elementMask |= (MASK_BLENDWEIGHTS | MASK_BLENDINDICES);
  1848. return elementMask;
  1849. }
  1850. aiNode* GetNode(const String& name, aiNode* rootNode, bool caseSensitive)
  1851. {
  1852. if (!rootNode)
  1853. return 0;
  1854. if (!name.Compare(rootNode->mName.data, caseSensitive))
  1855. return rootNode;
  1856. for (unsigned i = 0; i < rootNode->mNumChildren; ++i)
  1857. {
  1858. aiNode* found = GetNode(name, rootNode->mChildren[i], caseSensitive);
  1859. if (found)
  1860. return found;
  1861. }
  1862. return 0;
  1863. }
  1864. aiMatrix4x4 GetDerivedTransform(aiNode* node, aiNode* rootNode, bool rootInclusive)
  1865. {
  1866. return GetDerivedTransform(node->mTransformation, node, rootNode, rootInclusive);
  1867. }
  1868. aiMatrix4x4 GetDerivedTransform(aiMatrix4x4 transform, aiNode* node, aiNode* rootNode, bool rootInclusive)
  1869. {
  1870. // If basenode is defined, go only up to it in the parent chain
  1871. while (node && node != rootNode)
  1872. {
  1873. node = node->mParent;
  1874. if (!rootInclusive && node == rootNode)
  1875. break;
  1876. if (node)
  1877. transform = node->mTransformation * transform;
  1878. }
  1879. return transform;
  1880. }
  1881. aiMatrix4x4 GetMeshBakingTransform(aiNode* meshNode, aiNode* modelRootNode)
  1882. {
  1883. if (meshNode == modelRootNode)
  1884. return aiMatrix4x4();
  1885. else
  1886. return GetDerivedTransform(meshNode, modelRootNode);
  1887. }
  1888. void GetPosRotScale(const aiMatrix4x4& transform, Vector3& pos, Quaternion& rot, Vector3& scale)
  1889. {
  1890. aiVector3D aiPos;
  1891. aiQuaternion aiRot;
  1892. aiVector3D aiScale;
  1893. transform.Decompose(aiScale, aiRot, aiPos);
  1894. pos = ToVector3(aiPos);
  1895. rot = ToQuaternion(aiRot);
  1896. scale = ToVector3(aiScale);
  1897. }
  1898. String FromAIString(const aiString& str)
  1899. {
  1900. return String(str.data);
  1901. }
  1902. Vector3 ToVector3(const aiVector3D& vec)
  1903. {
  1904. return Vector3(vec.x, vec.y, vec.z);
  1905. }
  1906. Vector2 ToVector2(const aiVector2D& vec)
  1907. {
  1908. return Vector2(vec.x, vec.y);
  1909. }
  1910. Quaternion ToQuaternion(const aiQuaternion& quat)
  1911. {
  1912. return Quaternion(quat.w, quat.x, quat.y, quat.z);
  1913. }
  1914. Matrix3x4 ToMatrix3x4(const aiMatrix4x4& mat)
  1915. {
  1916. Matrix3x4 ret;
  1917. memcpy(&ret.m00_, &mat.a1, sizeof(Matrix3x4));
  1918. return ret;
  1919. }
  1920. String SanitateAssetName(const String& name)
  1921. {
  1922. String fixedName = name;
  1923. fixedName.Replace("<", "");
  1924. fixedName.Replace(">", "");
  1925. fixedName.Replace("?", "");
  1926. fixedName.Replace("*", "");
  1927. fixedName.Replace(":", "");
  1928. fixedName.Replace("\"", "");
  1929. fixedName.Replace("/", "");
  1930. fixedName.Replace("\\", "");
  1931. fixedName.Replace("|", "");
  1932. return fixedName;
  1933. }