OpenAssetImporter.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  1. //
  2. // Copyright (c) 2008-2015 the Atomic 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/IO/Log.h>
  27. #include <Atomic/IO/File.h>
  28. #include <Atomic/IO/FileSystem.h>
  29. #include <Atomic/Atomic3D/AnimatedModel.h>
  30. #include <Atomic/Atomic3D/Animation.h>
  31. #include <Atomic/Graphics/Geometry.h>
  32. #include <Atomic/Graphics/IndexBuffer.h>
  33. #include <Atomic/Graphics/VertexBuffer.h>
  34. #include "OpenAssetImporter.h"
  35. namespace ToolCore
  36. {
  37. OpenAssetImporter::OpenAssetImporter(Context* context) : Object(context) ,
  38. scene_(0),
  39. rootNode_(0),
  40. useSubdirs_(true),
  41. localIDs_(false),
  42. saveBinary_(false),
  43. createZone_(true),
  44. noAnimations_(false),
  45. noHierarchy_(false),
  46. noMaterials_(false),
  47. noTextures_(false),
  48. noMaterialDiffuseColor_(false),
  49. noEmptyNodes_(false),
  50. saveMaterialList_(false),
  51. includeNonSkinningBones_(false),
  52. verboseLog_(false),
  53. emissiveAO_(false),
  54. noOverwriteMaterial_(false),
  55. noOverwriteTexture_(false),
  56. noOverwriteNewerTexture_(false),
  57. checkUniqueModel_(true),
  58. maxBones_(64),
  59. defaultTicksPerSecond_(4800.0f)
  60. {
  61. aiFlagsDefault_ =
  62. aiProcess_ConvertToLeftHanded |
  63. aiProcess_JoinIdenticalVertices |
  64. aiProcess_Triangulate |
  65. aiProcess_GenSmoothNormals |
  66. aiProcess_LimitBoneWeights |
  67. aiProcess_ImproveCacheLocality |
  68. aiProcess_RemoveRedundantMaterials |
  69. aiProcess_FixInfacingNormals |
  70. aiProcess_FindInvalidData |
  71. aiProcess_GenUVCoords |
  72. aiProcess_FindInstances |
  73. aiProcess_OptimizeMeshes;
  74. aiCurrentFlags_ = aiFlagsDefault_;
  75. }
  76. OpenAssetImporter::~OpenAssetImporter()
  77. {
  78. if (scene_)
  79. aiReleaseImport(scene_);
  80. }
  81. bool OpenAssetImporter::Load(const String &assetPath)
  82. {
  83. if (verboseLog_)
  84. Assimp::DefaultLogger::create("", Assimp::Logger::VERBOSE, aiDefaultLogStream_STDOUT);
  85. PrintLine("Reading file " + assetPath);
  86. scene_ = aiImportFile(GetNativePath(assetPath).CString(), aiCurrentFlags_);
  87. if (!scene_)
  88. ErrorExit("Could not open or parse input file " + assetPath + ": " + String(aiGetErrorString()));
  89. if (verboseLog_)
  90. Assimp::DefaultLogger::kill();
  91. rootNode_ = scene_->mRootNode;
  92. // DumpNodes(rootNode_, 0);
  93. return true;
  94. }
  95. void OpenAssetImporter::ExportModel(const String& outName, bool animationOnly)
  96. {
  97. if (outName.Empty())
  98. ErrorExit("No output file defined");
  99. OutModel model;
  100. model.rootNode_ = rootNode_;
  101. model.outName_ = outName;
  102. CollectMeshes(scene_, model, model.rootNode_);
  103. CollectBones(model, animationOnly);
  104. BuildBoneCollisionInfo(model);
  105. BuildAndSaveModel(model);
  106. if (!noAnimations_)
  107. {
  108. CollectAnimations(&model);
  109. BuildAndSaveAnimations(&model);
  110. // Save scene-global animations
  111. CollectAnimations();
  112. BuildAndSaveAnimations();
  113. }
  114. }
  115. void OpenAssetImporter::BuildAndSaveModel(OutModel& model)
  116. {
  117. if (!model.rootNode_)
  118. ErrorExit("Null root node for model");
  119. String rootNodeName = FromAIString(model.rootNode_->mName);
  120. if (!model.meshes_.Size())
  121. ErrorExit("No geometries found starting from node " + rootNodeName);
  122. PrintLine("Writing model " + rootNodeName);
  123. SharedPtr<Model> outModel(new Model(context_));
  124. Vector<PODVector<unsigned> > allBoneMappings;
  125. BoundingBox box;
  126. unsigned numValidGeometries = 0;
  127. bool combineBuffers = true;
  128. // Check if buffers can be combined (same vertex element mask, under 65535 vertices)
  129. unsigned elementMask = GetElementMask(model.meshes_[0]);
  130. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  131. {
  132. if (GetNumValidFaces(model.meshes_[i]))
  133. {
  134. ++numValidGeometries;
  135. if (i > 0 && GetElementMask(model.meshes_[i]) != elementMask)
  136. combineBuffers = false;
  137. }
  138. }
  139. // Check if keeping separate buffers allows to avoid 32-bit indices
  140. if (combineBuffers && model.totalVertices_ > 65535)
  141. {
  142. bool allUnder65k = true;
  143. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  144. {
  145. if (GetNumValidFaces(model.meshes_[i]))
  146. {
  147. if (model.meshes_[i]->mNumVertices > 65535)
  148. allUnder65k = false;
  149. }
  150. }
  151. if (allUnder65k == true)
  152. combineBuffers = false;
  153. }
  154. SharedPtr<IndexBuffer> ib;
  155. SharedPtr<VertexBuffer> vb;
  156. Vector<SharedPtr<VertexBuffer> > vbVector;
  157. Vector<SharedPtr<IndexBuffer> > ibVector;
  158. unsigned startVertexOffset = 0;
  159. unsigned startIndexOffset = 0;
  160. unsigned destGeomIndex = 0;
  161. outModel->SetNumGeometries(numValidGeometries);
  162. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  163. {
  164. aiMesh* mesh = model.meshes_[i];
  165. unsigned elementMask = GetElementMask(mesh);
  166. unsigned validFaces = GetNumValidFaces(mesh);
  167. if (!validFaces)
  168. continue;
  169. bool largeIndices;
  170. if (combineBuffers)
  171. largeIndices = model.totalIndices_ > 65535;
  172. else
  173. largeIndices = mesh->mNumVertices > 65535;
  174. // Create new buffers if necessary
  175. if (!combineBuffers || vbVector.Empty())
  176. {
  177. vb = new VertexBuffer(context_);
  178. ib = new IndexBuffer(context_);
  179. if (combineBuffers)
  180. {
  181. ib->SetSize(model.totalIndices_, largeIndices);
  182. vb->SetSize(model.totalVertices_, elementMask);
  183. }
  184. else
  185. {
  186. ib->SetSize(validFaces * 3, largeIndices);
  187. vb->SetSize(mesh->mNumVertices, elementMask);
  188. }
  189. vbVector.Push(vb);
  190. ibVector.Push(ib);
  191. startVertexOffset = 0;
  192. startIndexOffset = 0;
  193. }
  194. // Get the world transform of the mesh for baking into the vertices
  195. Matrix3x4 vertexTransform;
  196. Matrix3 normalTransform;
  197. Vector3 pos, scale;
  198. Quaternion rot;
  199. GetPosRotScale(GetMeshBakingTransform(model.meshNodes_[i], model.rootNode_), pos, rot, scale);
  200. vertexTransform = Matrix3x4(pos, rot, scale);
  201. normalTransform = rot.RotationMatrix();
  202. SharedPtr<Geometry> geom(new Geometry(context_));
  203. PrintLine("Writing geometry " + String(i) + " with " + String(mesh->mNumVertices) + " vertices " +
  204. String(validFaces * 3) + " indices");
  205. unsigned char* vertexData = vb->GetShadowData();
  206. unsigned char* indexData = ib->GetShadowData();
  207. // Build the index data
  208. if (!largeIndices)
  209. {
  210. unsigned short* dest = (unsigned short*)indexData + startIndexOffset;
  211. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  212. WriteShortIndices(dest, mesh, j, startVertexOffset);
  213. }
  214. else
  215. {
  216. unsigned* dest = (unsigned*)indexData + startIndexOffset;
  217. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  218. WriteLargeIndices(dest, mesh, j, startVertexOffset);
  219. }
  220. // Build the vertex data
  221. // If there are bones, get blend data
  222. Vector<PODVector<unsigned char> > blendIndices;
  223. Vector<PODVector<float> > blendWeights;
  224. PODVector<unsigned> boneMappings;
  225. if (model.bones_.Size())
  226. GetBlendData(model, mesh, boneMappings, blendIndices, blendWeights, maxBones_);
  227. float* dest = (float*)((unsigned char*)vertexData + startVertexOffset * vb->GetVertexSize());
  228. for (unsigned j = 0; j < mesh->mNumVertices; ++j)
  229. WriteVertex(dest, mesh, j, elementMask, box, vertexTransform, normalTransform, blendIndices, blendWeights);
  230. // Calculate the geometry center
  231. Vector3 center = Vector3::ZERO;
  232. if (validFaces)
  233. {
  234. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  235. {
  236. if (mesh->mFaces[j].mNumIndices == 3)
  237. {
  238. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[0]]);
  239. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[1]]);
  240. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[2]]);
  241. }
  242. }
  243. center /= (float)validFaces * 3;
  244. }
  245. // Define the geometry
  246. geom->SetIndexBuffer(ib);
  247. geom->SetVertexBuffer(0, vb);
  248. geom->SetDrawRange(TRIANGLE_LIST, startIndexOffset, validFaces * 3, true);
  249. outModel->SetNumGeometryLodLevels(destGeomIndex, 1);
  250. outModel->SetGeometry(destGeomIndex, 0, geom);
  251. outModel->SetGeometryCenter(destGeomIndex, center);
  252. if (model.bones_.Size() > maxBones_)
  253. allBoneMappings.Push(boneMappings);
  254. startVertexOffset += mesh->mNumVertices;
  255. startIndexOffset += validFaces * 3;
  256. ++destGeomIndex;
  257. }
  258. // Define the model buffers and bounding box
  259. PODVector<unsigned> emptyMorphRange;
  260. outModel->SetVertexBuffers(vbVector, emptyMorphRange, emptyMorphRange);
  261. outModel->SetIndexBuffers(ibVector);
  262. outModel->SetBoundingBox(box);
  263. // Build skeleton if necessary
  264. if (model.bones_.Size() && model.rootBone_)
  265. {
  266. PrintLine("Writing skeleton with " + String(model.bones_.Size()) + " bones, rootbone " +
  267. FromAIString(model.rootBone_->mName));
  268. Skeleton skeleton;
  269. Vector<Bone>& bones = skeleton.GetModifiableBones();
  270. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  271. {
  272. aiNode* boneNode = model.bones_[i];
  273. String boneName(FromAIString(boneNode->mName));
  274. Bone newBone;
  275. newBone.name_ = boneName;
  276. aiMatrix4x4 transform = boneNode->mTransformation;
  277. // Make the root bone transform relative to the model's root node, if it is not already
  278. if (boneNode == model.rootBone_)
  279. transform = GetDerivedTransform(boneNode, model.rootNode_);
  280. GetPosRotScale(transform, newBone.initialPosition_, newBone.initialRotation_, newBone.initialScale_);
  281. // Get offset information if exists
  282. newBone.offsetMatrix_ = GetOffsetMatrix(model, boneName);
  283. newBone.radius_ = model.boneRadii_[i];
  284. newBone.boundingBox_ = model.boneHitboxes_[i];
  285. newBone.collisionMask_ = BONECOLLISION_SPHERE | BONECOLLISION_BOX;
  286. newBone.parentIndex_ = i;
  287. bones.Push(newBone);
  288. }
  289. // Set the bone hierarchy
  290. for (unsigned i = 1; i < model.bones_.Size(); ++i)
  291. {
  292. String parentName = FromAIString(model.bones_[i]->mParent->mName);
  293. for (unsigned j = 0; j < bones.Size(); ++j)
  294. {
  295. if (bones[j].name_ == parentName)
  296. {
  297. bones[i].parentIndex_ = j;
  298. break;
  299. }
  300. }
  301. }
  302. outModel->SetSkeleton(skeleton);
  303. if (model.bones_.Size() > maxBones_)
  304. outModel->SetGeometryBoneMappings(allBoneMappings);
  305. }
  306. File outFile(context_);
  307. if (!outFile.Open(model.outName_, FILE_WRITE))
  308. ErrorExit("Could not open output file " + model.outName_);
  309. outModel->Save(outFile);
  310. // If exporting materials, also save material list for use by the editor
  311. if (!noMaterials_ && saveMaterialList_)
  312. {
  313. String materialListName = ReplaceExtension(model.outName_, ".txt");
  314. File listFile(context_);
  315. if (listFile.Open(materialListName, FILE_WRITE))
  316. {
  317. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  318. listFile.WriteLine(GetMeshMaterialName(model.meshes_[i]));
  319. }
  320. else
  321. PrintLine("Warning: could not write material list file " + materialListName);
  322. }
  323. }
  324. String OpenAssetImporter::GetMeshMaterialName(aiMesh* mesh)
  325. {
  326. aiMaterial* material = scene_->mMaterials[mesh->mMaterialIndex];
  327. aiString matNameStr;
  328. material->Get(AI_MATKEY_NAME, matNameStr);
  329. String matName = SanitateAssetName(FromAIString(matNameStr));
  330. if (matName.Trimmed().Empty())
  331. matName = GenerateMaterialName(material);
  332. return (useSubdirs_ ? "Materials/" : "") + matName + ".xml";
  333. }
  334. String OpenAssetImporter::GenerateMaterialName(aiMaterial* material)
  335. {
  336. for (unsigned i = 0; i < scene_->mNumMaterials; ++i)
  337. {
  338. if (scene_->mMaterials[i] == material)
  339. return inputName_ + "_Material" + String(i);
  340. }
  341. // Should not go here
  342. return String::EMPTY;
  343. }
  344. String OpenAssetImporter::GetMaterialTextureName(const String& nameIn)
  345. {
  346. // Detect assimp embedded texture
  347. if (nameIn.Length() && nameIn[0] == '*')
  348. return GenerateTextureName(ToInt(nameIn.Substring(1)));
  349. else
  350. return (useSubdirs_ ? "Textures/" : "") + nameIn;
  351. }
  352. String OpenAssetImporter::GenerateTextureName(unsigned texIndex)
  353. {
  354. if (texIndex < scene_->mNumTextures)
  355. {
  356. // If embedded texture contains encoded data, use the format hint for file extension. Else save RGBA8 data as PNG
  357. aiTexture* tex = scene_->mTextures[texIndex];
  358. if (!tex->mHeight)
  359. return (useSubdirs_ ? "Textures/" : "") + inputName_ + "_Texture" + String(texIndex) + "." + tex->achFormatHint;
  360. else
  361. return (useSubdirs_ ? "Textures/" : "") + inputName_ + "_Texture" + String(texIndex) + ".png";
  362. }
  363. // Should not go here
  364. return String::EMPTY;
  365. }
  366. void OpenAssetImporter::CollectSceneModels(OutScene& scene, aiNode* node)
  367. {
  368. Vector<Pair<aiNode*, aiMesh*> > meshes;
  369. GetMeshesUnderNode(scene_, meshes, node);
  370. if (meshes.Size())
  371. {
  372. OutModel model;
  373. model.rootNode_ = node;
  374. model.outName_ = resourcePath_ + (useSubdirs_ ? "Models/" : "") + SanitateAssetName(FromAIString(node->mName)) + ".mdl";
  375. for (unsigned i = 0; i < meshes.Size(); ++i)
  376. {
  377. aiMesh* mesh = meshes[i].second_;
  378. unsigned meshIndex = GetMeshIndex(scene_, mesh);
  379. model.meshIndices_.Insert(meshIndex);
  380. model.meshes_.Push(mesh);
  381. model.meshNodes_.Push(meshes[i].first_);
  382. model.totalVertices_ += mesh->mNumVertices;
  383. model.totalIndices_ += GetNumValidFaces(mesh) * 3;
  384. }
  385. // Check if a model with identical mesh indices already exists. If yes, do not export twice
  386. bool unique = true;
  387. if (checkUniqueModel_)
  388. {
  389. for (unsigned i = 0; i < scene.models_.Size(); ++i)
  390. {
  391. if (scene.models_[i].meshIndices_ == model.meshIndices_)
  392. {
  393. PrintLine("Added node " + FromAIString(node->mName));
  394. scene.nodes_.Push(node);
  395. scene.nodeModelIndices_.Push(i);
  396. unique = false;
  397. break;
  398. }
  399. }
  400. }
  401. if (unique)
  402. {
  403. PrintLine("Added model " + model.outName_);
  404. PrintLine("Added node " + FromAIString(node->mName));
  405. CollectBones(model);
  406. BuildBoneCollisionInfo(model);
  407. if (!noAnimations_)
  408. {
  409. CollectAnimations(&model);
  410. BuildAndSaveAnimations(&model);
  411. }
  412. scene.models_.Push(model);
  413. scene.nodes_.Push(node);
  414. scene.nodeModelIndices_.Push(scene.models_.Size() - 1);
  415. }
  416. }
  417. for (unsigned i = 0; i < node->mNumChildren; ++i)
  418. CollectSceneModels(scene, node->mChildren[i]);
  419. }
  420. void OpenAssetImporter::CollectBones(OutModel& model, bool animationOnly)
  421. {
  422. HashSet<aiNode*> necessary;
  423. HashSet<aiNode*> rootNodes;
  424. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  425. {
  426. aiMesh* mesh = model.meshes_[i];
  427. aiNode* meshNode = model.meshNodes_[i];
  428. aiNode* meshParentNode = meshNode->mParent;
  429. aiNode* rootNode = 0;
  430. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  431. {
  432. aiBone* bone = mesh->mBones[j];
  433. String boneName(FromAIString(bone->mName));
  434. aiNode* boneNode = GetNode(boneName, scene_->mRootNode, true);
  435. if (!boneNode)
  436. ErrorExit("Could not find scene node for bone " + boneName);
  437. necessary.Insert(boneNode);
  438. rootNode = boneNode;
  439. for (;;)
  440. {
  441. boneNode = boneNode->mParent;
  442. if (!boneNode || ((boneNode == meshNode || boneNode == meshParentNode) && !animationOnly))
  443. break;
  444. rootNode = boneNode;
  445. necessary.Insert(boneNode);
  446. }
  447. if (rootNodes.Find(rootNode) == rootNodes.End())
  448. rootNodes.Insert(rootNode);
  449. }
  450. }
  451. // If we find multiple root nodes, try to remedy by using their parent instead
  452. if (rootNodes.Size() > 1)
  453. {
  454. aiNode* commonParent = (*rootNodes.Begin())->mParent;
  455. for (HashSet<aiNode*>::Iterator i = rootNodes.Begin(); i != rootNodes.End(); ++i)
  456. {
  457. if (*i != commonParent)
  458. {
  459. if (!commonParent || (*i)->mParent != commonParent)
  460. ErrorExit("Skeleton with multiple root nodes found, not supported");
  461. }
  462. }
  463. rootNodes.Clear();
  464. rootNodes.Insert(commonParent);
  465. necessary.Insert(commonParent);
  466. }
  467. if (rootNodes.Empty())
  468. return;
  469. model.rootBone_ = *rootNodes.Begin();
  470. CollectBonesFinal(model.bones_, necessary, model.rootBone_);
  471. // Initialize the bone collision info
  472. model.boneRadii_.Resize(model.bones_.Size());
  473. model.boneHitboxes_.Resize(model.bones_.Size());
  474. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  475. {
  476. model.boneRadii_[i] = 0.0f;
  477. model.boneHitboxes_[i] = BoundingBox(0.0f, 0.0f);
  478. }
  479. }
  480. void OpenAssetImporter::CollectBonesFinal(PODVector<aiNode*>& dest, const HashSet<aiNode*>& necessary, aiNode* node)
  481. {
  482. bool includeBone = necessary.Find(node) != necessary.End();
  483. String boneName = FromAIString(node->mName);
  484. // Check include/exclude filters for non-skinned bones
  485. if (!includeBone && includeNonSkinningBones_)
  486. {
  487. // If no includes specified, include by default but check for excludes
  488. if (nonSkinningBoneIncludes_.Empty())
  489. includeBone = true;
  490. // Check against includes/excludes
  491. for (unsigned i = 0; i < nonSkinningBoneIncludes_.Size(); ++i)
  492. {
  493. if (boneName.Contains(nonSkinningBoneIncludes_[i], false))
  494. {
  495. includeBone = true;
  496. break;
  497. }
  498. }
  499. for (unsigned i = 0; i < nonSkinningBoneExcludes_.Size(); ++i)
  500. {
  501. if (boneName.Contains(nonSkinningBoneExcludes_[i], false))
  502. {
  503. includeBone = false;
  504. break;
  505. }
  506. }
  507. if (includeBone)
  508. PrintLine("Including non-skinning bone " + boneName);
  509. }
  510. if (includeBone)
  511. dest.Push(node);
  512. for (unsigned i = 0; i < node->mNumChildren; ++i)
  513. CollectBonesFinal(dest, necessary, node->mChildren[i]);
  514. }
  515. void OpenAssetImporter::CollectAnimations(OutModel* model)
  516. {
  517. const aiScene* scene = scene_;
  518. for (unsigned i = 0; i < scene->mNumAnimations; ++i)
  519. {
  520. aiAnimation* anim = scene->mAnimations[i];
  521. if (allAnimations_.Contains(anim))
  522. continue;
  523. if (model)
  524. {
  525. bool modelBoneFound = false;
  526. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  527. {
  528. aiNodeAnim* channel = anim->mChannels[j];
  529. String channelName = FromAIString(channel->mNodeName);
  530. if (GetBoneIndex(*model, channelName) != M_MAX_UNSIGNED)
  531. {
  532. modelBoneFound = true;
  533. break;
  534. }
  535. }
  536. if (modelBoneFound)
  537. {
  538. model->animations_.Push(anim);
  539. allAnimations_.Insert(anim);
  540. }
  541. }
  542. else
  543. {
  544. sceneAnimations_.Push(anim);
  545. allAnimations_.Insert(anim);
  546. }
  547. }
  548. /// \todo Vertex morphs are ignored for now
  549. }
  550. void OpenAssetImporter::BuildBoneCollisionInfo(OutModel& model)
  551. {
  552. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  553. {
  554. aiMesh* mesh = model.meshes_[i];
  555. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  556. {
  557. aiBone* bone = mesh->mBones[j];
  558. String boneName = FromAIString(bone->mName);
  559. unsigned boneIndex = GetBoneIndex(model, boneName);
  560. if (boneIndex == M_MAX_UNSIGNED)
  561. continue;
  562. for (unsigned k = 0; k < bone->mNumWeights; ++k)
  563. {
  564. float weight = bone->mWeights[k].mWeight;
  565. // Require skinning weight to be sufficiently large before vertex contributes to bone hitbox
  566. if (weight > 0.33f)
  567. {
  568. aiVector3D vertexBoneSpace = bone->mOffsetMatrix * mesh->mVertices[bone->mWeights[k].mVertexId];
  569. Vector3 vertex = ToVector3(vertexBoneSpace);
  570. float radius = vertex.Length();
  571. if (radius > model.boneRadii_[boneIndex])
  572. model.boneRadii_[boneIndex] = radius;
  573. model.boneHitboxes_[boneIndex].Merge(vertex);
  574. }
  575. }
  576. }
  577. }
  578. }
  579. void OpenAssetImporter::BuildAndSaveAnimations(OutModel* model)
  580. {
  581. const PODVector<aiAnimation*>& animations = model ? model->animations_ : sceneAnimations_;
  582. for (unsigned i = 0; i < animations.Size(); ++i)
  583. {
  584. aiAnimation* anim = animations[i];
  585. float duration = (float)anim->mDuration;
  586. String animName = FromAIString(anim->mName);
  587. String animOutName;
  588. if (animName.Empty())
  589. animName = "Anim" + String(i + 1);
  590. if (model)
  591. animOutName = GetPath(model->outName_) + GetFileName(model->outName_) + "_" + SanitateAssetName(animName) + ".ani";
  592. else
  593. animOutName = outPath_ + SanitateAssetName(animName) + ".ani";
  594. float ticksPerSecond = (float)anim->mTicksPerSecond;
  595. // If ticks per second not specified, it's probably a .X file. In this case use the default tick rate
  596. if (ticksPerSecond < M_EPSILON)
  597. ticksPerSecond = defaultTicksPerSecond_;
  598. float tickConversion = 1.0f / ticksPerSecond;
  599. // Find out the start time of animation from each channel's first keyframe for adjusting the keyframe times
  600. // to start from zero
  601. float startTime = duration;
  602. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  603. {
  604. aiNodeAnim* channel = anim->mChannels[j];
  605. if (channel->mNumPositionKeys > 0)
  606. startTime = Min(startTime, (float)channel->mPositionKeys[0].mTime);
  607. if (channel->mNumRotationKeys > 0)
  608. startTime = Min(startTime, (float)channel->mRotationKeys[0].mTime);
  609. if (channel->mScalingKeys > 0)
  610. startTime = Min(startTime, (float)channel->mScalingKeys[0].mTime);
  611. }
  612. duration -= startTime;
  613. SharedPtr<Animation> outAnim(new Animation(context_));
  614. outAnim->SetAnimationName(animName);
  615. outAnim->SetLength(duration * tickConversion);
  616. PrintLine("Writing animation " + animName + " length " + String(outAnim->GetLength()));
  617. Vector<AnimationTrack> tracks;
  618. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  619. {
  620. aiNodeAnim* channel = anim->mChannels[j];
  621. String channelName = FromAIString(channel->mNodeName);
  622. aiNode* boneNode = 0;
  623. bool isRootBone = false;
  624. if (model)
  625. {
  626. unsigned boneIndex = GetBoneIndex(*model, channelName);
  627. if (boneIndex == M_MAX_UNSIGNED)
  628. {
  629. PrintLine("Warning: skipping animation track " + channelName + " not found in model skeleton");
  630. continue;
  631. }
  632. boneNode = model->bones_[boneIndex];
  633. isRootBone = boneIndex == 0;
  634. }
  635. else
  636. {
  637. boneNode = GetNode(channelName, scene_->mRootNode);
  638. if (!boneNode)
  639. {
  640. PrintLine("Warning: skipping animation track " + channelName + " whose scene node was not found");
  641. continue;
  642. }
  643. }
  644. // To export single frame animation, check if first key frame is identical to bone transformation
  645. aiVector3D bonePos, boneScale;
  646. aiQuaternion boneRot;
  647. boneNode->mTransformation.Decompose(boneScale, boneRot, bonePos);
  648. bool posEqual = true;
  649. bool scaleEqual = true;
  650. bool rotEqual = true;
  651. if (channel->mNumPositionKeys > 0 && !ToVector3(bonePos).Equals(ToVector3(channel->mPositionKeys[0].mValue)))
  652. posEqual = false;
  653. if (channel->mNumScalingKeys > 0 && !ToVector3(boneScale).Equals(ToVector3(channel->mScalingKeys[0].mValue)))
  654. scaleEqual = false;
  655. if (channel->mNumRotationKeys > 0 && !ToQuaternion(boneRot).Equals(ToQuaternion(channel->mRotationKeys[0].mValue)))
  656. rotEqual = false;
  657. AnimationTrack track;
  658. track.name_ = channelName;
  659. track.nameHash_ = channelName;
  660. // Check which channels are used
  661. track.channelMask_ = 0;
  662. if (channel->mNumPositionKeys > 1 || !posEqual)
  663. track.channelMask_ |= CHANNEL_POSITION;
  664. if (channel->mNumRotationKeys > 1 || !rotEqual)
  665. track.channelMask_ |= CHANNEL_ROTATION;
  666. if (channel->mNumScalingKeys > 1 || !scaleEqual)
  667. track.channelMask_ |= CHANNEL_SCALE;
  668. // Check for redundant identity scale in all keyframes and remove in that case
  669. if (track.channelMask_ & CHANNEL_SCALE)
  670. {
  671. bool redundantScale = true;
  672. for (unsigned k = 0; k < channel->mNumScalingKeys; ++k)
  673. {
  674. float SCALE_EPSILON = 0.000001f;
  675. Vector3 scaleVec = ToVector3(channel->mScalingKeys[k].mValue);
  676. if (fabsf(scaleVec.x_ - 1.0f) >= SCALE_EPSILON || fabsf(scaleVec.y_ - 1.0f) >= SCALE_EPSILON ||
  677. fabsf(scaleVec.z_ - 1.0f) >= SCALE_EPSILON)
  678. {
  679. redundantScale = false;
  680. break;
  681. }
  682. }
  683. if (redundantScale)
  684. track.channelMask_ &= ~CHANNEL_SCALE;
  685. }
  686. if (!track.channelMask_)
  687. PrintLine("Warning: skipping animation track " + channelName + " with no keyframes");
  688. // Currently only same amount of keyframes is supported
  689. // Note: should also check the times of individual keyframes for match
  690. if ((channel->mNumPositionKeys > 1 && channel->mNumRotationKeys > 1 && channel->mNumPositionKeys != channel->mNumRotationKeys) ||
  691. (channel->mNumPositionKeys > 1 && channel->mNumScalingKeys > 1 && channel->mNumPositionKeys != channel->mNumScalingKeys) ||
  692. (channel->mNumRotationKeys > 1 && channel->mNumScalingKeys > 1 && channel->mNumRotationKeys != channel->mNumScalingKeys))
  693. {
  694. PrintLine("Warning: differing amounts of channel keyframes, skipping animation track " + channelName);
  695. continue;
  696. }
  697. unsigned keyFrames = channel->mNumPositionKeys;
  698. if (channel->mNumRotationKeys > keyFrames)
  699. keyFrames = channel->mNumRotationKeys;
  700. if (channel->mNumScalingKeys > keyFrames)
  701. keyFrames = channel->mNumScalingKeys;
  702. for (unsigned k = 0; k < keyFrames; ++k)
  703. {
  704. AnimationKeyFrame kf;
  705. kf.time_ = 0.0f;
  706. kf.position_ = Vector3::ZERO;
  707. kf.rotation_ = Quaternion::IDENTITY;
  708. kf.scale_ = Vector3::ONE;
  709. // Get time for the keyframe. Adjust with animation's start time
  710. if (track.channelMask_ & CHANNEL_POSITION && k < channel->mNumPositionKeys)
  711. kf.time_ = ((float)channel->mPositionKeys[k].mTime - startTime) * tickConversion;
  712. else if (track.channelMask_ & CHANNEL_ROTATION && k < channel->mNumRotationKeys)
  713. kf.time_ = ((float)channel->mRotationKeys[k].mTime - startTime) * tickConversion;
  714. else if (track.channelMask_ & CHANNEL_SCALE && k < channel->mNumScalingKeys)
  715. kf.time_ = ((float)channel->mScalingKeys[k].mTime - startTime) * tickConversion;
  716. // Make sure time stays positive
  717. kf.time_ = Max(kf.time_, 0.0f);
  718. // Start with the bone's base transform
  719. aiMatrix4x4 boneTransform = boneNode->mTransformation;
  720. aiVector3D pos, scale;
  721. aiQuaternion rot;
  722. boneTransform.Decompose(scale, rot, pos);
  723. // Then apply the active channels
  724. if (track.channelMask_ & CHANNEL_POSITION && k < channel->mNumPositionKeys)
  725. pos = channel->mPositionKeys[k].mValue;
  726. if (track.channelMask_ & CHANNEL_ROTATION && k < channel->mNumRotationKeys)
  727. rot = channel->mRotationKeys[k].mValue;
  728. if (track.channelMask_ & CHANNEL_SCALE && k < channel->mNumScalingKeys)
  729. scale = channel->mScalingKeys[k].mValue;
  730. // If root bone, transform with the model root node transform
  731. if (model && isRootBone)
  732. {
  733. aiMatrix4x4 transMat, scaleMat, rotMat;
  734. aiMatrix4x4::Translation(pos, transMat);
  735. aiMatrix4x4::Scaling(scale, scaleMat);
  736. rotMat = aiMatrix4x4(rot.GetMatrix());
  737. aiMatrix4x4 tform = transMat * rotMat * scaleMat;
  738. tform = GetDerivedTransform(tform, boneNode, model->rootNode_);
  739. tform.Decompose(scale, rot, pos);
  740. }
  741. if (track.channelMask_ & CHANNEL_POSITION)
  742. kf.position_ = ToVector3(pos);
  743. if (track.channelMask_ & CHANNEL_ROTATION)
  744. kf.rotation_ = ToQuaternion(rot);
  745. if (track.channelMask_ & CHANNEL_SCALE)
  746. kf.scale_ = ToVector3(scale);
  747. track.keyFrames_.Push(kf);
  748. }
  749. tracks.Push(track);
  750. }
  751. outAnim->SetTracks(tracks);
  752. File outFile(context_);
  753. if (!outFile.Open(animOutName, FILE_WRITE))
  754. ErrorExit("Could not open output file " + animOutName);
  755. outAnim->Save(outFile);
  756. }
  757. }
  758. void OpenAssetImporter::DumpNodes(aiNode* rootNode, unsigned level)
  759. {
  760. if (!rootNode)
  761. return;
  762. String indent(' ', level * 2);
  763. Vector3 pos, scale;
  764. Quaternion rot;
  765. aiMatrix4x4 transform = GetDerivedTransform(rootNode, rootNode_);
  766. GetPosRotScale(transform, pos, rot, scale);
  767. PrintLine(indent + "Node " + FromAIString(rootNode->mName) + " pos " + String(pos));
  768. if (rootNode->mNumMeshes == 1)
  769. PrintLine(indent + " " + String(rootNode->mNumMeshes) + " geometry");
  770. if (rootNode->mNumMeshes > 1)
  771. PrintLine(indent + " " + String(rootNode->mNumMeshes) + " geometries");
  772. for (unsigned i = 0; i < rootNode->mNumChildren; ++i)
  773. DumpNodes(rootNode->mChildren[i], level + 1);
  774. }
  775. }