MD2Loader.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (ASSIMP)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2008, ASSIMP Development Team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the ASSIMP team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the ASSIMP Development Team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. #include "AssimpPCH.h"
  35. /** @file Implementation of the MD2 importer class */
  36. #include "MD2Loader.h"
  37. #include "MaterialSystem.h"
  38. #include "ByteSwap.h"
  39. #include "MD2NormalTable.h" // shouldn't be included by other units
  40. using namespace Assimp;
  41. using namespace Assimp::MD2;
  42. // helper macro to determine the size of an array
  43. #if (!defined ARRAYSIZE)
  44. # define ARRAYSIZE(_array) (int(sizeof(_array) / sizeof(_array[0])))
  45. #endif
  46. // ------------------------------------------------------------------------------------------------
  47. // Helper function to lookup a normal in Quake 2's precalculated table
  48. void MD2::LookupNormalIndex(uint8_t iNormalIndex,aiVector3D& vOut)
  49. {
  50. // make sure the normal index has a valid value
  51. if (iNormalIndex >= ARRAYSIZE(g_avNormals))
  52. {
  53. DefaultLogger::get()->warn("Index overflow in Quake II normal vector list (the "
  54. " LUT has only 162 entries). ");
  55. iNormalIndex = ARRAYSIZE(g_avNormals) - 1;
  56. }
  57. vOut = *((const aiVector3D*)(&g_avNormals[iNormalIndex]));
  58. }
  59. // ------------------------------------------------------------------------------------------------
  60. // Constructor to be privately used by Importer
  61. MD2Importer::MD2Importer()
  62. {
  63. }
  64. // ------------------------------------------------------------------------------------------------
  65. // Destructor, private as well
  66. MD2Importer::~MD2Importer()
  67. {
  68. }
  69. // ------------------------------------------------------------------------------------------------
  70. // Returns whether the class can handle the format of the given file.
  71. bool MD2Importer::CanRead( const std::string& pFile, IOSystem* pIOHandler) const
  72. {
  73. // simple check of file extension is enough for the moment
  74. std::string::size_type pos = pFile.find_last_of('.');
  75. // no file extension - can't read
  76. if( pos == std::string::npos)
  77. return false;
  78. std::string extension = pFile.substr( pos);
  79. if (extension.length() < 4)return false;
  80. if (extension[0] != '.')return false;
  81. if (extension[1] != 'm' && extension[1] != 'M')return false;
  82. if (extension[2] != 'd' && extension[2] != 'D')return false;
  83. if (extension[3] != '2')return false;
  84. return true;
  85. }
  86. // ------------------------------------------------------------------------------------------------
  87. // Setup configuration properties
  88. void MD2Importer::SetupProperties(const Importer* pImp)
  89. {
  90. // The AI_CONFIG_IMPORT_MD2_KEYFRAME option overrides the
  91. // AI_CONFIG_IMPORT_GLOBAL_KEYFRAME option.
  92. if(0xffffffff == (configFrameID = pImp->GetPropertyInteger(
  93. AI_CONFIG_IMPORT_MD2_KEYFRAME,0xffffffff)))
  94. {
  95. configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_GLOBAL_KEYFRAME,0);
  96. }
  97. }
  98. // ------------------------------------------------------------------------------------------------
  99. // Validate the file header
  100. void MD2Importer::ValidateHeader( )
  101. {
  102. // check magic number
  103. if (m_pcHeader->magic != AI_MD2_MAGIC_NUMBER_BE &&
  104. m_pcHeader->magic != AI_MD2_MAGIC_NUMBER_LE)
  105. {
  106. char szBuffer[5];
  107. szBuffer[0] = ((char*)&m_pcHeader->magic)[0];
  108. szBuffer[1] = ((char*)&m_pcHeader->magic)[1];
  109. szBuffer[2] = ((char*)&m_pcHeader->magic)[2];
  110. szBuffer[3] = ((char*)&m_pcHeader->magic)[3];
  111. szBuffer[4] = '\0';
  112. throw new ImportErrorException("Invalid MD2 magic word: should be IDP2, the "
  113. "magic word found is " + std::string(szBuffer));
  114. }
  115. // check file format version
  116. if (m_pcHeader->version != 8)
  117. DefaultLogger::get()->warn( "Unsupported md2 file version. Continuing happily ...");
  118. // check some values whether they are valid
  119. if (0 == m_pcHeader->numFrames)
  120. throw new ImportErrorException( "Invalid md2 file: NUM_FRAMES is 0");
  121. if (m_pcHeader->offsetEnd > (uint32_t)fileSize)
  122. throw new ImportErrorException( "Invalid md2 file: File is too small");
  123. if (m_pcHeader->offsetSkins + m_pcHeader->numSkins * sizeof (MD2::Skin) >= fileSize ||
  124. m_pcHeader->offsetTexCoords + m_pcHeader->numTexCoords * sizeof (MD2::TexCoord) >= fileSize ||
  125. m_pcHeader->offsetTriangles + m_pcHeader->numTriangles * sizeof (MD2::Triangle) >= fileSize ||
  126. m_pcHeader->offsetFrames + m_pcHeader->numFrames * sizeof (MD2::Frame) >= fileSize ||
  127. m_pcHeader->offsetEnd > fileSize)
  128. {
  129. throw new ImportErrorException("Invalid MD2 header: some offsets are outside the file");
  130. }
  131. if (m_pcHeader->numSkins > AI_MD2_MAX_SKINS)
  132. DefaultLogger::get()->warn("The model contains more skins than Quake 2 supports");
  133. if ( m_pcHeader->numFrames > AI_MD2_MAX_FRAMES)
  134. DefaultLogger::get()->warn("The model contains more frames than Quake 2 supports");
  135. if (m_pcHeader->numVertices > AI_MD2_MAX_VERTS)
  136. DefaultLogger::get()->warn("The model contains more vertices than Quake 2 supports");
  137. if (m_pcHeader->numFrames <= configFrameID )
  138. throw new ImportErrorException("The requested frame is not existing the file");
  139. }
  140. // ------------------------------------------------------------------------------------------------
  141. // Imports the given file into the given scene structure.
  142. void MD2Importer::InternReadFile( const std::string& pFile,
  143. aiScene* pScene, IOSystem* pIOHandler)
  144. {
  145. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile));
  146. // Check whether we can read from the file
  147. if( file.get() == NULL)
  148. throw new ImportErrorException( "Failed to open MD2 file " + pFile + "");
  149. // check whether the md3 file is large enough to contain
  150. // at least the file header
  151. fileSize = (unsigned int)file->FileSize();
  152. if( fileSize < sizeof(MD2::Header))
  153. throw new ImportErrorException( "MD2 File is too small");
  154. std::vector<uint8_t> mBuffer2(fileSize);
  155. file->Read(&mBuffer2[0], 1, fileSize);
  156. mBuffer = &mBuffer2[0];
  157. m_pcHeader = (BE_NCONST MD2::Header*)mBuffer;
  158. #ifdef AI_BUILD_BIG_ENDIAN
  159. ByteSwap::Swap4(&m_pcHeader->frameSize);
  160. ByteSwap::Swap4(&m_pcHeader->magic);
  161. ByteSwap::Swap4(&m_pcHeader->numFrames);
  162. ByteSwap::Swap4(&m_pcHeader->numGlCommands);
  163. ByteSwap::Swap4(&m_pcHeader->numSkins);
  164. ByteSwap::Swap4(&m_pcHeader->numTexCoords);
  165. ByteSwap::Swap4(&m_pcHeader->numTriangles);
  166. ByteSwap::Swap4(&m_pcHeader->numVertices);
  167. ByteSwap::Swap4(&m_pcHeader->offsetEnd);
  168. ByteSwap::Swap4(&m_pcHeader->offsetFrames);
  169. ByteSwap::Swap4(&m_pcHeader->offsetGlCommands);
  170. ByteSwap::Swap4(&m_pcHeader->offsetSkins);
  171. ByteSwap::Swap4(&m_pcHeader->offsetTexCoords);
  172. ByteSwap::Swap4(&m_pcHeader->offsetTriangles);
  173. ByteSwap::Swap4(&m_pcHeader->skinHeight);
  174. ByteSwap::Swap4(&m_pcHeader->skinWidth);
  175. ByteSwap::Swap4(&m_pcHeader->version);
  176. #endif
  177. ValidateHeader();
  178. // there won't be more than one mesh inside the file
  179. pScene->mNumMaterials = 1;
  180. pScene->mRootNode = new aiNode();
  181. pScene->mRootNode->mNumMeshes = 1;
  182. pScene->mRootNode->mMeshes = new unsigned int[1];
  183. pScene->mRootNode->mMeshes[0] = 0;
  184. pScene->mMaterials = new aiMaterial*[1];
  185. pScene->mMaterials[0] = new MaterialHelper();
  186. pScene->mNumMeshes = 1;
  187. pScene->mMeshes = new aiMesh*[1];
  188. aiMesh* pcMesh = pScene->mMeshes[0] = new aiMesh();
  189. pcMesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  190. // navigate to the begin of the frame data
  191. BE_NCONST MD2::Frame* pcFrame = (BE_NCONST MD2::Frame*) ((uint8_t*)
  192. m_pcHeader + m_pcHeader->offsetFrames);
  193. pcFrame += configFrameID;
  194. // navigate to the begin of the triangle data
  195. MD2::Triangle* pcTriangles = (MD2::Triangle*) ((uint8_t*)
  196. m_pcHeader + m_pcHeader->offsetTriangles);
  197. // navigate to the begin of the tex coords data
  198. BE_NCONST MD2::TexCoord* pcTexCoords = (BE_NCONST MD2::TexCoord*) ((uint8_t*)
  199. m_pcHeader + m_pcHeader->offsetTexCoords);
  200. // navigate to the begin of the vertex data
  201. BE_NCONST MD2::Vertex* pcVerts = (BE_NCONST MD2::Vertex*) (pcFrame->vertices);
  202. #ifdef AI_BUILD_BIG_ENDIAN
  203. for (uint32_t i = 0; i< m_pcHeader->numTriangles; ++i)
  204. {
  205. for (unsigned int p = 0; p < 3;++p)
  206. {
  207. ByteSwap::Swap2(& pcTriangles[i].textureIndices[p]);
  208. ByteSwap::Swap2(& pcTriangles[i].vertexIndices[p]);
  209. }
  210. }
  211. for (uint32_t i = 0; i < m_pcHeader->offsetTexCoords;++i)
  212. {
  213. ByteSwap::Swap2(& pcTexCoords[i].s);
  214. ByteSwap::Swap2(& pcTexCoords[i].t);
  215. }
  216. ByteSwap::Swap4( & pcFrame->scale[0] );
  217. ByteSwap::Swap4( & pcFrame->scale[1] );
  218. ByteSwap::Swap4( & pcFrame->scale[2] );
  219. ByteSwap::Swap4( & pcFrame->translate[0] );
  220. ByteSwap::Swap4( & pcFrame->translate[1] );
  221. ByteSwap::Swap4( & pcFrame->translate[2] );
  222. #endif
  223. pcMesh->mNumFaces = m_pcHeader->numTriangles;
  224. pcMesh->mFaces = new aiFace[m_pcHeader->numTriangles];
  225. // allocate output storage
  226. pcMesh->mNumVertices = (unsigned int)pcMesh->mNumFaces*3;
  227. pcMesh->mVertices = new aiVector3D[pcMesh->mNumVertices];
  228. pcMesh->mNormals = new aiVector3D[pcMesh->mNumVertices];
  229. // not sure whether there are MD2 files without texture coordinates
  230. // NOTE: texture coordinates can be there without a texture,
  231. // but a texture can't be there without a valid UV channel
  232. if (m_pcHeader->numTexCoords && m_pcHeader->numSkins)
  233. {
  234. // navigate to the first texture associated with the mesh
  235. const MD2::Skin* pcSkins = (const MD2::Skin*) ((unsigned char*)m_pcHeader +
  236. m_pcHeader->offsetSkins);
  237. const int iMode = (int)aiShadingMode_Gouraud;
  238. MaterialHelper* pcHelper = (MaterialHelper*)pScene->mMaterials[0];
  239. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  240. aiColor3D clr;
  241. clr.b = clr.g = clr.r = 1.0f;
  242. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_DIFFUSE);
  243. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_SPECULAR);
  244. clr.b = clr.g = clr.r = 0.05f;
  245. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_AMBIENT);
  246. if (pcSkins->name[0])
  247. {
  248. aiString szString;
  249. const size_t iLen = ::strlen(pcSkins->name);
  250. ::memcpy(szString.data,pcSkins->name,iLen);
  251. szString.data[iLen] = '\0';
  252. szString.length = iLen;
  253. pcHelper->AddProperty(&szString,AI_MATKEY_TEXTURE_DIFFUSE(0));
  254. }
  255. else
  256. {
  257. DefaultLogger::get()->warn("Texture file name has zero length. It will be skipped.");
  258. }
  259. }
  260. else
  261. {
  262. // apply a default material
  263. const int iMode = (int)aiShadingMode_Gouraud;
  264. MaterialHelper* pcHelper = (MaterialHelper*)pScene->mMaterials[0];
  265. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  266. aiColor3D clr;
  267. clr.b = clr.g = clr.r = 0.6f;
  268. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_DIFFUSE);
  269. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_SPECULAR);
  270. clr.b = clr.g = clr.r = 0.05f;
  271. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_AMBIENT);
  272. aiString szName;
  273. szName.Set(AI_DEFAULT_MATERIAL_NAME);
  274. pcHelper->AddProperty(&szName,AI_MATKEY_NAME);
  275. }
  276. // now read all triangles of the first frame, apply scaling and translation
  277. unsigned int iCurrent = 0;
  278. float fDivisorU = 1.0f;
  279. float fDivisorV = 1.0f;
  280. if (m_pcHeader->numTexCoords)
  281. {
  282. // allocate storage for texture coordinates, too
  283. pcMesh->mTextureCoords[0] = new aiVector3D[pcMesh->mNumVertices];
  284. pcMesh->mNumUVComponents[0] = 2;
  285. // check whether the skin width or height are zero (this would
  286. // cause a division through zero)
  287. if (!m_pcHeader->skinWidth)
  288. {
  289. DefaultLogger::get()->error("Skin width is zero but there are "
  290. "valid absolute texture coordinates");
  291. }
  292. else fDivisorU = (float)m_pcHeader->skinWidth;
  293. if (!m_pcHeader->skinHeight)
  294. {
  295. DefaultLogger::get()->error("Skin height is zero but there are "
  296. "valid absolute texture coordinates ");
  297. }
  298. else fDivisorV = (float)m_pcHeader->skinHeight;
  299. }
  300. for (unsigned int i = 0; i < (unsigned int)m_pcHeader->numTriangles;++i)
  301. {
  302. // allocate the face
  303. pScene->mMeshes[0]->mFaces[i].mIndices = new unsigned int[3];
  304. pScene->mMeshes[0]->mFaces[i].mNumIndices = 3;
  305. // copy texture coordinates
  306. // check whether they are different from the previous value at this index.
  307. // In this case, create a full separate set of vertices/normals/texcoords
  308. unsigned int iTemp = iCurrent;
  309. for (unsigned int c = 0; c < 3;++c,++iCurrent)
  310. {
  311. // validate vertex indices
  312. register unsigned int iIndex = (unsigned int)pcTriangles[i].vertexIndices[c];
  313. if (iIndex >= m_pcHeader->numVertices)
  314. {
  315. DefaultLogger::get()->error("MD2: Vertex index is outside the allowed range");
  316. iIndex = m_pcHeader->numVertices-1;
  317. }
  318. // read x,y, and z component of the vertex
  319. aiVector3D& vec = pcMesh->mVertices[iCurrent];
  320. vec.x = (float)pcVerts[iIndex].vertex[0] * pcFrame->scale[0];
  321. vec.x += pcFrame->translate[0];
  322. // invert y
  323. vec.y = (float)pcVerts[iIndex].vertex[1] * pcFrame->scale[1];
  324. vec.y += pcFrame->translate[1];
  325. vec.y *= -1.0f;
  326. vec.z = (float)pcVerts[iIndex].vertex[2] * pcFrame->scale[2];
  327. vec.z += pcFrame->translate[2];
  328. // read the normal vector from the precalculated normal table
  329. aiVector3D& vNormal = pcMesh->mNormals[iCurrent];
  330. LookupNormalIndex(pcVerts[iIndex].lightNormalIndex,vNormal);
  331. vNormal.y *= -1.0f;
  332. if (m_pcHeader->numTexCoords)
  333. {
  334. // validate texture coordinates
  335. iIndex = pcTriangles[iIndex].textureIndices[c];
  336. if (iIndex >= m_pcHeader->numTexCoords)
  337. {
  338. DefaultLogger::get()->error("MD2: UV index is outside the allowed range");
  339. iIndex = m_pcHeader->numTexCoords-1;
  340. }
  341. aiVector3D& pcOut = pcMesh->mTextureCoords[0][iCurrent];
  342. // the texture coordinates are absolute values but we
  343. // need relative values between 0 and 1
  344. pcOut.y = pcTexCoords[iIndex].s / fDivisorU;
  345. pcOut.x = pcTexCoords[iIndex].t / fDivisorV;
  346. }
  347. }
  348. // FIX: flip the face order for use with OpenGL
  349. pScene->mMeshes[0]->mFaces[i].mIndices[0] = iTemp+2;
  350. pScene->mMeshes[0]->mFaces[i].mIndices[1] = iTemp+1;
  351. pScene->mMeshes[0]->mFaces[i].mIndices[2] = iTemp+0;
  352. }
  353. }