MD5Loader.cpp 30 KB

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