MD5Loader.cpp 26 KB

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