MD5Loader.cpp 26 KB

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