Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/terrain.old/src/lib/graphics/importer/md2/md2Model.cc @ 10642

Last change on this file since 10642 was 9414, checked in by bensch, 18 years ago

merged back here the terrain.old

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