MD3Loader.cpp 17 KB

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