OpenAssetImporter.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327
  1. //
  2. // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
  3. // LICENSE: Atomic Game Engine Editor and Tools EULA
  4. // Please see LICENSE_ATOMIC_EDITOR_AND_TOOLS.md in repository root for
  5. // license information: https://github.com/AtomicGameEngine/AtomicGameEngine
  6. //
  7. //
  8. // Copyright (c) 2008-2015 the Urho3D project.
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining a copy
  11. // of this software and associated documentation files (the "Software"), to deal
  12. // in the Software without restriction, including without limitation the rights
  13. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14. // copies of the Software, and to permit persons to whom the Software is
  15. // furnished to do so, subject to the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be included in
  18. // all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  22. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  23. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  24. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  25. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  26. // THE SOFTWARE.
  27. //
  28. #include <Atomic/Core/ProcessUtils.h>
  29. #include <Atomic/Core/Context.h>
  30. #include <Atomic/IO/Log.h>
  31. #include <Atomic/IO/File.h>
  32. #include <Atomic/IO/FileSystem.h>
  33. #include <Atomic/Resource/XMLFile.h>
  34. #include <Atomic/Resource/ResourceCache.h>
  35. #include <Atomic/Atomic3D/AnimatedModel.h>
  36. #include <Atomic/Atomic3D/Animation.h>
  37. #include <Atomic/Atomic3D/AnimationController.h>
  38. #include <Atomic/Graphics/Geometry.h>
  39. #include <Atomic/Graphics/IndexBuffer.h>
  40. #include <Atomic/Graphics/VertexBuffer.h>
  41. #include <Atomic/Graphics/Material.h>
  42. #include "OpenAssetImporter.h"
  43. namespace ToolCore
  44. {
  45. OpenAssetImporter::OpenAssetImporter(Context* context) : Object(context) ,
  46. scene_(0),
  47. rootNode_(0),
  48. useSubdirs_(true),
  49. localIDs_(false),
  50. saveBinary_(false),
  51. createZone_(true),
  52. noAnimations_(false),
  53. noHierarchy_(false),
  54. noMaterials_(false),
  55. noTextures_(false),
  56. noMaterialDiffuseColor_(false),
  57. noEmptyNodes_(false),
  58. saveMaterialList_(false),
  59. includeNonSkinningBones_(false),
  60. verboseLog_(false),
  61. emissiveAO_(false),
  62. noOverwriteMaterial_(true),
  63. noOverwriteTexture_(true),
  64. noOverwriteNewerTexture_(true),
  65. checkUniqueModel_(true),
  66. scale_(1.0f),
  67. maxBones_(64),
  68. defaultTicksPerSecond_(4800.0f),
  69. startTime_(-1),
  70. endTime_(-1)
  71. {
  72. aiFlagsDefault_ =
  73. aiProcess_ConvertToLeftHanded |
  74. aiProcess_JoinIdenticalVertices |
  75. aiProcess_Triangulate |
  76. aiProcess_GenSmoothNormals |
  77. aiProcess_LimitBoneWeights |
  78. aiProcess_ImproveCacheLocality |
  79. aiProcess_FixInfacingNormals |
  80. aiProcess_FindInvalidData |
  81. aiProcess_GenUVCoords |
  82. aiProcess_FindInstances |
  83. aiProcess_OptimizeMeshes;
  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::BuildBoneCollisionInfo(OutModel& model)
  726. {
  727. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  728. {
  729. aiMesh* mesh = model.meshes_[i];
  730. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  731. {
  732. aiBone* bone = mesh->mBones[j];
  733. String boneName = FromAIString(bone->mName);
  734. unsigned boneIndex = GetBoneIndex(model, boneName);
  735. if (boneIndex == M_MAX_UNSIGNED)
  736. continue;
  737. for (unsigned k = 0; k < bone->mNumWeights; ++k)
  738. {
  739. float weight = bone->mWeights[k].mWeight;
  740. // Require skinning weight to be sufficiently large before vertex contributes to bone hitbox
  741. if (weight > 0.33f)
  742. {
  743. aiVector3D vertexBoneSpace = bone->mOffsetMatrix * mesh->mVertices[bone->mWeights[k].mVertexId];
  744. Vector3 vertex = ToVector3(vertexBoneSpace);
  745. float radius = vertex.Length();
  746. if (radius > model.boneRadii_[boneIndex])
  747. model.boneRadii_[boneIndex] = radius;
  748. model.boneHitboxes_[boneIndex].Merge(vertex);
  749. }
  750. }
  751. }
  752. }
  753. }
  754. bool OpenAssetImporter::BuildAndSaveAnimations(OutModel* model, const String &animNameOverride)
  755. {
  756. const PODVector<aiAnimation*>& animations = model ? model->animations_ : sceneAnimations_;
  757. for (unsigned i = 0; i < animations.Size(); ++i)
  758. {
  759. aiAnimation* anim = animations[i];
  760. float duration = (float)anim->mDuration;
  761. String animName = FromAIString(anim->mName);
  762. String animOutName;
  763. if (animName.Empty())
  764. animName = "Anim" + String(i + 1);
  765. if (model)
  766. animOutName = GetPath(model->outName_) + GetFileName(model->outName_) + "_" + SanitateAssetName(animName) + ".ani";
  767. else
  768. animOutName = outPath_ + SanitateAssetName(animName) + ".ani";
  769. if (animNameOverride.Length())
  770. {
  771. animOutName = GetPath(model->outName_) + GetFileName(model->outName_) + "_" + animNameOverride + ".ani";
  772. }
  773. float ticksPerSecond = (float)anim->mTicksPerSecond;
  774. // If ticks per second not specified, it's probably a .X file. In this case use the default tick rate
  775. if (ticksPerSecond < M_EPSILON)
  776. ticksPerSecond = defaultTicksPerSecond_;
  777. float tickConversion = 1.0f / ticksPerSecond;
  778. float startTime;
  779. if (startTime_ >= 0.0 && endTime_ >= 0.0)
  780. {
  781. startTime = startTime_;
  782. duration = endTime_ - startTime_;
  783. }
  784. else
  785. {
  786. // Find out the start time of animation from each channel's first keyframe for adjusting the keyframe times
  787. // to start from zero
  788. startTime = duration;
  789. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  790. {
  791. aiNodeAnim* channel = anim->mChannels[j];
  792. if (channel->mNumPositionKeys > 0)
  793. startTime = Min(startTime, (float)channel->mPositionKeys[0].mTime);
  794. if (channel->mNumRotationKeys > 0)
  795. startTime = Min(startTime, (float)channel->mRotationKeys[0].mTime);
  796. if (channel->mScalingKeys > 0)
  797. startTime = Min(startTime, (float)channel->mScalingKeys[0].mTime);
  798. }
  799. duration -= startTime;
  800. }
  801. SharedPtr<Animation> outAnim(new Animation(context_));
  802. outAnim->SetAnimationName(!animNameOverride.Length() ? animName : animNameOverride);
  803. outAnim->SetLength(duration * tickConversion);
  804. //PrintLine("Writing animation " + animName + " length " + String(outAnim->GetLength()));
  805. Vector<AnimationTrack> tracks;
  806. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  807. {
  808. aiNodeAnim* channel = anim->mChannels[j];
  809. String channelName = FromAIString(channel->mNodeName);
  810. aiNode* boneNode = 0;
  811. bool isRootBone = false;
  812. if (model)
  813. {
  814. unsigned boneIndex = GetBoneIndex(*model, channelName);
  815. if (boneIndex == M_MAX_UNSIGNED)
  816. {
  817. PrintLine("Warning: skipping animation track " + channelName + " not found in model skeleton");
  818. continue;
  819. }
  820. boneNode = model->bones_[boneIndex];
  821. isRootBone = boneIndex == 0;
  822. }
  823. else
  824. {
  825. boneNode = GetNode(channelName, scene_->mRootNode);
  826. if (!boneNode)
  827. {
  828. PrintLine("Warning: skipping animation track " + channelName + " whose scene node was not found");
  829. continue;
  830. }
  831. }
  832. // To export single frame animation, check if first key frame is identical to bone transformation
  833. aiVector3D bonePos, boneScale;
  834. aiQuaternion boneRot;
  835. boneNode->mTransformation.Decompose(boneScale, boneRot, bonePos);
  836. bool posEqual = true;
  837. bool scaleEqual = true;
  838. bool rotEqual = true;
  839. if (channel->mNumPositionKeys > 0 && !ToVector3(bonePos).Equals(ToVector3(channel->mPositionKeys[0].mValue)))
  840. posEqual = false;
  841. if (channel->mNumScalingKeys > 0 && !ToVector3(boneScale).Equals(ToVector3(channel->mScalingKeys[0].mValue)))
  842. scaleEqual = false;
  843. if (channel->mNumRotationKeys > 0 && !ToQuaternion(boneRot).Equals(ToQuaternion(channel->mRotationKeys[0].mValue)))
  844. rotEqual = false;
  845. AnimationTrack track;
  846. track.name_ = channelName;
  847. track.nameHash_ = channelName;
  848. // Check which channels are used
  849. track.channelMask_ = 0;
  850. if (channel->mNumPositionKeys > 1 || !posEqual)
  851. track.channelMask_ |= CHANNEL_POSITION;
  852. if (channel->mNumRotationKeys > 1 || !rotEqual)
  853. track.channelMask_ |= CHANNEL_ROTATION;
  854. if (channel->mNumScalingKeys > 1 || !scaleEqual)
  855. track.channelMask_ |= CHANNEL_SCALE;
  856. // Check for redundant identity scale in all keyframes and remove in that case
  857. if (track.channelMask_ & CHANNEL_SCALE)
  858. {
  859. bool redundantScale = true;
  860. for (unsigned k = 0; k < channel->mNumScalingKeys; ++k)
  861. {
  862. float SCALE_EPSILON = 0.000001f;
  863. Vector3 scaleVec = ToVector3(channel->mScalingKeys[k].mValue);
  864. if (fabsf(scaleVec.x_ - 1.0f) >= SCALE_EPSILON || fabsf(scaleVec.y_ - 1.0f) >= SCALE_EPSILON ||
  865. fabsf(scaleVec.z_ - 1.0f) >= SCALE_EPSILON)
  866. {
  867. redundantScale = false;
  868. break;
  869. }
  870. }
  871. if (redundantScale)
  872. track.channelMask_ &= ~CHANNEL_SCALE;
  873. }
  874. if (!track.channelMask_)
  875. PrintLine("Warning: skipping animation track " + channelName + " with no keyframes");
  876. // Currently only same amount of keyframes is supported
  877. // Note: should also check the times of individual keyframes for match
  878. if ((channel->mNumPositionKeys > 1 && channel->mNumRotationKeys > 1 && channel->mNumPositionKeys != channel->mNumRotationKeys) ||
  879. (channel->mNumPositionKeys > 1 && channel->mNumScalingKeys > 1 && channel->mNumPositionKeys != channel->mNumScalingKeys) ||
  880. (channel->mNumRotationKeys > 1 && channel->mNumScalingKeys > 1 && channel->mNumRotationKeys != channel->mNumScalingKeys))
  881. {
  882. PrintLine("Warning: differing amounts of channel keyframes, skipping animation track " + channelName);
  883. continue;
  884. }
  885. unsigned keyFrames = channel->mNumPositionKeys;
  886. if (channel->mNumRotationKeys > keyFrames)
  887. keyFrames = channel->mNumRotationKeys;
  888. if (channel->mNumScalingKeys > keyFrames)
  889. keyFrames = channel->mNumScalingKeys;
  890. for (unsigned k = 0; k < keyFrames; ++k)
  891. {
  892. AnimationKeyFrame kf;
  893. kf.time_ = 0.0f;
  894. kf.position_ = Vector3::ZERO;
  895. kf.rotation_ = Quaternion::IDENTITY;
  896. kf.scale_ = Vector3::ONE;
  897. // Get time for the keyframe. Adjust with animation's start time
  898. if (track.channelMask_ & CHANNEL_POSITION && k < channel->mNumPositionKeys)
  899. kf.time_ = ((float)channel->mPositionKeys[k].mTime - startTime) * tickConversion;
  900. else if (track.channelMask_ & CHANNEL_ROTATION && k < channel->mNumRotationKeys)
  901. kf.time_ = ((float)channel->mRotationKeys[k].mTime - startTime) * tickConversion;
  902. else if (track.channelMask_ & CHANNEL_SCALE && k < channel->mNumScalingKeys)
  903. kf.time_ = ((float)channel->mScalingKeys[k].mTime - startTime) * tickConversion;
  904. // Make sure time stays positive
  905. kf.time_ = Max(kf.time_, 0.0f);
  906. // Start with the bone's base transform
  907. aiMatrix4x4 boneTransform = boneNode->mTransformation;
  908. aiVector3D pos, scale;
  909. aiQuaternion rot;
  910. boneTransform.Decompose(scale, rot, pos);
  911. // Then apply the active channels
  912. if (track.channelMask_ & CHANNEL_POSITION && k < channel->mNumPositionKeys)
  913. pos = channel->mPositionKeys[k].mValue;
  914. if (track.channelMask_ & CHANNEL_ROTATION && k < channel->mNumRotationKeys)
  915. rot = channel->mRotationKeys[k].mValue;
  916. if (track.channelMask_ & CHANNEL_SCALE && k < channel->mNumScalingKeys)
  917. scale = channel->mScalingKeys[k].mValue;
  918. // If root bone, transform with the model root node transform
  919. if (model && isRootBone)
  920. {
  921. aiMatrix4x4 transMat, scaleMat, rotMat;
  922. aiMatrix4x4::Translation(pos, transMat);
  923. aiMatrix4x4::Scaling(scale, scaleMat);
  924. rotMat = aiMatrix4x4(rot.GetMatrix());
  925. aiMatrix4x4 tform = transMat * rotMat * scaleMat;
  926. tform = GetDerivedTransform(tform, boneNode, model->rootNode_);
  927. tform.Decompose(scale, rot, pos);
  928. }
  929. if (track.channelMask_ & CHANNEL_POSITION)
  930. kf.position_ = ToVector3(pos);
  931. if (track.channelMask_ & CHANNEL_ROTATION)
  932. kf.rotation_ = ToQuaternion(rot);
  933. if (track.channelMask_ & CHANNEL_SCALE)
  934. kf.scale_ = ToVector3(scale);
  935. track.keyFrames_.Push(kf);
  936. }
  937. tracks.Push(track);
  938. }
  939. outAnim->SetTracks(tracks);
  940. File outFile(context_);
  941. if (!outFile.Open(animOutName, FILE_WRITE))
  942. {
  943. errorMessage_ = "Could not open output file " + animOutName;
  944. return false;
  945. }
  946. outAnim->Save(outFile);
  947. AnimationInfo info;
  948. info.name_ = SanitateAssetName(animName);
  949. info.cacheFilename_ = animOutName;
  950. animationInfos_.Push(info);
  951. }
  952. return true;
  953. }
  954. // Materials
  955. void OpenAssetImporter::ExportMaterials(HashSet<String>& usedTextures)
  956. {
  957. if (useSubdirs_)
  958. {
  959. context_->GetSubsystem<FileSystem>()->CreateDir(sourceAssetPath_ + "Materials");
  960. }
  961. for (unsigned i = 0; i < scene_->mNumMaterials; ++i)
  962. BuildAndSaveMaterial(scene_->mMaterials[i], usedTextures);
  963. }
  964. bool OpenAssetImporter::BuildAndSaveMaterial(aiMaterial* material, HashSet<String>& usedTextures)
  965. {
  966. aiString matNameStr;
  967. material->Get(AI_MATKEY_NAME, matNameStr);
  968. String matName = SanitateAssetName(FromAIString(matNameStr));
  969. if (matName.Trimmed().Empty())
  970. matName = GenerateMaterialName(material);
  971. // Do not actually create a material instance, but instead craft an xml file manually
  972. XMLFile outMaterial(context_);
  973. XMLElement materialElem = outMaterial.CreateRoot("material");
  974. String diffuseTexName;
  975. String normalTexName;
  976. String specularTexName;
  977. String lightmapTexName;
  978. String emissiveTexName;
  979. Color diffuseColor = Color::WHITE;
  980. Color specularColor;
  981. Color emissiveColor = Color::BLACK;
  982. bool hasAlpha = false;
  983. bool twoSided = false;
  984. float specPower = 1.0f;
  985. aiString stringVal;
  986. float floatVal;
  987. int intVal;
  988. aiColor3D colorVal;
  989. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_DIFFUSE, 0), stringVal) == AI_SUCCESS)
  990. diffuseTexName = GetFileNameAndExtension(FromAIString(stringVal));
  991. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_NORMALS, 0), stringVal) == AI_SUCCESS)
  992. normalTexName = GetFileNameAndExtension(FromAIString(stringVal));
  993. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_SPECULAR, 0), stringVal) == AI_SUCCESS)
  994. specularTexName = GetFileNameAndExtension(FromAIString(stringVal));
  995. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_LIGHTMAP, 0), stringVal) == AI_SUCCESS)
  996. specularTexName = GetFileNameAndExtension(FromAIString(stringVal));
  997. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_EMISSIVE, 0), stringVal) == AI_SUCCESS)
  998. emissiveTexName = GetFileNameAndExtension(FromAIString(stringVal));
  999. diffuseTexName.Replace(".tif", ".png");
  1000. if (!noMaterialDiffuseColor_)
  1001. {
  1002. if (material->Get(AI_MATKEY_COLOR_DIFFUSE, colorVal) == AI_SUCCESS)
  1003. diffuseColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1004. }
  1005. if (material->Get(AI_MATKEY_COLOR_SPECULAR, colorVal) == AI_SUCCESS)
  1006. specularColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1007. if (!emissiveAO_)
  1008. {
  1009. // if (material->Get(AI_MATKEY_COLOR_EMISSIVE, colorVal) == AI_SUCCESS)
  1010. // emissiveColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1011. }
  1012. if (material->Get(AI_MATKEY_OPACITY, floatVal) == AI_SUCCESS)
  1013. {
  1014. if (floatVal < 1.0f)
  1015. hasAlpha = true;
  1016. diffuseColor.a_ = floatVal;
  1017. }
  1018. if (material->Get(AI_MATKEY_SHININESS, floatVal) == AI_SUCCESS)
  1019. specPower = floatVal;
  1020. if (material->Get(AI_MATKEY_TWOSIDED, intVal) == AI_SUCCESS)
  1021. twoSided = (intVal != 0);
  1022. String techniqueName = "Techniques/NoTexture";
  1023. if (!diffuseTexName.Empty())
  1024. {
  1025. techniqueName = "Techniques/Diff";
  1026. if (!normalTexName.Empty())
  1027. techniqueName += "Normal";
  1028. if (!specularTexName.Empty())
  1029. techniqueName += "Spec";
  1030. // For now lightmap does not coexist with normal & specular
  1031. if (normalTexName.Empty() && specularTexName.Empty() && !lightmapTexName.Empty())
  1032. techniqueName += "LightMap";
  1033. if (lightmapTexName.Empty() && !emissiveTexName.Empty())
  1034. techniqueName += emissiveAO_ ? "AO" : "Emissive";
  1035. }
  1036. if (hasAlpha)
  1037. techniqueName += "Alpha";
  1038. XMLElement techniqueElem = materialElem.CreateChild("technique");
  1039. techniqueElem.SetString("name", techniqueName + ".xml");
  1040. if (!diffuseTexName.Empty())
  1041. {
  1042. XMLElement diffuseElem = materialElem.CreateChild("texture");
  1043. diffuseElem.SetString("unit", "diffuse");
  1044. diffuseElem.SetString("name", GetMaterialTextureName(diffuseTexName));
  1045. usedTextures.Insert(diffuseTexName);
  1046. }
  1047. if (!normalTexName.Empty())
  1048. {
  1049. XMLElement normalElem = materialElem.CreateChild("texture");
  1050. normalElem.SetString("unit", "normal");
  1051. normalElem.SetString("name", GetMaterialTextureName(normalTexName));
  1052. usedTextures.Insert(normalTexName);
  1053. }
  1054. if (!specularTexName.Empty())
  1055. {
  1056. XMLElement specularElem = materialElem.CreateChild("texture");
  1057. specularElem.SetString("unit", "specular");
  1058. specularElem.SetString("name", GetMaterialTextureName(specularTexName));
  1059. usedTextures.Insert(specularTexName);
  1060. }
  1061. if (!lightmapTexName.Empty())
  1062. {
  1063. XMLElement lightmapElem = materialElem.CreateChild("texture");
  1064. lightmapElem.SetString("unit", "emissive");
  1065. lightmapElem.SetString("name", GetMaterialTextureName(lightmapTexName));
  1066. usedTextures.Insert(lightmapTexName);
  1067. }
  1068. if (!emissiveTexName.Empty())
  1069. {
  1070. XMLElement emissiveElem = materialElem.CreateChild("texture");
  1071. emissiveElem.SetString("unit", "emissive");
  1072. emissiveElem.SetString("name", GetMaterialTextureName(emissiveTexName));
  1073. usedTextures.Insert(emissiveTexName);
  1074. }
  1075. XMLElement diffuseColorElem = materialElem.CreateChild("parameter");
  1076. diffuseColorElem.SetString("name", "MatDiffColor");
  1077. diffuseColorElem.SetColor("value", diffuseColor);
  1078. XMLElement specularElem = materialElem.CreateChild("parameter");
  1079. specularElem.SetString("name", "MatSpecColor");
  1080. specularElem.SetVector4("value", Vector4(specularColor.r_, specularColor.g_, specularColor.b_, specPower));
  1081. XMLElement emissiveColorElem = materialElem.CreateChild("parameter");
  1082. emissiveColorElem.SetString("name", "MatEmissiveColor");
  1083. emissiveColorElem.SetColor("value", emissiveColor);
  1084. if (twoSided)
  1085. {
  1086. XMLElement cullElem = materialElem.CreateChild("cull");
  1087. XMLElement shadowCullElem = materialElem.CreateChild("shadowcull");
  1088. cullElem.SetString("value", "none");
  1089. shadowCullElem.SetString("value", "none");
  1090. }
  1091. FileSystem* fileSystem = context_->GetSubsystem<FileSystem>();
  1092. String outFileName = sourceAssetPath_ + (useSubdirs_ ? "Materials/" : "" ) + matName + ".material";
  1093. if (noOverwriteMaterial_ && fileSystem->FileExists(outFileName))
  1094. {
  1095. PrintLine("Skipping save of existing material " + matName);
  1096. return true;
  1097. }
  1098. PrintLine("Writing material " + matName);
  1099. File outFile(context_);
  1100. if (!outFile.Open(outFileName, FILE_WRITE))
  1101. {
  1102. errorMessage_ = "Could not open output file " + outFileName;
  1103. return false;
  1104. }
  1105. outMaterial.Save(outFile);
  1106. return true;
  1107. }
  1108. void OpenAssetImporter::DumpNodes(aiNode* rootNode, unsigned level)
  1109. {
  1110. if (!rootNode)
  1111. return;
  1112. String indent(' ', level * 2);
  1113. Vector3 pos, scale;
  1114. Quaternion rot;
  1115. aiMatrix4x4 transform = GetDerivedTransform(rootNode, rootNode_);
  1116. GetPosRotScale(transform, pos, rot, scale);
  1117. PrintLine(indent + "Node " + FromAIString(rootNode->mName) + " pos " + String(pos));
  1118. if (rootNode->mNumMeshes == 1)
  1119. PrintLine(indent + " " + String(rootNode->mNumMeshes) + " geometry");
  1120. if (rootNode->mNumMeshes > 1)
  1121. PrintLine(indent + " " + String(rootNode->mNumMeshes) + " geometries");
  1122. for (unsigned i = 0; i < rootNode->mNumChildren; ++i)
  1123. DumpNodes(rootNode->mChildren[i], level + 1);
  1124. }
  1125. }