OpenAssetImporter.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Copyright (c) 2014-2016 THUNDERBEAST GAMES LLC
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. #include <Atomic/Core/ProcessUtils.h>
  25. #include <Atomic/Core/Context.h>
  26. #include <Atomic/IO/Log.h>
  27. #include <Atomic/IO/File.h>
  28. #include <Atomic/IO/FileSystem.h>
  29. #include <Atomic/Resource/XMLFile.h>
  30. #include <Atomic/Resource/ResourceCache.h>
  31. #include <Atomic/Graphics/AnimatedModel.h>
  32. #include <Atomic/Graphics/Animation.h>
  33. #include <Atomic/Graphics/AnimationController.h>
  34. #include <Atomic/Graphics/Geometry.h>
  35. #include <Atomic/Graphics/IndexBuffer.h>
  36. #include <Atomic/Graphics/VertexBuffer.h>
  37. #include <Atomic/Graphics/Material.h>
  38. #include <ToolCore/Project/Project.h>
  39. #include <ToolCore/ToolSystem.h>
  40. #include <ToolCore/Import/ImportConfig.h>
  41. #include "OpenAssetImporter.h"
  42. namespace ToolCore
  43. {
  44. OpenAssetImporter::OpenAssetImporter(Context* context) : Object(context) ,
  45. scene_(0),
  46. rootNode_(0),
  47. useSubdirs_(true),
  48. importMaterials_(true),
  49. importMaterialsDefault_(true),
  50. localIDs_(false),
  51. saveBinary_(false),
  52. createZone_(true),
  53. noAnimations_(false),
  54. noHierarchy_(false),
  55. noMaterials_(false),
  56. noTextures_(false),
  57. noMaterialDiffuseColor_(false),
  58. noEmptyNodes_(false),
  59. saveMaterialList_(false),
  60. includeNonSkinningBones_(false),
  61. includeNonSkinningBonesDefault_(false),
  62. verboseLog_(false),
  63. emissiveAO_(false),
  64. noOverwriteMaterial_(true),
  65. noOverwriteTexture_(true),
  66. noOverwriteNewerTexture_(true),
  67. checkUniqueModel_(true),
  68. useVertexColors_(false),
  69. scale_(1.0f),
  70. maxBones_(64),
  71. defaultTicksPerSecond_(4800.0f),
  72. startTime_(-1),
  73. endTime_(-1)
  74. {
  75. aiFlagsDefault_ =
  76. aiProcess_ConvertToLeftHanded |
  77. aiProcess_JoinIdenticalVertices |
  78. aiProcess_Triangulate |
  79. aiProcess_GenSmoothNormals |
  80. aiProcess_LimitBoneWeights |
  81. aiProcess_ImproveCacheLocality |
  82. aiProcess_FixInfacingNormals |
  83. aiProcess_FindInvalidData |
  84. aiProcess_GenUVCoords |
  85. aiProcess_FindInstances |
  86. aiProcess_OptimizeMeshes;
  87. ApplyProjectImportConfig();
  88. // TODO: make this an option on importer
  89. aiFlagsDefault_ |= aiProcess_CalcTangentSpace;
  90. aiCurrentFlags_ = aiFlagsDefault_;
  91. }
  92. OpenAssetImporter::~OpenAssetImporter()
  93. {
  94. if (scene_)
  95. aiReleaseImport(scene_);
  96. }
  97. bool OpenAssetImporter::Load(const String &assetPath)
  98. {
  99. if (verboseLog_)
  100. Assimp::DefaultLogger::create("", Assimp::Logger::VERBOSE, aiDefaultLogStream_STDOUT);
  101. //PrintLine("Reading file " + assetPath);
  102. sourceAssetPath_ = GetPath(assetPath);
  103. scene_ = aiImportFile(GetNativePath(assetPath).CString(), aiCurrentFlags_);
  104. if (!scene_)
  105. {
  106. errorMessage_ = "Could not open or parse input file " + assetPath + ": " + String(aiGetErrorString());
  107. return false;
  108. }
  109. if (verboseLog_)
  110. Assimp::DefaultLogger::kill();
  111. rootNode_ = scene_->mRootNode;
  112. ApplyScale();
  113. // DumpNodes(rootNode_, 0);
  114. return true;
  115. }
  116. void OpenAssetImporter::ApplyScale(aiNode* node)
  117. {
  118. if (!node)
  119. return;
  120. aiVector3D pos, scale;
  121. aiQuaternion rot;
  122. node->mTransformation.Decompose(scale, rot, pos);
  123. pos *= scale_;
  124. node->mTransformation = aiMatrix4x4(scale, rot, pos);
  125. for (unsigned i = 0; i < node->mNumChildren; i++)
  126. {
  127. ApplyScale(node->mChildren[i]);
  128. }
  129. }
  130. void OpenAssetImporter::ApplyScale()
  131. {
  132. if (scale_ == 1.0f)
  133. return;
  134. ApplyScale(scene_->mRootNode);
  135. for (unsigned i = 0; i < scene_->mNumMeshes; i++)
  136. {
  137. aiMesh* mesh = scene_->mMeshes[i];
  138. for (unsigned j = 0; j < mesh->mNumVertices; j++)
  139. {
  140. mesh->mVertices[j] *= scale_;
  141. }
  142. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  143. {
  144. aiBone* bone = mesh->mBones[j];
  145. aiVector3D pos, scale;
  146. aiQuaternion rot;
  147. bone->mOffsetMatrix.Decompose(scale, rot, pos);
  148. pos *= scale_;
  149. bone->mOffsetMatrix = aiMatrix4x4(scale, rot, pos);
  150. }
  151. }
  152. for (unsigned i = 0; i < scene_->mNumAnimations; i++)
  153. {
  154. aiAnimation* animation = scene_->mAnimations[i];
  155. for (unsigned j = 0; j < animation->mNumChannels; j++)
  156. {
  157. aiNodeAnim* channel = animation->mChannels[j];
  158. for (unsigned k = 0; k < channel->mNumPositionKeys; k++)
  159. {
  160. channel->mPositionKeys[k].mValue *= scale_;
  161. }
  162. }
  163. }
  164. }
  165. bool OpenAssetImporter::ExportModel(const String& outName, const String &animName, bool animationOnly)
  166. {
  167. if (outName.Empty())
  168. {
  169. errorMessage_ = "No output file defined";
  170. return false;
  171. }
  172. OutModel model;
  173. model.rootNode_ = rootNode_;
  174. model.outName_ = outName + ".mdl";
  175. CollectMeshes(scene_, model, model.rootNode_);
  176. if (!CollectBones(model, animationOnly))
  177. return false;
  178. BuildBoneCollisionInfo(model);
  179. if (!animationOnly)
  180. {
  181. if (!BuildAndSaveModel(model))
  182. return false;
  183. }
  184. if (!noAnimations_)
  185. {
  186. CollectAnimations(&model);
  187. if (!BuildAndSaveAnimations(&model, animName))
  188. return false;
  189. // Save scene-global animations
  190. // CollectAnimations();
  191. // BuildAndSaveAnimations();
  192. }
  193. if (!noMaterials_ && !animationOnly)
  194. {
  195. HashSet<String> usedTextures;
  196. ExportMaterials(usedTextures);
  197. }
  198. if (importNode_.Null())
  199. {
  200. errorMessage_ = "NULL importNode_";
  201. return false;
  202. }
  203. ResourceCache* cache = GetSubsystem<ResourceCache>();
  204. Model* mdl = cache->GetResource<Model>( model.outName_);
  205. // Force a reload, though file watchers will catch this delayed and load again
  206. cache->ReloadResource(mdl);
  207. if (!mdl)
  208. {
  209. errorMessage_ = "Unable to load " + model.outName_ + " from Cache";
  210. return false;
  211. }
  212. StaticModel* modelComponent = 0;
  213. if (!mdl->GetSkeleton().GetNumBones())
  214. {
  215. modelComponent = importNode_->CreateComponent<StaticModel>();
  216. modelComponent->SetModel(mdl);
  217. }
  218. else
  219. {
  220. modelComponent = importNode_->CreateComponent<AnimatedModel>();
  221. importNode_->CreateComponent<AnimationController>();
  222. ((AnimatedModel*)modelComponent)->SetModel(mdl, false);
  223. }
  224. if (!noMaterials_)
  225. {
  226. // Set materials if they are known
  227. for (unsigned j = 0; j < model.meshes_.Size(); ++j)
  228. {
  229. String matName = GetMeshMaterialName(model.meshes_[j]);
  230. String materialName = sourceAssetPath_ + matName;
  231. modelComponent->SetMaterial(j, cache->GetResource<Material>(materialName));
  232. }
  233. }
  234. return true;
  235. }
  236. bool OpenAssetImporter::BuildAndSaveModel(OutModel& model)
  237. {
  238. if (!model.rootNode_)
  239. {
  240. errorMessage_ = "Null root node for model";
  241. return false;
  242. }
  243. String rootNodeName = FromAIString(model.rootNode_->mName);
  244. if (!model.meshes_.Size() && !includeNonSkinningBones_)
  245. {
  246. errorMessage_ = "No geometries found starting from node " + rootNodeName;
  247. return false;
  248. }
  249. //PrintLine("Writing model " + rootNodeName);
  250. SharedPtr<Model> outModel(new Model(context_));
  251. Vector<PODVector<unsigned> > allBoneMappings;
  252. BoundingBox box;
  253. unsigned numValidGeometries = 0;
  254. bool combineBuffers = true;
  255. // Check if buffers can be combined (same vertex element mask, under 65535 vertices)
  256. unsigned elementMask = (model.meshes_.Size() > 0) ? GetElementMask(model.meshes_[0]) : 0;
  257. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  258. {
  259. if (GetNumValidFaces(model.meshes_[i]))
  260. {
  261. ++numValidGeometries;
  262. if (i > 0 && GetElementMask(model.meshes_[i]) != elementMask)
  263. combineBuffers = false;
  264. }
  265. }
  266. // Check if keeping separate buffers allows to avoid 32-bit indices
  267. if (combineBuffers && model.totalVertices_ > 65535)
  268. {
  269. bool allUnder65k = true;
  270. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  271. {
  272. if (GetNumValidFaces(model.meshes_[i]))
  273. {
  274. if (model.meshes_[i]->mNumVertices > 65535)
  275. allUnder65k = false;
  276. }
  277. }
  278. if (allUnder65k == true)
  279. combineBuffers = false;
  280. }
  281. SharedPtr<IndexBuffer> ib;
  282. SharedPtr<VertexBuffer> vb;
  283. Vector<SharedPtr<VertexBuffer> > vbVector;
  284. Vector<SharedPtr<IndexBuffer> > ibVector;
  285. unsigned startVertexOffset = 0;
  286. unsigned startIndexOffset = 0;
  287. unsigned destGeomIndex = 0;
  288. outModel->SetNumGeometries(numValidGeometries);
  289. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  290. {
  291. aiMesh* mesh = model.meshes_[i];
  292. unsigned elementMask = GetElementMask(mesh);
  293. unsigned validFaces = GetNumValidFaces(mesh);
  294. if (!validFaces)
  295. continue;
  296. bool largeIndices;
  297. if (combineBuffers)
  298. largeIndices = model.totalIndices_ > 65535;
  299. else
  300. largeIndices = mesh->mNumVertices > 65535;
  301. // Create new buffers if necessary
  302. if (!combineBuffers || vbVector.Empty())
  303. {
  304. vb = new VertexBuffer(context_);
  305. ib = new IndexBuffer(context_);
  306. vb->SetShadowed(true);
  307. ib->SetShadowed(true);
  308. if (combineBuffers)
  309. {
  310. ib->SetSize(model.totalIndices_, largeIndices);
  311. vb->SetSize(model.totalVertices_, elementMask);
  312. }
  313. else
  314. {
  315. ib->SetSize(validFaces * 3, largeIndices);
  316. vb->SetSize(mesh->mNumVertices, elementMask);
  317. }
  318. vbVector.Push(vb);
  319. ibVector.Push(ib);
  320. startVertexOffset = 0;
  321. startIndexOffset = 0;
  322. }
  323. // Get the world transform of the mesh for baking into the vertices
  324. Matrix3x4 vertexTransform;
  325. Matrix3 normalTransform;
  326. Vector3 pos, scale;
  327. Quaternion rot;
  328. GetPosRotScale(GetMeshBakingTransform(model.meshNodes_[i], model.rootNode_), pos, rot, scale);
  329. vertexTransform = Matrix3x4(pos, rot, scale);
  330. normalTransform = rot.RotationMatrix();
  331. SharedPtr<Geometry> geom(new Geometry(context_));
  332. //PrintLine("Writing geometry " + String(i) + " with " + String(mesh->mNumVertices) + " vertices " +
  333. // String(validFaces * 3) + " indices");
  334. unsigned char* vertexData = vb->GetShadowData();
  335. unsigned char* indexData = ib->GetShadowData();
  336. assert(vertexData);
  337. assert(indexData);
  338. // Build the index data
  339. if (!largeIndices)
  340. {
  341. unsigned short* dest = (unsigned short*)indexData + startIndexOffset;
  342. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  343. WriteShortIndices(dest, mesh, j, startVertexOffset);
  344. }
  345. else
  346. {
  347. unsigned* dest = (unsigned*)indexData + startIndexOffset;
  348. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  349. WriteLargeIndices(dest, mesh, j, startVertexOffset);
  350. }
  351. // Build the vertex data
  352. // If there are bones, get blend data
  353. Vector<PODVector<unsigned char> > blendIndices;
  354. Vector<PODVector<float> > blendWeights;
  355. PODVector<unsigned> boneMappings;
  356. if (model.bones_.Size())
  357. {
  358. if (!GetBlendData(model, mesh, boneMappings, blendIndices, blendWeights, errorMessage_, maxBones_))
  359. return false;
  360. }
  361. float* dest = (float*)((unsigned char*)vertexData + startVertexOffset * vb->GetVertexSize());
  362. for (unsigned j = 0; j < mesh->mNumVertices; ++j)
  363. WriteVertex(dest, mesh, j, elementMask, box, vertexTransform, normalTransform, blendIndices, blendWeights);
  364. // Calculate the geometry center
  365. Vector3 center = Vector3::ZERO;
  366. if (validFaces)
  367. {
  368. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  369. {
  370. if (mesh->mFaces[j].mNumIndices == 3)
  371. {
  372. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[0]]);
  373. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[1]]);
  374. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[2]]);
  375. }
  376. }
  377. center /= (float)validFaces * 3;
  378. }
  379. // Define the geometry
  380. geom->SetIndexBuffer(ib);
  381. geom->SetVertexBuffer(0, vb);
  382. geom->SetDrawRange(TRIANGLE_LIST, startIndexOffset, validFaces * 3, true);
  383. outModel->SetNumGeometryLodLevels(destGeomIndex, 1);
  384. outModel->SetGeometry(destGeomIndex, 0, geom);
  385. outModel->SetGeometryCenter(destGeomIndex, center);
  386. outModel->SetGeometryName(destGeomIndex, FromAIString(model.meshNodes_[i]->mName));
  387. if (model.bones_.Size() > maxBones_)
  388. allBoneMappings.Push(boneMappings);
  389. startVertexOffset += mesh->mNumVertices;
  390. startIndexOffset += validFaces * 3;
  391. ++destGeomIndex;
  392. }
  393. // Define the model buffers and bounding box
  394. PODVector<unsigned> emptyMorphRange;
  395. outModel->SetVertexBuffers(vbVector, emptyMorphRange, emptyMorphRange);
  396. outModel->SetIndexBuffers(ibVector);
  397. outModel->SetBoundingBox(box);
  398. // Build skeleton if necessary
  399. if (model.bones_.Size() && model.rootBone_)
  400. {
  401. //PrintLine("Writing skeleton with " + String(model.bones_.Size()) + " bones, rootbone " +
  402. // FromAIString(model.rootBone_->mName));
  403. Skeleton skeleton;
  404. Vector<Bone>& bones = skeleton.GetModifiableBones();
  405. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  406. {
  407. aiNode* boneNode = model.bones_[i];
  408. String boneName(FromAIString(boneNode->mName));
  409. Bone newBone;
  410. newBone.name_ = boneName;
  411. aiMatrix4x4 transform = boneNode->mTransformation;
  412. // Make the root bone transform relative to the model's root node, if it is not already
  413. if (boneNode == model.rootBone_)
  414. transform = GetDerivedTransform(boneNode, model.rootNode_);
  415. GetPosRotScale(transform, newBone.initialPosition_, newBone.initialRotation_, newBone.initialScale_);
  416. // Get offset information if exists
  417. newBone.offsetMatrix_ = GetOffsetMatrix(model, boneName);
  418. newBone.radius_ = model.boneRadii_[i];
  419. newBone.boundingBox_ = model.boneHitboxes_[i];
  420. newBone.collisionMask_ = BONECOLLISION_SPHERE | BONECOLLISION_BOX;
  421. newBone.parentIndex_ = i;
  422. bones.Push(newBone);
  423. }
  424. // Set the bone hierarchy
  425. for (unsigned i = 1; i < model.bones_.Size(); ++i)
  426. {
  427. String parentName = FromAIString(model.bones_[i]->mParent->mName);
  428. for (unsigned j = 0; j < bones.Size(); ++j)
  429. {
  430. if (bones[j].name_ == parentName)
  431. {
  432. bones[i].parentIndex_ = j;
  433. break;
  434. }
  435. }
  436. }
  437. outModel->SetSkeleton(skeleton);
  438. if (model.bones_.Size() > maxBones_)
  439. outModel->SetGeometryBoneMappings(allBoneMappings);
  440. }
  441. File outFile(context_);
  442. if (!outFile.Open(model.outName_, FILE_WRITE))
  443. {
  444. errorMessage_ = "Could not open output file " + model.outName_;
  445. return false;
  446. }
  447. outModel->Save(outFile);
  448. // If exporting materials, also save material list for use by the editor
  449. if (!noMaterials_ && saveMaterialList_)
  450. {
  451. String materialListName = ReplaceExtension(model.outName_, ".txt");
  452. File listFile(context_);
  453. if (listFile.Open(materialListName, FILE_WRITE))
  454. {
  455. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  456. listFile.WriteLine(GetMeshMaterialName(model.meshes_[i]));
  457. }
  458. else
  459. {
  460. PrintLine("Warning: could not write material list file " + materialListName);
  461. }
  462. }
  463. return true;
  464. }
  465. String OpenAssetImporter::GetMeshMaterialName(aiMesh* mesh)
  466. {
  467. aiMaterial* material = scene_->mMaterials[mesh->mMaterialIndex];
  468. aiString matNameStr;
  469. material->Get(AI_MATKEY_NAME, matNameStr);
  470. String matName = SanitateAssetName(FromAIString(matNameStr));
  471. if (matName.Trimmed().Empty())
  472. matName = GenerateMaterialName(material);
  473. return (useSubdirs_ ? "Materials/" : "") + matName + ".material";
  474. }
  475. String OpenAssetImporter::GenerateMaterialName(aiMaterial* material)
  476. {
  477. for (unsigned i = 0; i < scene_->mNumMaterials; ++i)
  478. {
  479. if (scene_->mMaterials[i] == material)
  480. return inputName_ + "_Material" + String(i);
  481. }
  482. // Should not go here
  483. return String::EMPTY;
  484. }
  485. String OpenAssetImporter::GetMaterialTextureName(const String& nameIn)
  486. {
  487. // Detect assimp embedded texture
  488. if (nameIn.Length() && nameIn[0] == '*')
  489. return GenerateTextureName(ToInt(nameIn.Substring(1)));
  490. else
  491. return (useSubdirs_ ? "Textures/" : "") + nameIn;
  492. }
  493. String OpenAssetImporter::GenerateTextureName(unsigned texIndex)
  494. {
  495. if (texIndex < scene_->mNumTextures)
  496. {
  497. // If embedded texture contains encoded data, use the format hint for file extension. Else save RGBA8 data as PNG
  498. aiTexture* tex = scene_->mTextures[texIndex];
  499. if (!tex->mHeight)
  500. return (useSubdirs_ ? "Textures/" : "") + inputName_ + "_Texture" + String(texIndex) + "." + tex->achFormatHint;
  501. else
  502. return (useSubdirs_ ? "Textures/" : "") + inputName_ + "_Texture" + String(texIndex) + ".png";
  503. }
  504. // Should not go here
  505. return String::EMPTY;
  506. }
  507. void OpenAssetImporter::CollectSceneModels(OutScene& scene, aiNode* node)
  508. {
  509. Vector<Pair<aiNode*, aiMesh*> > meshes;
  510. GetMeshesUnderNode(scene_, meshes, node);
  511. if (meshes.Size())
  512. {
  513. OutModel model;
  514. model.rootNode_ = node;
  515. model.outName_ = resourcePath_ + (useSubdirs_ ? "Models/" : "") + SanitateAssetName(FromAIString(node->mName)) + ".mdl";
  516. for (unsigned i = 0; i < meshes.Size(); ++i)
  517. {
  518. aiMesh* mesh = meshes[i].second_;
  519. unsigned meshIndex = GetMeshIndex(scene_, mesh);
  520. model.meshIndices_.Insert(meshIndex);
  521. model.meshes_.Push(mesh);
  522. model.meshNodes_.Push(meshes[i].first_);
  523. model.totalVertices_ += mesh->mNumVertices;
  524. model.totalIndices_ += GetNumValidFaces(mesh) * 3;
  525. }
  526. // Check if a model with identical mesh indices already exists. If yes, do not export twice
  527. bool unique = true;
  528. if (checkUniqueModel_)
  529. {
  530. for (unsigned i = 0; i < scene.models_.Size(); ++i)
  531. {
  532. if (scene.models_[i].meshIndices_ == model.meshIndices_)
  533. {
  534. //PrintLine("Added node " + FromAIString(node->mName));
  535. scene.nodes_.Push(node);
  536. scene.nodeModelIndices_.Push(i);
  537. unique = false;
  538. break;
  539. }
  540. }
  541. }
  542. if (unique)
  543. {
  544. // PrintLine("Added model " + model.outName_);
  545. // PrintLine("Added node " + FromAIString(node->mName));
  546. CollectBones(model);
  547. BuildBoneCollisionInfo(model);
  548. if (!noAnimations_)
  549. {
  550. CollectAnimations(&model);
  551. BuildAndSaveAnimations(&model);
  552. }
  553. scene.models_.Push(model);
  554. scene.nodes_.Push(node);
  555. scene.nodeModelIndices_.Push(scene.models_.Size() - 1);
  556. }
  557. }
  558. for (unsigned i = 0; i < node->mNumChildren; ++i)
  559. CollectSceneModels(scene, node->mChildren[i]);
  560. }
  561. bool OpenAssetImporter::CollectBones(OutModel& model, bool animationOnly)
  562. {
  563. HashSet<aiNode*> necessary;
  564. HashSet<aiNode*> rootNodes;
  565. if (animationOnly && !model.meshes_.Size())
  566. {
  567. aiNode* rootNode = 0;
  568. for (unsigned i = 0; i < scene_->mNumAnimations; ++i)
  569. {
  570. aiAnimation* anim = scene_->mAnimations[i];
  571. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  572. {
  573. aiNodeAnim* channel = anim->mChannels[j];
  574. String channelName = FromAIString(channel->mNodeName);
  575. aiNode* boneNode = GetNode(channelName, scene_->mRootNode, true);
  576. necessary.Insert(boneNode);
  577. rootNode = boneNode;
  578. for (;;)
  579. {
  580. boneNode = boneNode->mParent;
  581. if (!boneNode)// || ((boneNode == meshNode || boneNode == meshParentNode) && !animationOnly))
  582. break;
  583. rootNode = boneNode;
  584. necessary.Insert(boneNode);
  585. }
  586. if (rootNodes.Find(rootNode) == rootNodes.End())
  587. rootNodes.Insert(rootNode);
  588. }
  589. }
  590. }
  591. else
  592. {
  593. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  594. {
  595. aiMesh* mesh = model.meshes_[i];
  596. aiNode* meshNode = model.meshNodes_[i];
  597. aiNode* meshParentNode = meshNode->mParent;
  598. aiNode* rootNode = 0;
  599. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  600. {
  601. aiBone* bone = mesh->mBones[j];
  602. String boneName(FromAIString(bone->mName));
  603. aiNode* boneNode = GetNode(boneName, scene_->mRootNode, true);
  604. if (!boneNode)
  605. {
  606. errorMessage_ = "Could not find scene node for bone " + boneName;
  607. return false;
  608. }
  609. necessary.Insert(boneNode);
  610. rootNode = boneNode;
  611. for (;;)
  612. {
  613. boneNode = boneNode->mParent;
  614. if (!boneNode || ((boneNode == meshNode || boneNode == meshParentNode) && !animationOnly))
  615. break;
  616. rootNode = boneNode;
  617. necessary.Insert(boneNode);
  618. }
  619. if (rootNodes.Find(rootNode) == rootNodes.End())
  620. rootNodes.Insert(rootNode);
  621. }
  622. }
  623. }
  624. // If we find multiple root nodes, try to remedy by using their parent instead
  625. if (rootNodes.Size() > 1)
  626. {
  627. aiNode* commonParent = (*rootNodes.Begin())->mParent;
  628. for (HashSet<aiNode*>::Iterator i = rootNodes.Begin(); i != rootNodes.End(); ++i)
  629. {
  630. if (*i != commonParent)
  631. {
  632. if (!commonParent || (*i)->mParent != commonParent)
  633. {
  634. errorMessage_ = "Skeleton with multiple root nodes found, not supported";
  635. return false;
  636. }
  637. }
  638. }
  639. rootNodes.Clear();
  640. rootNodes.Insert(commonParent);
  641. necessary.Insert(commonParent);
  642. }
  643. if (rootNodes.Empty())
  644. return true;
  645. model.rootBone_ = *rootNodes.Begin();
  646. CollectBonesFinal(model.bones_, necessary, model.rootBone_);
  647. // Initialize the bone collision info
  648. model.boneRadii_.Resize(model.bones_.Size());
  649. model.boneHitboxes_.Resize(model.bones_.Size());
  650. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  651. {
  652. model.boneRadii_[i] = 0.0f;
  653. model.boneHitboxes_[i] = BoundingBox(0.0f, 0.0f);
  654. }
  655. return true;
  656. }
  657. void OpenAssetImporter::CollectBonesFinal(PODVector<aiNode*>& dest, const HashSet<aiNode*>& necessary, aiNode* node)
  658. {
  659. bool includeBone = necessary.Find(node) != necessary.End();
  660. String boneName = FromAIString(node->mName);
  661. // Check include/exclude filters for non-skinned bones
  662. if (!includeBone && includeNonSkinningBones_)
  663. {
  664. // If no includes specified, include by default but check for excludes
  665. if (nonSkinningBoneIncludes_.Empty())
  666. includeBone = true;
  667. // Check against includes/excludes
  668. for (unsigned i = 0; i < nonSkinningBoneIncludes_.Size(); ++i)
  669. {
  670. if (boneName.Contains(nonSkinningBoneIncludes_[i], false))
  671. {
  672. includeBone = true;
  673. break;
  674. }
  675. }
  676. for (unsigned i = 0; i < nonSkinningBoneExcludes_.Size(); ++i)
  677. {
  678. if (boneName.Contains(nonSkinningBoneExcludes_[i], false))
  679. {
  680. includeBone = false;
  681. break;
  682. }
  683. }
  684. if (includeBone)
  685. {
  686. //PrintLine("Including non-skinning bone " + boneName);
  687. }
  688. }
  689. if (includeBone)
  690. dest.Push(node);
  691. for (unsigned i = 0; i < node->mNumChildren; ++i)
  692. CollectBonesFinal(dest, necessary, node->mChildren[i]);
  693. }
  694. void OpenAssetImporter::CollectAnimations(OutModel* model)
  695. {
  696. const aiScene* scene = scene_;
  697. for (unsigned i = 0; i < scene->mNumAnimations; ++i)
  698. {
  699. aiAnimation* anim = scene->mAnimations[i];
  700. if (allAnimations_.Contains(anim))
  701. continue;
  702. if (model)
  703. {
  704. bool modelBoneFound = false;
  705. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  706. {
  707. aiNodeAnim* channel = anim->mChannels[j];
  708. String channelName = FromAIString(channel->mNodeName);
  709. if (GetBoneIndex(*model, channelName) != M_MAX_UNSIGNED)
  710. {
  711. modelBoneFound = true;
  712. break;
  713. }
  714. }
  715. if (modelBoneFound)
  716. {
  717. model->animations_.Push(anim);
  718. allAnimations_.Insert(anim);
  719. }
  720. }
  721. else
  722. {
  723. sceneAnimations_.Push(anim);
  724. allAnimations_.Insert(anim);
  725. }
  726. }
  727. /// \todo Vertex morphs are ignored for now
  728. }
  729. void OpenAssetImporter::ApplyFlag(int flag, bool active)
  730. {
  731. aiFlagsDefault_ &= ~flag;
  732. if (active)
  733. aiFlagsDefault_ |= flag;
  734. }
  735. void OpenAssetImporter::SetOveriddenFlags(VariantMap& aiFlagParameters)
  736. {
  737. VariantMap::ConstIterator itr = aiFlagParameters.Begin();
  738. while (itr != aiFlagParameters.End())
  739. {
  740. if (itr->first_ == "aiProcess_ConvertToLeftHanded")
  741. ApplyFlag(aiProcess_ConvertToLeftHanded, itr->second_.GetBool());
  742. else if (itr->first_ == "aiProcess_JoinIdenticalVertices")
  743. ApplyFlag(aiProcess_JoinIdenticalVertices, itr->second_.GetBool());
  744. else if (itr->first_ == "aiProcess_Triangulate")
  745. ApplyFlag(aiProcess_Triangulate, itr->second_.GetBool());
  746. else if (itr->first_ == "aiProcess_GenSmoothNormals")
  747. ApplyFlag(aiProcess_GenSmoothNormals, itr->second_.GetBool());
  748. else if (itr->first_ == "aiProcess_LimitBoneWeights")
  749. ApplyFlag(aiProcess_LimitBoneWeights, itr->second_.GetBool());
  750. else if (itr->first_ == "aiProcess_ImproveCacheLocality")
  751. ApplyFlag(aiProcess_ImproveCacheLocality, itr->second_.GetBool());
  752. else if (itr->first_ == "aiProcess_FixInfacingNormals")
  753. ApplyFlag(aiProcess_FixInfacingNormals, itr->second_.GetBool());
  754. else if (itr->first_ == "aiProcess_FindInvalidData")
  755. ApplyFlag(aiProcess_FindInvalidData, itr->second_.GetBool());
  756. else if (itr->first_ == "aiProcess_GenUVCoords")
  757. ApplyFlag(aiProcess_GenUVCoords, itr->second_.GetBool());
  758. else if (itr->first_ == "aiProcess_FindInstances")
  759. ApplyFlag(aiProcess_FindInstances, itr->second_.GetBool());
  760. else if (itr->first_ == "aiProcess_OptimizeMeshes")
  761. ApplyFlag(aiProcess_OptimizeMeshes, itr->second_.GetBool());
  762. else if (itr->first_ == "ImportMaterials")
  763. importMaterialsDefault_ = itr->second_.GetBool();
  764. else if (itr->first_ == "IncludeNonSkinningBones")
  765. includeNonSkinningBonesDefault_ = itr->second_.GetBool();
  766. else if (itr->first_ == "useVertexColors")
  767. useVertexColors_ = itr->second_.GetBool();
  768. itr++;
  769. }
  770. }
  771. void OpenAssetImporter::ApplyProjectImportConfig()
  772. {
  773. if (ImportConfig::IsLoaded())
  774. {
  775. VariantMap aiFlagParameters;
  776. ImportConfig::ApplyConfig(aiFlagParameters);
  777. SetOveriddenFlags(aiFlagParameters);
  778. }
  779. }
  780. void OpenAssetImporter::BuildBoneCollisionInfo(OutModel& model)
  781. {
  782. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  783. {
  784. aiMesh* mesh = model.meshes_[i];
  785. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  786. {
  787. aiBone* bone = mesh->mBones[j];
  788. String boneName = FromAIString(bone->mName);
  789. unsigned boneIndex = GetBoneIndex(model, boneName);
  790. if (boneIndex == M_MAX_UNSIGNED)
  791. continue;
  792. for (unsigned k = 0; k < bone->mNumWeights; ++k)
  793. {
  794. float weight = bone->mWeights[k].mWeight;
  795. // Require skinning weight to be sufficiently large before vertex contributes to bone hitbox
  796. if (weight > 0.33f)
  797. {
  798. aiVector3D vertexBoneSpace = bone->mOffsetMatrix * mesh->mVertices[bone->mWeights[k].mVertexId];
  799. Vector3 vertex = ToVector3(vertexBoneSpace);
  800. float radius = vertex.Length();
  801. if (radius > model.boneRadii_[boneIndex])
  802. model.boneRadii_[boneIndex] = radius;
  803. model.boneHitboxes_[boneIndex].Merge(vertex);
  804. }
  805. }
  806. }
  807. }
  808. }
  809. bool OpenAssetImporter::BuildAndSaveAnimations(OutModel* model, const String &animNameOverride)
  810. {
  811. const PODVector<aiAnimation*>& animations = model ? model->animations_ : sceneAnimations_;
  812. for (unsigned i = 0; i < animations.Size(); ++i)
  813. {
  814. aiAnimation* anim = animations[i];
  815. float duration = (float)anim->mDuration;
  816. String animName = FromAIString(anim->mName);
  817. String animOutName;
  818. if (animName.Empty())
  819. animName = "Anim" + String(i + 1);
  820. if (model)
  821. animOutName = GetPath(model->outName_) + GetFileName(model->outName_) + "_" + SanitateAssetName(animName) + ".ani";
  822. else
  823. animOutName = outPath_ + SanitateAssetName(animName) + ".ani";
  824. if (animNameOverride.Length())
  825. {
  826. animOutName = GetPath(model->outName_) + GetFileName(model->outName_) + "_" + animNameOverride + ".ani";
  827. }
  828. float ticksPerSecond = (float)anim->mTicksPerSecond;
  829. // If ticks per second not specified, it's probably a .X file. In this case use the default tick rate
  830. if (ticksPerSecond < M_EPSILON)
  831. ticksPerSecond = defaultTicksPerSecond_;
  832. float tickConversion = 1.0f / ticksPerSecond;
  833. float startTime;
  834. if (startTime_ >= 0.0 && endTime_ >= 0.0)
  835. {
  836. startTime = startTime_;
  837. duration = endTime_ - startTime_;
  838. }
  839. else
  840. {
  841. // Find out the start time of animation from each channel's first keyframe for adjusting the keyframe times
  842. // to start from zero
  843. startTime = duration;
  844. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  845. {
  846. aiNodeAnim* channel = anim->mChannels[j];
  847. if (channel->mNumPositionKeys > 0)
  848. startTime = Min(startTime, (float)channel->mPositionKeys[0].mTime);
  849. if (channel->mNumRotationKeys > 0)
  850. startTime = Min(startTime, (float)channel->mRotationKeys[0].mTime);
  851. if (channel->mScalingKeys > 0)
  852. startTime = Min(startTime, (float)channel->mScalingKeys[0].mTime);
  853. }
  854. duration -= startTime;
  855. }
  856. SharedPtr<Animation> outAnim(new Animation(context_));
  857. outAnim->SetAnimationName(!animNameOverride.Length() ? animName : animNameOverride);
  858. outAnim->SetLength(duration * tickConversion);
  859. //PrintLine("Writing animation " + animName + " length " + String(outAnim->GetLength()));
  860. Vector<AnimationTrack> tracks;
  861. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  862. {
  863. aiNodeAnim* channel = anim->mChannels[j];
  864. String channelName = FromAIString(channel->mNodeName);
  865. aiNode* boneNode = 0;
  866. bool isRootBone = false;
  867. if (model)
  868. {
  869. unsigned boneIndex = GetBoneIndex(*model, channelName);
  870. if (boneIndex == M_MAX_UNSIGNED)
  871. {
  872. PrintLine("Warning: skipping animation track " + channelName + " not found in model skeleton");
  873. continue;
  874. }
  875. boneNode = model->bones_[boneIndex];
  876. isRootBone = boneIndex == 0;
  877. }
  878. else
  879. {
  880. boneNode = GetNode(channelName, scene_->mRootNode);
  881. if (!boneNode)
  882. {
  883. PrintLine("Warning: skipping animation track " + channelName + " whose scene node was not found");
  884. continue;
  885. }
  886. }
  887. // To export single frame animation, check if first key frame is identical to bone transformation
  888. aiVector3D bonePos, boneScale;
  889. aiQuaternion boneRot;
  890. boneNode->mTransformation.Decompose(boneScale, boneRot, bonePos);
  891. bool posEqual = true;
  892. bool scaleEqual = true;
  893. bool rotEqual = true;
  894. if (channel->mNumPositionKeys > 0 && !ToVector3(bonePos).Equals(ToVector3(channel->mPositionKeys[0].mValue)))
  895. posEqual = false;
  896. if (channel->mNumScalingKeys > 0 && !ToVector3(boneScale).Equals(ToVector3(channel->mScalingKeys[0].mValue)))
  897. scaleEqual = false;
  898. if (channel->mNumRotationKeys > 0 && !ToQuaternion(boneRot).Equals(ToQuaternion(channel->mRotationKeys[0].mValue)))
  899. rotEqual = false;
  900. AnimationTrack track;
  901. track.name_ = channelName;
  902. track.nameHash_ = channelName;
  903. // Check which channels are used
  904. track.channelMask_ = 0;
  905. if (channel->mNumPositionKeys > 1 || !posEqual)
  906. track.channelMask_ |= CHANNEL_POSITION;
  907. if (channel->mNumRotationKeys > 1 || !rotEqual)
  908. track.channelMask_ |= CHANNEL_ROTATION;
  909. if (channel->mNumScalingKeys > 1 || !scaleEqual)
  910. track.channelMask_ |= CHANNEL_SCALE;
  911. // Check for redundant identity scale in all keyframes and remove in that case
  912. if (track.channelMask_ & CHANNEL_SCALE)
  913. {
  914. bool redundantScale = true;
  915. for (unsigned k = 0; k < channel->mNumScalingKeys; ++k)
  916. {
  917. float SCALE_EPSILON = 0.000001f;
  918. Vector3 scaleVec = ToVector3(channel->mScalingKeys[k].mValue);
  919. if (fabsf(scaleVec.x_ - 1.0f) >= SCALE_EPSILON || fabsf(scaleVec.y_ - 1.0f) >= SCALE_EPSILON ||
  920. fabsf(scaleVec.z_ - 1.0f) >= SCALE_EPSILON)
  921. {
  922. redundantScale = false;
  923. break;
  924. }
  925. }
  926. if (redundantScale)
  927. track.channelMask_ &= ~CHANNEL_SCALE;
  928. }
  929. if (!track.channelMask_)
  930. PrintLine("Warning: skipping animation track " + channelName + " with no keyframes");
  931. // Currently only same amount of keyframes is supported
  932. // Note: should also check the times of individual keyframes for match
  933. if ((channel->mNumPositionKeys > 1 && channel->mNumRotationKeys > 1 && channel->mNumPositionKeys != channel->mNumRotationKeys) ||
  934. (channel->mNumPositionKeys > 1 && channel->mNumScalingKeys > 1 && channel->mNumPositionKeys != channel->mNumScalingKeys) ||
  935. (channel->mNumRotationKeys > 1 && channel->mNumScalingKeys > 1 && channel->mNumRotationKeys != channel->mNumScalingKeys))
  936. {
  937. PrintLine("Warning: differing amounts of channel keyframes, skipping animation track " + channelName);
  938. continue;
  939. }
  940. unsigned keyFrames = channel->mNumPositionKeys;
  941. if (channel->mNumRotationKeys > keyFrames)
  942. keyFrames = channel->mNumRotationKeys;
  943. if (channel->mNumScalingKeys > keyFrames)
  944. keyFrames = channel->mNumScalingKeys;
  945. for (unsigned k = 0; k < keyFrames; ++k)
  946. {
  947. AnimationKeyFrame kf;
  948. kf.time_ = 0.0f;
  949. kf.position_ = Vector3::ZERO;
  950. kf.rotation_ = Quaternion::IDENTITY;
  951. kf.scale_ = Vector3::ONE;
  952. // Get time for the keyframe. Adjust with animation's start time
  953. if (track.channelMask_ & CHANNEL_POSITION && k < channel->mNumPositionKeys)
  954. kf.time_ = ((float)channel->mPositionKeys[k].mTime - startTime) * tickConversion;
  955. else if (track.channelMask_ & CHANNEL_ROTATION && k < channel->mNumRotationKeys)
  956. kf.time_ = ((float)channel->mRotationKeys[k].mTime - startTime) * tickConversion;
  957. else if (track.channelMask_ & CHANNEL_SCALE && k < channel->mNumScalingKeys)
  958. kf.time_ = ((float)channel->mScalingKeys[k].mTime - startTime) * tickConversion;
  959. // Make sure time stays positive
  960. kf.time_ = Max(kf.time_, 0.0f);
  961. // Start with the bone's base transform
  962. aiMatrix4x4 boneTransform = boneNode->mTransformation;
  963. aiVector3D pos, scale;
  964. aiQuaternion rot;
  965. boneTransform.Decompose(scale, rot, pos);
  966. // Then apply the active channels
  967. if (track.channelMask_ & CHANNEL_POSITION && k < channel->mNumPositionKeys)
  968. pos = channel->mPositionKeys[k].mValue;
  969. if (track.channelMask_ & CHANNEL_ROTATION && k < channel->mNumRotationKeys)
  970. rot = channel->mRotationKeys[k].mValue;
  971. if (track.channelMask_ & CHANNEL_SCALE && k < channel->mNumScalingKeys)
  972. scale = channel->mScalingKeys[k].mValue;
  973. // If root bone, transform with the model root node transform
  974. if (model && isRootBone)
  975. {
  976. aiMatrix4x4 transMat, scaleMat, rotMat;
  977. aiMatrix4x4::Translation(pos, transMat);
  978. aiMatrix4x4::Scaling(scale, scaleMat);
  979. rotMat = aiMatrix4x4(rot.GetMatrix());
  980. aiMatrix4x4 tform = transMat * rotMat * scaleMat;
  981. tform = GetDerivedTransform(tform, boneNode, model->rootNode_);
  982. tform.Decompose(scale, rot, pos);
  983. }
  984. if (track.channelMask_ & CHANNEL_POSITION)
  985. kf.position_ = ToVector3(pos);
  986. if (track.channelMask_ & CHANNEL_ROTATION)
  987. kf.rotation_ = ToQuaternion(rot);
  988. if (track.channelMask_ & CHANNEL_SCALE)
  989. kf.scale_ = ToVector3(scale);
  990. track.keyFrames_.Push(kf);
  991. }
  992. tracks.Push(track);
  993. }
  994. outAnim->SetTracks(tracks);
  995. File outFile(context_);
  996. if (!outFile.Open(animOutName, FILE_WRITE))
  997. {
  998. errorMessage_ = "Could not open output file " + animOutName;
  999. return false;
  1000. }
  1001. outAnim->Save(outFile);
  1002. AnimationInfo info;
  1003. info.name_ = SanitateAssetName(animName);
  1004. info.cacheFilename_ = animOutName;
  1005. animationInfos_.Push(info);
  1006. }
  1007. return true;
  1008. }
  1009. // Materials
  1010. void OpenAssetImporter::ExportMaterials(HashSet<String>& usedTextures)
  1011. {
  1012. if (importMaterials_ )
  1013. {
  1014. if (useSubdirs_)
  1015. {
  1016. context_->GetSubsystem<FileSystem>()->CreateDir(sourceAssetPath_ + "Materials");
  1017. }
  1018. for (unsigned i = 0; i < scene_->mNumMaterials; ++i)
  1019. BuildAndSaveMaterial(scene_->mMaterials[i], usedTextures);
  1020. }
  1021. }
  1022. bool OpenAssetImporter::BuildAndSaveMaterial(aiMaterial* material, HashSet<String>& usedTextures)
  1023. {
  1024. aiString matNameStr;
  1025. material->Get(AI_MATKEY_NAME, matNameStr);
  1026. String matName = SanitateAssetName(FromAIString(matNameStr));
  1027. if (matName.Trimmed().Empty())
  1028. matName = GenerateMaterialName(material);
  1029. // Do not actually create a material instance, but instead craft an xml file manually
  1030. XMLFile outMaterial(context_);
  1031. XMLElement materialElem = outMaterial.CreateRoot("material");
  1032. String diffuseTexName;
  1033. String normalTexName;
  1034. String specularTexName;
  1035. String lightmapTexName;
  1036. String emissiveTexName;
  1037. Color diffuseColor = Color::WHITE;
  1038. Color specularColor;
  1039. Color emissiveColor = Color::BLACK;
  1040. bool hasAlpha = false;
  1041. bool twoSided = false;
  1042. float specPower = 1.0f;
  1043. aiString stringVal;
  1044. float floatVal;
  1045. int intVal;
  1046. aiColor3D colorVal;
  1047. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_DIFFUSE, 0), stringVal) == AI_SUCCESS)
  1048. diffuseTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1049. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_NORMALS, 0), stringVal) == AI_SUCCESS)
  1050. normalTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1051. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_SPECULAR, 0), stringVal) == AI_SUCCESS)
  1052. specularTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1053. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_LIGHTMAP, 0), stringVal) == AI_SUCCESS)
  1054. specularTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1055. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_EMISSIVE, 0), stringVal) == AI_SUCCESS)
  1056. emissiveTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1057. diffuseTexName.Replace(".tif", ".png");
  1058. if (!noMaterialDiffuseColor_)
  1059. {
  1060. if (material->Get(AI_MATKEY_COLOR_DIFFUSE, colorVal) == AI_SUCCESS)
  1061. diffuseColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1062. }
  1063. if (material->Get(AI_MATKEY_COLOR_SPECULAR, colorVal) == AI_SUCCESS)
  1064. specularColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1065. if (!emissiveAO_)
  1066. {
  1067. // if (material->Get(AI_MATKEY_COLOR_EMISSIVE, colorVal) == AI_SUCCESS)
  1068. // emissiveColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1069. }
  1070. if (material->Get(AI_MATKEY_OPACITY, floatVal) == AI_SUCCESS)
  1071. {
  1072. if (floatVal < 1.0f)
  1073. hasAlpha = true;
  1074. diffuseColor.a_ = floatVal;
  1075. }
  1076. if (material->Get(AI_MATKEY_SHININESS, floatVal) == AI_SUCCESS)
  1077. specPower = floatVal;
  1078. if (material->Get(AI_MATKEY_TWOSIDED, intVal) == AI_SUCCESS)
  1079. twoSided = (intVal != 0);
  1080. String techniqueName = "Techniques/NoTexture";
  1081. if (!diffuseTexName.Empty())
  1082. {
  1083. techniqueName = "Techniques/Diff";
  1084. if (!normalTexName.Empty())
  1085. techniqueName += "Normal";
  1086. if (!specularTexName.Empty())
  1087. techniqueName += "Spec";
  1088. // For now lightmap does not coexist with normal & specular
  1089. if (normalTexName.Empty() && specularTexName.Empty() && !lightmapTexName.Empty())
  1090. techniqueName += "LightMap";
  1091. if (lightmapTexName.Empty() && !emissiveTexName.Empty())
  1092. techniqueName += emissiveAO_ ? "AO" : "Emissive";
  1093. }
  1094. if (hasAlpha)
  1095. techniqueName += "Alpha";
  1096. // See if any mesh that uses this material has vertex colors
  1097. // and set the technique accordingly, if enabled
  1098. for (unsigned i = 0; i < scene_->mNumMeshes && useVertexColors_; i++)
  1099. {
  1100. aiMesh* mesh = scene_->mMeshes[i];
  1101. aiMaterial* mesh_material = scene_->mMaterials[mesh->mMaterialIndex];
  1102. aiString meshMatNameStr;
  1103. mesh_material->Get(AI_MATKEY_NAME, meshMatNameStr);
  1104. if(mesh->GetNumColorChannels() > 0)
  1105. {
  1106. if(matNameStr == meshMatNameStr)
  1107. {
  1108. techniqueName += "VCol";
  1109. break;
  1110. }
  1111. }
  1112. }
  1113. XMLElement techniqueElem = materialElem.CreateChild("technique");
  1114. techniqueElem.SetString("name", techniqueName + ".xml");
  1115. if (!diffuseTexName.Empty())
  1116. {
  1117. XMLElement diffuseElem = materialElem.CreateChild("texture");
  1118. diffuseElem.SetString("unit", "diffuse");
  1119. diffuseElem.SetString("name", GetMaterialTextureName(diffuseTexName));
  1120. usedTextures.Insert(diffuseTexName);
  1121. }
  1122. if (!normalTexName.Empty())
  1123. {
  1124. XMLElement normalElem = materialElem.CreateChild("texture");
  1125. normalElem.SetString("unit", "normal");
  1126. normalElem.SetString("name", GetMaterialTextureName(normalTexName));
  1127. usedTextures.Insert(normalTexName);
  1128. }
  1129. if (!specularTexName.Empty())
  1130. {
  1131. XMLElement specularElem = materialElem.CreateChild("texture");
  1132. specularElem.SetString("unit", "specular");
  1133. specularElem.SetString("name", GetMaterialTextureName(specularTexName));
  1134. usedTextures.Insert(specularTexName);
  1135. }
  1136. if (!lightmapTexName.Empty())
  1137. {
  1138. XMLElement lightmapElem = materialElem.CreateChild("texture");
  1139. lightmapElem.SetString("unit", "emissive");
  1140. lightmapElem.SetString("name", GetMaterialTextureName(lightmapTexName));
  1141. usedTextures.Insert(lightmapTexName);
  1142. }
  1143. if (!emissiveTexName.Empty())
  1144. {
  1145. XMLElement emissiveElem = materialElem.CreateChild("texture");
  1146. emissiveElem.SetString("unit", "emissive");
  1147. emissiveElem.SetString("name", GetMaterialTextureName(emissiveTexName));
  1148. usedTextures.Insert(emissiveTexName);
  1149. }
  1150. XMLElement diffuseColorElem = materialElem.CreateChild("parameter");
  1151. diffuseColorElem.SetString("name", "MatDiffColor");
  1152. diffuseColorElem.SetColor("value", diffuseColor);
  1153. XMLElement specularElem = materialElem.CreateChild("parameter");
  1154. specularElem.SetString("name", "MatSpecColor");
  1155. specularElem.SetVector4("value", Vector4(specularColor.r_, specularColor.g_, specularColor.b_, specPower));
  1156. XMLElement emissiveColorElem = materialElem.CreateChild("parameter");
  1157. emissiveColorElem.SetString("name", "MatEmissiveColor");
  1158. emissiveColorElem.SetColor("value", emissiveColor);
  1159. if (twoSided)
  1160. {
  1161. XMLElement cullElem = materialElem.CreateChild("cull");
  1162. XMLElement shadowCullElem = materialElem.CreateChild("shadowcull");
  1163. cullElem.SetString("value", "none");
  1164. shadowCullElem.SetString("value", "none");
  1165. }
  1166. FileSystem* fileSystem = context_->GetSubsystem<FileSystem>();
  1167. String outFileName = sourceAssetPath_ + (useSubdirs_ ? "Materials/" : "" ) + matName + ".material";
  1168. if (noOverwriteMaterial_ && fileSystem->FileExists(outFileName))
  1169. {
  1170. PrintLine("Skipping save of existing material " + matName);
  1171. return true;
  1172. }
  1173. PrintLine("Writing material " + matName);
  1174. File outFile(context_);
  1175. if (!outFile.Open(outFileName, FILE_WRITE))
  1176. {
  1177. errorMessage_ = "Could not open output file " + outFileName;
  1178. return false;
  1179. }
  1180. outMaterial.Save(outFile);
  1181. return true;
  1182. }
  1183. void OpenAssetImporter::DumpNodes(aiNode* rootNode, unsigned level)
  1184. {
  1185. if (!rootNode)
  1186. return;
  1187. String indent(' ', level * 2);
  1188. Vector3 pos, scale;
  1189. Quaternion rot;
  1190. aiMatrix4x4 transform = GetDerivedTransform(rootNode, rootNode_);
  1191. GetPosRotScale(transform, pos, rot, scale);
  1192. PrintLine(indent + "Node " + FromAIString(rootNode->mName) + " pos " + String(pos));
  1193. if (rootNode->mNumMeshes == 1)
  1194. PrintLine(indent + " " + String(rootNode->mNumMeshes) + " geometry");
  1195. if (rootNode->mNumMeshes > 1)
  1196. PrintLine(indent + " " + String(rootNode->mNumMeshes) + " geometries");
  1197. for (unsigned i = 0; i < rootNode->mNumChildren; ++i)
  1198. DumpNodes(rootNode->mChildren[i], level + 1);
  1199. }
  1200. }