OpenAssetImporter.cpp 44 KB

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