MD3Loader.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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 MD3 importer class */
  35. #include "MD3Loader.h"
  36. #include "MaterialSystem.h"
  37. #include "StringComparison.h"
  38. #include "../include/IOStream.h"
  39. #include "../include/IOSystem.h"
  40. #include "../include/aiMesh.h"
  41. #include "../include/aiScene.h"
  42. #include "../include/aiAssert.h"
  43. #include "../include/DefaultLogger.h"
  44. #include <boost/scoped_ptr.hpp>
  45. using namespace Assimp;
  46. // ------------------------------------------------------------------------------------------------
  47. // Constructor to be privately used by Importer
  48. MD3Importer::MD3Importer()
  49. {
  50. }
  51. // ------------------------------------------------------------------------------------------------
  52. // Destructor, private as well
  53. MD3Importer::~MD3Importer()
  54. {
  55. }
  56. // ------------------------------------------------------------------------------------------------
  57. // Returns whether the class can handle the format of the given file.
  58. bool MD3Importer::CanRead( const std::string& pFile, IOSystem* pIOHandler) const
  59. {
  60. // simple check of file extension is enough for the moment
  61. std::string::size_type pos = pFile.find_last_of('.');
  62. // no file extension - can't read
  63. if( pos == std::string::npos)
  64. return false;
  65. std::string extension = pFile.substr( pos);
  66. if (extension.length() < 4)return false;
  67. if (extension[0] != '.')return false;
  68. if (extension[1] != 'm' && extension[1] != 'M')return false;
  69. if (extension[2] != 'd' && extension[2] != 'D')return false;
  70. if (extension[3] != '3')return false;
  71. return true;
  72. }
  73. // ------------------------------------------------------------------------------------------------
  74. void MD3Importer::ValidateHeaderOffsets()
  75. {
  76. // check file format version
  77. if (this->m_pcHeader->VERSION > 15)
  78. DefaultLogger::get()->warn( "Unsupported md3 file version. Continuing happily ...");
  79. // check some values whether they are valid
  80. if (0 == this->m_pcHeader->NUM_FRAMES)
  81. throw new ImportErrorException( "Invalid md3 file: NUM_FRAMES is 0");
  82. if (0 == this->m_pcHeader->NUM_SURFACES)
  83. throw new ImportErrorException( "Invalid md3 file: NUM_SURFACES is 0");
  84. if (this->m_pcHeader->OFS_FRAMES >= this->fileSize ||
  85. this->m_pcHeader->OFS_SURFACES >= this->fileSize ||
  86. this->m_pcHeader->OFS_EOF > this->fileSize)
  87. {
  88. throw new ImportErrorException("Invalid MD3 header: some offsets are outside the file");
  89. }
  90. }
  91. // ------------------------------------------------------------------------------------------------
  92. void MD3Importer::ValidateSurfaceHeaderOffsets(const MD3::Surface* pcSurf)
  93. {
  94. // calculate the relative offset of the surface
  95. int32_t ofs = int32_t((const unsigned char*)pcSurf-this->mBuffer);
  96. if (pcSurf->OFS_TRIANGLES + ofs + pcSurf->NUM_TRIANGLES * sizeof(MD3::Triangle) > this->fileSize ||
  97. pcSurf->OFS_SHADERS + ofs + pcSurf->NUM_SHADER * sizeof(MD3::Shader) > this->fileSize ||
  98. pcSurf->OFS_ST + ofs + pcSurf->NUM_VERTICES * sizeof(MD3::TexCoord) > this->fileSize ||
  99. pcSurf->OFS_XYZNORMAL + ofs + pcSurf->NUM_VERTICES * sizeof(MD3::Vertex) > this->fileSize)
  100. {
  101. throw new ImportErrorException("Invalid MD3 surface header: some offsets are outside the file");
  102. }
  103. if (pcSurf->NUM_TRIANGLES > AI_MD3_MAX_TRIANGLES)
  104. DefaultLogger::get()->warn("The model contains more triangles than Quake 3 supports");
  105. if (pcSurf->NUM_SHADER > AI_MD3_MAX_SHADERS)
  106. DefaultLogger::get()->warn("The model contains more shaders than Quake 3 supports");
  107. if (pcSurf->NUM_VERTICES > AI_MD3_MAX_VERTS)
  108. DefaultLogger::get()->warn("The model contains more vertices than Quake 3 supports");
  109. if (pcSurf->NUM_FRAMES > AI_MD3_MAX_FRAMES)
  110. DefaultLogger::get()->warn("The model contains more frames than Quake 3 supports");
  111. }
  112. // ------------------------------------------------------------------------------------------------
  113. // Imports the given file into the given scene structure.
  114. void MD3Importer::InternReadFile(
  115. const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
  116. {
  117. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile));
  118. // Check whether we can read from the file
  119. if( file.get() == NULL)
  120. {
  121. throw new ImportErrorException( "Failed to open md3 file " + pFile + ".");
  122. }
  123. // check whether the md3 file is large enough to contain
  124. // at least the file header
  125. fileSize = (unsigned int)file->FileSize();
  126. if( fileSize < sizeof(MD3::Header))
  127. {
  128. throw new ImportErrorException( ".md3 File is too small.");
  129. }
  130. // allocate storage and copy the contents of the file to a memory buffer
  131. this->mBuffer = new unsigned char[fileSize];
  132. file->Read( (void*)mBuffer, 1, fileSize);
  133. try
  134. {
  135. this->m_pcHeader = (const MD3::Header*)this->mBuffer;
  136. // check magic number
  137. if (this->m_pcHeader->IDENT != AI_MD3_MAGIC_NUMBER_BE &&
  138. this->m_pcHeader->IDENT != AI_MD3_MAGIC_NUMBER_LE)
  139. {
  140. throw new ImportErrorException( "Invalid md3 file: Magic bytes not found");
  141. }
  142. // validate the header
  143. this->ValidateHeaderOffsets();
  144. // now navigate to the list of surfaces
  145. const MD3::Surface* pcSurfaces = (const MD3::Surface*)
  146. (this->mBuffer + this->m_pcHeader->OFS_SURFACES);
  147. // allocate output storage
  148. pScene->mNumMeshes = this->m_pcHeader->NUM_SURFACES;
  149. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  150. pScene->mNumMaterials = this->m_pcHeader->NUM_SURFACES;
  151. pScene->mMaterials = new aiMaterial*[pScene->mNumMeshes];
  152. // if an exception is thrown before the meshes are allocated ->
  153. // otherwise the pointer value would be invalid and delete would crash
  154. ::memset(pScene->mMeshes,0,pScene->mNumMeshes*sizeof(aiMesh*));
  155. ::memset(pScene->mMaterials,0,pScene->mNumMaterials*sizeof(aiMaterial*));
  156. unsigned int iNum = this->m_pcHeader->NUM_SURFACES;
  157. unsigned int iNumMaterials = 0;
  158. unsigned int iDefaultMatIndex = 0xFFFFFFFF;
  159. while (iNum-- > 0)
  160. {
  161. // validate the surface
  162. this->ValidateSurfaceHeaderOffsets(pcSurfaces);
  163. // navigate to the vertex list of the surface
  164. const MD3::Vertex* pcVertices = (const MD3::Vertex*)
  165. (((unsigned char*)pcSurfaces) + pcSurfaces->OFS_XYZNORMAL);
  166. // navigate to the triangle list of the surface
  167. const MD3::Triangle* pcTriangles = (const MD3::Triangle*)
  168. (((unsigned char*)pcSurfaces) + pcSurfaces->OFS_TRIANGLES);
  169. // navigate to the texture coordinate list of the surface
  170. const MD3::TexCoord* pcUVs = (const MD3::TexCoord*)
  171. (((unsigned char*)pcSurfaces) + pcSurfaces->OFS_ST);
  172. // navigate to the shader list of the surface
  173. const MD3::Shader* pcShaders = (const MD3::Shader*)
  174. (((unsigned char*)pcSurfaces) + pcSurfaces->OFS_SHADERS);
  175. // if the submesh is empty ignore it
  176. if (0 == pcSurfaces->NUM_VERTICES || 0 == pcSurfaces->NUM_TRIANGLES)
  177. {
  178. pcSurfaces = (const MD3::Surface*)(((unsigned char*)pcSurfaces) + pcSurfaces->OFS_END);
  179. pScene->mNumMeshes--;
  180. continue;
  181. }
  182. // allocate the output mesh
  183. pScene->mMeshes[iNum] = new aiMesh();
  184. aiMesh* pcMesh = pScene->mMeshes[iNum];
  185. pcMesh->mNumVertices = pcSurfaces->NUM_TRIANGLES*3;
  186. pcMesh->mNumFaces = pcSurfaces->NUM_TRIANGLES;
  187. pcMesh->mFaces = new aiFace[pcSurfaces->NUM_TRIANGLES];
  188. pcMesh->mNormals = new aiVector3D[pcMesh->mNumVertices];
  189. pcMesh->mVertices = new aiVector3D[pcMesh->mNumVertices];
  190. pcMesh->mTextureCoords[0] = new aiVector3D[pcMesh->mNumVertices];
  191. pcMesh->mNumUVComponents[0] = 2;
  192. // fill in all triangles
  193. unsigned int iCurrent = 0;
  194. for (unsigned int i = 0; i < (unsigned int)pcSurfaces->NUM_TRIANGLES;++i)
  195. {
  196. pcMesh->mFaces[i].mIndices = new unsigned int[3];
  197. pcMesh->mFaces[i].mNumIndices = 3;
  198. unsigned int iTemp = iCurrent;
  199. for (unsigned int c = 0; c < 3;++c,++iCurrent)
  200. {
  201. // read vertices
  202. pcMesh->mVertices[iCurrent].x = pcVertices[ pcTriangles->INDEXES[c]].X;
  203. pcMesh->mVertices[iCurrent].y = pcVertices[ pcTriangles->INDEXES[c]].Y*-1.0f;
  204. pcMesh->mVertices[iCurrent].z = pcVertices[ pcTriangles->INDEXES[c]].Z;
  205. // convert the normal vector to uncompressed float3 format
  206. LatLngNormalToVec3(pcVertices[pcTriangles->INDEXES[c]].NORMAL,
  207. (float*)&pcMesh->mNormals[iCurrent]);
  208. pcMesh->mNormals[iCurrent].y *= -1.0f;
  209. // read texture coordinates
  210. pcMesh->mTextureCoords[0][iCurrent].x = pcUVs[ pcTriangles->INDEXES[c]].U;
  211. pcMesh->mTextureCoords[0][iCurrent].y = 1.0f-pcUVs[ pcTriangles->INDEXES[c]].V;
  212. }
  213. // FIX: flip the face ordering for use with OpenGL
  214. pcMesh->mFaces[i].mIndices[0] = iTemp+2;
  215. pcMesh->mFaces[i].mIndices[1] = iTemp+1;
  216. pcMesh->mFaces[i].mIndices[2] = iTemp+0;
  217. pcTriangles++;
  218. }
  219. // get the first shader (= texture?) assigned to the surface
  220. if (0 != pcSurfaces->NUM_SHADER)
  221. {
  222. // make a relative path.
  223. // if the MD3's internal path itself and the given path are using
  224. // the same directory remove it
  225. const char* szEndDir1 = ::strrchr((const char*)this->m_pcHeader->NAME,'\\');
  226. if (!szEndDir1)szEndDir1 = ::strrchr((const char*)this->m_pcHeader->NAME,'/');
  227. const char* szEndDir2 = ::strrchr((const char*)pcShaders->NAME,'\\');
  228. if (!szEndDir2)szEndDir2 = ::strrchr((const char*)pcShaders->NAME,'/');
  229. if (szEndDir1 && szEndDir2)
  230. {
  231. // both of them are valid
  232. const unsigned int iLen1 = (unsigned int)(szEndDir1 - (const char*)this->m_pcHeader->NAME);
  233. const unsigned int iLen2 = std::min (iLen1, (unsigned int)(szEndDir2 - (const char*)pcShaders->NAME) );
  234. bool bSuccess = true;
  235. for (unsigned int a = 0; a < iLen2;++a)
  236. {
  237. char sz = ::tolower ( pcShaders->NAME[a] );
  238. char sz2 = ::tolower ( this->m_pcHeader->NAME[a] );
  239. if (sz != sz2)
  240. {
  241. bSuccess = false;
  242. break;
  243. }
  244. }
  245. if (bSuccess)
  246. {
  247. // use the file name only
  248. szEndDir2++;
  249. }
  250. else
  251. {
  252. // use the full path
  253. szEndDir2 = (const char*)pcShaders->NAME;
  254. }
  255. }
  256. // now try to find out whether we have this shader already
  257. bool bHave = false;
  258. for (unsigned int p = 0; p < iNumMaterials;++p)
  259. {
  260. if (iDefaultMatIndex == p)continue;
  261. aiString szOut;
  262. if(AI_SUCCESS == aiGetMaterialString ( (aiMaterial*)pScene->mMaterials[p],
  263. AI_MATKEY_TEXTURE_DIFFUSE(0),&szOut))
  264. {
  265. if (0 == ASSIMP_stricmp(szOut.data,szEndDir2))
  266. {
  267. // equal. reuse this material (texture)
  268. bHave = true;
  269. pcMesh->mMaterialIndex = p;
  270. break;
  271. }
  272. }
  273. }
  274. if (!bHave)
  275. {
  276. MaterialHelper* pcHelper = new MaterialHelper();
  277. if (szEndDir2)
  278. {
  279. if (szEndDir2[0])
  280. {
  281. aiString szString;
  282. const size_t iLen = ::strlen(szEndDir2);
  283. ::memcpy(szString.data,szEndDir2,iLen);
  284. szString.data[iLen] = '\0';
  285. szString.length = iLen;
  286. pcHelper->AddProperty(&szString,AI_MATKEY_TEXTURE_DIFFUSE(0));
  287. }
  288. else
  289. {
  290. DefaultLogger::get()->warn("Texture file name has zero length. "
  291. "It will be skipped.");
  292. }
  293. }
  294. int iMode = (int)aiShadingMode_Gouraud;
  295. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  296. // add a small ambient color value - Quake 3 seems to have one
  297. aiColor3D clr;
  298. clr.b = clr.g = clr.r = 0.05f;
  299. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_AMBIENT);
  300. aiString szName;
  301. szName.Set(AI_DEFAULT_MATERIAL_NAME);
  302. pcHelper->AddProperty(&szName,AI_MATKEY_NAME);
  303. pScene->mMaterials[iNumMaterials] = (aiMaterial*)pcHelper;
  304. pcMesh->mMaterialIndex = iNumMaterials++;
  305. }
  306. }
  307. else
  308. {
  309. if (0xFFFFFFFF != iDefaultMatIndex)
  310. {
  311. pcMesh->mMaterialIndex = iDefaultMatIndex;
  312. }
  313. else
  314. {
  315. MaterialHelper* pcHelper = new MaterialHelper();
  316. // fill in a default material
  317. int iMode = (int)aiShadingMode_Gouraud;
  318. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  319. aiColor3D clr;
  320. clr.b = clr.g = clr.r = 0.6f;
  321. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_DIFFUSE);
  322. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_SPECULAR);
  323. clr.b = clr.g = clr.r = 0.05f;
  324. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_AMBIENT);
  325. pScene->mMaterials[iNumMaterials] = (aiMaterial*)pcHelper;
  326. pcMesh->mMaterialIndex = iNumMaterials++;
  327. }
  328. }
  329. // go to the next surface
  330. pcSurfaces = (const MD3::Surface*)(((unsigned char*)pcSurfaces) + pcSurfaces->OFS_END);
  331. }
  332. if (0 == pScene->mNumMeshes)
  333. throw new ImportErrorException( "Invalid md3 file: File contains no valid mesh");
  334. pScene->mNumMaterials = iNumMaterials;
  335. // now we need to generate an empty node graph
  336. pScene->mRootNode = new aiNode();
  337. pScene->mRootNode->mNumMeshes = pScene->mNumMeshes;
  338. pScene->mRootNode->mMeshes = new unsigned int[pScene->mNumMeshes];
  339. for (unsigned int i = 0; i < pScene->mNumMeshes;++i)
  340. pScene->mRootNode->mMeshes[i] = i;
  341. }
  342. catch (ImportErrorException* ex)
  343. {
  344. delete[] this->mBuffer; AI_DEBUG_INVALIDATE_PTR(this->mBuffer);
  345. throw ex;
  346. }
  347. delete[] this->mBuffer; AI_DEBUG_INVALIDATE_PTR(this->mBuffer);
  348. }