AssetImporter.cpp 85 KB

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