MD5Loader.cpp 26 KB

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