OpenAssetImporter.cpp 47 KB

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