MD3Loader.cpp 16 KB

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