vrshoot

view libs/assimp/MD2Loader.cpp @ 0:b2f14e535253

initial commit
author John Tsiombikas <nuclear@member.fsf.org>
date Sat, 01 Feb 2014 19:58:19 +0200
parents
children
line source
1 /*
2 ---------------------------------------------------------------------------
3 Open Asset Import Library (assimp)
4 ---------------------------------------------------------------------------
6 Copyright (c) 2006-2012, assimp team
8 All rights reserved.
10 Redistribution and use of this software in source and binary forms,
11 with or without modification, are permitted provided that the following
12 conditions are met:
14 * Redistributions of source code must retain the above
15 copyright notice, this list of conditions and the
16 following disclaimer.
18 * Redistributions in binary form must reproduce the above
19 copyright notice, this list of conditions and the
20 following disclaimer in the documentation and/or other
21 materials provided with the distribution.
23 * Neither the name of the assimp team, nor the names of its
24 contributors may be used to endorse or promote products
25 derived from this software without specific prior
26 written permission of the assimp team.
28 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 ---------------------------------------------------------------------------
40 */
42 #include "AssimpPCH.h"
43 #ifndef ASSIMP_BUILD_NO_MD2_IMPORTER
45 /** @file Implementation of the MD2 importer class */
46 #include "MD2Loader.h"
47 #include "ByteSwap.h"
48 #include "MD2NormalTable.h" // shouldn't be included by other units
50 using namespace Assimp;
51 using namespace Assimp::MD2;
54 // helper macro to determine the size of an array
55 #if (!defined ARRAYSIZE)
56 # define ARRAYSIZE(_array) (int(sizeof(_array) / sizeof(_array[0])))
57 #endif
59 static const aiImporterDesc desc = {
60 "Quake II Mesh Importer",
61 "",
62 "",
63 "",
64 aiImporterFlags_SupportBinaryFlavour,
65 0,
66 0,
67 0,
68 0,
69 "md2"
70 };
72 // ------------------------------------------------------------------------------------------------
73 // Helper function to lookup a normal in Quake 2's precalculated table
74 void MD2::LookupNormalIndex(uint8_t iNormalIndex,aiVector3D& vOut)
75 {
76 // make sure the normal index has a valid value
77 if (iNormalIndex >= ARRAYSIZE(g_avNormals)) {
78 DefaultLogger::get()->warn("Index overflow in Quake II normal vector list");
79 iNormalIndex = ARRAYSIZE(g_avNormals) - 1;
80 }
81 vOut = *((const aiVector3D*)(&g_avNormals[iNormalIndex]));
82 }
85 // ------------------------------------------------------------------------------------------------
86 // Constructor to be privately used by Importer
87 MD2Importer::MD2Importer()
88 {}
90 // ------------------------------------------------------------------------------------------------
91 // Destructor, private as well
92 MD2Importer::~MD2Importer()
93 {}
95 // ------------------------------------------------------------------------------------------------
96 // Returns whether the class can handle the format of the given file.
97 bool MD2Importer::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
98 {
99 const std::string extension = GetExtension(pFile);
100 if (extension == "md2")
101 return true;
103 // if check for extension is not enough, check for the magic tokens
104 if (!extension.length() || checkSig) {
105 uint32_t tokens[1];
106 tokens[0] = AI_MD2_MAGIC_NUMBER_LE;
107 return CheckMagicToken(pIOHandler,pFile,tokens,1);
108 }
109 return false;
110 }
112 // ------------------------------------------------------------------------------------------------
113 // Get a list of all extensions supported by this loader
114 const aiImporterDesc* MD2Importer::GetInfo () const
115 {
116 return &desc;
117 }
119 // ------------------------------------------------------------------------------------------------
120 // Setup configuration properties
121 void MD2Importer::SetupProperties(const Importer* pImp)
122 {
123 // The
124 // AI_CONFIG_IMPORT_MD2_KEYFRAME option overrides the
125 // AI_CONFIG_IMPORT_GLOBAL_KEYFRAME option.
126 configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_MD2_KEYFRAME,-1);
127 if(static_cast<unsigned int>(-1) == configFrameID){
128 configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_GLOBAL_KEYFRAME,0);
129 }
130 }
131 // ------------------------------------------------------------------------------------------------
132 // Validate the file header
133 void MD2Importer::ValidateHeader( )
134 {
135 // check magic number
136 if (m_pcHeader->magic != AI_MD2_MAGIC_NUMBER_BE &&
137 m_pcHeader->magic != AI_MD2_MAGIC_NUMBER_LE)
138 {
139 char szBuffer[5];
140 szBuffer[0] = ((char*)&m_pcHeader->magic)[0];
141 szBuffer[1] = ((char*)&m_pcHeader->magic)[1];
142 szBuffer[2] = ((char*)&m_pcHeader->magic)[2];
143 szBuffer[3] = ((char*)&m_pcHeader->magic)[3];
144 szBuffer[4] = '\0';
146 throw DeadlyImportError("Invalid MD2 magic word: should be IDP2, the "
147 "magic word found is " + std::string(szBuffer));
148 }
150 // check file format version
151 if (m_pcHeader->version != 8)
152 DefaultLogger::get()->warn( "Unsupported md2 file version. Continuing happily ...");
154 // check some values whether they are valid
155 if (0 == m_pcHeader->numFrames)
156 throw DeadlyImportError( "Invalid md2 file: NUM_FRAMES is 0");
158 if (m_pcHeader->offsetEnd > (uint32_t)fileSize)
159 throw DeadlyImportError( "Invalid md2 file: File is too small");
161 if (m_pcHeader->offsetSkins + m_pcHeader->numSkins * sizeof (MD2::Skin) >= fileSize ||
162 m_pcHeader->offsetTexCoords + m_pcHeader->numTexCoords * sizeof (MD2::TexCoord) >= fileSize ||
163 m_pcHeader->offsetTriangles + m_pcHeader->numTriangles * sizeof (MD2::Triangle) >= fileSize ||
164 m_pcHeader->offsetFrames + m_pcHeader->numFrames * sizeof (MD2::Frame) >= fileSize ||
165 m_pcHeader->offsetEnd > fileSize)
166 {
167 throw DeadlyImportError("Invalid MD2 header: some offsets are outside the file");
168 }
170 if (m_pcHeader->numSkins > AI_MD2_MAX_SKINS)
171 DefaultLogger::get()->warn("The model contains more skins than Quake 2 supports");
172 if ( m_pcHeader->numFrames > AI_MD2_MAX_FRAMES)
173 DefaultLogger::get()->warn("The model contains more frames than Quake 2 supports");
174 if (m_pcHeader->numVertices > AI_MD2_MAX_VERTS)
175 DefaultLogger::get()->warn("The model contains more vertices than Quake 2 supports");
177 if (m_pcHeader->numFrames <= configFrameID )
178 throw DeadlyImportError("The requested frame is not existing the file");
179 }
181 // ------------------------------------------------------------------------------------------------
182 // Imports the given file into the given scene structure.
183 void MD2Importer::InternReadFile( const std::string& pFile,
184 aiScene* pScene, IOSystem* pIOHandler)
185 {
186 boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile));
188 // Check whether we can read from the file
189 if( file.get() == NULL)
190 throw DeadlyImportError( "Failed to open MD2 file " + pFile + "");
192 // check whether the md3 file is large enough to contain
193 // at least the file header
194 fileSize = (unsigned int)file->FileSize();
195 if( fileSize < sizeof(MD2::Header))
196 throw DeadlyImportError( "MD2 File is too small");
198 std::vector<uint8_t> mBuffer2(fileSize);
199 file->Read(&mBuffer2[0], 1, fileSize);
200 mBuffer = &mBuffer2[0];
203 m_pcHeader = (BE_NCONST MD2::Header*)mBuffer;
205 #ifdef AI_BUILD_BIG_ENDIAN
207 ByteSwap::Swap4(&m_pcHeader->frameSize);
208 ByteSwap::Swap4(&m_pcHeader->magic);
209 ByteSwap::Swap4(&m_pcHeader->numFrames);
210 ByteSwap::Swap4(&m_pcHeader->numGlCommands);
211 ByteSwap::Swap4(&m_pcHeader->numSkins);
212 ByteSwap::Swap4(&m_pcHeader->numTexCoords);
213 ByteSwap::Swap4(&m_pcHeader->numTriangles);
214 ByteSwap::Swap4(&m_pcHeader->numVertices);
215 ByteSwap::Swap4(&m_pcHeader->offsetEnd);
216 ByteSwap::Swap4(&m_pcHeader->offsetFrames);
217 ByteSwap::Swap4(&m_pcHeader->offsetGlCommands);
218 ByteSwap::Swap4(&m_pcHeader->offsetSkins);
219 ByteSwap::Swap4(&m_pcHeader->offsetTexCoords);
220 ByteSwap::Swap4(&m_pcHeader->offsetTriangles);
221 ByteSwap::Swap4(&m_pcHeader->skinHeight);
222 ByteSwap::Swap4(&m_pcHeader->skinWidth);
223 ByteSwap::Swap4(&m_pcHeader->version);
225 #endif
227 ValidateHeader();
229 // there won't be more than one mesh inside the file
230 pScene->mNumMaterials = 1;
231 pScene->mRootNode = new aiNode();
232 pScene->mRootNode->mNumMeshes = 1;
233 pScene->mRootNode->mMeshes = new unsigned int[1];
234 pScene->mRootNode->mMeshes[0] = 0;
235 pScene->mMaterials = new aiMaterial*[1];
236 pScene->mMaterials[0] = new aiMaterial();
237 pScene->mNumMeshes = 1;
238 pScene->mMeshes = new aiMesh*[1];
240 aiMesh* pcMesh = pScene->mMeshes[0] = new aiMesh();
241 pcMesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
243 // navigate to the begin of the frame data
244 BE_NCONST MD2::Frame* pcFrame = (BE_NCONST MD2::Frame*) ((uint8_t*)
245 m_pcHeader + m_pcHeader->offsetFrames);
247 pcFrame += configFrameID;
249 // navigate to the begin of the triangle data
250 MD2::Triangle* pcTriangles = (MD2::Triangle*) ((uint8_t*)
251 m_pcHeader + m_pcHeader->offsetTriangles);
253 // navigate to the begin of the tex coords data
254 BE_NCONST MD2::TexCoord* pcTexCoords = (BE_NCONST MD2::TexCoord*) ((uint8_t*)
255 m_pcHeader + m_pcHeader->offsetTexCoords);
257 // navigate to the begin of the vertex data
258 BE_NCONST MD2::Vertex* pcVerts = (BE_NCONST MD2::Vertex*) (pcFrame->vertices);
260 #ifdef AI_BUILD_BIG_ENDIAN
261 for (uint32_t i = 0; i< m_pcHeader->numTriangles; ++i)
262 {
263 for (unsigned int p = 0; p < 3;++p)
264 {
265 ByteSwap::Swap2(& pcTriangles[i].textureIndices[p]);
266 ByteSwap::Swap2(& pcTriangles[i].vertexIndices[p]);
267 }
268 }
269 for (uint32_t i = 0; i < m_pcHeader->offsetTexCoords;++i)
270 {
271 ByteSwap::Swap2(& pcTexCoords[i].s);
272 ByteSwap::Swap2(& pcTexCoords[i].t);
273 }
274 ByteSwap::Swap4( & pcFrame->scale[0] );
275 ByteSwap::Swap4( & pcFrame->scale[1] );
276 ByteSwap::Swap4( & pcFrame->scale[2] );
277 ByteSwap::Swap4( & pcFrame->translate[0] );
278 ByteSwap::Swap4( & pcFrame->translate[1] );
279 ByteSwap::Swap4( & pcFrame->translate[2] );
280 #endif
282 pcMesh->mNumFaces = m_pcHeader->numTriangles;
283 pcMesh->mFaces = new aiFace[m_pcHeader->numTriangles];
285 // allocate output storage
286 pcMesh->mNumVertices = (unsigned int)pcMesh->mNumFaces*3;
287 pcMesh->mVertices = new aiVector3D[pcMesh->mNumVertices];
288 pcMesh->mNormals = new aiVector3D[pcMesh->mNumVertices];
290 // Not sure whether there are MD2 files without texture coordinates
291 // NOTE: texture coordinates can be there without a texture,
292 // but a texture can't be there without a valid UV channel
293 aiMaterial* pcHelper = (aiMaterial*)pScene->mMaterials[0];
294 const int iMode = (int)aiShadingMode_Gouraud;
295 pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
297 if (m_pcHeader->numTexCoords && m_pcHeader->numSkins)
298 {
299 // navigate to the first texture associated with the mesh
300 const MD2::Skin* pcSkins = (const MD2::Skin*) ((unsigned char*)m_pcHeader +
301 m_pcHeader->offsetSkins);
303 aiColor3D clr;
304 clr.b = clr.g = clr.r = 1.0f;
305 pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_DIFFUSE);
306 pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_SPECULAR);
308 clr.b = clr.g = clr.r = 0.05f;
309 pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_AMBIENT);
311 if (pcSkins->name[0])
312 {
313 aiString szString;
314 const size_t iLen = ::strlen(pcSkins->name);
315 ::memcpy(szString.data,pcSkins->name,iLen);
316 szString.data[iLen] = '\0';
317 szString.length = iLen;
319 pcHelper->AddProperty(&szString,AI_MATKEY_TEXTURE_DIFFUSE(0));
320 }
321 else{
322 DefaultLogger::get()->warn("Texture file name has zero length. It will be skipped.");
323 }
324 }
325 else {
326 // apply a default material
327 aiColor3D clr;
328 clr.b = clr.g = clr.r = 0.6f;
329 pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_DIFFUSE);
330 pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_SPECULAR);
332 clr.b = clr.g = clr.r = 0.05f;
333 pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_AMBIENT);
335 aiString szName;
336 szName.Set(AI_DEFAULT_MATERIAL_NAME);
337 pcHelper->AddProperty(&szName,AI_MATKEY_NAME);
339 aiString sz;
341 // TODO: Try to guess the name of the texture file from the model file name
343 sz.Set("$texture_dummy.bmp");
344 pcHelper->AddProperty(&sz,AI_MATKEY_TEXTURE_DIFFUSE(0));
345 }
348 // now read all triangles of the first frame, apply scaling and translation
349 unsigned int iCurrent = 0;
351 float fDivisorU = 1.0f,fDivisorV = 1.0f;
352 if (m_pcHeader->numTexCoords) {
353 // allocate storage for texture coordinates, too
354 pcMesh->mTextureCoords[0] = new aiVector3D[pcMesh->mNumVertices];
355 pcMesh->mNumUVComponents[0] = 2;
357 // check whether the skin width or height are zero (this would
358 // cause a division through zero)
359 if (!m_pcHeader->skinWidth) {
360 DefaultLogger::get()->error("MD2: No valid skin width given");
361 }
362 else fDivisorU = (float)m_pcHeader->skinWidth;
363 if (!m_pcHeader->skinHeight){
364 DefaultLogger::get()->error("MD2: No valid skin height given");
365 }
366 else fDivisorV = (float)m_pcHeader->skinHeight;
367 }
369 for (unsigned int i = 0; i < (unsigned int)m_pcHeader->numTriangles;++i) {
370 // Allocate the face
371 pScene->mMeshes[0]->mFaces[i].mIndices = new unsigned int[3];
372 pScene->mMeshes[0]->mFaces[i].mNumIndices = 3;
374 // copy texture coordinates
375 // check whether they are different from the previous value at this index.
376 // In this case, create a full separate set of vertices/normals/texcoords
377 for (unsigned int c = 0; c < 3;++c,++iCurrent) {
379 // validate vertex indices
380 register unsigned int iIndex = (unsigned int)pcTriangles[i].vertexIndices[c];
381 if (iIndex >= m_pcHeader->numVertices) {
382 DefaultLogger::get()->error("MD2: Vertex index is outside the allowed range");
383 iIndex = m_pcHeader->numVertices-1;
384 }
386 // read x,y, and z component of the vertex
387 aiVector3D& vec = pcMesh->mVertices[iCurrent];
389 vec.x = (float)pcVerts[iIndex].vertex[0] * pcFrame->scale[0];
390 vec.x += pcFrame->translate[0];
392 vec.y = (float)pcVerts[iIndex].vertex[1] * pcFrame->scale[1];
393 vec.y += pcFrame->translate[1];
395 vec.z = (float)pcVerts[iIndex].vertex[2] * pcFrame->scale[2];
396 vec.z += pcFrame->translate[2];
398 // read the normal vector from the precalculated normal table
399 aiVector3D& vNormal = pcMesh->mNormals[iCurrent];
400 LookupNormalIndex(pcVerts[iIndex].lightNormalIndex,vNormal);
402 // flip z and y to become right-handed
403 std::swap((float&)vNormal.z,(float&)vNormal.y);
404 std::swap((float&)vec.z,(float&)vec.y);
406 if (m_pcHeader->numTexCoords) {
407 // validate texture coordinates
408 iIndex = pcTriangles[i].textureIndices[c];
409 if (iIndex >= m_pcHeader->numTexCoords) {
410 DefaultLogger::get()->error("MD2: UV index is outside the allowed range");
411 iIndex = m_pcHeader->numTexCoords-1;
412 }
414 aiVector3D& pcOut = pcMesh->mTextureCoords[0][iCurrent];
416 // the texture coordinates are absolute values but we
417 // need relative values between 0 and 1
418 pcOut.x = pcTexCoords[iIndex].s / fDivisorU;
419 pcOut.y = 1.f-pcTexCoords[iIndex].t / fDivisorV;
420 }
421 pScene->mMeshes[0]->mFaces[i].mIndices[c] = iCurrent;
422 }
423 }
424 }
426 #endif // !! ASSIMP_BUILD_NO_MD2_IMPORTER