AssetImporter.cpp 81 KB

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