AssetImporter.cpp 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  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. #include "PhysicsWorld.h"
  36. #include "ProcessUtils.h"
  37. #include "Quaternion.h"
  38. #include "ResourceCache.h"
  39. #include "Scene.h"
  40. #include "StaticModel.h"
  41. #include "StringUtils.h"
  42. #include "Vector3.h"
  43. #include "VertexBuffer.h"
  44. #include "WorkQueue.h"
  45. #include "XMLFile.h"
  46. #include "Zone.h"
  47. #include "Sort.h"
  48. #include "Set.h"
  49. #ifdef WIN32
  50. #include <windows.h>
  51. #endif
  52. #include <assimp.hpp>
  53. #include <aiScene.h>
  54. #include <aiPostProcess.h>
  55. #include <cstring>
  56. #include "DebugNew.h"
  57. struct OutModel
  58. {
  59. OutModel() :
  60. totalVertices_(0),
  61. totalIndices_(0),
  62. rootBone_(0)
  63. {
  64. }
  65. String outName_;
  66. aiNode* rootNode_;
  67. Set<unsigned> meshIndices_;
  68. PODVector<aiMesh*> meshes_;
  69. PODVector<aiNode*> meshNodes_;
  70. PODVector<aiNode*> bones_;
  71. PODVector<aiAnimation*> animations_;
  72. PODVector<float> boneRadii_;
  73. PODVector<BoundingBox> boneHitboxes_;
  74. aiNode* rootBone_;
  75. unsigned totalVertices_;
  76. unsigned totalIndices_;
  77. };
  78. struct OutScene
  79. {
  80. String outName_;
  81. aiNode* rootNode_;
  82. Vector<OutModel> models_;
  83. PODVector<aiNode*> nodes_;
  84. PODVector<unsigned> nodeModelIndices_;
  85. };
  86. SharedPtr<Context> context_(new Context());
  87. const aiScene* scene_ = 0;
  88. aiNode* rootNode_ = 0;
  89. String materialListName_;
  90. String resourcePath_;
  91. bool useSubdirs_ = true;
  92. bool localIDs_ = false;
  93. bool saveBinary_ = false;
  94. bool createZone_ = true;
  95. bool noAnimations_ = false;
  96. float defaultTicksPerSecond_ = 4800.0f;
  97. int main(int argc, char** argv);
  98. void Run(const Vector<String>& arguments);
  99. void DumpNodes(aiNode* rootNode, unsigned level);
  100. void ExportModel(const String& outName);
  101. void CollectMeshes(OutModel& model, aiNode* node);
  102. void CollectBones(OutModel& model);
  103. void CollectBonesFinal(PODVector<aiNode*>& dest, const Set<aiNode*>& necessary, aiNode* node);
  104. void CollectAnimations(OutModel& model);
  105. void BuildBoneCollisionInfo(OutModel& model);
  106. void BuildAndSaveModel(OutModel& model);
  107. void BuildAndSaveAnimations(OutModel& model);
  108. void ExportScene(const String& outName);
  109. void CollectSceneModels(OutScene& scene, aiNode* node);
  110. void BuildAndSaveScene(OutScene& scene);
  111. void ExportMaterials(Set<String>& usedTextures);
  112. void BuildAndSaveMaterial(aiMaterial* material, Set<String>& usedTextures);
  113. void CopyTextures(const Set<String>& usedTextures, const String& sourcePath);
  114. void CombineLods(const PODVector<float>& lodDistances, const Vector<String>& modelNames, const String& outName);
  115. void GetMeshesUnderNode(Vector<Pair<aiNode*, aiMesh*> >& meshes, aiNode* node);
  116. unsigned GetMeshIndex(aiMesh* mesh);
  117. unsigned GetBoneIndex(OutModel& model, const String& boneName);
  118. aiBone* GetMeshBone(OutModel& model, const String& boneName);
  119. Matrix3x4 GetOffsetMatrix(OutModel& model, const String& boneName);
  120. void GetBlendData(OutModel& model, aiMesh* mesh, PODVector<unsigned>& boneMappings, Vector<PODVector<unsigned char> >&
  121. blendIndices, Vector<PODVector<float> >& blendWeights);
  122. String GetMeshMaterialName(aiMesh* mesh);
  123. void WriteShortIndices(unsigned short*& dest, aiMesh* mesh, unsigned index, unsigned offset);
  124. void WriteLargeIndices(unsigned*& dest, aiMesh* mesh, unsigned index, unsigned offset);
  125. void WriteVertex(float*& dest, aiMesh* mesh, unsigned index, unsigned elementMask, BoundingBox& box,
  126. const Matrix3x4& vertexTransform, const Matrix3& normalTransform, Vector<PODVector<unsigned char> >& blendIndices,
  127. Vector<PODVector<float> >& blendWeights);
  128. unsigned GetElementMask(aiMesh* mesh);
  129. aiNode* GetNode(const String& name, aiNode* rootNode, bool caseSensitive = true);
  130. aiMatrix4x4 GetDerivedTransform(aiNode* node, aiNode* rootNode);
  131. aiMatrix4x4 GetDerivedTransform(aiMatrix4x4 transform, aiNode* node, aiNode* rootNode);
  132. aiMatrix4x4 GetMeshBakingTransform(aiNode* meshNode, aiNode* modelRootNode);
  133. void GetPosRotScale(const aiMatrix4x4& transform, Vector3& pos, Quaternion& rot, Vector3& scale);
  134. String FromAIString(const aiString& str);
  135. Vector3 ToVector3(const aiVector3D& vec);
  136. Vector2 ToVector2(const aiVector2D& vec);
  137. Quaternion ToQuaternion(const aiQuaternion& quat);
  138. String SanitateAssetName(const String& name);
  139. int main(int argc, char** argv)
  140. {
  141. Vector<String> arguments;
  142. #ifdef WIN32
  143. arguments = ParseArguments(GetCommandLineW());
  144. #else
  145. arguments = ParseArguments(argc, argv);
  146. #endif
  147. Run(arguments);
  148. return 0;
  149. }
  150. void Run(const Vector<String>& arguments)
  151. {
  152. if (arguments.Size() < 2)
  153. {
  154. ErrorExit(
  155. "Usage: AssetImporter <command> <input file> <output file> [options]\n"
  156. "See http://assimp.sourceforge.net/main_features_formats.html for input formats\n\n"
  157. "Commands:\n"
  158. "model Output a model\n"
  159. "scene Output a scene\n"
  160. "dump Dump scene node structure. No output file is generated\n"
  161. "lod Combine several Urho3D models as LOD levels of the output model\n"
  162. " Syntax: lod <dist0> <mdl0> <dist1 <mdl1> ... <output file>\n"
  163. "\n"
  164. "Options:\n"
  165. "-b Save scene in binary format, default format is XML\n"
  166. "-i Use local ID's for scene nodes\n"
  167. "-mX Output a material list file X (model mode only)\n"
  168. "-na Do not output animations\n"
  169. "-nm Do not output materials\n"
  170. "-ns Do not create subdirectories for resources\n"
  171. "-nz Do not create a zone and a directional light (scene mode only)\n"
  172. "-pX Set path X for scene resources. Default is output file path\n"
  173. "-rX Use scene node X as root node\n"
  174. "-fX Animation tick frequency to use if unspecified. Default 4800\n"
  175. "-t Generate tangents to model(s)\n"
  176. );
  177. }
  178. RegisterSceneLibrary(context_);
  179. RegisterGraphicsLibrary(context_);
  180. RegisterPhysicsLibrary(context_);
  181. context_->RegisterSubsystem(new FileSystem(context_));
  182. context_->RegisterSubsystem(new ResourceCache(context_));
  183. context_->RegisterSubsystem(new WorkQueue(context_));
  184. String command = arguments[0].ToLower();
  185. String rootNodeName;
  186. bool noMaterials = false;
  187. unsigned flags =
  188. aiProcess_ConvertToLeftHanded |
  189. aiProcess_JoinIdenticalVertices |
  190. aiProcess_Triangulate |
  191. aiProcess_GenSmoothNormals |
  192. aiProcess_LimitBoneWeights |
  193. aiProcess_ImproveCacheLocality |
  194. aiProcess_RemoveRedundantMaterials |
  195. aiProcess_FixInfacingNormals |
  196. aiProcess_FindInvalidData |
  197. aiProcess_GenUVCoords |
  198. aiProcess_FindInstances |
  199. aiProcess_OptimizeMeshes;
  200. for (unsigned i = 2; i < arguments.Size(); ++i)
  201. {
  202. if (arguments[i].Length() >= 2 && arguments[i][0] == '-')
  203. {
  204. String parameter;
  205. if (arguments[i].Length() >= 3)
  206. parameter = arguments[i].Substring(2);
  207. switch (tolower(arguments[i][1]))
  208. {
  209. case 'b':
  210. saveBinary_ = true;
  211. break;
  212. case 'i':
  213. localIDs_ = true;
  214. break;
  215. case 'm':
  216. materialListName_ = GetInternalPath(parameter);
  217. break;
  218. case 'p':
  219. resourcePath_ = AddTrailingSlash(parameter);
  220. break;
  221. case 'r':
  222. rootNodeName = parameter;
  223. break;
  224. case 't':
  225. flags |= aiProcess_CalcTangentSpace;
  226. break;
  227. case 'f':
  228. defaultTicksPerSecond_ = ToFloat(parameter);
  229. break;
  230. case 'n':
  231. if (!parameter.Empty())
  232. {
  233. switch (tolower(parameter[0]))
  234. {
  235. case 'a':
  236. noAnimations_ = true;
  237. break;
  238. case 'm':
  239. noMaterials = true;
  240. break;
  241. case 's':
  242. useSubdirs_ = false;
  243. break;
  244. case 'z':
  245. createZone_ = false;
  246. break;
  247. }
  248. }
  249. break;
  250. }
  251. }
  252. }
  253. if (command == "model" || command == "scene" || command == "dump")
  254. {
  255. String inFile = arguments[1];
  256. String outFile;
  257. if (arguments.Size() > 2 && arguments[2][0] != '-')
  258. outFile = GetInternalPath(arguments[2]);
  259. if (resourcePath_.Empty())
  260. {
  261. resourcePath_ = GetPath(outFile);
  262. // If output file already has the Models/ path (model mode), do not take it into the resource path
  263. if (command == "model")
  264. {
  265. String resPathLower = resourcePath_.ToLower();
  266. if (resPathLower.FindLast("models/") == resPathLower.Length() - 7)
  267. resourcePath_ = resourcePath_.Substring(0, resourcePath_.Length() - 7);
  268. }
  269. if (resourcePath_.Empty())
  270. resourcePath_ = "./";
  271. }
  272. resourcePath_ = AddTrailingSlash(resourcePath_);
  273. Assimp::Importer importer;
  274. PrintLine("Reading file " + inFile);
  275. scene_ = importer.ReadFile(GetNativePath(inFile).CString(), flags);
  276. if (!scene_)
  277. ErrorExit("Could not open or parse input file " + inFile);
  278. rootNode_ = scene_->mRootNode;
  279. if (!rootNodeName.Empty())
  280. {
  281. rootNode_ = GetNode(rootNodeName, rootNode_, false);
  282. if (!rootNode_)
  283. ErrorExit("Could not find scene node " + rootNodeName);
  284. }
  285. if (command == "dump")
  286. {
  287. DumpNodes(rootNode_, 0);
  288. return;
  289. }
  290. if (command == "model")
  291. ExportModel(outFile);
  292. if (command == "scene")
  293. ExportScene(outFile);
  294. if (!noMaterials)
  295. {
  296. Set<String> usedTextures;
  297. ExportMaterials(usedTextures);
  298. CopyTextures(usedTextures, GetPath(inFile));
  299. }
  300. }
  301. else if (command == "lod")
  302. {
  303. PODVector<float> lodDistances;
  304. Vector<String> modelNames;
  305. String outFile;
  306. unsigned numLodArguments = 0;
  307. for (unsigned i = 1; i < arguments.Size(); ++i)
  308. {
  309. if (arguments[i][0] == '-')
  310. break;
  311. ++numLodArguments;
  312. }
  313. if (numLodArguments < 4)
  314. ErrorExit("Must define at least 2 LOD levels");
  315. if (!(numLodArguments & 1))
  316. ErrorExit("No output file defined");
  317. for (unsigned i = 1; i < numLodArguments + 1; ++i)
  318. {
  319. if (i == numLodArguments)
  320. outFile = GetInternalPath(arguments[i]);
  321. else
  322. {
  323. if (i & 1)
  324. lodDistances.Push(Max(ToFloat(arguments[i]), 0.0f));
  325. else
  326. modelNames.Push(GetInternalPath(arguments[i]));
  327. }
  328. }
  329. if (lodDistances[0] != 0.0f)
  330. {
  331. PrintLine("Warning: first LOD distance forced to 0");
  332. lodDistances[0] = 0.0f;
  333. }
  334. CombineLods(lodDistances, modelNames, outFile);
  335. }
  336. else
  337. ErrorExit("Unrecognized command " + command);
  338. }
  339. void DumpNodes(aiNode* rootNode, unsigned level)
  340. {
  341. if (!rootNode)
  342. return;
  343. String indent(' ', level * 2);
  344. Vector3 pos, scale;
  345. Quaternion rot;
  346. aiMatrix4x4 transform = GetDerivedTransform(rootNode, rootNode_);
  347. GetPosRotScale(transform, pos, rot, scale);
  348. PrintLine(indent + "Node " + FromAIString(rootNode->mName) + " pos " + String(pos));
  349. if (rootNode->mNumMeshes == 1)
  350. PrintLine(indent + " " + String(rootNode->mNumMeshes) + " geometry");
  351. if (rootNode->mNumMeshes > 1)
  352. PrintLine(indent + " " + String(rootNode->mNumMeshes) + " geometries");
  353. for (unsigned i = 0; i < rootNode->mNumChildren; ++i)
  354. DumpNodes(rootNode->mChildren[i], level + 1);
  355. }
  356. void ExportModel(const String& outName)
  357. {
  358. if (outName.Empty())
  359. ErrorExit("No output file defined");
  360. OutModel model;
  361. model.rootNode_ = rootNode_;
  362. model.outName_ = outName;
  363. CollectMeshes(model, model.rootNode_);
  364. CollectBones(model);
  365. BuildBoneCollisionInfo(model);
  366. BuildAndSaveModel(model);
  367. if (!noAnimations_)
  368. {
  369. CollectAnimations(model);
  370. BuildAndSaveAnimations(model);
  371. }
  372. // Write material references if requested
  373. if (!materialListName_.Empty())
  374. {
  375. File listFile(context_);
  376. if (listFile.Open(materialListName_, FILE_WRITE))
  377. {
  378. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  379. listFile.WriteLine(GetMeshMaterialName(model.meshes_[i]));
  380. }
  381. else
  382. PrintLine("Warning: could not write material list file " + materialListName_);
  383. }
  384. }
  385. void CollectMeshes(OutModel& model, aiNode* node)
  386. {
  387. for (unsigned i = 0; i < node->mNumMeshes; ++i)
  388. {
  389. aiMesh* mesh = scene_->mMeshes[node->mMeshes[i]];
  390. for (unsigned j = 0; j < model.meshes_.Size(); ++j)
  391. {
  392. if (mesh == model.meshes_[j])
  393. {
  394. PrintLine("Warning: same mesh found multiple times");
  395. break;
  396. }
  397. }
  398. model.meshIndices_.Insert(node->mMeshes[i]);
  399. model.meshes_.Push(mesh);
  400. model.meshNodes_.Push(node);
  401. model.totalVertices_ += mesh->mNumVertices;
  402. model.totalIndices_ += mesh->mNumFaces * 3;
  403. }
  404. for (unsigned i = 0; i < node->mNumChildren; ++i)
  405. CollectMeshes(model, node->mChildren[i]);
  406. }
  407. void CollectBones(OutModel& model)
  408. {
  409. Set<aiNode*> necessary;
  410. Set<aiNode*> rootNodes;
  411. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  412. {
  413. aiMesh* mesh = model.meshes_[i];
  414. aiNode* meshNode = model.meshNodes_[i];
  415. aiNode* meshParentNode = meshNode->mParent;
  416. aiNode* rootNode = 0;
  417. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  418. {
  419. aiBone* bone = mesh->mBones[j];
  420. String boneName(FromAIString(bone->mName));
  421. aiNode* boneNode = GetNode(boneName, scene_->mRootNode, true);
  422. if (!boneNode)
  423. ErrorExit("Could not find scene node for bone " + boneName);
  424. necessary.Insert(boneNode);
  425. rootNode = boneNode;
  426. for (;;)
  427. {
  428. boneNode = boneNode->mParent;
  429. if (!boneNode || boneNode == meshNode || boneNode == meshParentNode)
  430. break;
  431. rootNode = boneNode;
  432. necessary.Insert(boneNode);
  433. }
  434. if (rootNodes.Find(rootNode) == rootNodes.End())
  435. rootNodes.Insert(rootNode);
  436. }
  437. }
  438. // If we find multiple root nodes, try to remedy by using their parent instead
  439. if (rootNodes.Size() > 1)
  440. {
  441. aiNode* commonParent = (*rootNodes.Begin())->mParent;
  442. for (Set<aiNode*>::Iterator i = rootNodes.Begin(); i != rootNodes.End(); ++i)
  443. {
  444. if (*i != commonParent)
  445. {
  446. if (!commonParent || (*i)->mParent != commonParent)
  447. ErrorExit("Skeleton with multiple root nodes found, not supported");
  448. }
  449. }
  450. rootNodes.Clear();
  451. rootNodes.Insert(commonParent);
  452. necessary.Insert(commonParent);
  453. }
  454. if (rootNodes.Empty())
  455. return;
  456. model.rootBone_ = *rootNodes.Begin();
  457. CollectBonesFinal(model.bones_, necessary, model.rootBone_);
  458. // Initialize the bone collision info
  459. model.boneRadii_.Resize(model.bones_.Size());
  460. model.boneHitboxes_.Resize(model.bones_.Size());
  461. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  462. {
  463. model.boneRadii_[i] = 0.0f;
  464. model.boneHitboxes_[i] = BoundingBox(0.0f, 0.0f);
  465. }
  466. }
  467. void CollectBonesFinal(PODVector<aiNode*>& dest, const Set<aiNode*>& necessary, aiNode* node)
  468. {
  469. if (necessary.Find(node) != necessary.End())
  470. {
  471. dest.Push(node);
  472. for (unsigned i = 0; i < node->mNumChildren; ++i)
  473. CollectBonesFinal(dest, necessary, node->mChildren[i]);
  474. }
  475. }
  476. void CollectAnimations(OutModel& model)
  477. {
  478. const aiScene* scene = scene_;
  479. for (unsigned i = 0; i < scene->mNumAnimations; ++i)
  480. {
  481. aiAnimation* anim = scene->mAnimations[i];
  482. bool modelBoneFound = false;
  483. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  484. {
  485. aiNodeAnim* channel = anim->mChannels[j];
  486. String channelName = FromAIString(channel->mNodeName);
  487. if (GetBoneIndex(model, channelName) != M_MAX_UNSIGNED)
  488. {
  489. modelBoneFound = true;
  490. break;
  491. }
  492. }
  493. if (modelBoneFound)
  494. model.animations_.Push(anim);
  495. }
  496. /// \todo Vertex morphs are ignored for now
  497. }
  498. void BuildBoneCollisionInfo(OutModel& model)
  499. {
  500. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  501. {
  502. aiMesh* mesh = model.meshes_[i];
  503. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  504. {
  505. aiBone* bone = mesh->mBones[j];
  506. String boneName = FromAIString(bone->mName);
  507. unsigned boneIndex = GetBoneIndex(model, boneName);
  508. if (boneIndex == M_MAX_UNSIGNED)
  509. continue;
  510. aiNode* boneNode = model.bones_[boneIndex];
  511. for (unsigned k = 0; k < bone->mNumWeights; ++k)
  512. {
  513. float weight = bone->mWeights[k].mWeight;
  514. if (weight > 0.33f)
  515. {
  516. aiVector3D vertexBoneSpace = bone->mOffsetMatrix * mesh->mVertices[bone->mWeights[k].mVertexId];
  517. Vector3 vertex = ToVector3(vertexBoneSpace);
  518. float radius = vertex.Length();
  519. if (radius > model.boneRadii_[boneIndex])
  520. model.boneRadii_[boneIndex] = radius;
  521. model.boneHitboxes_[boneIndex].Merge(vertex);
  522. }
  523. }
  524. }
  525. }
  526. }
  527. void BuildAndSaveModel(OutModel& model)
  528. {
  529. if (!model.rootNode_)
  530. ErrorExit("Null root node for model");
  531. String rootNodeName = FromAIString(model.rootNode_->mName);
  532. if (!model.meshes_.Size())
  533. ErrorExit("No geometries found starting from node " + rootNodeName);
  534. PrintLine("Writing model " + rootNodeName);
  535. SharedPtr<Model> outModel(new Model(context_));
  536. outModel->SetNumGeometries(model.meshes_.Size());
  537. Vector<PODVector<unsigned> > allBoneMappings;
  538. BoundingBox box;
  539. bool combineBuffers = true;
  540. // Check if buffers can be combined (same vertex element mask, under 65535 vertices)
  541. unsigned elementMask = GetElementMask(model.meshes_[0]);
  542. for (unsigned i = 1; i < model.meshes_.Size(); ++i)
  543. {
  544. if (GetElementMask(model.meshes_[i]) != elementMask)
  545. {
  546. combineBuffers = false;
  547. break;
  548. }
  549. }
  550. // Check if keeping separate buffers allows to avoid 32-bit indices
  551. if (combineBuffers && model.totalVertices_ > 65535)
  552. {
  553. bool allUnder65k = true;
  554. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  555. {
  556. if (model.meshes_[i]->mNumVertices > 65535)
  557. allUnder65k = false;
  558. }
  559. if (allUnder65k == true)
  560. combineBuffers = false;
  561. }
  562. if (!combineBuffers)
  563. {
  564. PrintLine("Writing separate buffers");
  565. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  566. {
  567. // Get the world transform of the mesh for baking into the vertices
  568. Matrix3x4 vertexTransform;
  569. Matrix3 normalTransform;
  570. Vector3 pos, scale;
  571. Quaternion rot;
  572. GetPosRotScale(GetMeshBakingTransform(model.meshNodes_[i], model.rootNode_), pos, rot, scale);
  573. vertexTransform = Matrix3x4(pos, rot, scale);
  574. normalTransform = rot.RotationMatrix();
  575. SharedPtr<IndexBuffer> ib(new IndexBuffer(context_));
  576. SharedPtr<VertexBuffer> vb(new VertexBuffer(context_));
  577. SharedPtr<Geometry> geom(new Geometry(context_));
  578. aiMesh* mesh = model.meshes_[i];
  579. PrintLine("Writing geometry " + String(i) + " with " + String(mesh->mNumVertices) + " vertices " +
  580. String(mesh->mNumFaces * 3) + " indices");
  581. bool largeIndices = mesh->mNumVertices > 65535;
  582. unsigned elementMask = GetElementMask(mesh);
  583. ib->SetSize(mesh->mNumFaces * 3, largeIndices);
  584. vb->SetSize(mesh->mNumVertices, elementMask);
  585. // Build the index data
  586. void* indexData = ib->GetShadowData();
  587. if (!largeIndices)
  588. {
  589. unsigned short* dest = (unsigned short*)indexData;
  590. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  591. WriteShortIndices(dest, mesh, j, 0);
  592. }
  593. else
  594. {
  595. unsigned* dest = (unsigned*)indexData;
  596. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  597. WriteLargeIndices(dest, mesh, j, 0);
  598. }
  599. // Build the vertex data
  600. // If there are bones, get blend data
  601. Vector<PODVector<unsigned char> > blendIndices;
  602. Vector<PODVector<float> > blendWeights;
  603. PODVector<unsigned> boneMappings;
  604. if (model.bones_.Size())
  605. GetBlendData(model, mesh, boneMappings, blendIndices, blendWeights);
  606. void* vertexData = vb->GetShadowData();
  607. float* dest = (float*)vertexData;
  608. for (unsigned j = 0; j < mesh->mNumVertices; ++j)
  609. WriteVertex(dest, mesh, j, elementMask, box, vertexTransform, normalTransform, blendIndices, blendWeights);
  610. // Calculate the geometry center
  611. Vector3 center = Vector3::ZERO;
  612. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  613. {
  614. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[0]]);
  615. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[1]]);
  616. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[2]]);
  617. }
  618. if (mesh->mNumFaces)
  619. center /= (float)mesh->mNumFaces * 3;
  620. // Define the model buffers
  621. Vector<SharedPtr<VertexBuffer> > vbVector;
  622. Vector<SharedPtr<IndexBuffer> > ibVector;
  623. PODVector<unsigned> emptyMorphRange;
  624. vbVector.Push(vb);
  625. ibVector.Push(ib);
  626. outModel->SetVertexBuffers(vbVector, emptyMorphRange, emptyMorphRange);
  627. outModel->SetIndexBuffers(ibVector);
  628. // Define the geometry
  629. geom->SetIndexBuffer(ib);
  630. geom->SetVertexBuffer(0, vb);
  631. geom->SetDrawRange(TRIANGLE_LIST, 0, mesh->mNumFaces * 3, true);
  632. outModel->SetNumGeometryLodLevels(i, 1);
  633. outModel->SetGeometry(i, 0, geom);
  634. outModel->SetGeometryCenter(i, center);
  635. if (model.bones_.Size() > MAX_SKIN_MATRICES)
  636. allBoneMappings.Push(boneMappings);
  637. }
  638. }
  639. else
  640. {
  641. SharedPtr<IndexBuffer> ib(new IndexBuffer(context_));
  642. SharedPtr<VertexBuffer> vb(new VertexBuffer(context_));
  643. bool largeIndices = model.totalIndices_ > 65535;
  644. ib->SetSize(model.totalIndices_, largeIndices);
  645. vb->SetSize(model.totalVertices_, elementMask);
  646. unsigned startVertexOffset = 0;
  647. unsigned startIndexOffset = 0;
  648. void* indexData = ib->GetShadowData();
  649. void* vertexData = vb->GetShadowData();
  650. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  651. {
  652. // Get the world transform of the mesh for baking into the vertices
  653. Matrix3x4 vertexTransform;
  654. Matrix3 normalTransform;
  655. Vector3 pos, scale;
  656. Quaternion rot;
  657. GetPosRotScale(GetMeshBakingTransform(model.meshNodes_[i], model.rootNode_), pos, rot, scale);
  658. vertexTransform = Matrix3x4(pos, rot, scale);
  659. normalTransform = rot.RotationMatrix();
  660. SharedPtr<Geometry> geom(new Geometry(context_));
  661. aiMesh* mesh = model.meshes_[i];
  662. PrintLine("Writing geometry " + String(i) + " with " + String(mesh->mNumVertices) + " vertices " +
  663. String(mesh->mNumFaces * 3) + " indices");
  664. // Build the index data
  665. if (!largeIndices)
  666. {
  667. unsigned short* dest = (unsigned short*)indexData + startIndexOffset;
  668. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  669. WriteShortIndices(dest, mesh, j, startVertexOffset);
  670. }
  671. else
  672. {
  673. unsigned* dest = (unsigned*)indexData + startIndexOffset;
  674. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  675. WriteLargeIndices(dest, mesh, j, startVertexOffset);
  676. }
  677. // Build the vertex data
  678. // If there are bones, get blend data
  679. Vector<PODVector<unsigned char> > blendIndices;
  680. Vector<PODVector<float> > blendWeights;
  681. PODVector<unsigned> boneMappings;
  682. if (model.bones_.Size())
  683. GetBlendData(model, mesh, boneMappings, blendIndices, blendWeights);
  684. float* dest = (float*)((unsigned char*)vertexData + startVertexOffset * vb->GetVertexSize());
  685. for (unsigned j = 0; j < mesh->mNumVertices; ++j)
  686. WriteVertex(dest, mesh, j, elementMask, box, vertexTransform, normalTransform, blendIndices, blendWeights);
  687. // Calculate the geometry center
  688. Vector3 center = Vector3::ZERO;
  689. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  690. {
  691. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[0]]);
  692. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[1]]);
  693. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[2]]);
  694. }
  695. if (mesh->mNumFaces)
  696. center /= (float)mesh->mNumFaces * 3;
  697. // Define the model buffers
  698. Vector<SharedPtr<VertexBuffer> > vbVector;
  699. Vector<SharedPtr<IndexBuffer> > ibVector;
  700. PODVector<unsigned> emptyMorphRange;
  701. vbVector.Push(vb);
  702. ibVector.Push(ib);
  703. outModel->SetVertexBuffers(vbVector, emptyMorphRange, emptyMorphRange);
  704. outModel->SetIndexBuffers(ibVector);
  705. // Define the geometry
  706. geom->SetIndexBuffer(ib);
  707. geom->SetVertexBuffer(0, vb);
  708. geom->SetDrawRange(TRIANGLE_LIST, startIndexOffset, mesh->mNumFaces * 3, true);
  709. outModel->SetNumGeometryLodLevels(i, 1);
  710. outModel->SetGeometry(i, 0, geom);
  711. outModel->SetGeometryCenter(i, center);
  712. if (model.bones_.Size() > MAX_SKIN_MATRICES)
  713. allBoneMappings.Push(boneMappings);
  714. startVertexOffset += mesh->mNumVertices;
  715. startIndexOffset += mesh->mNumFaces * 3;
  716. }
  717. }
  718. outModel->SetBoundingBox(box);
  719. // Build skeleton if necessary
  720. if (model.bones_.Size() && model.rootBone_)
  721. {
  722. PrintLine("Writing skeleton with " + String(model.bones_.Size()) + " bones, rootbone " +
  723. FromAIString(model.rootBone_->mName));
  724. Skeleton skeleton;
  725. Vector<Bone>& bones = skeleton.GetModifiableBones();
  726. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  727. {
  728. aiNode* boneNode = model.bones_[i];
  729. String boneName(FromAIString(boneNode->mName));
  730. Bone newBone;
  731. newBone.name_ = boneName;
  732. aiMatrix4x4 transform = boneNode->mTransformation;
  733. // Make the root bone transform relative to the model's root node, if it is not already
  734. if (boneNode == model.rootBone_)
  735. transform = GetDerivedTransform(boneNode, model.rootNode_);
  736. GetPosRotScale(transform, newBone.initialPosition_, newBone.initialRotation_, newBone.initialScale_);
  737. // Get offset information if exists
  738. newBone.offsetMatrix_ = GetOffsetMatrix(model, boneName);
  739. newBone.radius_ = model.boneRadii_[i];
  740. newBone.boundingBox_ = model.boneHitboxes_[i];
  741. newBone.collisionMask_ = BONECOLLISION_SPHERE | BONECOLLISION_BOX;
  742. newBone.parentIndex_ = i;
  743. bones.Push(newBone);
  744. }
  745. // Set the bone hierarchy
  746. for (unsigned i = 1; i < model.bones_.Size(); ++i)
  747. {
  748. String parentName = FromAIString(model.bones_[i]->mParent->mName);
  749. for (unsigned j = 0; j < bones.Size(); ++j)
  750. {
  751. if (bones[j].name_ == parentName)
  752. {
  753. bones[i].parentIndex_ = j;
  754. break;
  755. }
  756. }
  757. }
  758. outModel->SetSkeleton(skeleton);
  759. if (model.bones_.Size() > MAX_SKIN_MATRICES)
  760. outModel->SetGeometryBoneMappings(allBoneMappings);
  761. }
  762. File outFile(context_);
  763. if (!outFile.Open(model.outName_, FILE_WRITE))
  764. ErrorExit("Could not open output file " + model.outName_);
  765. outModel->Save(outFile);
  766. }
  767. void BuildAndSaveAnimations(OutModel& model)
  768. {
  769. for (unsigned i = 0; i < model.animations_.Size(); ++i)
  770. {
  771. aiAnimation* anim = model.animations_[i];
  772. String animName = FromAIString(anim->mName);
  773. if (animName.Empty())
  774. animName = "Anim" + String(i + 1);
  775. String animOutName = GetPath(model.outName_) + GetFileName(model.outName_) + "_" + SanitateAssetName(animName) + ".ani";
  776. SharedPtr<Animation> outAnim(new Animation(context_));
  777. float ticksPerSecond = (float)anim->mTicksPerSecond;
  778. // If ticks per second not specified, it's probably a .X file. In this case use the default tick rate
  779. if (ticksPerSecond < M_EPSILON)
  780. ticksPerSecond = defaultTicksPerSecond_;
  781. float tickConversion = 1.0f / ticksPerSecond;
  782. outAnim->SetAnimationName(animName);
  783. outAnim->SetLength((float)anim->mDuration * tickConversion);
  784. PrintLine("Writing animation " + animName + " length " + String(outAnim->GetLength()));
  785. Vector<AnimationTrack> tracks;
  786. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  787. {
  788. aiNodeAnim* channel = anim->mChannels[j];
  789. String channelName = FromAIString(channel->mNodeName);
  790. unsigned boneIndex = GetBoneIndex(model, channelName);
  791. if (boneIndex == M_MAX_UNSIGNED)
  792. {
  793. PrintLine("Warning: skipping animation track " + channelName + " not found in model skeleton");
  794. continue;
  795. }
  796. aiNode* boneNode = model.bones_[boneIndex];
  797. AnimationTrack track;
  798. track.name_ = channelName;
  799. track.nameHash_ = StringHash(channelName);
  800. // Check which channels are used
  801. track.channelMask_ = 0;
  802. if (channel->mNumPositionKeys > 1)
  803. track.channelMask_ |= CHANNEL_POSITION;
  804. if (channel->mNumRotationKeys > 1)
  805. track.channelMask_ |= CHANNEL_ROTATION;
  806. if (channel->mNumScalingKeys > 1)
  807. track.channelMask_ |= CHANNEL_SCALE;
  808. // Check for redundant identity scale in all keyframes and remove in that case
  809. if (track.channelMask_ & CHANNEL_SCALE)
  810. {
  811. bool redundantScale = true;
  812. for (unsigned k = 0; k < channel->mNumScalingKeys; ++k)
  813. {
  814. float SCALE_EPSILON = 0.000001f;
  815. Vector3 scaleVec = ToVector3(channel->mScalingKeys[k].mValue);
  816. if (fabsf(scaleVec.x_ - 1.0f) >= SCALE_EPSILON || fabsf(scaleVec.y_ - 1.0f) >= SCALE_EPSILON ||
  817. fabsf(scaleVec.z_ - 1.0f) >= SCALE_EPSILON)
  818. {
  819. redundantScale = false;
  820. break;
  821. }
  822. }
  823. if (redundantScale)
  824. track.channelMask_ &= ~CHANNEL_SCALE;
  825. }
  826. if (!track.channelMask_)
  827. PrintLine("Warning: skipping animation track " + channelName + " with no keyframes");
  828. // Currently only same amount of keyframes is supported
  829. // Note: should also check the times of individual keyframes for match
  830. if ((channel->mNumPositionKeys > 1 && channel->mNumRotationKeys > 1 && channel->mNumPositionKeys != channel->mNumRotationKeys) ||
  831. (channel->mNumPositionKeys > 1 && channel->mNumScalingKeys > 1 && channel->mNumPositionKeys != channel->mNumScalingKeys) ||
  832. (channel->mNumRotationKeys > 1 && channel->mNumScalingKeys > 1 && channel->mNumRotationKeys != channel->mNumScalingKeys))
  833. {
  834. PrintLine("Warning: differing amounts of channel keyframes, skipping animation track " + channelName);
  835. continue;
  836. }
  837. unsigned keyFrames = channel->mNumPositionKeys;
  838. if (channel->mNumRotationKeys > keyFrames)
  839. keyFrames = channel->mNumRotationKeys;
  840. if (channel->mNumScalingKeys > keyFrames)
  841. keyFrames = channel->mNumScalingKeys;
  842. for (unsigned k = 0; k < keyFrames; ++k)
  843. {
  844. AnimationKeyFrame kf;
  845. kf.time_ = 0.0f;
  846. kf.position_ = Vector3::ZERO;
  847. kf.rotation_ = Quaternion::IDENTITY;
  848. kf.scale_ = Vector3::ONE;
  849. // Get time for the keyframe
  850. if (track.channelMask_ & CHANNEL_POSITION && k < channel->mNumPositionKeys)
  851. kf.time_ = (float)channel->mPositionKeys[k].mTime * tickConversion;
  852. else if (track.channelMask_ & CHANNEL_ROTATION && k < channel->mNumRotationKeys)
  853. kf.time_ = (float)channel->mRotationKeys[k].mTime * tickConversion;
  854. else if (track.channelMask_ & CHANNEL_SCALE && k < channel->mNumScalingKeys)
  855. kf.time_ = (float)channel->mScalingKeys[k].mTime * tickConversion;
  856. // Start with the bone's base transform
  857. aiMatrix4x4 boneTransform = boneNode->mTransformation;
  858. aiVector3D pos, scale;
  859. aiQuaternion rot;
  860. boneTransform.Decompose(scale, rot, pos);
  861. // Then apply the active channels
  862. if (track.channelMask_ & CHANNEL_POSITION && k < channel->mNumPositionKeys)
  863. pos = channel->mPositionKeys[k].mValue;
  864. if (track.channelMask_ & CHANNEL_ROTATION && k < channel->mNumRotationKeys)
  865. rot = channel->mRotationKeys[k].mValue;
  866. if (track.channelMask_ & CHANNEL_SCALE && k < channel->mNumScalingKeys)
  867. scale = channel->mScalingKeys[k].mValue;
  868. // If root bone, transform with the model root node transform
  869. if (!boneIndex)
  870. {
  871. aiMatrix4x4 transMat, scaleMat, rotMat;
  872. aiMatrix4x4::Translation(pos, transMat);
  873. aiMatrix4x4::Scaling(scale, scaleMat);
  874. rotMat = aiMatrix4x4(rot.GetMatrix());
  875. aiMatrix4x4 tform = transMat * rotMat * scaleMat;
  876. tform = GetDerivedTransform(tform, boneNode, model.rootNode_);
  877. tform.Decompose(scale, rot, pos);
  878. }
  879. if (track.channelMask_ & CHANNEL_POSITION)
  880. kf.position_ = ToVector3(pos);
  881. if (track.channelMask_ & CHANNEL_ROTATION)
  882. kf.rotation_ = ToQuaternion(rot);
  883. if (track.channelMask_ & CHANNEL_SCALE)
  884. kf.scale_ = ToVector3(scale);
  885. track.keyFrames_.Push(kf);
  886. }
  887. tracks.Push(track);
  888. }
  889. outAnim->SetTracks(tracks);
  890. File outFile(context_);
  891. if (!outFile.Open(animOutName, FILE_WRITE))
  892. ErrorExit("Could not open output file " + animOutName);
  893. outAnim->Save(outFile);
  894. }
  895. }
  896. void ExportScene(const String& outName)
  897. {
  898. OutScene outScene;
  899. outScene.outName_ = outName;
  900. outScene.rootNode_ = rootNode_;
  901. if (useSubdirs_)
  902. context_->GetSubsystem<FileSystem>()->CreateDir(resourcePath_ + "Models");
  903. CollectSceneModels(outScene, rootNode_);
  904. // Save models
  905. for (unsigned i = 0; i < outScene.models_.Size(); ++i)
  906. BuildAndSaveModel(outScene.models_[i]);
  907. // Save scene
  908. BuildAndSaveScene(outScene);
  909. }
  910. void CollectSceneModels(OutScene& scene, aiNode* node)
  911. {
  912. Vector<Pair<aiNode*, aiMesh*> > meshes;
  913. GetMeshesUnderNode(meshes, node);
  914. if (meshes.Size())
  915. {
  916. OutModel model;
  917. model.rootNode_ = node;
  918. model.outName_ = resourcePath_ + (useSubdirs_ ? "Models/" : "") + SanitateAssetName(FromAIString(node->mName)) + ".mdl";
  919. for (unsigned i = 0; i < meshes.Size(); ++i)
  920. {
  921. aiMesh* mesh = meshes[i].second_;
  922. unsigned meshIndex = GetMeshIndex(mesh);
  923. model.meshIndices_.Insert(meshIndex);
  924. model.meshes_.Push(mesh);
  925. model.meshNodes_.Push(meshes[i].first_);
  926. model.totalVertices_ += mesh->mNumVertices;
  927. model.totalIndices_ += mesh->mNumFaces * 3;
  928. }
  929. // Check if a model with identical mesh indices already exists. If yes, do not export twice
  930. bool unique = true;
  931. for (unsigned i = 0; i < scene.models_.Size(); ++i)
  932. {
  933. if (scene.models_[i].meshIndices_ == model.meshIndices_)
  934. {
  935. PrintLine("Added node " + FromAIString(node->mName));
  936. scene.nodes_.Push(node);
  937. scene.nodeModelIndices_.Push(i);
  938. unique = false;
  939. break;
  940. }
  941. }
  942. if (unique)
  943. {
  944. PrintLine("Added model " + model.outName_);
  945. PrintLine("Added node " + FromAIString(node->mName));
  946. CollectBones(model);
  947. BuildBoneCollisionInfo(model);
  948. if (!noAnimations_)
  949. {
  950. CollectAnimations(model);
  951. BuildAndSaveAnimations(model);
  952. }
  953. scene.models_.Push(model);
  954. scene.nodes_.Push(node);
  955. scene.nodeModelIndices_.Push(scene.models_.Size() - 1);
  956. }
  957. }
  958. for (unsigned i = 0; i < node->mNumChildren; ++i)
  959. CollectSceneModels(scene, node->mChildren[i]);
  960. }
  961. void BuildAndSaveScene(OutScene& scene)
  962. {
  963. PrintLine("Writing scene");
  964. SharedPtr<Scene> outScene(new Scene(context_));
  965. /// \todo Make the physics properties configurable
  966. PhysicsWorld* physicsWorld = outScene->CreateComponent<PhysicsWorld>();
  967. /// \todo Make the octree properties configurable, or detect from the scene contents
  968. Octree* octree = outScene->CreateComponent<Octree>();
  969. DebugRenderer* debug = outScene->CreateComponent<DebugRenderer>();
  970. if (createZone_)
  971. {
  972. Node* zoneNode = outScene->CreateChild("Zone", localIDs_ ? LOCAL : REPLICATED);
  973. Zone* zone = zoneNode->CreateComponent<Zone>();
  974. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.f));
  975. zone->SetAmbientColor(Color(0.25f, 0.25f, 0.25f));
  976. Node* lightNode = outScene->CreateChild("GlobalLight", localIDs_ ? LOCAL : REPLICATED);
  977. Light* light = lightNode->CreateComponent<Light>();
  978. light->SetLightType(LIGHT_DIRECTIONAL);
  979. lightNode->SetRotation(Quaternion(60.0f, 30.0f, 0.0f));
  980. }
  981. ResourceCache* cache = context_->GetSubsystem<ResourceCache>();
  982. for (unsigned i = 0; i < scene.nodes_.Size(); ++i)
  983. {
  984. const OutModel& model = scene.models_[scene.nodeModelIndices_[i]];
  985. // Create a static model component for each node
  986. Node* modelNode = outScene->CreateChild(FromAIString(scene.nodes_[i]->mName), localIDs_ ? LOCAL : REPLICATED);
  987. StaticModel* staticModel = modelNode->CreateComponent<StaticModel>();
  988. // Create a dummy model so that the reference can be stored
  989. String modelName = (useSubdirs_ ? "Models/" : "") + GetFileNameAndExtension(model.outName_);
  990. if (!cache->Exists(modelName))
  991. {
  992. Model* dummyModel = new Model(context_);
  993. dummyModel->SetName(modelName);
  994. dummyModel->SetNumGeometries(model.meshes_.Size());
  995. cache->AddManualResource(dummyModel);
  996. }
  997. staticModel->SetModel(cache->GetResource<Model>(modelName));
  998. // Set a flattened transform
  999. Vector3 pos, scale;
  1000. Quaternion rot;
  1001. GetPosRotScale(GetDerivedTransform(scene.nodes_[i], rootNode_), pos, rot, scale);
  1002. modelNode->SetTransform(pos, rot, scale);
  1003. // Set materials if they are known
  1004. for (unsigned j = 0; j < model.meshes_.Size(); ++j)
  1005. {
  1006. String matName = GetMeshMaterialName(model.meshes_[j]);
  1007. if (!matName.Empty())
  1008. {
  1009. // Create a dummy material so that the reference can be stored
  1010. if (!cache->Exists(matName))
  1011. {
  1012. Material* dummyMat = new Material(context_);
  1013. dummyMat->SetName(matName);
  1014. cache->AddManualResource(dummyMat);
  1015. }
  1016. staticModel->SetMaterial(j, cache->GetResource<Material>(matName));
  1017. }
  1018. }
  1019. }
  1020. File file(context_);
  1021. if (!file.Open(scene.outName_, FILE_WRITE))
  1022. ErrorExit("Could not open output file " + scene.outName_);
  1023. if (!saveBinary_)
  1024. outScene->SaveXML(file);
  1025. else
  1026. outScene->Save(file);
  1027. }
  1028. void ExportMaterials(Set<String>& usedTextures)
  1029. {
  1030. if (useSubdirs_)
  1031. context_->GetSubsystem<FileSystem>()->CreateDir(resourcePath_ + "Materials");
  1032. for (unsigned i = 0; i < scene_->mNumMaterials; ++i)
  1033. BuildAndSaveMaterial(scene_->mMaterials[i], usedTextures);
  1034. }
  1035. void BuildAndSaveMaterial(aiMaterial* material, Set<String>& usedTextures)
  1036. {
  1037. // Material must have name so it can be successfully saved
  1038. aiString matNameStr;
  1039. material->Get(AI_MATKEY_NAME, matNameStr);
  1040. String matName = SanitateAssetName(FromAIString(matNameStr));
  1041. if (matName.Empty())
  1042. return;
  1043. PrintLine("Writing material " + matName);
  1044. // Do not actually create a material instance, but instead craft an xml file manually
  1045. XMLFile outMaterial(context_);
  1046. XMLElement materialElem = outMaterial.CreateRoot("material");
  1047. String diffuseTexName;
  1048. String normalTexName;
  1049. Color diffuseColor;
  1050. bool hasAlpha = false;
  1051. bool twoSided = false;
  1052. float specIntensity = 0.0f;
  1053. float specPower = 1.0f;
  1054. aiString stringVal;
  1055. float floatVal;
  1056. int intVal;
  1057. aiColor3D colorVal;
  1058. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_DIFFUSE, 0), stringVal) == AI_SUCCESS)
  1059. diffuseTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1060. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_NORMALS, 0), stringVal) == AI_SUCCESS)
  1061. normalTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1062. if (material->Get(AI_MATKEY_COLOR_DIFFUSE, colorVal) == AI_SUCCESS)
  1063. diffuseColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1064. if (material->Get(AI_MATKEY_OPACITY, floatVal) == AI_SUCCESS)
  1065. {
  1066. if (floatVal < 1.0f)
  1067. hasAlpha = true;
  1068. diffuseColor.a_ = floatVal;
  1069. }
  1070. if (material->Get(AI_MATKEY_SHININESS, floatVal) == AI_SUCCESS)
  1071. specPower = floatVal;
  1072. if (material->Get(AI_MATKEY_SHININESS_STRENGTH, floatVal) == AI_SUCCESS)
  1073. specIntensity = floatVal;
  1074. if (material->Get(AI_MATKEY_TWOSIDED, intVal) == AI_SUCCESS)
  1075. twoSided = (intVal != 0);
  1076. String techniqueName = "Techniques/NoTexture";
  1077. if (!diffuseTexName.Empty())
  1078. {
  1079. techniqueName = "Techniques/Diff";
  1080. if (!normalTexName.Empty())
  1081. techniqueName += "Normal";
  1082. }
  1083. if (hasAlpha)
  1084. techniqueName += "Alpha";
  1085. XMLElement techniqueElem = materialElem.CreateChild("technique");
  1086. techniqueElem.SetString("name", techniqueName + ".xml");
  1087. if (!diffuseTexName.Empty())
  1088. {
  1089. XMLElement diffuseElem = materialElem.CreateChild("texture");
  1090. diffuseElem.SetString("unit", "diffuse");
  1091. diffuseElem.SetString("name", (useSubdirs_ ? "Textures/" : "") + diffuseTexName);
  1092. usedTextures.Insert(diffuseTexName);
  1093. }
  1094. if (!normalTexName.Empty())
  1095. {
  1096. XMLElement normalElem = materialElem.CreateChild("texture");
  1097. normalElem.SetString("unit", "diffuse");
  1098. normalElem.SetString("name", (useSubdirs_ ? "Textures/" : "") + normalTexName);
  1099. usedTextures.Insert(normalTexName);
  1100. }
  1101. XMLElement diffuseColorElem = materialElem.CreateChild("parameter");
  1102. diffuseColorElem.SetString("name", "MatDiffColor");
  1103. diffuseColorElem.SetColor("value", diffuseColor);
  1104. XMLElement specularElem = materialElem.CreateChild("parameter");
  1105. specularElem.SetString("name", "MatSpecProperties");
  1106. specularElem.SetVector2("value", Vector2(specIntensity, specPower));
  1107. if (twoSided)
  1108. {
  1109. XMLElement cullElem = materialElem.CreateChild("cull");
  1110. XMLElement shadowCullElem = materialElem.CreateChild("shadowcull");
  1111. cullElem.SetString("value", "none");
  1112. shadowCullElem.SetString("value", "none");
  1113. }
  1114. File outFile(context_);
  1115. String outFileName = resourcePath_ + (useSubdirs_ ? "Materials/" : "" ) + matName + ".xml";
  1116. if (!outFile.Open(outFileName, FILE_WRITE))
  1117. ErrorExit("Could not open output file " + outFileName);
  1118. outMaterial.Save(outFile);
  1119. }
  1120. void CopyTextures(const Set<String>& usedTextures, const String& sourcePath)
  1121. {
  1122. if (useSubdirs_)
  1123. context_->GetSubsystem<FileSystem>()->CreateDir(resourcePath_ + "Textures");
  1124. for (Set<String>::ConstIterator i = usedTextures.Begin(); i != usedTextures.End(); ++i)
  1125. {
  1126. PrintLine("Copying texture " + (*i));
  1127. context_->GetSubsystem<FileSystem>()->Copy(sourcePath + *i, resourcePath_ + (useSubdirs_ ? "Textures/" : "") + *i);
  1128. }
  1129. }
  1130. void CombineLods(const PODVector<float>& lodDistances, const Vector<String>& modelNames, const String& outName)
  1131. {
  1132. // Load models
  1133. Vector<SharedPtr<Model> > srcModels;
  1134. for (unsigned i = 0; i < modelNames.Size(); ++i)
  1135. {
  1136. PrintLine("Reading LOD level " + String(i) + ": model " + modelNames[i] + " distance " + String(lodDistances[i]));
  1137. File srcFile(context_);
  1138. srcFile.Open(modelNames[i]);
  1139. SharedPtr<Model> srcModel(new Model(context_));
  1140. if (!srcModel->Load(srcFile))
  1141. ErrorExit("Could not load input model " + modelNames[i]);
  1142. srcModels.Push(srcModel);
  1143. }
  1144. // Check that none of the models already has LOD levels
  1145. for (unsigned i = 0; i < srcModels.Size(); ++i)
  1146. {
  1147. for (unsigned j = 0; j < srcModels[i]->GetNumGeometries(); ++j)
  1148. {
  1149. if (srcModels[i]->GetNumGeometryLodLevels(j) > 1)
  1150. ErrorExit(modelNames[i] + " already has multiple LOD levels defined");
  1151. }
  1152. }
  1153. // Check for number of geometries (need to have same amount for now)
  1154. for (unsigned i = 1; i < srcModels.Size(); ++i)
  1155. {
  1156. if (srcModels[i]->GetNumGeometries() != srcModels[0]->GetNumGeometries())
  1157. ErrorExit(modelNames[i] + " has different amount of geometries than " + modelNames[0]);
  1158. }
  1159. // If there are bones, check for compatibility (need to have exact match for now)
  1160. for (unsigned i = 1; i < srcModels.Size(); ++i)
  1161. {
  1162. if (srcModels[i]->GetSkeleton().GetNumBones() != srcModels[0]->GetSkeleton().GetNumBones())
  1163. ErrorExit(modelNames[i] + " has different amount of bones than " + modelNames[0]);
  1164. for (unsigned j = 0; j < srcModels[0]->GetSkeleton().GetNumBones(); ++j)
  1165. {
  1166. if (srcModels[i]->GetSkeleton().GetBone(j)->name_ != srcModels[0]->GetSkeleton().GetBone(j)->name_)
  1167. ErrorExit(modelNames[i] + " has different bones than " + modelNames[0]);
  1168. }
  1169. if (srcModels[i]->GetGeometryBoneMappings() != srcModels[0]->GetGeometryBoneMappings())
  1170. ErrorExit(modelNames[i] + " has different per-geometry bone mappings than " + modelNames[0]);
  1171. }
  1172. // Create the final model
  1173. SharedPtr<Model> outModel(new Model(context_));
  1174. outModel->SetNumGeometries(srcModels[0]->GetNumGeometries());
  1175. for (unsigned i = 0; i < srcModels[0]->GetNumGeometries(); ++i)
  1176. {
  1177. outModel->SetNumGeometryLodLevels(i, srcModels.Size());
  1178. for (unsigned j = 0; j < srcModels.Size(); ++j)
  1179. {
  1180. Geometry* geom = srcModels[j]->GetGeometry(i, 0);
  1181. geom->SetLodDistance(lodDistances[j]);
  1182. outModel->SetGeometry(i, j, geom);
  1183. }
  1184. }
  1185. outModel->SetSkeleton(srcModels[0]->GetSkeleton());
  1186. outModel->SetGeometryBoneMappings(srcModels[0]->GetGeometryBoneMappings());
  1187. outModel->SetBoundingBox(srcModels[0]->GetBoundingBox());
  1188. /// \todo Vertex morphs are ignored for now
  1189. // Save the final model
  1190. PrintLine("Writing output model");
  1191. File outFile(context_);
  1192. if (!outFile.Open(outName, FILE_WRITE))
  1193. ErrorExit("Could not open output file " + outName);
  1194. outModel->Save(outFile);
  1195. }
  1196. void GetMeshesUnderNode(Vector<Pair<aiNode*, aiMesh*> >& dest, aiNode* node)
  1197. {
  1198. for (unsigned i = 0; i < node->mNumMeshes; ++i)
  1199. dest.Push(MakePair(node, scene_->mMeshes[node->mMeshes[i]]));
  1200. }
  1201. unsigned GetMeshIndex(aiMesh* mesh)
  1202. {
  1203. for (unsigned i = 0; i < scene_->mNumMeshes; ++i)
  1204. {
  1205. if (scene_->mMeshes[i] == mesh)
  1206. return i;
  1207. }
  1208. return M_MAX_UNSIGNED;
  1209. }
  1210. unsigned GetBoneIndex(OutModel& model, const String& boneName)
  1211. {
  1212. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  1213. {
  1214. if (boneName == model.bones_[i]->mName.data)
  1215. return i;
  1216. }
  1217. return M_MAX_UNSIGNED;
  1218. }
  1219. aiBone* GetMeshBone(OutModel& model, const String& boneName)
  1220. {
  1221. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  1222. {
  1223. aiMesh* mesh = model.meshes_[i];
  1224. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  1225. {
  1226. aiBone* bone = mesh->mBones[j];
  1227. if (boneName == bone->mName.data)
  1228. return bone;
  1229. }
  1230. }
  1231. return 0;
  1232. }
  1233. Matrix3x4 GetOffsetMatrix(OutModel& model, const String& boneName)
  1234. {
  1235. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  1236. {
  1237. aiMesh* mesh = model.meshes_[i];
  1238. aiNode* node = model.meshNodes_[i];
  1239. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  1240. {
  1241. aiBone* bone = mesh->mBones[j];
  1242. if (boneName == bone->mName.data)
  1243. {
  1244. aiMatrix4x4 offset = bone->mOffsetMatrix;
  1245. aiMatrix4x4 nodeDerivedInverse = GetMeshBakingTransform(node, model.rootNode_);
  1246. nodeDerivedInverse.Inverse();
  1247. offset *= nodeDerivedInverse;
  1248. Matrix3x4 ret;
  1249. memcpy(&ret.m00_, &offset.a1, sizeof(Matrix3x4));
  1250. return ret;
  1251. }
  1252. }
  1253. }
  1254. return Matrix3x4::IDENTITY;
  1255. }
  1256. void GetBlendData(OutModel& model, aiMesh* mesh, PODVector<unsigned>& boneMappings, Vector<PODVector<unsigned char> >&
  1257. blendIndices, Vector<PODVector<float> >& blendWeights)
  1258. {
  1259. blendIndices.Resize(mesh->mNumVertices);
  1260. blendWeights.Resize(mesh->mNumVertices);
  1261. boneMappings.Clear();
  1262. // If model has more bones than can fit vertex shader parameters, write the per-geometry mappings
  1263. if (model.bones_.Size() > MAX_SKIN_MATRICES)
  1264. {
  1265. if (mesh->mNumBones > MAX_SKIN_MATRICES)
  1266. ErrorExit("Geometry has too many bone influences");
  1267. boneMappings.Resize(mesh->mNumBones);
  1268. for (unsigned i = 0; i < mesh->mNumBones; ++i)
  1269. {
  1270. aiBone* bone = mesh->mBones[i];
  1271. String boneName = FromAIString(bone->mName);
  1272. unsigned globalIndex = GetBoneIndex(model, boneName);
  1273. if (globalIndex == M_MAX_UNSIGNED)
  1274. ErrorExit("Bone " + boneName + " not found");
  1275. boneMappings[i] = globalIndex;
  1276. for (unsigned j = 0; j < bone->mNumWeights; ++j)
  1277. {
  1278. unsigned vertex = bone->mWeights[j].mVertexId;
  1279. blendIndices[vertex].Push(i);
  1280. blendWeights[vertex].Push(bone->mWeights[j].mWeight);
  1281. if (blendWeights[vertex].Size() > 4)
  1282. ErrorExit("More than 4 bone influences on vertex");
  1283. }
  1284. }
  1285. }
  1286. else
  1287. {
  1288. for (unsigned i = 0; i < mesh->mNumBones; ++i)
  1289. {
  1290. aiBone* bone = mesh->mBones[i];
  1291. String boneName = FromAIString(bone->mName);
  1292. unsigned globalIndex = GetBoneIndex(model, boneName);
  1293. if (globalIndex == M_MAX_UNSIGNED)
  1294. ErrorExit("Bone " + boneName + " not found");
  1295. for (unsigned j = 0; j < bone->mNumWeights; ++j)
  1296. {
  1297. unsigned vertex = bone->mWeights[j].mVertexId;
  1298. blendIndices[vertex].Push(globalIndex);
  1299. blendWeights[vertex].Push(bone->mWeights[j].mWeight);
  1300. if (blendWeights[vertex].Size() > 4)
  1301. ErrorExit("More than 4 bone influences on vertex");
  1302. }
  1303. }
  1304. }
  1305. }
  1306. String GetMeshMaterialName(aiMesh* mesh)
  1307. {
  1308. aiMaterial* material = scene_->mMaterials[mesh->mMaterialIndex];
  1309. aiString matNameStr;
  1310. material->Get(AI_MATKEY_NAME, matNameStr);
  1311. String matName = SanitateAssetName(FromAIString(matNameStr));
  1312. if (matName.Empty())
  1313. return matName;
  1314. else
  1315. return (useSubdirs_ ? "Materials/" : "") + matName + ".xml";
  1316. }
  1317. void WriteShortIndices(unsigned short*& dest, aiMesh* mesh, unsigned index, unsigned offset)
  1318. {
  1319. *dest++ = mesh->mFaces[index].mIndices[0] + offset;
  1320. *dest++ = mesh->mFaces[index].mIndices[1] + offset;
  1321. *dest++ = mesh->mFaces[index].mIndices[2] + offset;
  1322. }
  1323. void WriteLargeIndices(unsigned*& dest, aiMesh* mesh, unsigned index, unsigned offset)
  1324. {
  1325. *dest++ = mesh->mFaces[index].mIndices[0] + offset;
  1326. *dest++ = mesh->mFaces[index].mIndices[1] + offset;
  1327. *dest++ = mesh->mFaces[index].mIndices[2] + offset;
  1328. }
  1329. void WriteVertex(float*& dest, aiMesh* mesh, unsigned index, unsigned elementMask, BoundingBox& box,
  1330. const Matrix3x4& vertexTransform, const Matrix3& normalTransform, Vector<PODVector<unsigned char> >& blendIndices,
  1331. Vector<PODVector<float> >& blendWeights)
  1332. {
  1333. Vector3 vertex = vertexTransform * ToVector3(mesh->mVertices[index]);
  1334. box.Merge(vertex);
  1335. *dest++ = vertex.x_;
  1336. *dest++ = vertex.y_;
  1337. *dest++ = vertex.z_;
  1338. if (elementMask & MASK_NORMAL)
  1339. {
  1340. Vector3 normal = normalTransform * ToVector3(mesh->mNormals[index]);
  1341. *dest++ = normal.x_;
  1342. *dest++ = normal.y_;
  1343. *dest++ = normal.z_;
  1344. }
  1345. if (elementMask & MASK_COLOR)
  1346. {
  1347. *((unsigned*)dest) = Color(mesh->mColors[0][index].r, mesh->mColors[0][index].g, mesh->mColors[0][index].b,
  1348. mesh->mColors[0][index].a).ToUInt();
  1349. ++dest;
  1350. }
  1351. if (elementMask & MASK_TEXCOORD1)
  1352. {
  1353. Vector3 texCoord = ToVector3(mesh->mTextureCoords[0][index]);
  1354. *dest++ = texCoord.x_;
  1355. *dest++ = texCoord.y_;
  1356. }
  1357. if (elementMask & MASK_TEXCOORD2)
  1358. {
  1359. Vector3 texCoord = ToVector3(mesh->mTextureCoords[1][index]);
  1360. *dest++ = texCoord.x_;
  1361. *dest++ = texCoord.y_;
  1362. }
  1363. if (elementMask & MASK_TANGENT)
  1364. {
  1365. Vector3 tangent = normalTransform * ToVector3(mesh->mTangents[index]);
  1366. Vector3 normal = normalTransform * ToVector3(mesh->mNormals[index]);
  1367. Vector3 bitangent = normalTransform * ToVector3(mesh->mBitangents[index]);
  1368. // Check handedness
  1369. float w = 1.0f;
  1370. if ((tangent.CrossProduct(normal)).DotProduct(bitangent) < 0.5f)
  1371. w = -1.0f;
  1372. *dest++ = tangent.x_;
  1373. *dest++ = tangent.y_;
  1374. *dest++ = tangent.z_;
  1375. *dest++ = w;
  1376. }
  1377. if (elementMask & MASK_BLENDWEIGHTS)
  1378. {
  1379. for (unsigned i = 0; i < 4; ++i)
  1380. {
  1381. if (i < blendWeights[index].Size())
  1382. *dest++ = blendWeights[index][i];
  1383. else
  1384. *dest++ = 0.0f;
  1385. }
  1386. }
  1387. if (elementMask & MASK_BLENDINDICES)
  1388. {
  1389. unsigned char* destBytes = (unsigned char*)dest;
  1390. ++dest;
  1391. for (unsigned i = 0; i < 4; ++i)
  1392. {
  1393. if (i < blendIndices[index].Size())
  1394. *destBytes++ = blendIndices[index][i];
  1395. else
  1396. *destBytes++ = 0;
  1397. }
  1398. }
  1399. }
  1400. unsigned GetElementMask(aiMesh* mesh)
  1401. {
  1402. unsigned elementMask = MASK_POSITION;
  1403. if (mesh->HasNormals())
  1404. elementMask |= MASK_NORMAL;
  1405. if (mesh->HasTangentsAndBitangents())
  1406. elementMask |= MASK_TANGENT;
  1407. if (mesh->GetNumColorChannels() > 0)
  1408. elementMask |= MASK_COLOR;
  1409. if (mesh->GetNumUVChannels() > 0)
  1410. elementMask |= MASK_TEXCOORD1;
  1411. if (mesh->GetNumUVChannels() > 1)
  1412. elementMask |= MASK_TEXCOORD2;
  1413. if (mesh->HasBones())
  1414. elementMask |= (MASK_BLENDWEIGHTS | MASK_BLENDINDICES);
  1415. return elementMask;
  1416. }
  1417. aiNode* GetNode(const String& name, aiNode* rootNode, bool caseSensitive)
  1418. {
  1419. if (!rootNode)
  1420. return 0;
  1421. if (!name.Compare(rootNode->mName.data, caseSensitive))
  1422. return rootNode;
  1423. for (unsigned i = 0; i < rootNode->mNumChildren; ++i)
  1424. {
  1425. aiNode* found = GetNode(name, rootNode->mChildren[i], caseSensitive);
  1426. if (found)
  1427. return found;
  1428. }
  1429. return 0;
  1430. }
  1431. aiMatrix4x4 GetDerivedTransform(aiNode* node, aiNode* rootNode)
  1432. {
  1433. return GetDerivedTransform(node->mTransformation, node, rootNode);
  1434. }
  1435. aiMatrix4x4 GetDerivedTransform(aiMatrix4x4 transform, aiNode* node, aiNode* rootNode)
  1436. {
  1437. // If basenode is defined, go only up to it in the parent chain
  1438. while (node && node != rootNode)
  1439. {
  1440. node = node->mParent;
  1441. if (node)
  1442. transform = node->mTransformation * transform;
  1443. }
  1444. return transform;
  1445. }
  1446. aiMatrix4x4 GetMeshBakingTransform(aiNode* meshNode, aiNode* modelRootNode)
  1447. {
  1448. if (meshNode == modelRootNode)
  1449. return aiMatrix4x4();
  1450. else
  1451. return GetDerivedTransform(meshNode, modelRootNode);
  1452. }
  1453. void GetPosRotScale(const aiMatrix4x4& transform, Vector3& pos, Quaternion& rot, Vector3& scale)
  1454. {
  1455. aiVector3D aiPos;
  1456. aiQuaternion aiRot;
  1457. aiVector3D aiScale;
  1458. transform.Decompose(aiScale, aiRot, aiPos);
  1459. pos = ToVector3(aiPos);
  1460. rot = ToQuaternion(aiRot);
  1461. scale = ToVector3(aiScale);
  1462. }
  1463. String FromAIString(const aiString& str)
  1464. {
  1465. return String(str.data);
  1466. }
  1467. Vector3 ToVector3(const aiVector3D& vec)
  1468. {
  1469. return Vector3(vec.x, vec.y, vec.z);
  1470. }
  1471. Vector2 ToVector2(const aiVector2D& vec)
  1472. {
  1473. return Vector2(vec.x, vec.y);
  1474. }
  1475. Quaternion ToQuaternion(const aiQuaternion& quat)
  1476. {
  1477. return Quaternion(quat.w, quat.x, quat.y, quat.z);
  1478. }
  1479. String SanitateAssetName(const String& name)
  1480. {
  1481. String fixedName = name;
  1482. fixedName.Replace("<", "");
  1483. fixedName.Replace(">", "");
  1484. fixedName.Replace("?", "");
  1485. fixedName.Replace("*", "");
  1486. fixedName.Replace(":", "");
  1487. fixedName.Replace("\"", "");
  1488. fixedName.Replace("/", "");
  1489. fixedName.Replace("\\", "");
  1490. fixedName.Replace("|", "");
  1491. return fixedName;
  1492. }