MD5Loader.cpp 26 KB

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