OpenAssetImporter.cpp 47 KB

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