MD2Loader.cpp 16 KB

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