MDRLoader.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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 MDR importer class */
  35. #include "AssimpPCH.h"
  36. #include "MDRLoader.h"
  37. using namespace Assimp;
  38. using namespace Assimp::MDR;
  39. // ------------------------------------------------------------------------------------------------
  40. // Constructor to be privately used by Importer
  41. MDRImporter::MDRImporter()
  42. {
  43. }
  44. // ------------------------------------------------------------------------------------------------
  45. // Destructor, private as well
  46. MDRImporter::~MDRImporter()
  47. {
  48. }
  49. // ------------------------------------------------------------------------------------------------
  50. // Returns whether the class can handle the format of the given file.
  51. bool MDRImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler) const
  52. {
  53. // simple check of file extension is enough for the moment
  54. std::string::size_type pos = pFile.find_last_of('.');
  55. // no file extension - can't read
  56. if( pos == std::string::npos)
  57. return false;
  58. std::string extension = pFile.substr( pos);
  59. return !(extension.length() != 4 || extension[0] != '.' ||
  60. extension[1] != 'm' && extension[1] != 'M' ||
  61. extension[2] != 'd' && extension[2] != 'D' ||
  62. extension[3] != 'r' && extension[3] != 'R');
  63. }
  64. // ------------------------------------------------------------------------------------------------
  65. // Uncompress a matrix
  66. void MDRImporter::MatrixUncompress(aiMatrix4x4& mat,const uint8_t * compressed)
  67. {
  68. int value;
  69. // First decompress the translation part
  70. for (unsigned int n = 0; n < 3;++n)
  71. {
  72. value = (int)((uint16_t *)(compressed))[n];
  73. mat[0][n] = ((float)(value-(1<<15)))/64.f;
  74. }
  75. // Then decompress the rotation matrix
  76. for (unsigned int n = 0, p = 3; n < 3;++n)
  77. {
  78. for (unsigned int m = 0; m < 3;++m,++p)
  79. {
  80. value = (int)((uint16_t *)(compressed))[p];
  81. mat[n][m]=((float)(value-(1<<15)))*(1.0f/(float)((1<<(15))-2));
  82. }
  83. }
  84. // now zero the final row of the matrix
  85. mat[3][0] = mat[3][1] = mat[3][2] = 0.f;
  86. mat[3][3] = 1.f;
  87. }
  88. // ------------------------------------------------------------------------------------------------
  89. // Validate the header of the given MDR file
  90. void MDRImporter::ValidateHeader()
  91. {
  92. // Check the magic word - '5MDR'
  93. if (pcHeader->ident != AI_MDR_MAGIC_NUMBER_BE &&
  94. pcHeader->ident != AI_MDR_MAGIC_NUMBER_LE)
  95. {
  96. char szBuffer[5];
  97. szBuffer[0] = ((char*)&pcHeader->ident)[0];
  98. szBuffer[1] = ((char*)&pcHeader->ident)[1];
  99. szBuffer[2] = ((char*)&pcHeader->ident)[2];
  100. szBuffer[3] = ((char*)&pcHeader->ident)[3];
  101. szBuffer[4] = '\0';
  102. throw new ImportErrorException("Invalid MDR magic word: should be 5MDR, the "
  103. "magic word found is " + std::string( szBuffer ));
  104. }
  105. // Big endian - swap the fields in the header
  106. AI_SWAP4(pcHeader->numBones);
  107. AI_SWAP4(pcHeader->numFrames);
  108. AI_SWAP4(pcHeader->ofsFrames);
  109. AI_SWAP4(pcHeader->ofsLODs);
  110. AI_SWAP4(pcHeader->ofsTags);
  111. AI_SWAP4(pcHeader->version);
  112. AI_SWAP4(pcHeader->numTags);
  113. AI_SWAP4(pcHeader->numLODs);
  114. // MDR file version should always be 2
  115. if (pcHeader->version != AI_MDR_VERSION)
  116. DefaultLogger::get()->warn("Unsupported MDR file version (2 was expected)");
  117. // We compute the vertex positions from the bones,
  118. // so we need at least one bone.
  119. if (!pcHeader->numBones)
  120. DefaultLogger::get()->warn("MDR: At least one bone must be there");
  121. // We should have at least the first LOD in the valid range
  122. if (pcHeader->ofsLODs > (int)fileSize)
  123. throw new ImportErrorException("MDR: header is invalid - LOD out of range");
  124. // header::ofsFrames is negative if the frames are compressed
  125. if (pcHeader->ofsFrames < 0)
  126. {
  127. // Ugly, but it will be our only change to make further
  128. // reading easier
  129. int32_t* p = const_cast<int32_t*>(&pcHeader->ofsFrames);
  130. *p = -pcHeader->ofsFrames;
  131. compressed = true;
  132. DefaultLogger::get()->info("MDR: Compressed frames");
  133. }
  134. else compressed = false;
  135. // validate all frames
  136. if ( pcHeader->ofsFrames + sizeof(MDR::Frame) *
  137. (pcHeader->numBones -1) * sizeof(MDR::Bone) *
  138. pcHeader->numFrames > fileSize)
  139. {
  140. throw new ImportErrorException("MDR: header is invalid - frame out of range");
  141. }
  142. // Check whether the requested frame is existing
  143. if (configFrameID >= (unsigned int) pcHeader->numFrames)
  144. throw new ImportErrorException("The requested frame is not available");
  145. }
  146. // ------------------------------------------------------------------------------------------------
  147. // Validate the surface header of a given MDR file LOD
  148. void MDRImporter::ValidateLODHeader(BE_NCONST MDR::LOD* pcLOD)
  149. {
  150. AI_SWAP4(pcLOD->ofsSurfaces);
  151. AI_SWAP4(pcLOD->numSurfaces);
  152. AI_SWAP4(pcLOD->ofsEnd);
  153. const unsigned int iMax = fileSize - (unsigned int)((int8_t*)pcLOD-(int8_t*)pcHeader);
  154. // We should have at least one surface here
  155. if (!pcLOD->numSurfaces)
  156. throw new ImportErrorException("MDR: LOD has zero surfaces assigned");
  157. if (pcLOD->ofsSurfaces > iMax)
  158. throw new ImportErrorException("MDR: LOD header is invalid - surface out of range");
  159. }
  160. // ------------------------------------------------------------------------------------------------
  161. // Validate the header of a given MDR file surface
  162. void MDRImporter::ValidateSurfaceHeader(BE_NCONST MDR::Surface* pcSurf)
  163. {
  164. AI_SWAP4(pcSurf->ident);
  165. AI_SWAP4(pcSurf->numBoneReferences);
  166. AI_SWAP4(pcSurf->numTriangles);
  167. AI_SWAP4(pcSurf->numVerts);
  168. AI_SWAP4(pcSurf->ofsBoneReferences);
  169. AI_SWAP4(pcSurf->ofsEnd);
  170. AI_SWAP4(pcSurf->ofsTriangles);
  171. AI_SWAP4(pcSurf->ofsVerts);
  172. AI_SWAP4(pcSurf->shaderIndex);
  173. // Find out how many bytes
  174. const unsigned int iMax = fileSize - (unsigned int)((int8_t*)pcSurf-(int8_t*)pcHeader);
  175. // Not exact - there could be extra data in the vertices.
  176. if (pcSurf->ofsTriangles + pcSurf->numTriangles*sizeof(MDR::Triangle) > iMax ||
  177. pcSurf->ofsVerts + pcSurf->numVerts*sizeof(MDR::Vertex) > iMax)
  178. {
  179. throw new ImportErrorException("MDR: Surface header is invalid");
  180. }
  181. }
  182. // ------------------------------------------------------------------------------------------------
  183. // Setup configuration properties
  184. void MDRImporter::SetupProperties(const Importer* pImp)
  185. {
  186. // **************************************************************
  187. // The AI_CONFIG_IMPORT_MDR_KEYFRAME option overrides the
  188. // AI_CONFIG_IMPORT_GLOBAL_KEYFRAME option.
  189. // **************************************************************
  190. configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_MDR_KEYFRAME,0xffffffff);
  191. if(0xffffffff == configFrameID)
  192. configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_GLOBAL_KEYFRAME,0);
  193. }
  194. // ------------------------------------------------------------------------------------------------
  195. // Imports the given file into the given scene structure.
  196. void MDRImporter::InternReadFile( const std::string& pFile,
  197. aiScene* pScene, IOSystem* pIOHandler)
  198. {
  199. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  200. // Check whether we can read from the file
  201. if( file.get() == NULL)
  202. throw new ImportErrorException( "Failed to open MDR file " + pFile + ".");
  203. // Check whether the mdr file is large enough to contain the file header
  204. fileSize = (unsigned int)file->FileSize();
  205. if( fileSize < sizeof(MDR::Header))
  206. throw new ImportErrorException( "MDR File is too small.");
  207. // Copy the contents of the file to a buffer
  208. std::vector<unsigned char> mBuffer2(fileSize);
  209. file->Read( &mBuffer2[0], 1, fileSize);
  210. mBuffer = &mBuffer2[0];
  211. // Validate the file header and do BigEndian byte swapping for all sub headers
  212. pcHeader = (BE_NCONST MDR::Header*)mBuffer;
  213. ValidateHeader();
  214. // Go to the first LOD
  215. LE_NCONST MDR::LOD* lod = (LE_NCONST MDR::LOD*)((uint8_t*)pcHeader+pcHeader->ofsLODs);
  216. std::vector<aiMesh*> outMeshes;
  217. outMeshes.reserve(lod->numSurfaces);
  218. // Get a pointer to the first surface and continue processing them all
  219. LE_NCONST MDR::Surface* surf = (LE_NCONST MDR::Surface*)((uint8_t*)lod+lod->ofsSurfaces);
  220. for (uint32_t i = 0; i < lod->numSurfaces; ++i)
  221. {
  222. // The surface must have a) faces b) vertices and c) bone references
  223. if (surf->numTriangles && surf->numVerts && surf->numBoneReferences)
  224. {
  225. outMeshes.push_back(new aiMesh());
  226. aiMesh* mesh = outMeshes.back();
  227. mesh->mNumFaces = surf->numTriangles;
  228. mesh->mNumVertices = mesh->mNumFaces*3;
  229. mesh->mNumBones = surf->numBoneReferences;
  230. mesh->mFaces = new aiFace[mesh->mNumFaces];
  231. mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  232. mesh->mTextureCoords[0] = new aiVector3D[mesh->mNumVertices];
  233. mesh->mBones = new aiBone*[mesh->mNumBones];
  234. // Allocate output bones and generate proper names for them
  235. for (unsigned int p = 0; p < mesh->mNumBones;++p)
  236. {
  237. aiBone* bone = mesh->mBones[p] = new aiBone();
  238. bone->mName.length = ::sprintf( bone->mName.data, "B_%i",p);
  239. }
  240. std::vector<BoneWeightInfo> mWeights;
  241. mWeights.reserve(surf->numVerts << 1);
  242. std::vector<VertexInfo> mVertices(surf->numVerts);
  243. // get a pointer to the first vertex
  244. LE_NCONST MDR::Vertex* v = (LE_NCONST MDR::Vertex*)((uint8_t*)surf+surf->ofsVerts);
  245. for (unsigned int m = 0; m < surf->numVerts; ++m)
  246. {
  247. // get a pointer to the next vertex
  248. v = (LE_NCONST MDR::Vertex*)((uint8_t*)(v+1) + v->numWeights*sizeof(MDR::Weight));
  249. // Big Endian - swap the vertex data structure
  250. #ifndef AI_BUILD_BIG_ENDIAN
  251. AI_SWAP4(v->numWeights);
  252. AI_SWAP4(v->normal.x);
  253. AI_SWAP4(v->normal.y);
  254. AI_SWAP4(v->normal.z);
  255. AI_SWAP4(v->texCoords.x);
  256. AI_SWAP4(v->texCoords.y);
  257. #endif
  258. // Fill out output structure
  259. VertexInfo& vert = mVertices[m];
  260. vert.uv.x = v->texCoords.x; vert.uv.y = v->texCoords.y;
  261. vert.normal = v->normal;
  262. vert.start = (unsigned int)mWeights.size();
  263. vert.num = v->numWeights;
  264. // Now compute the final vertex position by averaging
  265. // the positions affecting this vertex, weighting by
  266. // the given vertex weights.
  267. for (unsigned int l = 0; l < vert.num; ++l)
  268. {
  269. }
  270. }
  271. // Find out how large the output weight buffers must be
  272. LE_NCONST MDR::Triangle* tri = (LE_NCONST MDR::Triangle*)((uint8_t*)surf+surf->ofsTriangles);
  273. LE_NCONST MDR::Triangle* const triEnd = tri + surf->numTriangles;
  274. for (; tri != triEnd; ++tri)
  275. {
  276. for (unsigned int o = 0; o < 3;++o)
  277. {
  278. // Big endian: swap the 32 Bit index
  279. #ifndef AI_BUILD_BIG_ENDIAN
  280. AI_SWAP4(tri->indexes[o]);
  281. #endif
  282. register unsigned int temp = tri->indexes[o];
  283. if (temp >= surf->numVerts)
  284. throw new ImportErrorException("MDR: Vertex index is out of range");
  285. VertexInfo& vert = mVertices[temp];
  286. for (unsigned int l = vert.start; l < vert.start + vert.num; ++l)
  287. {
  288. if (mWeights[l].first >= surf->numBoneReferences)
  289. throw new ImportErrorException("MDR: Bone index is out of range");
  290. ++mesh->mBones[mWeights[l].first]->mNumWeights;
  291. }
  292. }
  293. }
  294. // Allocate storage for output bone weights
  295. for (unsigned int p = 0; p < mesh->mNumBones;++p)
  296. {
  297. aiBone* bone = mesh->mBones[p];
  298. ai_assert(0 != bone->mNumWeights);
  299. bone->mWeights = new aiVertexWeight[bone->mNumWeights];
  300. }
  301. // and build the final output buffers
  302. }
  303. // Get a pointer to the next surface and continue
  304. surf = (LE_NCONST MDR::Surface*)((uint8_t*)surf + surf->ofsEnd);
  305. }
  306. // Copy the vector to the C-style output array
  307. pScene->mNumMeshes = (unsigned int) outMeshes.size();
  308. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  309. ::memcpy(pScene->mMeshes,&outMeshes[0],sizeof(void*)*pScene->mNumMeshes);
  310. }