MD5Loader.cpp 26 KB

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