MD2Loader.cpp 15 KB

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