MD2Loader.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2022, 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. #ifndef ASSIMP_BUILD_NO_MD2_IMPORTER
  35. /** @file Implementation of the MD2 importer class */
  36. #include "MD2Loader.h"
  37. #include <assimp/ByteSwapper.h>
  38. #include "MD2NormalTable.h" // shouldn't be included by other units
  39. #include <assimp/DefaultLogger.hpp>
  40. #include <assimp/Importer.hpp>
  41. #include <assimp/IOSystem.hpp>
  42. #include <assimp/scene.h>
  43. #include <assimp/importerdesc.h>
  44. #include <assimp/StringUtils.h>
  45. #include <memory>
  46. using namespace Assimp;
  47. using namespace Assimp::MD2;
  48. // helper macro to determine the size of an array
  49. #if (!defined ARRAYSIZE)
  50. # define ARRAYSIZE(_array) (int(sizeof(_array) / sizeof(_array[0])))
  51. #endif
  52. static const aiImporterDesc desc = {
  53. "Quake II Mesh Importer",
  54. "",
  55. "",
  56. "",
  57. aiImporterFlags_SupportBinaryFlavour,
  58. 0,
  59. 0,
  60. 0,
  61. 0,
  62. "md2"
  63. };
  64. // ------------------------------------------------------------------------------------------------
  65. // Helper function to lookup a normal in Quake 2's precalculated table
  66. void MD2::LookupNormalIndex(uint8_t iNormalIndex,aiVector3D& vOut)
  67. {
  68. // make sure the normal index has a valid value
  69. if (iNormalIndex >= ARRAYSIZE(g_avNormals)) {
  70. ASSIMP_LOG_WARN("Index overflow in Quake II normal vector list");
  71. iNormalIndex = ARRAYSIZE(g_avNormals) - 1;
  72. }
  73. vOut = *((const aiVector3D*)(&g_avNormals[iNormalIndex]));
  74. }
  75. // ------------------------------------------------------------------------------------------------
  76. // Constructor to be privately used by Importer
  77. MD2Importer::MD2Importer()
  78. : configFrameID(),
  79. m_pcHeader(),
  80. mBuffer(),
  81. fileSize()
  82. {}
  83. // ------------------------------------------------------------------------------------------------
  84. // Destructor, private as well
  85. MD2Importer::~MD2Importer() = default;
  86. // ------------------------------------------------------------------------------------------------
  87. // Returns whether the class can handle the format of the given file.
  88. bool MD2Importer::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool /*checkSig*/) const
  89. {
  90. static const uint32_t tokens[] = { AI_MD2_MAGIC_NUMBER_LE };
  91. return CheckMagicToken(pIOHandler,pFile,tokens,AI_COUNT_OF(tokens));
  92. }
  93. // ------------------------------------------------------------------------------------------------
  94. // Get a list of all extensions supported by this loader
  95. const aiImporterDesc* MD2Importer::GetInfo () const
  96. {
  97. return &desc;
  98. }
  99. // ------------------------------------------------------------------------------------------------
  100. // Setup configuration properties
  101. void MD2Importer::SetupProperties(const Importer* pImp)
  102. {
  103. // The
  104. // AI_CONFIG_IMPORT_MD2_KEYFRAME option overrides the
  105. // AI_CONFIG_IMPORT_GLOBAL_KEYFRAME option.
  106. configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_MD2_KEYFRAME,-1);
  107. if(static_cast<unsigned int>(-1) == configFrameID){
  108. configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_GLOBAL_KEYFRAME,0);
  109. }
  110. }
  111. // ------------------------------------------------------------------------------------------------
  112. // Validate the file header
  113. void MD2Importer::ValidateHeader( )
  114. {
  115. // check magic number
  116. if (m_pcHeader->magic != AI_MD2_MAGIC_NUMBER_BE &&
  117. m_pcHeader->magic != AI_MD2_MAGIC_NUMBER_LE)
  118. {
  119. throw DeadlyImportError("Invalid MD2 magic word: expected IDP2, found ",
  120. ai_str_toprintable((char *)&m_pcHeader->magic, 4));
  121. }
  122. // check file format version
  123. if (m_pcHeader->version != 8)
  124. ASSIMP_LOG_WARN( "Unsupported MD2 file version. Continuing happily ...");
  125. // check some values whether they are valid
  126. if (0 == m_pcHeader->numFrames)
  127. throw DeadlyImportError( "Invalid MD2 file: NUM_FRAMES is 0");
  128. if (m_pcHeader->offsetEnd > (uint32_t)fileSize)
  129. throw DeadlyImportError( "Invalid MD2 file: File is too small");
  130. if (m_pcHeader->numSkins > AI_MAX_ALLOC(MD2::Skin)) {
  131. throw DeadlyImportError("Invalid MD2 header: Too many skins, would overflow");
  132. }
  133. if (m_pcHeader->numVertices > AI_MAX_ALLOC(MD2::Vertex)) {
  134. throw DeadlyImportError("Invalid MD2 header: Too many vertices, would overflow");
  135. }
  136. if (m_pcHeader->numTexCoords > AI_MAX_ALLOC(MD2::TexCoord)) {
  137. throw DeadlyImportError("Invalid MD2 header: Too many texcoords, would overflow");
  138. }
  139. if (m_pcHeader->numTriangles > AI_MAX_ALLOC(MD2::Triangle)) {
  140. throw DeadlyImportError("Invalid MD2 header: Too many triangles, would overflow");
  141. }
  142. if (m_pcHeader->numFrames > AI_MAX_ALLOC(MD2::Frame)) {
  143. throw DeadlyImportError("Invalid MD2 header: Too many frames, would overflow");
  144. }
  145. // -1 because Frame already contains one
  146. unsigned int frameSize = sizeof (MD2::Frame) + (m_pcHeader->numVertices - 1) * sizeof(MD2::Vertex);
  147. if (m_pcHeader->offsetSkins + m_pcHeader->numSkins * sizeof (MD2::Skin) >= fileSize ||
  148. m_pcHeader->offsetTexCoords + m_pcHeader->numTexCoords * sizeof (MD2::TexCoord) >= fileSize ||
  149. m_pcHeader->offsetTriangles + m_pcHeader->numTriangles * sizeof (MD2::Triangle) >= fileSize ||
  150. m_pcHeader->offsetFrames + m_pcHeader->numFrames * frameSize >= fileSize ||
  151. m_pcHeader->offsetEnd > fileSize)
  152. {
  153. throw DeadlyImportError("Invalid MD2 header: Some offsets are outside the file");
  154. }
  155. if (m_pcHeader->numSkins > AI_MD2_MAX_SKINS)
  156. ASSIMP_LOG_WARN("The model contains more skins than Quake 2 supports");
  157. if ( m_pcHeader->numFrames > AI_MD2_MAX_FRAMES)
  158. ASSIMP_LOG_WARN("The model contains more frames than Quake 2 supports");
  159. if (m_pcHeader->numVertices > AI_MD2_MAX_VERTS)
  160. ASSIMP_LOG_WARN("The model contains more vertices than Quake 2 supports");
  161. if (m_pcHeader->numFrames <= configFrameID )
  162. throw DeadlyImportError("MD2: The requested frame (", configFrameID, ") does not exist in the file");
  163. }
  164. // ------------------------------------------------------------------------------------------------
  165. // Imports the given file into the given scene structure.
  166. void MD2Importer::InternReadFile( const std::string& pFile,
  167. aiScene* pScene, IOSystem* pIOHandler)
  168. {
  169. std::unique_ptr<IOStream> file( pIOHandler->Open( pFile));
  170. // Check whether we can read from the file
  171. if (file.get() == nullptr) {
  172. throw DeadlyImportError("Failed to open MD2 file ", pFile, "");
  173. }
  174. // check whether the md3 file is large enough to contain
  175. // at least the file header
  176. fileSize = (unsigned int)file->FileSize();
  177. if (fileSize < sizeof(MD2::Header)) {
  178. throw DeadlyImportError("MD2 File is too small");
  179. }
  180. std::vector<uint8_t> mBuffer2(fileSize);
  181. file->Read(&mBuffer2[0], 1, fileSize);
  182. mBuffer = &mBuffer2[0];
  183. m_pcHeader = (BE_NCONST MD2::Header*)mBuffer;
  184. #ifdef AI_BUILD_BIG_ENDIAN
  185. ByteSwap::Swap4(&m_pcHeader->frameSize);
  186. ByteSwap::Swap4(&m_pcHeader->magic);
  187. ByteSwap::Swap4(&m_pcHeader->numFrames);
  188. ByteSwap::Swap4(&m_pcHeader->numGlCommands);
  189. ByteSwap::Swap4(&m_pcHeader->numSkins);
  190. ByteSwap::Swap4(&m_pcHeader->numTexCoords);
  191. ByteSwap::Swap4(&m_pcHeader->numTriangles);
  192. ByteSwap::Swap4(&m_pcHeader->numVertices);
  193. ByteSwap::Swap4(&m_pcHeader->offsetEnd);
  194. ByteSwap::Swap4(&m_pcHeader->offsetFrames);
  195. ByteSwap::Swap4(&m_pcHeader->offsetGlCommands);
  196. ByteSwap::Swap4(&m_pcHeader->offsetSkins);
  197. ByteSwap::Swap4(&m_pcHeader->offsetTexCoords);
  198. ByteSwap::Swap4(&m_pcHeader->offsetTriangles);
  199. ByteSwap::Swap4(&m_pcHeader->skinHeight);
  200. ByteSwap::Swap4(&m_pcHeader->skinWidth);
  201. ByteSwap::Swap4(&m_pcHeader->version);
  202. #endif
  203. ValidateHeader();
  204. // there won't be more than one mesh inside the file
  205. pScene->mNumMaterials = 1;
  206. pScene->mRootNode = new aiNode();
  207. pScene->mRootNode->mNumMeshes = 1;
  208. pScene->mRootNode->mMeshes = new unsigned int[1];
  209. pScene->mRootNode->mMeshes[0] = 0;
  210. pScene->mMaterials = new aiMaterial*[1];
  211. pScene->mMaterials[0] = new aiMaterial();
  212. pScene->mNumMeshes = 1;
  213. pScene->mMeshes = new aiMesh*[1];
  214. aiMesh* pcMesh = pScene->mMeshes[0] = new aiMesh();
  215. pcMesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  216. // navigate to the begin of the current frame data
  217. BE_NCONST MD2::Frame* pcFrame = (BE_NCONST MD2::Frame*) ((uint8_t*)
  218. m_pcHeader + m_pcHeader->offsetFrames + (m_pcHeader->frameSize * configFrameID));
  219. // navigate to the begin of the triangle data
  220. MD2::Triangle* pcTriangles = (MD2::Triangle*) ((uint8_t*)
  221. m_pcHeader + m_pcHeader->offsetTriangles);
  222. // navigate to the begin of the tex coords data
  223. BE_NCONST MD2::TexCoord* pcTexCoords = (BE_NCONST MD2::TexCoord*) ((uint8_t*)
  224. m_pcHeader + m_pcHeader->offsetTexCoords);
  225. // navigate to the begin of the vertex data
  226. BE_NCONST MD2::Vertex* pcVerts = (BE_NCONST MD2::Vertex*) (pcFrame->vertices);
  227. #ifdef AI_BUILD_BIG_ENDIAN
  228. for (uint32_t i = 0; i< m_pcHeader->numTriangles; ++i)
  229. {
  230. for (unsigned int p = 0; p < 3;++p)
  231. {
  232. ByteSwap::Swap2(& pcTriangles[i].textureIndices[p]);
  233. ByteSwap::Swap2(& pcTriangles[i].vertexIndices[p]);
  234. }
  235. }
  236. for (uint32_t i = 0; i < m_pcHeader->offsetTexCoords;++i)
  237. {
  238. ByteSwap::Swap2(& pcTexCoords[i].s);
  239. ByteSwap::Swap2(& pcTexCoords[i].t);
  240. }
  241. ByteSwap::Swap4( & pcFrame->scale[0] );
  242. ByteSwap::Swap4( & pcFrame->scale[1] );
  243. ByteSwap::Swap4( & pcFrame->scale[2] );
  244. ByteSwap::Swap4( & pcFrame->translate[0] );
  245. ByteSwap::Swap4( & pcFrame->translate[1] );
  246. ByteSwap::Swap4( & pcFrame->translate[2] );
  247. #endif
  248. pcMesh->mNumFaces = m_pcHeader->numTriangles;
  249. pcMesh->mFaces = new aiFace[m_pcHeader->numTriangles];
  250. // allocate output storage
  251. pcMesh->mNumVertices = (unsigned int)pcMesh->mNumFaces*3;
  252. pcMesh->mVertices = new aiVector3D[pcMesh->mNumVertices];
  253. pcMesh->mNormals = new aiVector3D[pcMesh->mNumVertices];
  254. // Not sure whether there are MD2 files without texture coordinates
  255. // NOTE: texture coordinates can be there without a texture,
  256. // but a texture can't be there without a valid UV channel
  257. aiMaterial* pcHelper = (aiMaterial*)pScene->mMaterials[0];
  258. const int iMode = (int)aiShadingMode_Gouraud;
  259. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  260. if (m_pcHeader->numTexCoords && m_pcHeader->numSkins)
  261. {
  262. // navigate to the first texture associated with the mesh
  263. const MD2::Skin* pcSkins = (const MD2::Skin*) ((unsigned char*)m_pcHeader +
  264. m_pcHeader->offsetSkins);
  265. aiColor3D clr;
  266. clr.b = clr.g = clr.r = 1.0f;
  267. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_DIFFUSE);
  268. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_SPECULAR);
  269. clr.b = clr.g = clr.r = 0.05f;
  270. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_AMBIENT);
  271. if (pcSkins->name[0])
  272. {
  273. aiString szString;
  274. const ai_uint32 iLen = (ai_uint32) ::strlen(pcSkins->name);
  275. ::memcpy(szString.data,pcSkins->name,iLen);
  276. szString.data[iLen] = '\0';
  277. szString.length = iLen;
  278. pcHelper->AddProperty(&szString,AI_MATKEY_TEXTURE_DIFFUSE(0));
  279. }
  280. else{
  281. ASSIMP_LOG_WARN("Texture file name has zero length. It will be skipped.");
  282. }
  283. }
  284. else {
  285. // apply a default material
  286. aiColor3D clr;
  287. clr.b = clr.g = clr.r = 0.6f;
  288. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_DIFFUSE);
  289. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_SPECULAR);
  290. clr.b = clr.g = clr.r = 0.05f;
  291. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_AMBIENT);
  292. aiString szName;
  293. szName.Set(AI_DEFAULT_MATERIAL_NAME);
  294. pcHelper->AddProperty(&szName,AI_MATKEY_NAME);
  295. aiString sz;
  296. // TODO: Try to guess the name of the texture file from the model file name
  297. sz.Set("$texture_dummy.bmp");
  298. pcHelper->AddProperty(&sz,AI_MATKEY_TEXTURE_DIFFUSE(0));
  299. }
  300. // now read all triangles of the first frame, apply scaling and translation
  301. unsigned int iCurrent = 0;
  302. float fDivisorU = 1.0f,fDivisorV = 1.0f;
  303. if (m_pcHeader->numTexCoords) {
  304. // allocate storage for texture coordinates, too
  305. pcMesh->mTextureCoords[0] = new aiVector3D[pcMesh->mNumVertices];
  306. pcMesh->mNumUVComponents[0] = 2;
  307. // check whether the skin width or height are zero (this would
  308. // cause a division through zero)
  309. if (!m_pcHeader->skinWidth) {
  310. ASSIMP_LOG_ERROR("MD2: No valid skin width given");
  311. }
  312. else fDivisorU = (float)m_pcHeader->skinWidth;
  313. if (!m_pcHeader->skinHeight){
  314. ASSIMP_LOG_ERROR("MD2: No valid skin height given");
  315. }
  316. else fDivisorV = (float)m_pcHeader->skinHeight;
  317. }
  318. for (unsigned int i = 0; i < (unsigned int)m_pcHeader->numTriangles;++i) {
  319. // Allocate the face
  320. pScene->mMeshes[0]->mFaces[i].mIndices = new unsigned int[3];
  321. pScene->mMeshes[0]->mFaces[i].mNumIndices = 3;
  322. // copy texture coordinates
  323. // check whether they are different from the previous value at this index.
  324. // In this case, create a full separate set of vertices/normals/texcoords
  325. for (unsigned int c = 0; c < 3;++c,++iCurrent) {
  326. // validate vertex indices
  327. unsigned int iIndex = (unsigned int)pcTriangles[i].vertexIndices[c];
  328. if (iIndex >= m_pcHeader->numVertices) {
  329. ASSIMP_LOG_ERROR("MD2: Vertex index is outside the allowed range");
  330. iIndex = m_pcHeader->numVertices-1;
  331. }
  332. // read x,y, and z component of the vertex
  333. aiVector3D& vec = pcMesh->mVertices[iCurrent];
  334. vec.x = (float)pcVerts[iIndex].vertex[0] * pcFrame->scale[0];
  335. vec.x += pcFrame->translate[0];
  336. vec.y = (float)pcVerts[iIndex].vertex[1] * pcFrame->scale[1];
  337. vec.y += pcFrame->translate[1];
  338. vec.z = (float)pcVerts[iIndex].vertex[2] * pcFrame->scale[2];
  339. vec.z += pcFrame->translate[2];
  340. // read the normal vector from the precalculated normal table
  341. aiVector3D& vNormal = pcMesh->mNormals[iCurrent];
  342. LookupNormalIndex(pcVerts[iIndex].lightNormalIndex,vNormal);
  343. if (m_pcHeader->numTexCoords) {
  344. // validate texture coordinates
  345. iIndex = pcTriangles[i].textureIndices[c];
  346. if (iIndex >= m_pcHeader->numTexCoords) {
  347. ASSIMP_LOG_ERROR("MD2: UV index is outside the allowed range");
  348. iIndex = m_pcHeader->numTexCoords-1;
  349. }
  350. aiVector3D& pcOut = pcMesh->mTextureCoords[0][iCurrent];
  351. // the texture coordinates are absolute values but we
  352. // need relative values between 0 and 1
  353. pcOut.x = pcTexCoords[iIndex].s / fDivisorU;
  354. pcOut.y = 1.f-pcTexCoords[iIndex].t / fDivisorV;
  355. }
  356. pScene->mMeshes[0]->mFaces[i].mIndices[c] = iCurrent;
  357. }
  358. // flip the face order
  359. std::swap( pScene->mMeshes[0]->mFaces[i].mIndices[0], pScene->mMeshes[0]->mFaces[i].mIndices[2] );
  360. }
  361. // Now rotate the whole scene 90 degrees around the x axis to convert to internal coordinate system
  362. pScene->mRootNode->mTransformation = aiMatrix4x4(
  363. 1.f, 0.f, 0.f, 0.f,
  364. 0.f, 0.f, 1.f, 0.f,
  365. 0.f, -1.f, 0.f, 0.f,
  366. 0.f, 0.f, 0.f, 1.f);
  367. }
  368. #endif // !! ASSIMP_BUILD_NO_MD2_IMPORTER