MD5Loader.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2020, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file MD5Loader.cpp
  35. * @brief Implementation of the MD5 importer class
  36. */
  37. #ifndef ASSIMP_BUILD_NO_MD5_IMPORTER
  38. // internal headers
  39. #include <assimp/RemoveComments.h>
  40. #include "MD5Loader.h"
  41. #include <assimp/StringComparison.h>
  42. #include <assimp/fast_atof.h>
  43. #include <assimp/MathFunctions.h>
  44. #include <assimp/SkeletonMeshBuilder.h>
  45. #include <assimp/Importer.hpp>
  46. #include <assimp/scene.h>
  47. #include <assimp/IOSystem.hpp>
  48. #include <assimp/DefaultLogger.hpp>
  49. #include <assimp/importerdesc.h>
  50. #include <memory>
  51. using namespace Assimp;
  52. // Minimum weight value. Weights inside [-n ... n] are ignored
  53. #define AI_MD5_WEIGHT_EPSILON Math::getEpsilon<float>()
  54. static const aiImporterDesc desc = {
  55. "Doom 3 / MD5 Mesh Importer",
  56. "",
  57. "",
  58. "",
  59. aiImporterFlags_SupportBinaryFlavour,
  60. 0,
  61. 0,
  62. 0,
  63. 0,
  64. "md5mesh md5camera md5anim"
  65. };
  66. // ------------------------------------------------------------------------------------------------
  67. // Constructor to be privately used by Importer
  68. MD5Importer::MD5Importer()
  69. : mIOHandler()
  70. , mBuffer()
  71. , fileSize()
  72. , iLineNumber()
  73. , pScene()
  74. , pIOHandler()
  75. , bHadMD5Mesh()
  76. , bHadMD5Anim()
  77. , bHadMD5Camera()
  78. , configNoAutoLoad (false)
  79. {}
  80. // ------------------------------------------------------------------------------------------------
  81. // Destructor, private as well
  82. MD5Importer::~MD5Importer()
  83. {}
  84. // ------------------------------------------------------------------------------------------------
  85. // Returns whether the class can handle the format of the given file.
  86. bool MD5Importer::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  87. {
  88. const std::string extension = GetExtension(pFile);
  89. if (extension == "md5anim" || extension == "md5mesh" || extension == "md5camera")
  90. return true;
  91. else if (!extension.length() || checkSig) {
  92. if (!pIOHandler) {
  93. return true;
  94. }
  95. const char* tokens[] = {"MD5Version"};
  96. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,1);
  97. }
  98. return false;
  99. }
  100. // ------------------------------------------------------------------------------------------------
  101. // Get list of all supported extensions
  102. const aiImporterDesc* MD5Importer::GetInfo () const
  103. {
  104. return &desc;
  105. }
  106. // ------------------------------------------------------------------------------------------------
  107. // Setup import properties
  108. void MD5Importer::SetupProperties(const Importer* pImp)
  109. {
  110. // AI_CONFIG_IMPORT_MD5_NO_ANIM_AUTOLOAD
  111. configNoAutoLoad = (0 != pImp->GetPropertyInteger(AI_CONFIG_IMPORT_MD5_NO_ANIM_AUTOLOAD,0));
  112. }
  113. // ------------------------------------------------------------------------------------------------
  114. // Imports the given file into the given scene structure.
  115. void MD5Importer::InternReadFile( const std::string& pFile,
  116. aiScene* _pScene, IOSystem* _pIOHandler)
  117. {
  118. pIOHandler = _pIOHandler;
  119. pScene = _pScene;
  120. bHadMD5Mesh = bHadMD5Anim = bHadMD5Camera = false;
  121. // remove the file extension
  122. const std::string::size_type pos = pFile.find_last_of('.');
  123. mFile = (std::string::npos == pos ? pFile : pFile.substr(0,pos+1));
  124. const std::string extension = GetExtension(pFile);
  125. try {
  126. if (extension == "md5camera") {
  127. LoadMD5CameraFile();
  128. }
  129. else if (configNoAutoLoad || extension == "md5anim") {
  130. // determine file extension and process just *one* file
  131. if (extension.length() == 0) {
  132. throw DeadlyImportError("Failure, need file extension to determine MD5 part type");
  133. }
  134. if (extension == "md5anim") {
  135. LoadMD5AnimFile();
  136. }
  137. else if (extension == "md5mesh") {
  138. LoadMD5MeshFile();
  139. }
  140. }
  141. else {
  142. LoadMD5MeshFile();
  143. LoadMD5AnimFile();
  144. }
  145. }
  146. catch ( ... ) { // std::exception, Assimp::DeadlyImportError
  147. UnloadFileFromMemory();
  148. throw;
  149. }
  150. // make sure we have at least one file
  151. if (!bHadMD5Mesh && !bHadMD5Anim && !bHadMD5Camera) {
  152. throw DeadlyImportError("Failed to read valid contents out of this MD5* file");
  153. }
  154. // Now rotate the whole scene 90 degrees around the x axis to match our internal coordinate system
  155. pScene->mRootNode->mTransformation = aiMatrix4x4(1.f,0.f,0.f,0.f,
  156. 0.f,0.f,1.f,0.f,0.f,-1.f,0.f,0.f,0.f,0.f,0.f,1.f);
  157. // the output scene wouldn't pass the validation without this flag
  158. if (!bHadMD5Mesh) {
  159. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  160. }
  161. // clean the instance -- the BaseImporter instance may be reused later.
  162. UnloadFileFromMemory();
  163. }
  164. // ------------------------------------------------------------------------------------------------
  165. // Load a file into a memory buffer
  166. void MD5Importer::LoadFileIntoMemory (IOStream* file)
  167. {
  168. // unload the previous buffer, if any
  169. UnloadFileFromMemory();
  170. ai_assert(NULL != file);
  171. fileSize = (unsigned int)file->FileSize();
  172. ai_assert(fileSize);
  173. // allocate storage and copy the contents of the file to a memory buffer
  174. mBuffer = new char[fileSize+1];
  175. file->Read( (void*)mBuffer, 1, fileSize);
  176. iLineNumber = 1;
  177. // append a terminal 0
  178. mBuffer[fileSize] = '\0';
  179. // now remove all line comments from the file
  180. CommentRemover::RemoveLineComments("//",mBuffer,' ');
  181. }
  182. // ------------------------------------------------------------------------------------------------
  183. // Unload the current memory buffer
  184. void MD5Importer::UnloadFileFromMemory ()
  185. {
  186. // delete the file buffer
  187. delete[] mBuffer;
  188. mBuffer = NULL;
  189. fileSize = 0;
  190. }
  191. // ------------------------------------------------------------------------------------------------
  192. // Build unique vertices
  193. void MD5Importer::MakeDataUnique (MD5::MeshDesc& meshSrc)
  194. {
  195. std::vector<bool> abHad(meshSrc.mVertices.size(),false);
  196. // allocate enough storage to keep the output structures
  197. const unsigned int iNewNum = static_cast<unsigned int>(meshSrc.mFaces.size()*3);
  198. unsigned int iNewIndex = static_cast<unsigned int>(meshSrc.mVertices.size());
  199. meshSrc.mVertices.resize(iNewNum);
  200. // try to guess how much storage we'll need for new weights
  201. const float fWeightsPerVert = meshSrc.mWeights.size() / (float)iNewIndex;
  202. const unsigned int guess = (unsigned int)(fWeightsPerVert*iNewNum);
  203. meshSrc.mWeights.reserve(guess + (guess >> 3)); // + 12.5% as buffer
  204. for (FaceList::const_iterator iter = meshSrc.mFaces.begin(),iterEnd = meshSrc.mFaces.end();iter != iterEnd;++iter){
  205. const aiFace& face = *iter;
  206. for (unsigned int i = 0; i < 3;++i) {
  207. if (face.mIndices[0] >= meshSrc.mVertices.size()) {
  208. throw DeadlyImportError("MD5MESH: Invalid vertex index");
  209. }
  210. if (abHad[face.mIndices[i]]) {
  211. // generate a new vertex
  212. meshSrc.mVertices[iNewIndex] = meshSrc.mVertices[face.mIndices[i]];
  213. face.mIndices[i] = iNewIndex++;
  214. }
  215. else abHad[face.mIndices[i]] = true;
  216. }
  217. // swap face order
  218. std::swap(face.mIndices[0],face.mIndices[2]);
  219. }
  220. }
  221. // ------------------------------------------------------------------------------------------------
  222. // Recursive node graph construction from a MD5MESH
  223. void MD5Importer::AttachChilds_Mesh(int iParentID,aiNode* piParent, BoneList& bones)
  224. {
  225. ai_assert(NULL != piParent && !piParent->mNumChildren);
  226. // First find out how many children we'll have
  227. for (int i = 0; i < (int)bones.size();++i) {
  228. if (iParentID != i && bones[i].mParentIndex == iParentID) {
  229. ++piParent->mNumChildren;
  230. }
  231. }
  232. if (piParent->mNumChildren) {
  233. piParent->mChildren = new aiNode*[piParent->mNumChildren];
  234. for (int i = 0; i < (int)bones.size();++i) {
  235. // (avoid infinite recursion)
  236. if (iParentID != i && bones[i].mParentIndex == iParentID) {
  237. aiNode* pc;
  238. // setup a new node
  239. *piParent->mChildren++ = pc = new aiNode();
  240. pc->mName = aiString(bones[i].mName);
  241. pc->mParent = piParent;
  242. // get the transformation matrix from rotation and translational components
  243. aiQuaternion quat;
  244. MD5::ConvertQuaternion ( bones[i].mRotationQuat, quat );
  245. bones[i].mTransform = aiMatrix4x4 ( quat.GetMatrix());
  246. bones[i].mTransform.a4 = bones[i].mPositionXYZ.x;
  247. bones[i].mTransform.b4 = bones[i].mPositionXYZ.y;
  248. bones[i].mTransform.c4 = bones[i].mPositionXYZ.z;
  249. // store it for later use
  250. pc->mTransformation = bones[i].mInvTransform = bones[i].mTransform;
  251. bones[i].mInvTransform.Inverse();
  252. // the transformations for each bone are absolute, so we need to multiply them
  253. // with the inverse of the absolute matrix of the parent joint
  254. if (-1 != iParentID) {
  255. pc->mTransformation = bones[iParentID].mInvTransform * pc->mTransformation;
  256. }
  257. // add children to this node, too
  258. AttachChilds_Mesh( i, pc, bones);
  259. }
  260. }
  261. // undo offset computations
  262. piParent->mChildren -= piParent->mNumChildren;
  263. }
  264. }
  265. // ------------------------------------------------------------------------------------------------
  266. // Recursive node graph construction from a MD5ANIM
  267. void MD5Importer::AttachChilds_Anim(int iParentID,aiNode* piParent, AnimBoneList& bones,const aiNodeAnim** node_anims)
  268. {
  269. ai_assert(NULL != piParent && !piParent->mNumChildren);
  270. // First find out how many children we'll have
  271. for (int i = 0; i < (int)bones.size();++i) {
  272. if (iParentID != i && bones[i].mParentIndex == iParentID) {
  273. ++piParent->mNumChildren;
  274. }
  275. }
  276. if (piParent->mNumChildren) {
  277. piParent->mChildren = new aiNode*[piParent->mNumChildren];
  278. for (int i = 0; i < (int)bones.size();++i) {
  279. // (avoid infinite recursion)
  280. if (iParentID != i && bones[i].mParentIndex == iParentID)
  281. {
  282. aiNode* pc;
  283. // setup a new node
  284. *piParent->mChildren++ = pc = new aiNode();
  285. pc->mName = aiString(bones[i].mName);
  286. pc->mParent = piParent;
  287. // get the corresponding animation channel and its first frame
  288. const aiNodeAnim** cur = node_anims;
  289. while ((**cur).mNodeName != pc->mName)++cur;
  290. aiMatrix4x4::Translation((**cur).mPositionKeys[0].mValue,pc->mTransformation);
  291. pc->mTransformation = pc->mTransformation * aiMatrix4x4((**cur).mRotationKeys[0].mValue.GetMatrix()) ;
  292. // add children to this node, too
  293. AttachChilds_Anim( i, pc, bones,node_anims);
  294. }
  295. }
  296. // undo offset computations
  297. piParent->mChildren -= piParent->mNumChildren;
  298. }
  299. }
  300. // ------------------------------------------------------------------------------------------------
  301. // Load a MD5MESH file
  302. void MD5Importer::LoadMD5MeshFile ()
  303. {
  304. std::string pFile = mFile + "md5mesh";
  305. std::unique_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  306. // Check whether we can read from the file
  307. if( file.get() == NULL || !file->FileSize()) {
  308. ASSIMP_LOG_WARN("Failed to access MD5MESH file: " + pFile);
  309. return;
  310. }
  311. bHadMD5Mesh = true;
  312. LoadFileIntoMemory(file.get());
  313. // now construct a parser and parse the file
  314. MD5::MD5Parser parser(mBuffer,fileSize);
  315. // load the mesh information from it
  316. MD5::MD5MeshParser meshParser(parser.mSections);
  317. // create the bone hierarchy - first the root node and dummy nodes for all meshes
  318. pScene->mRootNode = new aiNode("<MD5_Root>");
  319. pScene->mRootNode->mNumChildren = 2;
  320. pScene->mRootNode->mChildren = new aiNode*[2];
  321. // build the hierarchy from the MD5MESH file
  322. aiNode* pcNode = pScene->mRootNode->mChildren[1] = new aiNode();
  323. pcNode->mName.Set("<MD5_Hierarchy>");
  324. pcNode->mParent = pScene->mRootNode;
  325. AttachChilds_Mesh(-1,pcNode,meshParser.mJoints);
  326. pcNode = pScene->mRootNode->mChildren[0] = new aiNode();
  327. pcNode->mName.Set("<MD5_Mesh>");
  328. pcNode->mParent = pScene->mRootNode;
  329. #if 0
  330. if (pScene->mRootNode->mChildren[1]->mNumChildren) /* start at the right hierarchy level */
  331. SkeletonMeshBuilder skeleton_maker(pScene,pScene->mRootNode->mChildren[1]->mChildren[0]);
  332. #else
  333. // FIX: MD5 files exported from Blender can have empty meshes
  334. for (std::vector<MD5::MeshDesc>::const_iterator it = meshParser.mMeshes.begin(),end = meshParser.mMeshes.end(); it != end;++it) {
  335. if (!(*it).mFaces.empty() && !(*it).mVertices.empty())
  336. ++pScene->mNumMaterials;
  337. }
  338. // generate all meshes
  339. pScene->mNumMeshes = pScene->mNumMaterials;
  340. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  341. pScene->mMaterials = new aiMaterial*[pScene->mNumMeshes];
  342. // storage for node mesh indices
  343. pcNode->mNumMeshes = pScene->mNumMeshes;
  344. pcNode->mMeshes = new unsigned int[pcNode->mNumMeshes];
  345. for (unsigned int m = 0; m < pcNode->mNumMeshes;++m)
  346. pcNode->mMeshes[m] = m;
  347. unsigned int n = 0;
  348. for (std::vector<MD5::MeshDesc>::iterator it = meshParser.mMeshes.begin(),end = meshParser.mMeshes.end(); it != end;++it) {
  349. MD5::MeshDesc& meshSrc = *it;
  350. if (meshSrc.mFaces.empty() || meshSrc.mVertices.empty())
  351. continue;
  352. aiMesh* mesh = pScene->mMeshes[n] = new aiMesh();
  353. mesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  354. // generate unique vertices in our internal verbose format
  355. MakeDataUnique(meshSrc);
  356. std::string name( meshSrc.mShader.C_Str() );
  357. name += ".msh";
  358. mesh->mName = name;
  359. mesh->mNumVertices = (unsigned int) meshSrc.mVertices.size();
  360. mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  361. mesh->mTextureCoords[0] = new aiVector3D[mesh->mNumVertices];
  362. mesh->mNumUVComponents[0] = 2;
  363. // copy texture coordinates
  364. aiVector3D* pv = mesh->mTextureCoords[0];
  365. for (MD5::VertexList::const_iterator iter = meshSrc.mVertices.begin();iter != meshSrc.mVertices.end();++iter,++pv) {
  366. pv->x = (*iter).mUV.x;
  367. pv->y = 1.0f-(*iter).mUV.y; // D3D to OpenGL
  368. pv->z = 0.0f;
  369. }
  370. // sort all bone weights - per bone
  371. unsigned int* piCount = new unsigned int[meshParser.mJoints.size()];
  372. ::memset(piCount,0,sizeof(unsigned int)*meshParser.mJoints.size());
  373. for (MD5::VertexList::const_iterator iter = meshSrc.mVertices.begin();iter != meshSrc.mVertices.end();++iter,++pv) {
  374. for (unsigned int jub = (*iter).mFirstWeight, w = jub; w < jub + (*iter).mNumWeights;++w)
  375. {
  376. MD5::WeightDesc& weightDesc = meshSrc.mWeights[w];
  377. /* FIX for some invalid exporters */
  378. if (!(weightDesc.mWeight < AI_MD5_WEIGHT_EPSILON && weightDesc.mWeight >= -AI_MD5_WEIGHT_EPSILON ))
  379. ++piCount[weightDesc.mBone];
  380. }
  381. }
  382. // check how many we will need
  383. for (unsigned int p = 0; p < meshParser.mJoints.size();++p)
  384. if (piCount[p])mesh->mNumBones++;
  385. if (mesh->mNumBones) // just for safety
  386. {
  387. mesh->mBones = new aiBone*[mesh->mNumBones];
  388. for (unsigned int q = 0,h = 0; q < meshParser.mJoints.size();++q)
  389. {
  390. if (!piCount[q])continue;
  391. aiBone* p = mesh->mBones[h] = new aiBone();
  392. p->mNumWeights = piCount[q];
  393. p->mWeights = new aiVertexWeight[p->mNumWeights];
  394. p->mName = aiString(meshParser.mJoints[q].mName);
  395. p->mOffsetMatrix = meshParser.mJoints[q].mInvTransform;
  396. // store the index for later use
  397. MD5::BoneDesc& boneSrc = meshParser.mJoints[q];
  398. boneSrc.mMap = h++;
  399. // compute w-component of quaternion
  400. MD5::ConvertQuaternion( boneSrc.mRotationQuat, boneSrc.mRotationQuatConverted );
  401. }
  402. pv = mesh->mVertices;
  403. for (MD5::VertexList::const_iterator iter = meshSrc.mVertices.begin();iter != meshSrc.mVertices.end();++iter,++pv) {
  404. // compute the final vertex position from all single weights
  405. *pv = aiVector3D();
  406. // there are models which have weights which don't sum to 1 ...
  407. ai_real fSum = 0.0;
  408. for (unsigned int jub = (*iter).mFirstWeight, w = jub; w < jub + (*iter).mNumWeights;++w)
  409. fSum += meshSrc.mWeights[w].mWeight;
  410. if (!fSum) {
  411. ASSIMP_LOG_ERROR("MD5MESH: The sum of all vertex bone weights is 0");
  412. continue;
  413. }
  414. // process bone weights
  415. for (unsigned int jub = (*iter).mFirstWeight, w = jub; w < jub + (*iter).mNumWeights;++w) {
  416. if (w >= meshSrc.mWeights.size())
  417. throw DeadlyImportError("MD5MESH: Invalid weight index");
  418. MD5::WeightDesc& weightDesc = meshSrc.mWeights[w];
  419. if ( weightDesc.mWeight < AI_MD5_WEIGHT_EPSILON && weightDesc.mWeight >= -AI_MD5_WEIGHT_EPSILON) {
  420. continue;
  421. }
  422. const ai_real fNewWeight = weightDesc.mWeight / fSum;
  423. // transform the local position into worldspace
  424. MD5::BoneDesc& boneSrc = meshParser.mJoints[weightDesc.mBone];
  425. const aiVector3D v = boneSrc.mRotationQuatConverted.Rotate (weightDesc.vOffsetPosition);
  426. // use the original weight to compute the vertex position
  427. // (some MD5s seem to depend on the invalid weight values ...)
  428. *pv += ((boneSrc.mPositionXYZ+v)* (ai_real)weightDesc.mWeight);
  429. aiBone* bone = mesh->mBones[boneSrc.mMap];
  430. *bone->mWeights++ = aiVertexWeight((unsigned int)(pv-mesh->mVertices),fNewWeight);
  431. }
  432. }
  433. // undo our nice offset tricks ...
  434. for (unsigned int p = 0; p < mesh->mNumBones;++p) {
  435. mesh->mBones[p]->mWeights -= mesh->mBones[p]->mNumWeights;
  436. }
  437. }
  438. delete[] piCount;
  439. // now setup all faces - we can directly copy the list
  440. // (however, take care that the aiFace destructor doesn't delete the mIndices array)
  441. mesh->mNumFaces = (unsigned int)meshSrc.mFaces.size();
  442. mesh->mFaces = new aiFace[mesh->mNumFaces];
  443. for (unsigned int c = 0; c < mesh->mNumFaces;++c) {
  444. mesh->mFaces[c].mNumIndices = 3;
  445. mesh->mFaces[c].mIndices = meshSrc.mFaces[c].mIndices;
  446. meshSrc.mFaces[c].mIndices = NULL;
  447. }
  448. // generate a material for the mesh
  449. aiMaterial* mat = new aiMaterial();
  450. pScene->mMaterials[n] = mat;
  451. // insert the typical doom3 textures:
  452. // nnn_local.tga - normal map
  453. // nnn_h.tga - height map
  454. // nnn_s.tga - specular map
  455. // nnn_d.tga - diffuse map
  456. if (meshSrc.mShader.length && !strchr(meshSrc.mShader.data,'.')) {
  457. aiString temp(meshSrc.mShader);
  458. temp.Append("_local.tga");
  459. mat->AddProperty(&temp,AI_MATKEY_TEXTURE_NORMALS(0));
  460. temp = aiString(meshSrc.mShader);
  461. temp.Append("_s.tga");
  462. mat->AddProperty(&temp,AI_MATKEY_TEXTURE_SPECULAR(0));
  463. temp = aiString(meshSrc.mShader);
  464. temp.Append("_d.tga");
  465. mat->AddProperty(&temp,AI_MATKEY_TEXTURE_DIFFUSE(0));
  466. temp = aiString(meshSrc.mShader);
  467. temp.Append("_h.tga");
  468. mat->AddProperty(&temp,AI_MATKEY_TEXTURE_HEIGHT(0));
  469. // set this also as material name
  470. mat->AddProperty(&meshSrc.mShader,AI_MATKEY_NAME);
  471. }
  472. else {
  473. mat->AddProperty(&meshSrc.mShader, AI_MATKEY_TEXTURE_DIFFUSE(0));
  474. }
  475. mesh->mMaterialIndex = n++;
  476. }
  477. #endif
  478. }
  479. // ------------------------------------------------------------------------------------------------
  480. // Load an MD5ANIM file
  481. void MD5Importer::LoadMD5AnimFile ()
  482. {
  483. std::string pFile = mFile + "md5anim";
  484. std::unique_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  485. // Check whether we can read from the file
  486. if( !file.get() || !file->FileSize()) {
  487. ASSIMP_LOG_WARN("Failed to read MD5ANIM file: " + pFile);
  488. return;
  489. }
  490. LoadFileIntoMemory(file.get());
  491. // parse the basic file structure
  492. MD5::MD5Parser parser(mBuffer,fileSize);
  493. // load the animation information from the parse tree
  494. MD5::MD5AnimParser animParser(parser.mSections);
  495. // generate and fill the output animation
  496. if (animParser.mAnimatedBones.empty() || animParser.mFrames.empty() ||
  497. animParser.mBaseFrames.size() != animParser.mAnimatedBones.size()) {
  498. ASSIMP_LOG_ERROR("MD5ANIM: No frames or animated bones loaded");
  499. }
  500. else {
  501. bHadMD5Anim = true;
  502. pScene->mAnimations = new aiAnimation*[pScene->mNumAnimations = 1];
  503. aiAnimation* anim = pScene->mAnimations[0] = new aiAnimation();
  504. anim->mNumChannels = (unsigned int)animParser.mAnimatedBones.size();
  505. anim->mChannels = new aiNodeAnim*[anim->mNumChannels];
  506. for (unsigned int i = 0; i < anim->mNumChannels;++i) {
  507. aiNodeAnim* node = anim->mChannels[i] = new aiNodeAnim();
  508. node->mNodeName = aiString( animParser.mAnimatedBones[i].mName );
  509. // allocate storage for the keyframes
  510. node->mPositionKeys = new aiVectorKey[animParser.mFrames.size()];
  511. node->mRotationKeys = new aiQuatKey[animParser.mFrames.size()];
  512. }
  513. // 1 tick == 1 frame
  514. anim->mTicksPerSecond = animParser.fFrameRate;
  515. for (FrameList::const_iterator iter = animParser.mFrames.begin(), iterEnd = animParser.mFrames.end();iter != iterEnd;++iter){
  516. double dTime = (double)(*iter).iIndex;
  517. aiNodeAnim** pcAnimNode = anim->mChannels;
  518. if (!(*iter).mValues.empty() || iter == animParser.mFrames.begin()) /* be sure we have at least one frame */
  519. {
  520. // now process all values in there ... read all joints
  521. MD5::BaseFrameDesc* pcBaseFrame = &animParser.mBaseFrames[0];
  522. for (AnimBoneList::const_iterator iter2 = animParser.mAnimatedBones.begin(); iter2 != animParser.mAnimatedBones.end();++iter2,
  523. ++pcAnimNode,++pcBaseFrame)
  524. {
  525. if((*iter2).iFirstKeyIndex >= (*iter).mValues.size()) {
  526. // Allow for empty frames
  527. if ((*iter2).iFlags != 0) {
  528. throw DeadlyImportError("MD5: Keyframe index is out of range");
  529. }
  530. continue;
  531. }
  532. const float* fpCur = &(*iter).mValues[(*iter2).iFirstKeyIndex];
  533. aiNodeAnim* pcCurAnimBone = *pcAnimNode;
  534. aiVectorKey* vKey = &pcCurAnimBone->mPositionKeys[pcCurAnimBone->mNumPositionKeys++];
  535. aiQuatKey* qKey = &pcCurAnimBone->mRotationKeys [pcCurAnimBone->mNumRotationKeys++];
  536. aiVector3D vTemp;
  537. // translational component
  538. for (unsigned int i = 0; i < 3; ++i) {
  539. if ((*iter2).iFlags & (1u << i)) {
  540. vKey->mValue[i] = *fpCur++;
  541. }
  542. else vKey->mValue[i] = pcBaseFrame->vPositionXYZ[i];
  543. }
  544. // orientation component
  545. for (unsigned int i = 0; i < 3; ++i) {
  546. if ((*iter2).iFlags & (8u << i)) {
  547. vTemp[i] = *fpCur++;
  548. }
  549. else vTemp[i] = pcBaseFrame->vRotationQuat[i];
  550. }
  551. MD5::ConvertQuaternion(vTemp, qKey->mValue);
  552. qKey->mTime = vKey->mTime = dTime;
  553. }
  554. }
  555. // compute the duration of the animation
  556. anim->mDuration = std::max(dTime,anim->mDuration);
  557. }
  558. // If we didn't build the hierarchy yet (== we didn't load a MD5MESH),
  559. // construct it now from the data given in the MD5ANIM.
  560. if (!pScene->mRootNode) {
  561. pScene->mRootNode = new aiNode();
  562. pScene->mRootNode->mName.Set("<MD5_Hierarchy>");
  563. AttachChilds_Anim(-1,pScene->mRootNode,animParser.mAnimatedBones,(const aiNodeAnim**)anim->mChannels);
  564. // Call SkeletonMeshBuilder to construct a mesh to represent the shape
  565. if (pScene->mRootNode->mNumChildren) {
  566. SkeletonMeshBuilder skeleton_maker(pScene,pScene->mRootNode->mChildren[0]);
  567. }
  568. }
  569. }
  570. }
  571. // ------------------------------------------------------------------------------------------------
  572. // Load an MD5CAMERA file
  573. void MD5Importer::LoadMD5CameraFile ()
  574. {
  575. std::string pFile = mFile + "md5camera";
  576. std::unique_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  577. // Check whether we can read from the file
  578. if( !file.get() || !file->FileSize()) {
  579. throw DeadlyImportError("Failed to read MD5CAMERA file: " + pFile);
  580. }
  581. bHadMD5Camera = true;
  582. LoadFileIntoMemory(file.get());
  583. // parse the basic file structure
  584. MD5::MD5Parser parser(mBuffer,fileSize);
  585. // load the camera animation data from the parse tree
  586. MD5::MD5CameraParser cameraParser(parser.mSections);
  587. if (cameraParser.frames.empty()) {
  588. throw DeadlyImportError("MD5CAMERA: No frames parsed");
  589. }
  590. std::vector<unsigned int>& cuts = cameraParser.cuts;
  591. std::vector<MD5::CameraAnimFrameDesc>& frames = cameraParser.frames;
  592. // Construct output graph - a simple root with a dummy child.
  593. // The root node performs the coordinate system conversion
  594. aiNode* root = pScene->mRootNode = new aiNode("<MD5CameraRoot>");
  595. root->mChildren = new aiNode*[root->mNumChildren = 1];
  596. root->mChildren[0] = new aiNode("<MD5Camera>");
  597. root->mChildren[0]->mParent = root;
  598. // ... but with one camera assigned to it
  599. pScene->mCameras = new aiCamera*[pScene->mNumCameras = 1];
  600. aiCamera* cam = pScene->mCameras[0] = new aiCamera();
  601. cam->mName = "<MD5Camera>";
  602. // FIXME: Fov is currently set to the first frame's value
  603. cam->mHorizontalFOV = AI_DEG_TO_RAD( frames.front().fFOV );
  604. // every cut is written to a separate aiAnimation
  605. if (!cuts.size()) {
  606. cuts.push_back(0);
  607. cuts.push_back(static_cast<unsigned int>(frames.size()-1));
  608. }
  609. else {
  610. cuts.insert(cuts.begin(),0);
  611. if (cuts.back() < frames.size()-1)
  612. cuts.push_back(static_cast<unsigned int>(frames.size()-1));
  613. }
  614. pScene->mNumAnimations = static_cast<unsigned int>(cuts.size()-1);
  615. aiAnimation** tmp = pScene->mAnimations = new aiAnimation*[pScene->mNumAnimations];
  616. for (std::vector<unsigned int>::const_iterator it = cuts.begin(); it != cuts.end()-1; ++it) {
  617. aiAnimation* anim = *tmp++ = new aiAnimation();
  618. anim->mName.length = ::ai_snprintf(anim->mName.data, MAXLEN, "anim%u_from_%u_to_%u",(unsigned int)(it-cuts.begin()),(*it),*(it+1));
  619. anim->mTicksPerSecond = cameraParser.fFrameRate;
  620. anim->mChannels = new aiNodeAnim*[anim->mNumChannels = 1];
  621. aiNodeAnim* nd = anim->mChannels[0] = new aiNodeAnim();
  622. nd->mNodeName.Set("<MD5Camera>");
  623. nd->mNumPositionKeys = nd->mNumRotationKeys = *(it+1) - (*it);
  624. nd->mPositionKeys = new aiVectorKey[nd->mNumPositionKeys];
  625. nd->mRotationKeys = new aiQuatKey [nd->mNumRotationKeys];
  626. for (unsigned int i = 0; i < nd->mNumPositionKeys; ++i) {
  627. nd->mPositionKeys[i].mValue = frames[*it+i].vPositionXYZ;
  628. MD5::ConvertQuaternion(frames[*it+i].vRotationQuat,nd->mRotationKeys[i].mValue);
  629. nd->mRotationKeys[i].mTime = nd->mPositionKeys[i].mTime = *it+i;
  630. }
  631. }
  632. }
  633. #endif // !! ASSIMP_BUILD_NO_MD5_IMPORTER