OpenAssetImporter.cpp 47 KB

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