MD2Loader.cpp 17 KB

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