Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/world_entities/world_entity.cc @ 7068

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

trunk: the modelinfo of md2 models is now written too

File size: 15.1 KB
Line 
1
2
3/*
4   orxonox - the future of 3D-vertical-scrollers
5
6   Copyright (C) 2004 orx
7
8   This program is free software; you can redistribute it and/or modify
9   it under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2, or (at your option)
11   any later version.
12
13   ### File Specific:
14   main-programmer: Patrick Boenzli
15   co-programmer: Christian Meyer
16*/
17#define DEBUG_SPECIAL_MODULE DEBUG_MODULE_WORLD_ENTITY
18
19#include "world_entity.h"
20#include "shell_command.h"
21
22#include "model.h"
23#include "md2Model.h"
24#include "resource_manager.h"
25#include "load_param.h"
26#include "vector.h"
27#include "obb_tree.h"
28
29#include "glgui_bar.h"
30
31#include "state.h"
32#include "camera.h"
33
34using namespace std;
35
36SHELL_COMMAND(model, WorldEntity, loadModel)
37->describe("sets the Model of the WorldEntity")
38->defaultValues(2, "models/ships/fighter.obj", 1.0);
39
40SHELL_COMMAND(debugEntity, WorldEntity, debugWE);
41
42/**
43 *  Loads the WordEntity-specific Part of any derived Class
44 *
45 * @param root: Normally NULL, as the Derived Entities define a loadParams Function themeselves,
46 *              that can calls WorldEntities loadParams for itself.
47 */
48WorldEntity::WorldEntity()
49    : Synchronizeable()
50{
51  this->setClassID(CL_WORLD_ENTITY, "WorldEntity");
52
53  this->obbTree = NULL;
54  this->healthWidget = NULL;
55  this->healthMax = 1.0f;
56  this->health = 1.0f;
57  this->scaling = 1.0f;
58
59  /* OSOLETE */
60  this->bVisible = true;
61  this->bCollide = true;
62
63  this->md2TextureFileName = NULL;
64
65  this->objectListNumber = OM_INIT;
66  this->objectListIterator = NULL;
67
68  this->toList(OM_NULL);
69}
70
71/**
72 *  standard destructor
73*/
74WorldEntity::~WorldEntity ()
75{
76  // Delete the obbTree
77  if( this->obbTree != NULL)
78    delete this->obbTree;
79
80  if (this->healthWidget != NULL)
81    delete this->healthWidget;
82
83  // Delete the model (unregister it with the ResourceManager)
84  for (unsigned int i = 0; i < this->models.size(); i++)
85    this->setModel(NULL, i);
86
87  State::getObjectManager()->toList(this, OM_INIT);
88}
89
90/**
91 * loads the WorldEntity Specific Parameters.
92 * @param root: the XML-Element to load the Data From
93 */
94void WorldEntity::loadParams(const TiXmlElement* root)
95{
96  // Do the PNode loading stuff
97  PNode::loadParams(root);
98
99  LoadParam(root, "md2texture", this, WorldEntity, loadMD2Texture)
100  .describe("the fileName of the texture, that should be loaded onto this world-entity. (must be relative to the data-dir)")
101  .defaultValues(1, NULL);
102
103  // Model Loading
104  LoadParam(root, "model", this, WorldEntity, loadModel)
105  .describe("the fileName of the model, that should be loaded onto this world-entity. (must be relative to the data-dir)")
106  .defaultValues(3, NULL, 1.0f, 0);
107
108  LoadParam(root, "maxHealth", this, WorldEntity, setHealthMax)
109  .describe("The Maximum health that can be loaded onto this entity")
110  .defaultValues(1, 1.0f);
111
112  LoadParam(root, "health", this, WorldEntity, setHealth)
113  .describe("The Health the WorldEntity has at this moment")
114  .defaultValues(1, 1.0f);
115}
116
117
118/**
119 * loads a Model onto a WorldEntity
120 * @param fileName the name of the model to load
121 * @param scaling the Scaling of the model
122 *
123 * @todo fix this, so it only has one loadModel-Function.
124*/
125void WorldEntity::loadModel(const char* fileName, float scaling, unsigned int modelNumber)
126{
127  this->modelLODName = fileName;
128  this->scaling = scaling;
129  if ( fileName != NULL && strcmp(fileName, "") )
130  {
131    // search for the special character # in the LoadParam
132    if (strchr(fileName, '#') != NULL)
133    {
134      PRINTF(4)("Found # in %s... searching for LOD's\n", fileName);
135      char* lodFile = new char[strlen(fileName)+1];
136      strcpy(lodFile, fileName);
137      char* depth = strchr(lodFile, '#');
138      for (unsigned int i = 0; i < 3; i++)
139      {
140        *depth = 48+(int)i;
141        if (ResourceManager::isInDataDir(lodFile))
142          this->loadModel(lodFile, scaling, i);
143      }
144      return;
145    }
146    if (this->scaling <= 0.0)
147    {
148      this->scaling = 1.0;
149      PRINTF(1)("YOU GAVE ME A CRAPY SCALE resetting to 1\n");
150    }
151    if(strstr(fileName, ".obj"))
152    {
153      PRINTF(4)("fetching OBJ file: %s\n", fileName);
154      if (this->scaling == 1.0)
155        this->setModel((Model*)ResourceManager::getInstance()->load(fileName, OBJ, RP_CAMPAIGN), modelNumber);
156      else
157        this->setModel((Model*)ResourceManager::getInstance()->load(fileName, OBJ, RP_CAMPAIGN, this->scaling), modelNumber);
158
159      if( modelNumber == 0)
160        this->buildObbTree(4);
161    }
162    else if(strstr(fileName, ".md2"))
163    {
164      PRINTF(4)("fetching MD2 file: %s\n", fileName);
165      Model* m = new MD2Model(fileName, this->md2TextureFileName, this->scaling);
166      //this->setModel((Model*)ResourceManager::getInstance()->load(fileName, MD2, RP_CAMPAIGN), 0);
167      this->setModel(m, 0);
168
169      if( m != NULL)
170        this->buildObbTree(4);
171    }
172  }
173  else
174  {
175    this->setModel(NULL);
176  }
177}
178
179/**
180 * sets a specific Model for the Object.
181 * @param model The Model to set
182 * @param modelNumber the n'th model in the List to get.
183 */
184void WorldEntity::setModel(Model* model, unsigned int modelNumber)
185{
186  if (this->models.size() <= modelNumber)
187    this->models.resize(modelNumber+1, NULL);
188
189  if (this->models[modelNumber] != NULL)
190  {
191    Resource* resource = ResourceManager::getInstance()->locateResourceByPointer(this->models[modelNumber]);
192    //     if (resource != NULL)
193    ResourceManager::getInstance()->unload(resource, RP_LEVEL);
194  }
195  else
196    delete this->models[modelNumber];
197
198  this->models[modelNumber] = model;
199
200
201  //   if (this->model != NULL)
202  //     this->buildObbTree(4);
203}
204
205
206/**
207 * builds the obb-tree
208 * @param depth the depth to calculate
209 */
210bool WorldEntity::buildObbTree(unsigned int depth)
211{
212  if (this->obbTree)
213    delete this->obbTree;
214
215  if (this->models[0] != NULL)
216  {
217    PRINTF(4)("creating obb tree\n");
218
219
220    this->obbTree = new OBBTree(depth, (sVec3D*)this->models[0]->getVertexArray(), this->models[0]->getVertexCount());
221    return true;
222  }
223  else
224  {
225    PRINTF(2)("could not create obb-tree, because no model was loaded yet\n");
226    this->obbTree = NULL;
227    return false;
228  }
229}
230
231/**
232 * @brief moves this entity to the List OM_List
233 * @param list the list to set this Entity to.
234 *
235 * this is the same as a call to State::getObjectManager()->toList(entity , list);
236 * directly, but with an easier interface.
237 *
238 * @todo inline this (peut etre)
239 */
240void WorldEntity::toList(OM_LIST list)
241{
242  State::getObjectManager()->toList(this, list);
243}
244
245
246
247/**
248 * sets the character attributes of a worldentity
249 * @param character attributes
250 *
251 * these attributes don't have to be set, only use them, if you need them
252*/
253//void WorldEntity::setCharacterAttributes(CharacterAttributes* charAttr)
254//{}
255
256
257/**
258 *  this function is called, when two entities collide
259 * @param entity: the world entity with whom it collides
260 *
261 * Implement behaviour like damage application or other miscellaneous collision stuff in this function
262 */
263void WorldEntity::collidesWith(WorldEntity* entity, const Vector& location)
264{
265  /**
266   * THIS IS A DEFAULT COLLISION-Effect.
267   * IF YOU WANT TO CREATE A SPECIFIC COLLISION ON EACH OBJECT
268   * USE::
269   * if (entity->isA(CL_WHAT_YOU_ARE_LOOKING_FOR)) { printf "dothings"; };
270   *
271   * You can always define a default Action.... don't be affraid just test it :)
272   */
273  //  PRINTF(3)("collision %s vs %s @ (%f,%f,%f)\n", this->getClassName(), entity->getClassName(), location.x, location.y, location.z);
274}
275
276
277/**
278 *  this is called immediately after the Entity has been constructed, initialized and then Spawned into the World
279 *
280 */
281void WorldEntity::postSpawn ()
282{}
283
284
285/**
286 *  this method is called by the world if the WorldEntity leaves the game
287 */
288void WorldEntity::leaveWorld ()
289{}
290
291
292/**
293 *  this method is called every frame
294 * @param time: the time in seconds that has passed since the last tick
295 *
296 * Handle all stuff that should update with time inside this method (movement, animation, etc.)
297*/
298void WorldEntity::tick(float time)
299{}
300
301
302/**
303 *  the entity is drawn onto the screen with this function
304 *
305 * This is a central function of an entity: call it to let the entity painted to the screen.
306 * Just override this function with whatever you want to be drawn.
307*/
308void WorldEntity::draw() const
309{
310  //PRINTF(0)("(%s::%s)\n", this->getClassName(), this->getName());
311  //  assert(!unlikely(this->models.empty()));
312  {
313    glMatrixMode(GL_MODELVIEW);
314    glPushMatrix();
315
316    /* translate */
317    glTranslatef (this->getAbsCoor ().x,
318                  this->getAbsCoor ().y,
319                  this->getAbsCoor ().z);
320    Vector tmpRot = this->getAbsDir().getSpacialAxis();
321    glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
322
323
324    // This Draws the LOD's
325    float cameraDistance = State::getCamera()->distance(this);
326    if (cameraDistance > 30 && this->models.size() >= 3 && this->models[2] != NULL)
327    {
328      this->models[2]->draw();
329    }
330    else if (cameraDistance > 10 && this->models.size() >= 2 && this->models[1] != NULL)
331    {
332      this->models[1]->draw();
333    }
334    else if (this->models.size() >= 1 && this->models[0] != NULL)
335    {
336      this->models[0]->draw();
337    }
338    glPopMatrix();
339  }
340}
341
342/**
343 * @param health the Health to add.
344 * @returns the health left (this->healthMax - health+this->health)
345 */
346float WorldEntity::increaseHealth(float health)
347{
348  this->health += health;
349  if (this->health > this->healthMax)
350  {
351    float retHealth = this->healthMax - this->health;
352    this->health = this->healthMax;
353    this->updateHealthWidget();
354    return retHealth;
355  }
356  this->updateHealthWidget();
357  return 0.0;
358}
359
360/**
361 * @param health the Health to be removed
362 * @returns 0.0 or the rest, that was not substracted (bellow 0.0)
363 */
364float WorldEntity::decreaseHealth(float health)
365{
366  this->health -= health;
367
368  if (this->health < 0)
369  {
370    float retHealth = -this->health;
371    this->health = 0.0f;
372    this->updateHealthWidget();
373    return retHealth;
374  }
375  this->updateHealthWidget();
376  return 0.0;
377
378}
379
380/**
381 * @param maxHealth the maximal health that can be loaded onto the entity.
382 */
383void WorldEntity::setHealthMax(float healthMax)
384{
385  this->healthMax = healthMax;
386  if (this->health > this->healthMax)
387  {
388    PRINTF(3)("new maxHealth is bigger as the old health. Did you really intend to do this for (%s::%s)\n", this->getClassName(), this->getName());
389    this->health = this->healthMax;
390  }
391  this->updateHealthWidget();
392}
393
394/**
395 * @brief creates the HealthWidget
396 *
397 * since not all entities need an HealthWidget, it is only created on request.
398 */
399void WorldEntity::createHealthWidget()
400{
401  if (this->healthWidget == NULL)
402  {
403    this->healthWidget = new GLGuiBar();
404    this->healthWidget->setSize2D(30,400);
405    this->healthWidget->setAbsCoor2D(10,100);
406
407    this->updateHealthWidget();
408  }
409  else
410    PRINTF(3)("Allready created the HealthWidget for %s::%s\n", this->getClassName(), this->getName());
411}
412
413void WorldEntity::increaseHealthMax(float increaseHealth)
414{
415  this->healthMax += increaseHealth;
416  this->updateHealthWidget();
417}
418
419
420GLGuiWidget* WorldEntity::getHealthWidget()
421{
422  this->createHealthWidget();
423  return this->healthWidget;
424}
425
426/**
427 * @param visibility shows or hides the health-bar
428 * (creates the widget if needed)
429 */
430void WorldEntity::setHealthWidgetVisibilit(bool visibility)
431{
432    if (visibility)
433    {
434      if (this->healthWidget != NULL)
435        this->healthWidget->show();
436      else
437      {
438        this->createHealthWidget();
439        this->updateHealthWidget();
440        this->healthWidget->show();
441      }
442    }
443    else if (this->healthWidget != NULL)
444      this->healthWidget->hide();
445}
446
447/**
448 * @brief updates the HealthWidget
449 */
450void WorldEntity::updateHealthWidget()
451{
452  if (this->healthWidget != NULL)
453  {
454    this->healthWidget->setMaximum(this->healthMax);
455    this->healthWidget->setValue(this->health);
456  }
457}
458
459
460/**
461 * DEBUG-DRAW OF THE BV-Tree.
462 * @param depth What depth to draw
463 * @param drawMode the mode to draw this entity under
464 */
465void WorldEntity::drawBVTree(unsigned int depth, int drawMode) const
466{
467  glMatrixMode(GL_MODELVIEW);
468  glPushMatrix();
469  /* translate */
470  glTranslatef (this->getAbsCoor ().x,
471                this->getAbsCoor ().y,
472                this->getAbsCoor ().z);
473  /* rotate */
474  Vector tmpRot = this->getAbsDir().getSpacialAxis();
475  glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
476
477  if (this->obbTree)
478    this->obbTree->drawBV(depth, drawMode);
479  glPopMatrix();
480}
481
482
483/**
484 * Debug the WorldEntity
485 */
486void WorldEntity::debugEntity() const
487{
488  PRINT(0)("WorldEntity %s::%s  (DEBUG)\n", this->getClassName(), this->getName());
489  this->debugNode();
490  PRINT(0)("List: %s ; ModelCount %d - ", ObjectManager::OMListToString(this->objectListNumber) , this->models.size());
491  for (unsigned int i = 0; i < this->models.size(); i++)
492  {
493    if (models[i] != NULL)
494      PRINT(0)(" : %d:%s", i, this->models[i]->getName());
495  }
496  PRINT(0)("\n");
497
498}
499
500
501
502
503/********************************************************************************************
504 NETWORK STUFF
505 ********************************************************************************************/
506
507
508/**
509 * Writes data from network containing information about the state
510 * @param data pointer to data
511 * @param length length of data
512 * @param sender hostID of sender
513 */
514int WorldEntity::writeState( const byte * data, int length, int sender )
515{
516  char* modelFileName;
517  SYNCHELP_READ_BEGIN();
518
519  SYNCHELP_READ_FKT( PNode::writeState, NWT_WE_PN_WRITESTATE );
520
521  SYNCHELP_READ_STRINGM( modelFileName, NWT_WE_PN_MODELFILENAME );
522  SYNCHELP_READ_FLOAT( scaling, NWT_WE_PN_SCALING );
523  //check if modelFileName is relative to datadir or absolute
524
525
526  PRINTF(0)("================ LOADING MODEL %s, %f\n", modelFileName, scaling);
527
528  if ( strcmp(modelFileName, "") )
529  {
530    loadModel( modelFileName, scaling);
531    PRINTF(0)("modelfilename: %s\n", getModel( 0 )->getName());
532  }
533  delete[] modelFileName;
534
535  /*SYNCHELP_READ_STRINGM( modelFileName );
536
537  if ( strcmp(modelFileName, "") )
538    if ( strstr(modelFileName, ResourceManager::getInstance()->getDataDir()) )
539    {
540      this->md2TextureFileName = new char[strlen(modelFileName)-strlen(ResourceManager::getInstance()->getDataDir())+1];
541      strcpy((char*)this->md2TextureFileName, modelFileName+strlen(ResourceManager::getInstance()->getDataDir()));
542    }
543    else
544    {
545      this->md2TextureFileName = modelFileName;
546    }
547  */
548
549  return SYNCHELP_READ_N;
550}
551
552
553/**
554 * data copied in data will bee sent to another host
555 * @param data pointer to data
556 * @param maxLength max length of data
557 * @return the number of bytes writen
558 */
559int WorldEntity::readState( byte * data, int maxLength )
560{
561  SYNCHELP_WRITE_BEGIN();
562
563  SYNCHELP_WRITE_FKT( PNode::readState, NWT_WE_PN_WRITESTATE );
564
565  if ( getModel(0) && getModel(0)->getName() )
566  {
567    char* name = (char*)(getModel( 0 )->getName());
568
569    if ( strstr(name, ResourceManager::getInstance()->getDataDir()) )
570    {
571      name += strlen(ResourceManager::getInstance()->getDataDir());
572    }
573
574    SYNCHELP_WRITE_STRING( name, NWT_WE_PN_MODELFILENAME );
575  }
576  else
577  {
578    SYNCHELP_WRITE_STRING("", NWT_WE_PN_MODELFILENAME);
579  }
580
581  SYNCHELP_WRITE_FLOAT( scaling, NWT_WE_PN_SCALING );
582  /*if ( this->md2TextureFileName!=NULL && strcmp(this->md2TextureFileName, "") )
583  {
584    SYNCHELP_WRITE_STRING(this->md2TextureFileName);
585  }
586  else
587  {
588    SYNCHELP_WRITE_STRING("");
589}*/
590
591  return SYNCHELP_WRITE_N;
592}
Note: See TracBrowser for help on using the repository browser.