Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/proxy/src/lib/graphics/importer/md2/md2Model.cc @ 9643

Last change on this file since 9643 was 9406, checked in by bensch, 18 years ago

orxonox/trunk: merged the proxy back

merged with commandsvn merge -r9346:HEAD https://svn.orxonox.net/orxonox/branches/proxy .

no conflicts

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