OpenAssetImporter.cpp 44 KB

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