OpenAssetImporter.cpp 32 KB

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