MD5Loader.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2015, 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 "RemoveComments.h"
  40. #include "MD5Loader.h"
  41. #include "StringComparison.h"
  42. #include "fast_atof.h"
  43. #include "SkeletonMeshBuilder.h"
  44. #include "../include/assimp/Importer.hpp"
  45. #include "../include/assimp/scene.h"
  46. #include <boost/scoped_ptr.hpp>
  47. #include "../include/assimp/IOSystem.hpp"
  48. #include "../include/assimp/DefaultLogger.hpp"
  49. using namespace Assimp;
  50. // Minimum weight value. Weights inside [-n ... n] are ignored
  51. #define AI_MD5_WEIGHT_EPSILON 1e-5f
  52. static const aiImporterDesc desc = {
  53. "Doom 3 / MD5 Mesh Importer",
  54. "",
  55. "",
  56. "",
  57. aiImporterFlags_SupportBinaryFlavour,
  58. 0,
  59. 0,
  60. 0,
  61. 0,
  62. "md5mesh md5camera md5anim"
  63. };
  64. // ------------------------------------------------------------------------------------------------
  65. // Constructor to be privately used by Importer
  66. MD5Importer::MD5Importer()
  67. : mIOHandler()
  68. , mBuffer()
  69. , fileSize()
  70. , iLineNumber()
  71. , pScene()
  72. , pIOHandler()
  73. , bHadMD5Mesh()
  74. , bHadMD5Anim()
  75. , bHadMD5Camera()
  76. , configNoAutoLoad (false)
  77. {}
  78. // ------------------------------------------------------------------------------------------------
  79. // Destructor, private as well
  80. MD5Importer::~MD5Importer()
  81. {}
  82. // ------------------------------------------------------------------------------------------------
  83. // Returns whether the class can handle the format of the given file.
  84. bool MD5Importer::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  85. {
  86. const std::string extension = GetExtension(pFile);
  87. if (extension == "md5anim" || extension == "md5mesh" || extension == "md5camera")
  88. return true;
  89. else if (!extension.length() || checkSig) {
  90. if (!pIOHandler) {
  91. return true;
  92. }
  93. const char* tokens[] = {"MD5Version"};
  94. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,1);
  95. }
  96. return false;
  97. }
  98. // ------------------------------------------------------------------------------------------------
  99. // Get list of all supported extensions
  100. const aiImporterDesc* MD5Importer::GetInfo () const
  101. {
  102. return &desc;
  103. }
  104. // ------------------------------------------------------------------------------------------------
  105. // Setup import properties
  106. void MD5Importer::SetupProperties(const Importer* pImp)
  107. {
  108. // AI_CONFIG_IMPORT_MD5_NO_ANIM_AUTOLOAD
  109. configNoAutoLoad = (0 != pImp->GetPropertyInteger(AI_CONFIG_IMPORT_MD5_NO_ANIM_AUTOLOAD,0));
  110. }
  111. // ------------------------------------------------------------------------------------------------
  112. // Imports the given file into the given scene structure.
  113. void MD5Importer::InternReadFile( const std::string& pFile,
  114. aiScene* _pScene, IOSystem* _pIOHandler)
  115. {
  116. pIOHandler = _pIOHandler;
  117. pScene = _pScene;
  118. bHadMD5Mesh = bHadMD5Anim = bHadMD5Camera = false;
  119. // remove the file extension
  120. const std::string::size_type pos = pFile.find_last_of('.');
  121. mFile = (std::string::npos == pos ? pFile : pFile.substr(0,pos+1));
  122. const std::string extension = GetExtension(pFile);
  123. try {
  124. if (extension == "md5camera") {
  125. LoadMD5CameraFile();
  126. }
  127. else if (configNoAutoLoad || extension == "md5anim") {
  128. // determine file extension and process just *one* file
  129. if (extension.length() == 0) {
  130. throw DeadlyImportError("Failure, need file extension to determine MD5 part type");
  131. }
  132. if (extension == "md5anim") {
  133. LoadMD5AnimFile();
  134. }
  135. else if (extension == "md5mesh") {
  136. LoadMD5MeshFile();
  137. }
  138. }
  139. else {
  140. LoadMD5MeshFile();
  141. LoadMD5AnimFile();
  142. }
  143. }
  144. catch ( ... ) { // std::exception, Assimp::DeadlyImportError
  145. UnloadFileFromMemory();
  146. throw;
  147. }
  148. // make sure we have at least one file
  149. if (!bHadMD5Mesh && !bHadMD5Anim && !bHadMD5Camera) {
  150. throw DeadlyImportError("Failed to read valid contents out of this MD5* file");
  151. }
  152. // Now rotate the whole scene 90 degrees around the x axis to match our internal coordinate system
  153. pScene->mRootNode->mTransformation = aiMatrix4x4(1.f,0.f,0.f,0.f,
  154. 0.f,0.f,1.f,0.f,0.f,-1.f,0.f,0.f,0.f,0.f,0.f,1.f);
  155. // the output scene wouldn't pass the validation without this flag
  156. if (!bHadMD5Mesh) {
  157. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  158. }
  159. // clean the instance -- the BaseImporter instance may be reused later.
  160. UnloadFileFromMemory();
  161. }
  162. // ------------------------------------------------------------------------------------------------
  163. // Load a file into a memory buffer
  164. void MD5Importer::LoadFileIntoMemory (IOStream* file)
  165. {
  166. // unload the previous buffer, if any
  167. UnloadFileFromMemory();
  168. ai_assert(NULL != file);
  169. fileSize = (unsigned int)file->FileSize();
  170. ai_assert(fileSize);
  171. // allocate storage and copy the contents of the file to a memory buffer
  172. mBuffer = new char[fileSize+1];
  173. file->Read( (void*)mBuffer, 1, fileSize);
  174. iLineNumber = 1;
  175. // append a terminal 0
  176. mBuffer[fileSize] = '\0';
  177. // now remove all line comments from the file
  178. CommentRemover::RemoveLineComments("//",mBuffer,' ');
  179. }
  180. // ------------------------------------------------------------------------------------------------
  181. // Unload the current memory buffer
  182. void MD5Importer::UnloadFileFromMemory ()
  183. {
  184. // delete the file buffer
  185. delete[] mBuffer;
  186. mBuffer = NULL;
  187. fileSize = 0;
  188. }
  189. // ------------------------------------------------------------------------------------------------
  190. // Build unique vertices
  191. void MD5Importer::MakeDataUnique (MD5::MeshDesc& meshSrc)
  192. {
  193. std::vector<bool> abHad(meshSrc.mVertices.size(),false);
  194. // allocate enough storage to keep the output structures
  195. const unsigned int iNewNum = meshSrc.mFaces.size()*3;
  196. unsigned int iNewIndex = meshSrc.mVertices.size();
  197. meshSrc.mVertices.resize(iNewNum);
  198. // try to guess how much storage we'll need for new weights
  199. const float fWeightsPerVert = meshSrc.mWeights.size() / (float)iNewIndex;
  200. const unsigned int guess = (unsigned int)(fWeightsPerVert*iNewNum);
  201. meshSrc.mWeights.reserve(guess + (guess >> 3)); // + 12.5% as buffer
  202. for (FaceList::const_iterator iter = meshSrc.mFaces.begin(),iterEnd = meshSrc.mFaces.end();iter != iterEnd;++iter){
  203. const aiFace& face = *iter;
  204. for (unsigned int i = 0; i < 3;++i) {
  205. if (face.mIndices[0] >= meshSrc.mVertices.size()) {
  206. throw DeadlyImportError("MD5MESH: Invalid vertex index");
  207. }
  208. if (abHad[face.mIndices[i]]) {
  209. // generate a new vertex
  210. meshSrc.mVertices[iNewIndex] = meshSrc.mVertices[face.mIndices[i]];
  211. face.mIndices[i] = iNewIndex++;
  212. }
  213. else abHad[face.mIndices[i]] = true;
  214. }
  215. // swap face order
  216. std::swap(face.mIndices[0],face.mIndices[2]);
  217. }
  218. }
  219. // ------------------------------------------------------------------------------------------------
  220. // Recursive node graph construction from a MD5MESH
  221. void MD5Importer::AttachChilds_Mesh(int iParentID,aiNode* piParent, BoneList& bones)
  222. {
  223. ai_assert(NULL != piParent && !piParent->mNumChildren);
  224. // First find out how many children we'll have
  225. for (int i = 0; i < (int)bones.size();++i) {
  226. if (iParentID != i && bones[i].mParentIndex == iParentID) {
  227. ++piParent->mNumChildren;
  228. }
  229. }
  230. if (piParent->mNumChildren) {
  231. piParent->mChildren = new aiNode*[piParent->mNumChildren];
  232. for (int i = 0; i < (int)bones.size();++i) {
  233. // (avoid infinite recursion)
  234. if (iParentID != i && bones[i].mParentIndex == iParentID) {
  235. aiNode* pc;
  236. // setup a new node
  237. *piParent->mChildren++ = pc = new aiNode();
  238. pc->mName = aiString(bones[i].mName);
  239. pc->mParent = piParent;
  240. // get the transformation matrix from rotation and translational components
  241. aiQuaternion quat;
  242. MD5::ConvertQuaternion ( bones[i].mRotationQuat, quat );
  243. // FIX to get to Assimp's quaternion conventions
  244. quat.w *= -1.f;
  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. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  306. // Check whether we can read from the file
  307. if( file.get() == NULL || !file->FileSize()) {
  308. DefaultLogger::get()->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. mesh->mNumVertices = (unsigned int) meshSrc.mVertices.size();
  357. mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  358. mesh->mTextureCoords[0] = new aiVector3D[mesh->mNumVertices];
  359. mesh->mNumUVComponents[0] = 2;
  360. // copy texture coordinates
  361. aiVector3D* pv = mesh->mTextureCoords[0];
  362. for (MD5::VertexList::const_iterator iter = meshSrc.mVertices.begin();iter != meshSrc.mVertices.end();++iter,++pv) {
  363. pv->x = (*iter).mUV.x;
  364. pv->y = 1.0f-(*iter).mUV.y; // D3D to OpenGL
  365. pv->z = 0.0f;
  366. }
  367. // sort all bone weights - per bone
  368. unsigned int* piCount = new unsigned int[meshParser.mJoints.size()];
  369. ::memset(piCount,0,sizeof(unsigned int)*meshParser.mJoints.size());
  370. for (MD5::VertexList::const_iterator iter = meshSrc.mVertices.begin();iter != meshSrc.mVertices.end();++iter,++pv) {
  371. for (unsigned int jub = (*iter).mFirstWeight, w = jub; w < jub + (*iter).mNumWeights;++w)
  372. {
  373. MD5::WeightDesc& desc = meshSrc.mWeights[w];
  374. /* FIX for some invalid exporters */
  375. if (!(desc.mWeight < AI_MD5_WEIGHT_EPSILON && desc.mWeight >= -AI_MD5_WEIGHT_EPSILON ))
  376. ++piCount[desc.mBone];
  377. }
  378. }
  379. // check how many we will need
  380. for (unsigned int p = 0; p < meshParser.mJoints.size();++p)
  381. if (piCount[p])mesh->mNumBones++;
  382. if (mesh->mNumBones) // just for safety
  383. {
  384. mesh->mBones = new aiBone*[mesh->mNumBones];
  385. for (unsigned int q = 0,h = 0; q < meshParser.mJoints.size();++q)
  386. {
  387. if (!piCount[q])continue;
  388. aiBone* p = mesh->mBones[h] = new aiBone();
  389. p->mNumWeights = piCount[q];
  390. p->mWeights = new aiVertexWeight[p->mNumWeights];
  391. p->mName = aiString(meshParser.mJoints[q].mName);
  392. p->mOffsetMatrix = meshParser.mJoints[q].mInvTransform;
  393. // store the index for later use
  394. MD5::BoneDesc& boneSrc = meshParser.mJoints[q];
  395. boneSrc.mMap = h++;
  396. // compute w-component of quaternion
  397. MD5::ConvertQuaternion( boneSrc.mRotationQuat, boneSrc.mRotationQuatConverted );
  398. }
  399. //unsigned int g = 0;
  400. pv = mesh->mVertices;
  401. for (MD5::VertexList::const_iterator iter = meshSrc.mVertices.begin();iter != meshSrc.mVertices.end();++iter,++pv) {
  402. // compute the final vertex position from all single weights
  403. *pv = aiVector3D();
  404. // there are models which have weights which don't sum to 1 ...
  405. float fSum = 0.0f;
  406. for (unsigned int jub = (*iter).mFirstWeight, w = jub; w < jub + (*iter).mNumWeights;++w)
  407. fSum += meshSrc.mWeights[w].mWeight;
  408. if (!fSum) {
  409. DefaultLogger::get()->error("MD5MESH: The sum of all vertex bone weights is 0");
  410. continue;
  411. }
  412. // process bone weights
  413. for (unsigned int jub = (*iter).mFirstWeight, w = jub; w < jub + (*iter).mNumWeights;++w) {
  414. if (w >= meshSrc.mWeights.size())
  415. throw DeadlyImportError("MD5MESH: Invalid weight index");
  416. MD5::WeightDesc& desc = meshSrc.mWeights[w];
  417. if ( desc.mWeight < AI_MD5_WEIGHT_EPSILON && desc.mWeight >= -AI_MD5_WEIGHT_EPSILON) {
  418. continue;
  419. }
  420. const float fNewWeight = desc.mWeight / fSum;
  421. // transform the local position into worldspace
  422. MD5::BoneDesc& boneSrc = meshParser.mJoints[desc.mBone];
  423. const aiVector3D v = boneSrc.mRotationQuatConverted.Rotate (desc.vOffsetPosition);
  424. // use the original weight to compute the vertex position
  425. // (some MD5s seem to depend on the invalid weight values ...)
  426. *pv += ((boneSrc.mPositionXYZ+v)* desc.mWeight);
  427. aiBone* bone = mesh->mBones[boneSrc.mMap];
  428. *bone->mWeights++ = aiVertexWeight((unsigned int)(pv-mesh->mVertices),fNewWeight);
  429. }
  430. }
  431. // undo our nice offset tricks ...
  432. for (unsigned int p = 0; p < mesh->mNumBones;++p) {
  433. mesh->mBones[p]->mWeights -= mesh->mBones[p]->mNumWeights;
  434. }
  435. }
  436. delete[] piCount;
  437. // now setup all faces - we can directly copy the list
  438. // (however, take care that the aiFace destructor doesn't delete the mIndices array)
  439. mesh->mNumFaces = (unsigned int)meshSrc.mFaces.size();
  440. mesh->mFaces = new aiFace[mesh->mNumFaces];
  441. for (unsigned int c = 0; c < mesh->mNumFaces;++c) {
  442. mesh->mFaces[c].mNumIndices = 3;
  443. mesh->mFaces[c].mIndices = meshSrc.mFaces[c].mIndices;
  444. meshSrc.mFaces[c].mIndices = NULL;
  445. }
  446. // generate a material for the mesh
  447. aiMaterial* mat = new aiMaterial();
  448. pScene->mMaterials[n] = mat;
  449. // insert the typical doom3 textures:
  450. // nnn_local.tga - normal map
  451. // nnn_h.tga - height map
  452. // nnn_s.tga - specular map
  453. // nnn_d.tga - diffuse map
  454. if (meshSrc.mShader.length && !strchr(meshSrc.mShader.data,'.')) {
  455. aiString temp(meshSrc.mShader);
  456. temp.Append("_local.tga");
  457. mat->AddProperty(&temp,AI_MATKEY_TEXTURE_NORMALS(0));
  458. temp = aiString(meshSrc.mShader);
  459. temp.Append("_s.tga");
  460. mat->AddProperty(&temp,AI_MATKEY_TEXTURE_SPECULAR(0));
  461. temp = aiString(meshSrc.mShader);
  462. temp.Append("_d.tga");
  463. mat->AddProperty(&temp,AI_MATKEY_TEXTURE_DIFFUSE(0));
  464. temp = aiString(meshSrc.mShader);
  465. temp.Append("_h.tga");
  466. mat->AddProperty(&temp,AI_MATKEY_TEXTURE_HEIGHT(0));
  467. // set this also as material name
  468. mat->AddProperty(&meshSrc.mShader,AI_MATKEY_NAME);
  469. }
  470. else mat->AddProperty(&meshSrc.mShader,AI_MATKEY_TEXTURE_DIFFUSE(0));
  471. mesh->mMaterialIndex = n++;
  472. }
  473. #endif
  474. }
  475. // ------------------------------------------------------------------------------------------------
  476. // Load an MD5ANIM file
  477. void MD5Importer::LoadMD5AnimFile ()
  478. {
  479. std::string pFile = mFile + "md5anim";
  480. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  481. // Check whether we can read from the file
  482. if( !file.get() || !file->FileSize()) {
  483. DefaultLogger::get()->warn("Failed to read MD5ANIM file: " + pFile);
  484. return;
  485. }
  486. LoadFileIntoMemory(file.get());
  487. // parse the basic file structure
  488. MD5::MD5Parser parser(mBuffer,fileSize);
  489. // load the animation information from the parse tree
  490. MD5::MD5AnimParser animParser(parser.mSections);
  491. // generate and fill the output animation
  492. if (animParser.mAnimatedBones.empty() || animParser.mFrames.empty() ||
  493. animParser.mBaseFrames.size() != animParser.mAnimatedBones.size()) {
  494. DefaultLogger::get()->error("MD5ANIM: No frames or animated bones loaded");
  495. }
  496. else {
  497. bHadMD5Anim = true;
  498. pScene->mAnimations = new aiAnimation*[pScene->mNumAnimations = 1];
  499. aiAnimation* anim = pScene->mAnimations[0] = new aiAnimation();
  500. anim->mNumChannels = (unsigned int)animParser.mAnimatedBones.size();
  501. anim->mChannels = new aiNodeAnim*[anim->mNumChannels];
  502. for (unsigned int i = 0; i < anim->mNumChannels;++i) {
  503. aiNodeAnim* node = anim->mChannels[i] = new aiNodeAnim();
  504. node->mNodeName = aiString( animParser.mAnimatedBones[i].mName );
  505. // allocate storage for the keyframes
  506. node->mPositionKeys = new aiVectorKey[animParser.mFrames.size()];
  507. node->mRotationKeys = new aiQuatKey[animParser.mFrames.size()];
  508. }
  509. // 1 tick == 1 frame
  510. anim->mTicksPerSecond = animParser.fFrameRate;
  511. for (FrameList::const_iterator iter = animParser.mFrames.begin(), iterEnd = animParser.mFrames.end();iter != iterEnd;++iter){
  512. double dTime = (double)(*iter).iIndex;
  513. aiNodeAnim** pcAnimNode = anim->mChannels;
  514. if (!(*iter).mValues.empty() || iter == animParser.mFrames.begin()) /* be sure we have at least one frame */
  515. {
  516. // now process all values in there ... read all joints
  517. MD5::BaseFrameDesc* pcBaseFrame = &animParser.mBaseFrames[0];
  518. for (AnimBoneList::const_iterator iter2 = animParser.mAnimatedBones.begin(); iter2 != animParser.mAnimatedBones.end();++iter2,
  519. ++pcAnimNode,++pcBaseFrame)
  520. {
  521. if((*iter2).iFirstKeyIndex >= (*iter).mValues.size()) {
  522. // Allow for empty frames
  523. if ((*iter2).iFlags != 0) {
  524. throw DeadlyImportError("MD5: Keyframe index is out of range");
  525. }
  526. continue;
  527. }
  528. const float* fpCur = &(*iter).mValues[(*iter2).iFirstKeyIndex];
  529. aiNodeAnim* pcCurAnimBone = *pcAnimNode;
  530. aiVectorKey* vKey = &pcCurAnimBone->mPositionKeys[pcCurAnimBone->mNumPositionKeys++];
  531. aiQuatKey* qKey = &pcCurAnimBone->mRotationKeys [pcCurAnimBone->mNumRotationKeys++];
  532. aiVector3D vTemp;
  533. // translational component
  534. for (unsigned int i = 0; i < 3; ++i) {
  535. if ((*iter2).iFlags & (1u << i)) {
  536. vKey->mValue[i] = *fpCur++;
  537. }
  538. else vKey->mValue[i] = pcBaseFrame->vPositionXYZ[i];
  539. }
  540. // orientation component
  541. for (unsigned int i = 0; i < 3; ++i) {
  542. if ((*iter2).iFlags & (8u << i)) {
  543. vTemp[i] = *fpCur++;
  544. }
  545. else vTemp[i] = pcBaseFrame->vRotationQuat[i];
  546. }
  547. MD5::ConvertQuaternion(vTemp, qKey->mValue);
  548. qKey->mTime = vKey->mTime = dTime;
  549. // we need this to get to Assimp quaternion conventions
  550. qKey->mValue.w *= -1.f;
  551. }
  552. }
  553. // compute the duration of the animation
  554. anim->mDuration = std::max(dTime,anim->mDuration);
  555. }
  556. // If we didn't build the hierarchy yet (== we didn't load a MD5MESH),
  557. // construct it now from the data given in the MD5ANIM.
  558. if (!pScene->mRootNode) {
  559. pScene->mRootNode = new aiNode();
  560. pScene->mRootNode->mName.Set("<MD5_Hierarchy>");
  561. AttachChilds_Anim(-1,pScene->mRootNode,animParser.mAnimatedBones,(const aiNodeAnim**)anim->mChannels);
  562. // Call SkeletonMeshBuilder to construct a mesh to represent the shape
  563. if (pScene->mRootNode->mNumChildren) {
  564. SkeletonMeshBuilder skeleton_maker(pScene,pScene->mRootNode->mChildren[0]);
  565. }
  566. }
  567. }
  568. }
  569. // ------------------------------------------------------------------------------------------------
  570. // Load an MD5CAMERA file
  571. void MD5Importer::LoadMD5CameraFile ()
  572. {
  573. std::string pFile = mFile + "md5camera";
  574. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  575. // Check whether we can read from the file
  576. if( !file.get() || !file->FileSize()) {
  577. throw DeadlyImportError("Failed to read MD5CAMERA file: " + pFile);
  578. }
  579. bHadMD5Camera = true;
  580. LoadFileIntoMemory(file.get());
  581. // parse the basic file structure
  582. MD5::MD5Parser parser(mBuffer,fileSize);
  583. // load the camera animation data from the parse tree
  584. MD5::MD5CameraParser cameraParser(parser.mSections);
  585. if (cameraParser.frames.empty()) {
  586. throw DeadlyImportError("MD5CAMERA: No frames parsed");
  587. }
  588. std::vector<unsigned int>& cuts = cameraParser.cuts;
  589. std::vector<MD5::CameraAnimFrameDesc>& frames = cameraParser.frames;
  590. // Construct output graph - a simple root with a dummy child.
  591. // The root node performs the coordinate system conversion
  592. aiNode* root = pScene->mRootNode = new aiNode("<MD5CameraRoot>");
  593. root->mChildren = new aiNode*[root->mNumChildren = 1];
  594. root->mChildren[0] = new aiNode("<MD5Camera>");
  595. root->mChildren[0]->mParent = root;
  596. // ... but with one camera assigned to it
  597. pScene->mCameras = new aiCamera*[pScene->mNumCameras = 1];
  598. aiCamera* cam = pScene->mCameras[0] = new aiCamera();
  599. cam->mName = "<MD5Camera>";
  600. // FIXME: Fov is currently set to the first frame's value
  601. cam->mHorizontalFOV = AI_DEG_TO_RAD( frames.front().fFOV );
  602. // every cut is written to a separate aiAnimation
  603. if (!cuts.size()) {
  604. cuts.push_back(0);
  605. cuts.push_back(frames.size()-1);
  606. }
  607. else {
  608. cuts.insert(cuts.begin(),0);
  609. if (cuts.back() < frames.size()-1)
  610. cuts.push_back(frames.size()-1);
  611. }
  612. pScene->mNumAnimations = cuts.size()-1;
  613. aiAnimation** tmp = pScene->mAnimations = new aiAnimation*[pScene->mNumAnimations];
  614. for (std::vector<unsigned int>::const_iterator it = cuts.begin(); it != cuts.end()-1; ++it) {
  615. aiAnimation* anim = *tmp++ = new aiAnimation();
  616. anim->mName.length = ::sprintf(anim->mName.data,"anim%u_from_%u_to_%u",(unsigned int)(it-cuts.begin()),(*it),*(it+1));
  617. anim->mTicksPerSecond = cameraParser.fFrameRate;
  618. anim->mChannels = new aiNodeAnim*[anim->mNumChannels = 1];
  619. aiNodeAnim* nd = anim->mChannels[0] = new aiNodeAnim();
  620. nd->mNodeName.Set("<MD5Camera>");
  621. nd->mNumPositionKeys = nd->mNumRotationKeys = *(it+1) - (*it);
  622. nd->mPositionKeys = new aiVectorKey[nd->mNumPositionKeys];
  623. nd->mRotationKeys = new aiQuatKey [nd->mNumRotationKeys];
  624. for (unsigned int i = 0; i < nd->mNumPositionKeys; ++i) {
  625. nd->mPositionKeys[i].mValue = frames[*it+i].vPositionXYZ;
  626. MD5::ConvertQuaternion(frames[*it+i].vRotationQuat,nd->mRotationKeys[i].mValue);
  627. nd->mRotationKeys[i].mTime = nd->mPositionKeys[i].mTime = *it+i;
  628. }
  629. }
  630. }
  631. #endif // !! ASSIMP_BUILD_NO_MD5_IMPORTER