OpenAssetImporter.cpp 44 KB

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