OpenAssetImporter.cpp 48 KB

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