AssetImporter.cpp 76 KB

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