Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/osx/src/lib/graphics/importer/md2Model.cc @ 8160

Last change on this file since 8160 was 8122, checked in by ponder, 19 years ago

Md2loader seems to work

File size: 17.3 KB
Line 
1/*
2   orxonox - the future of 3D-vertical-scrollers
3
4   Copyright (C) 2004 orx
5
6   This program is free software; you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation; either version 2, or (at your option)
9   any later version.
10
11   ### File Specific:
12   main-programmer: Patrick Boenzli
13*/
14
15#define DEBUG_SPECIAL_MODULE DEBUG_MODULE_IMPORTER
16#include "config.h"
17#ifdef HAVE_SDL_SDL_H
18#include <SDL/SDL.h>
19#include <SDL/SDL_endian.h>
20#else
21#include <SDL.h>
22#include <SDL_endian.h>
23#endif
24#include "md2Model.h"
25#include "material.h"
26
27#include "debug.h"
28#include "util/loading/resource_manager.h"
29
30using namespace std;
31
32//! the model anorms
33sVec3D MD2Model::anorms[NUM_VERTEX_NORMALS] = {
34 #include "anorms.h"
35};
36
37//! anormal dots, no idea of how this shall work, but it does
38float MD2Model::anormsDots[SHADEDOT_QUANT][256] = {
39  #include "anormtab.h"
40};
41
42
43//! the angle under which the model is viewd, used internaly
44float md2Angle = 0.0f;
45
46
47//! list of all different animations a std md2model supports
48sAnim MD2Model::animationList[21] =
49  {
50 // begin, end, fps, interruptable
51    {   0,  39,  9, 1 },   //!< STAND
52    {  40,  45, 10, 1 },   //!< RUN
53    {  46,  53, 10, 0 },   //!< ATTACK
54    {  54,  57,  7, 1 },   //!< PAIN_A
55    {  58,  61,  7, 1 },   //!< PAIN_B
56    {  62,  65,  7, 1 },   //!< PAIN_C
57    {  66,  71,  7, 0 },   //!< JUMP
58    {  72,  83,  7, 1 },   //!< FLIP
59    {  84,  94,  7, 1 },   //!< SALUTE
60    {  95, 111, 10, 1 },   //!< FALLBACK
61    { 112, 122,  7, 1 },   //!< WAVE
62    { 123, 134,  6, 1 },   //!< POINTT
63    { 135, 153, 10, 1 },   //!< CROUCH_STAND
64    { 154, 159,  7, 1 },   //!< CROUCH_WALK
65    { 160, 168, 10, 1 },   //!< CROUCH_ATTACK
66    { 196, 172,  7, 1 },   //!< CROUCH_PAIN
67    { 173, 177,  5, 0 },   //!< CROUCH_DEATH
68    { 178, 183,  10, 0 },   //!< DEATH_FALLBACK
69    { 184, 189,  10, 0 },   //!< DEATH_FALLFORWARD
70    { 190, 197,  10, 0 },   //!< DEATH_FALLBACKSLOW
71    { 198, 198,  5, 1 },   //!< BOOM
72  };
73
74
75#ifdef SDL_LIL_ENDIAN
76#define BULK_CONV( _ptr, _num ) do { \
77        int  _cnt = _num;\
78        int* _iptr = (int*)_ptr;\
79        for( int _l = 0; _l<_cnt; ++_l )\
80                _iptr[_l] = SDL_SwapLE32( _iptr[_l] );\
81} while( 0 )
82#else
83#define BULK_CONV( _ptr, _num )
84#endif 
85
86/********************************************************************************
87 *   MD2Model                                                                   *
88 ********************************************************************************/
89
90/**
91  \brief simple constructor initializing all variables
92*/
93MD2Model::MD2Model(const std::string& modelFileName, const std::string& skinFileName, float scale)
94{
95  this->setClassID(CL_MD2_MODEL, "MD2Model");
96  /* this creates the data container via ressource manager */
97  if (!modelFileName.empty())
98    this->data = (MD2Data*)ResourceManager::getInstance()->load( 
99                        modelFileName, MD2, RP_GAME, skinFileName, scale);
100                       
101        //When arriving here it is assumed that everything is in the correct byte order.       
102  if( unlikely(this->data == NULL))
103    PRINTF(0)("The model was not found, MD2Model Loader finished abnormaly. Update the data-repos\n");
104
105  this->scaleFactor = scale;
106
107  shadeDots = MD2Model::anormsDots[0];
108  /* set the animation stat mannualy */
109  this->animationState.type = STAND;
110  this->animationState.numPlays = 1;
111  this->setAnim(STAND);
112
113  this->debug();
114
115    //write the modelinfo information
116  this->pModelInfo.numVertices = this->data->numVertices;
117  this->pModelInfo.numTriangles = this->data->numTriangles;
118  this->pModelInfo.numNormals = 0;
119  this->pModelInfo.numTexCoor = this->data->numTexCoor;
120       
121  this->pModelInfo.pVertices = (float*)this->data->pVertices;
122               
123  this->pModelInfo.pNormals = NULL;
124
125  this->pModelInfo.pTexCoor = (float*)this->data->pTexCoor;
126       
127  // triangle conversion
128  this->pModelInfo.pTriangles = new sTriangleExt[this->data->numTriangles];
129  for( int i = 0; i < this->data->numTriangles; i++)
130  {
131    this->pModelInfo.pTriangles[i].indexToVertices[0] = this->data->pTriangles[i].indexToVertices[0];
132    this->pModelInfo.pTriangles[i].indexToVertices[1] = this->data->pTriangles[i].indexToVertices[1];
133    this->pModelInfo.pTriangles[i].indexToVertices[2] = this->data->pTriangles[i].indexToVertices[2];
134
135    this->pModelInfo.pTriangles[i].indexToTexCoor[0] = this->data->pTriangles[i].indexToTexCoor[0];
136    this->pModelInfo.pTriangles[i].indexToTexCoor[1] = this->data->pTriangles[i].indexToTexCoor[1];
137    this->pModelInfo.pTriangles[i].indexToTexCoor[2] = this->data->pTriangles[i].indexToTexCoor[2];
138  }
139}
140
141
142/**
143  \brief simple destructor, dereferencing all variables
144
145  this is where the ressource manager is cleaning the stuff
146*/
147MD2Model::~MD2Model()
148{
149  this->pModelInfo.pVertices = NULL;
150  this->pModelInfo.pNormals = NULL;
151  this->pModelInfo.pTexCoor = NULL;
152  this->pModelInfo.pTriangles = NULL;
153
154  ResourceManager::getInstance()->unload(this->data);
155}
156
157
158/**
159 *  initializes an array of vert with the current frame scaled vertices
160 * @param this->verticesList: the list of vertices to interpolate between
161
162   we won't use the pVertices array directly, since its much easier and we need
163   saving of data anyway
164*/
165void MD2Model::interpolate(/*sVec3D* this->verticesList*/)
166{
167  sVec3D* currVec;
168  sVec3D* nextVec;
169
170  currVec = &this->data->pVertices[this->data->numVertices * this->animationState.currentFrame];
171  nextVec = &this->data->pVertices[this->data->numVertices * this->animationState.nextFrame];
172
173  for( int i = 0; i < this->data->numVertices; ++i)
174    {
175      this->verticesList[i][0] = currVec[i][0] + this->animationState.interpolationState * (nextVec[i][0] - currVec[i][0]);
176      this->verticesList[i][1] = currVec[i][1] + this->animationState.interpolationState * (nextVec[i][1] - currVec[i][1]);
177      this->verticesList[i][2] = currVec[i][2] + this->animationState.interpolationState * (nextVec[i][2] - currVec[i][2]);
178    }
179}
180
181
182/**
183  \brief sets the animation type
184* @param type: animation type
185
186  the animation types can be looked up in the animationType table
187*/
188void MD2Model::setAnim(int type, int animPlayback)
189{
190  if( (type < 0) || (type > MAX_ANIMATIONS) )
191    type = STAND;
192
193  if( MD2Model::animationList[this->animationState.type].bStoppable == 0)
194  {
195    if( this->animationState.numPlays == 0 )
196      return;
197  }
198
199  this->animationState.startFrame = animationList[type].firstFrame;
200  this->animationState.endFrame = animationList[type].lastFrame;
201  this->animationState.nextFrame = animationList[type].firstFrame + 1;
202  this->animationState.fps = animationList[type].fps;
203  this->animationState.type = type;
204  this->animationState.numPlays = 0;
205  this->animationState.animPlaybackMode = animPlayback;
206
207  this->animationState.interpolationState = 0.0f;
208  this->animationState.localTime = 0.0f;
209  this->animationState.lastTime = 0.0f;
210  this->animationState.currentFrame = animationList[type].firstFrame;
211}
212
213
214/**
215  \brief sets the time in seconds passed since the last tick
216* @param time: in sec
217*/
218void MD2Model::tick(float time)
219{
220  this->animate(time);
221  this->processLighting();
222  this->interpolate(/*this->verticesList*/);
223}
224
225
226/**
227 * @brief draws the model: interface for all other classes out in the world
228 * @todo make it const and virtual
229 * FIXME
230 */
231void MD2Model::draw() const
232{
233  glPushMatrix();
234  this->renderFrame();
235  // renderFrameTriangles();
236  glPopMatrix();
237}
238
239
240/**
241  \brief this is an internal function to render this special frame selected by animate()
242*/
243void MD2Model::renderFrame() const
244{
245  int* pCommands = this->data->pGLCommands;
246
247  /* some face culling stuff */
248  glPushAttrib(GL_POLYGON_BIT);
249  glFrontFace(GL_CW);
250  glEnable(GL_CULL_FACE);
251  glCullFace(GL_BACK);
252
253  this->data->material.select();
254
255  /* draw the triangles */
256  while( int i = *(pCommands++)) /* strange looking while loop for maximum performance */
257    {
258      if( i < 0)
259        {
260          glBegin(GL_TRIANGLE_FAN);
261          i = -i;
262        }
263      else
264        {
265          glBegin(GL_TRIANGLE_STRIP);
266        }
267
268      for(; i > 0; i--, pCommands += 3) /* down counting for loop, next 3 gl commands */
269        {
270          glTexCoord2f( ((float *)pCommands)[0], ((float *)pCommands)[1] );
271          glNormal3fv(anorms[this->data->pLightNormals[pCommands[2]]]);
272          glVertex3fv(this->verticesList[pCommands[2]]);
273        }
274      glEnd();
275
276    }
277  glDisable(GL_CULL_FACE);
278  glPopAttrib();
279}
280
281
282void MD2Model::renderFrameTriangles() const
283{
284  //static sVec3D this->verticesList[MD2_MAX_VERTICES]; /* performance: created only once in a lifetime */
285  int* pCommands = this->data->pGLCommands;
286  /* some face culling stuff */
287//   glPushAttrib(GL_POLYGON_BIT);
288//   glFrontFace(GL_CW);
289//   glEnable(GL_CULL_FACE);
290//   glCullFace(GL_BACK);
291//
292//   this->processLighting();
293//   this->interpolate(/*this->verticesList*/);
294  this->data->material.select();
295
296  /* draw the triangles */
297  glBegin(GL_TRIANGLES);
298
299  for( int i = 0, k = 0; i < this->data->numTriangles; ++i, k += 3)
300  {
301    float* v = this->data->pVertices[this->data->pTriangles[i].indexToVertices[0]];
302
303    printf("triangle: %i\n", i);
304    printf("     v0: (%f, %f, %f)\n", v[0], v[1], v[2]);
305    v = this->data->pVertices[this->data->pTriangles[i].indexToVertices[1]];
306    printf("     v1: (%f, %f, %f)\n", v[0], v[1], v[2]);
307    v = this->data->pVertices[this->data->pTriangles[i].indexToVertices[2]];
308    printf("     v2: (%f, %f, %f)\n", v[0], v[1], v[2]);
309
310
311    glNormal3f(anorms[i][0], anorms[i][1], anorms[i][2]);
312    glVertex3fv(this->data->pVertices[this->data->pTriangles[i].indexToVertices[0]]);
313
314    glNormal3f(anorms[i][0], anorms[i][1], anorms[i][2]);
315    glVertex3fv(this->data->pVertices[this->data->pTriangles[i].indexToVertices[1]]);
316
317    glNormal3f(anorms[i][0], anorms[i][1], anorms[i][2]);
318    glVertex3fv(this->data->pVertices[this->data->pTriangles[i].indexToVertices[2]]);
319  }
320
321  glEnd();
322}
323
324
325/**
326  \brief animates the current model
327
328  depending on the time passed (tick function), the player will select another model
329*/
330void MD2Model::animate(float time)
331{
332  this->animationState.localTime += time;
333
334  if( this->animationState.localTime - this->animationState.lastTime > (1.0f / this->animationState.fps))
335    {
336      this->animationState.currentFrame = this->animationState.nextFrame;
337      this->animationState.nextFrame++;
338
339      if( this->animationState.nextFrame > this->animationState.endFrame )
340      {
341        if( this->animationState.animPlaybackMode == MD2_ANIM_LOOP)
342        {
343          this->animationState.nextFrame = this->animationState.startFrame;
344          this->animationState.numPlays++;
345        }
346        else
347        {
348          this->animationState.nextFrame = this->animationState.endFrame;
349        }
350      }
351      this->animationState.lastTime = this->animationState.localTime;
352    }
353
354//     if( this->animationState.currentFrame > (this->data->numFrames - 1) )
355//       this->animationState.currentFrame = 0;
356
357//     if( (this->animationState.nextFrame > (this->data->numFrames - 1)) && this->animationState.animPlaybackMode == MD2_ANIM_LOOP)
358//     this->animationState.nextFrame = 0;
359
360  this->animationState.interpolationState = this->animationState.fps *
361    (this->animationState.localTime - this->animationState.lastTime);
362}
363
364
365/**
366  \brief this is how id is precessing their lightning
367
368  the details of how the whole lighting process is beeing handled - i have no idea... :)
369*/
370void MD2Model::processLighting()
371{
372  shadeDots = anormsDots[((int)(md2Angle*(SHADEDOT_QUANT / 360.0)))&(SHADEDOT_QUANT - 1)];
373}
374
375
376/**
377  \brief prints out debug informations
378*/
379void MD2Model::debug()
380{
381  //PRINTF(0)("\n==========================| MD2Model::debug() |===\n");
382  PRINTF(0)("=  Model FileName:\t%s\n", this->data->fileName.c_str());
383  PRINTF(0)("=  Skin FileName:\t%s\n", this->data->skinFileName.c_str());
384  PRINTF(0)("=  Size in Memory:\t%i Bytes\n", this->data->header->frameSize * this->data->header->numFrames + 64); // 64bytes is the header size
385  PRINTF(0)("=  Number of Vertices:\t%i\n", this->data->header->numVertices);
386  PRINTF(0)("=  Number of Frames: \t%i\n", this->data->header->numFrames);
387  PRINTF(0)("=  Height, Width:\t%i, %i\n", this->data->header->skinHeight, this->data->header->skinWidth);
388  PRINTF(0)("=  Pointer to the data object: %p\n", this->data);
389  //PRINTF(0)("===================================================\n\n");
390}
391
392
393/********************************************************************************
394 *   MD2Data                                                                    *
395 ********************************************************************************/
396
397/**
398  \brief simple constructor
399*/
400MD2Data::MD2Data(const std::string& modelFileName, const std::string& skinFileName, float scale)
401{
402  scale *= 0.1f;
403
404  this->pVertices = NULL;
405  this->pGLCommands = NULL;
406  this->pLightNormals = NULL;
407  this->pTexCoor = NULL;
408
409  this->numFrames = 0;
410  this->numVertices = 0;
411  this->numGLCommands = 0;
412  this->numTexCoor = 0;
413
414//   this->scaleFactor = 1.0f;
415  this->scaleFactor = scale;
416
417  this->fileName = "";
418  this->skinFileName = "";
419  this->loadModel(modelFileName);
420  this->loadSkin(skinFileName);
421}
422
423
424/**
425  \brief simple destructor
426
427  this will clean out all the necessary data for a specific md2model
428*/
429MD2Data::~MD2Data()
430{
431  delete this->header;
432
433  delete [] this->pVertices;
434  delete [] this->pGLCommands;
435  delete [] this->pLightNormals;
436  delete [] this->pTexCoor;
437}
438
439
440
441/**
442  \brief this will load the whole model data (vertices, opengl command list, ...)
443* @param fileName: the name of the model file
444  \return true if success
445*/
446bool MD2Data::loadModel(const std::string& fileName)
447{
448  FILE *pFile;                            //file stream
449  char* buffer;                           //buffer for frame data
450  sFrame* frame;                          //temp frame
451  sVec3D *pVertex;
452  int* pNormals;
453
454  //! @todo this chek should include deleting a loaded model (eventually)
455  if (fileName.empty())
456    return false;
457
458  pFile = fopen(fileName.c_str(), "rb");
459  if( unlikely(!pFile))
460    {
461      PRINTF(1)("Couldn't open the MD2 File for loading. Exiting.\n");
462      return false;
463    }
464  this->header = new MD2Header;
465  fread(this->header, 1, sizeof(MD2Header), pFile);
466        BULK_CONV( this->header, sizeof(MD2Header)/4 );
467  /* check for the header version: make sure its a md2 file :) */
468  if( unlikely( this->header->version != MD2_VERSION) && unlikely( this->header->ident != MD2_IDENT))
469    {
470      PRINTF(1)("Couldn't load file %s: invalid file format: stop loading\n", fileName.c_str());
471      return false;
472    }
473
474  this->fileName = fileName;
475  /* got the data: map it to locals */
476  this->numFrames = this->header->numFrames;
477  this->numVertices = this->header->numVertices;
478  this->numTriangles = this->header->numTriangles;
479  this->numGLCommands = this->header->numGlCommands;
480  this->numTexCoor = this->header->numTexCoords;
481  /* allocate memory for the data storage */
482  this->pVertices = new sVec3D[this->numVertices * this->numFrames];
483  this->pGLCommands = new int[this->numGLCommands];
484  this->pLightNormals = new int[this->numVertices * this->numFrames];
485  this->pTriangles = new sTriangle[this->numTriangles];
486  this->pTexCoor = new sTexCoor[this->numTexCoor];
487  buffer = new char[this->numFrames * this->header->frameSize];
488
489
490  /* read frame data from the file to a temp buffer */
491  fseek(pFile, this->header->offsetFrames, SEEK_SET);
492  fread(buffer, this->header->frameSize, this->numFrames, pFile);
493        BULK_CONV( buffer, this->header->frameSize*this->numFrames*sizeof(char)/4 );
494  /* read opengl commands */
495  fseek(pFile, this->header->offsetGlCommands, SEEK_SET);
496
497  fread(this->pGLCommands, sizeof(int), this->numGLCommands, pFile);
498        BULK_CONV( this->pGLCommands, this->numGLCommands );
499  /* triangle list */
500  fseek(pFile, this->header->offsetTriangles, SEEK_SET);
501  fread(this->pTriangles, sizeof(sTriangle), this->numTriangles, pFile);       
502        BULK_CONV( this->pTriangles, this->numTriangles*(sizeof(sTriangle)/4) );
503
504  /*  read in texture coordinates */
505  fseek(pFile, this->header->offsetTexCoords, SEEK_SET);
506  fread(this->pTexCoor, sizeof(sTexCoor), this->numTexCoor, pFile);
507        BULK_CONV( this->pTexCoor, this->numTexCoor*(sizeof(sTexCoor)/4) );
508
509  for(int i = 0; i < this->numFrames; ++i)
510    {
511      frame = (sFrame*)(buffer + this->header->frameSize * i);
512      pVertex = this->pVertices + this->numVertices  * i;
513      pNormals = this->pLightNormals + this->numVertices * i;
514
515      for(int j = 0; j < this->numVertices; ++j)
516        {
517          /* SPEEDUP: *(pVerts + i + 0) = (*(frame->pVertices + i + 0)...  */
518           pVertex[j][0] = ((frame->pVertices[j].v[0] * frame->scale[0] ) + frame->translate[0] )* this->scaleFactor;
519           pVertex[j][1] = ((frame->pVertices[j].v[2] * frame->scale[2]) + frame->translate[2]) * this->scaleFactor;
520           pVertex[j][2] = (-1.0 * (frame->pVertices[j].v[1] * frame->scale[1] + frame->translate[1])) * this->scaleFactor;
521
522          //printf("vertex %i/%i: (%f, %f, %f)\n", j, this->numVertices, pVertex[j][0], pVertex[j][1], pVertex[j][2]);
523
524          pNormals[j] = frame->pVertices[j].lightNormalIndex;
525        }
526    }
527    PRINTF(4)("Finished loading the md2 file\n");
528
529  delete [] buffer;
530  fclose(pFile);
531}
532
533
534/**
535  \brief loads the skin/material stuff
536* @param fileName: name of the skin file
537  \return true if success
538*/
539bool MD2Data::loadSkin(const std::string& fileName)
540{
541  if( fileName.empty())
542    {
543      this->skinFileName = "";
544      return false;
545    }
546
547  this->skinFileName = fileName;
548
549  this->material.setName("md2ModelMaterial");
550  this->material.setDiffuseMap(fileName);
551  this->material.setIllum(3);
552  this->material.setAmbient(1.0, 1.0, 1.0);
553}
Note: See TracBrowser for help on using the repository browser.