Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 6719 was 6700, checked in by bensch, 19 years ago

trunk: Energy→Health

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