MD5Loader.cpp 30 KB

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