OpenAssetImporter.cpp 33 KB

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