AssetImporter.cpp 76 KB

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