Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/single_player_map/src/lib/graphics/importer/md2/md2Model.cc @ 8878

Last change on this file since 8878 was 8878, checked in by patrick, 18 years ago

altering md2 model for dynamic animations choosement

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