Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/presentation/src/world_entities/world_entity.cc @ 10717

Last change on this file since 10717 was 10714, checked in by nicolasc, 18 years ago

initial upload form mouse aiming in VS

File size: 30.8 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   main-programmer: Benjamin Grauer
16   co-programmer:   Christian Meier
17*/
18#define DEBUG_SPECIAL_MODULE DEBUG_MODULE_WORLD_ENTITY
19
20#include "world_entity.h"
21#include "shell_command.h"
22
23#include "util/loading/resource_manager.h"
24#include "resource_obj.h"
25#include "md2/md2Model.h"
26#include "md3/md3_model.h"
27
28#include "oif/object_information_file.h"
29#include "tools/mount_point.h"
30
31#include "aabb_tree_node.h"
32
33#include "util/loading/load_param.h"
34#include "loading/load_param_xml.h"
35#include "util/loading/factory.h"
36
37#include "obb_tree.h"
38
39#include "elements/glgui_energywidget.h"
40#include "elements/glgui_energywidgetvertical.h"
41
42#include "state.h"
43#include "tools/camera.h"
44
45#include "collision_filter.h"
46#include "collision_event.h"
47#include "game_rules.h"
48#include "kill.h"
49#include "debug.h"
50
51#include "track/track.h"
52
53#include "projectiles/projectile.h"
54
55SHELL_COMMAND(model, WorldEntity, loadModel)
56->describe("sets the Model of the WorldEntity")
57->defaultValues("models/ships/fighter.obj", 1.0f);
58
59SHELL_COMMAND(debugEntity, WorldEntity, debugWE);
60
61
62ObjectListDefinition(WorldEntity);
63/**
64 *  Loads the WordEntity-specific Part of any derived Class
65 *
66 * @param root: Normally NULL, as the Derived Entities define a loadParams Function themeselves,
67 *              that can calls WorldEntities loadParams for itself.
68 */
69WorldEntity::WorldEntity()
70    : Synchronizeable(), _collisionFilter(this)
71{
72  this->registerObject(this, WorldEntity::_objectList);
73
74  this->obbTree = NULL;
75  this->aabbNode = NULL;
76  this->healthWidget = NULL;
77  this->electronicWidget = NULL;
78  this->shieldWidget = NULL;
79  this->healthMax = 1.0f;
80  this->health = 1.0f;
81  this->damage = 0.0f; // no damage dealt by a default entity
82  this->scaling = 1.0f;
83  this->oiFile = NULL;
84  // add 10 members to this array
85  this->mountPoints.reserve(10);
86
87  /* OSOLETE */
88  this->bVisible = true;
89  this->bCollide = true;
90
91  this->objectListNumber = OM_INIT;
92  this->lastObjectListNumber = OM_INIT;
93
94  this->_bOnGround = false;
95
96  // Track of this entity
97  this->entityTrack = NULL;
98  this->bDrawTrack = false;
99 
100  this->forwardDamageToParent = false;
101  this->damageable = false;
102
103  // registering default reactions:
104  this->subscribeReaction(CoRe::CREngine::CR_OBJECT_DAMAGE, Projectile::staticClassID());
105
106  this->toList(OM_NULL);
107
108  this->registerVar( new SynchronizeableString( &this->md2TextureFileName, &this->md2TextureFileName, "md2TextureFileName", PERMISSION_MASTER_SERVER ) );
109  this->modelFileName_handle = registerVarId( new SynchronizeableString( &modelFileName, &modelFileName, "modelFileName", PERMISSION_MASTER_SERVER ) );
110  this->scaling_handle = registerVarId( new SynchronizeableFloat( &scaling, &scaling, "scaling", PERMISSION_MASTER_SERVER ) );
111  this->list_handle = registerVarId( new SynchronizeableInt( (int*)&objectListNumber, &list_write, "list", PERMISSION_MASTER_SERVER ) );
112
113  this->health_handle = registerVarId( new SynchronizeableFloat( &this->health, &this->health_write, "health", PERMISSION_MASTER_SERVER ) );
114  this->healthMax_handle = registerVarId( new SynchronizeableFloat( &this->healthMax, &this->healthMax_write, "maxHealth", PERMISSION_MASTER_SERVER ) );
115}
116
117/**
118 *  standard destructor
119*/
120WorldEntity::~WorldEntity ()
121{
122  State::getObjectManager()->toList(this, OM_INIT);
123
124  // Delete the model (unregister it with the ResourceManager)
125  for (unsigned int i = 0; i < this->models.size(); i++)
126    this->setModel(NULL, i);
127
128  // remove the object information file
129  if( this->oiFile)
130    delete this->oiFile;
131  // and clear all monut points
132  this->mountPoints.clear();
133
134  // Delete the obbTree
135  if( this->obbTree)
136    delete this->obbTree;
137
138  if (this->healthWidget)
139    delete this->healthWidget;
140
141  if(this->shieldWidget)
142    delete this->shieldWidget;
143
144  if( this->electronicWidget)
145    delete this->electronicWidget;
146
147  this->unsubscribeReactions();
148}
149
150/**
151 * loads the WorldEntity Specific Parameters.
152 * @param root: the XML-Element to load the Data From
153 */
154void WorldEntity::loadParams(const TiXmlElement* root)
155{
156  // Do the PNode loading stuff
157  PNode::loadParams(root);
158
159  LoadParam(root, "md2texture", this, WorldEntity, loadMD2Texture)
160  .describe("the fileName of the texture, that should be loaded onto this world-entity. (must be relative to the data-dir)")
161  .defaultValues("");
162
163  // Model Loading
164  LoadParam(root, "model", this, WorldEntity, loadModel)
165  .describe("the fileName of the model, that should be loaded onto this world-entity. (must be relative to the data-dir)")
166  .defaultValues("", 1.0f, 0);
167
168  LoadParam(root, "mountpoints", this, WorldEntity, loadMountPoints)
169  .describe("the fileName of the object information file (optional)");
170
171  // Entity Attributes
172  LoadParam(root, "maxHealth", this, WorldEntity, setHealthMax)
173  .describe("The Maximum health that can be loaded onto this entity")
174  .defaultValues(1.0f);
175
176  LoadParam(root, "health", this, WorldEntity, setHealth)
177  .describe("The Health the WorldEntity has at this moment")
178  .defaultValues(1.0f);
179
180  LoadParam(root, "list", this, WorldEntity, toListS);
181
182  LoadParam(root, "drawTrack", this, WorldEntity, drawDebugTrack)
183      .describe("draws the track for debugging purposes");
184 
185  LoadParam(root, "forwardDamageToParent", this, WorldEntity, setForwardDamageToParent);
186 
187  LoadParam(root, "damageable", this, WorldEntity, setDamageable);
188
189  // Track
190  LoadParamXML(root, "Track", this, WorldEntity, addTrack)
191  .describe("creates and adds a track to this WorldEntity");
192}
193
194
195/**
196 * this functions adds a track to this workd entity. This can be usefull, if you like this WE to follow a some waypoints.
197 * here the track is created and further initializing left for the Track itself
198 */
199void WorldEntity::addTrack(const TiXmlElement* root)
200{
201  // The problem we have is most likely here. The track should be constructed WITH the XML-Code
202  this->entityTrack = new Track(root);
203  this->setParent(this->entityTrack->getTrackNode());
204  this->entityTrack->getTrackNode()->setParentMode(PNODE_ALL);
205  /*LOAD_PARAM_START_CYCLE(root, element);
206  {
207    PRINTF(4)("element is: %s\n", element->Value());
208    Factory::fabricate(element);
209  }
210  LOAD_PARAM_END_CYCLE(element);*/
211
212
213}
214
215void WorldEntity::pauseTrack(bool stop)
216{
217     if(this->entityTrack)
218       this->entityTrack->pauseTrack(stop);
219}
220
221
222/**
223 * loads a Model onto a WorldEntity
224 * @param fileName the name of the model to load
225 * @param scaling the Scaling of the model
226 *
227 * FIXME
228 * @todo: separate the obb tree generation from the model
229 */
230void WorldEntity::loadModel(const std::string& fileName, float scaling, unsigned int modelNumber, unsigned int obbTreeDepth)
231{
232  this->modelLODName = fileName;
233  this->scaling = scaling;
234
235  std::string name = fileName;
236
237  if (  name.find( Resources::ResourceManager::getInstance()->mainGlobalPath().name() ) == 0 )
238  {
239    name.erase(Resources::ResourceManager::getInstance()->mainGlobalPath().name().size());
240  }
241
242  this->modelFileName = name;
243
244  if (!fileName.empty())
245  {
246    // search for the special character # in the LoadParam
247    if (fileName.find('#') != std::string::npos)
248    {
249      PRINTF(4)("Found # in %s... searching for LOD's\n", fileName.c_str());
250      std::string lodFile = fileName;
251      unsigned int offset = lodFile.find('#');
252      for (unsigned int i = 0; i < 3; i++)
253      {
254        lodFile[offset] = 48+(int)i;
255        if (Resources::ResourceManager::getInstance()->checkFileInMainPath( lodFile))
256          this->loadModel(lodFile, scaling, i);
257      }
258      return;
259    }
260    if (this->scaling <= 0.0)
261    {
262      PRINTF(1)("YOU GAVE ME A CRAPY SCALE resetting to 1.0\n");
263      this->scaling = 1.0;
264    }
265    /// LOADING AN OBJ FILE
266    if(fileName.find(".obj") != std::string::npos)
267    {
268      PRINTF(4)("fetching OBJ file: %s\n", fileName.c_str());
269      // creating the model and loading it
270      StaticModel* model = new StaticModel();
271      *model = ResourceOBJ(fileName, this->scaling);
272
273      // check if ther is a valid model and load other stuff
274      if (model->getVertexCount() > 0)
275      {
276        this->setModel(model, modelNumber);
277
278        if( modelNumber == 0)
279        {
280          this->buildObbTree(obbTreeDepth);
281        }
282      }
283      else
284        delete model;
285    }
286    /// LOADING AN MD2-model
287    else if(fileName.find(".md2") != std::string::npos)
288    {
289      PRINTF(4)("fetching MD2 file: %s\n", fileName.c_str());
290      Model* m = new MD2Model(fileName, this->md2TextureFileName, this->scaling);
291      //this->setModel((Model*)ResourceManager::getInstance()->load(fileName, MD2, RP_CAMPAIGN), 0);
292      this->setModel(m, 0);
293
294      if( m != NULL)
295        this->buildObbTree(obbTreeDepth);
296    }
297    /// LOADING AN MD3-MODEL.
298    else if(fileName.find(".md3") != std::string::npos)
299    {
300      PRINTF(4)("fetching MD3 file: %s\n", fileName.c_str());
301      //      Model* m = new md3::MD3Model(fileName, this->scaling);
302      //      this->setModel(m, 0);
303
304      //       if( m != NULL)
305      //         this->buildObbTree(obbTreeDepth);
306    }
307  }
308  else
309  {
310    this->setModel(NULL);
311  }
312}
313
314/**
315 * sets a specific Model for the Object.
316 * @param model The Model to set
317 * @param modelNumber the n'th model in the List to get.
318 */
319void WorldEntity::setModel(Model* model, unsigned int modelNumber)
320{
321  if (this->models.size() <= modelNumber)
322    this->models.resize(modelNumber+1, NULL);
323
324  if (this->models[modelNumber] != NULL)
325  {
326    delete this->models[modelNumber];
327  }
328
329  this->models[modelNumber] = model;
330}
331
332
333
334/**
335 * loads the object information file for this model
336 * @param fileName the name of the file
337 */
338void WorldEntity::loadMountPoints(const std::string& fileName)
339{
340  PRINTF(5)("loading the oif File: %s\n", fileName.c_str());
341
342  // now load the object information file
343  this->oiFile = new ObjectInformationFile(fileName);
344
345  // get the model to load
346  Model* model = this->getModel();
347
348  // extract the mount points
349  // Patrick: they get extracted automaticaly now within the model finalization process
350  /*
351
352  if(model != NULL)
353    model->extractMountPoints();
354  else
355  {
356    PRINTF(0)("Worldentity %s has no mount points", (this->getName()).c_str());
357    return;
358  }*/
359
360  // first get all mount points from the model
361  const std::list<mountPointSkeleton> mpList = model->getMountPoints();
362  // for each skeleton create a mounting point world entity
363  std::list<mountPointSkeleton>::const_iterator it = mpList.begin();
364
365  for( ; it != mpList.end(); it++)
366  {
367    // create the mount points world entity
368    MountPoint* mp = new MountPoint( (*it).up, (*it).forward, (*it).center, (*it).name);
369    // parent it to this WE
370    mp->setParent( this);
371    // now add to the right group
372    mp->toList( (OM_LIST)(this->getOMListNumber()+1));
373    // now get the number and add the mount point to the slot
374    std::string nrStr = (*it).name.substr(3, 2);
375    // add the mount point
376    this->addMountPoint(atoi(nrStr.c_str()), mp);
377
378    // now fill the mount point
379    mp->initMountPoint( this->oiFile->getMountPointDescription());
380  }
381
382}
383
384
385/**
386 * builds the obb-tree
387 * @param depth the depth to calculate
388 */
389bool WorldEntity::buildObbTree(int depth)
390{
391  if( this->obbTree != NULL)
392  {
393    delete this->obbTree;
394    this->obbTree = NULL;
395  }
396
397  if (this->models[0] != NULL)
398    this->obbTree = new OBBTree(depth, models[0]->getModelInfo(), this);
399  else
400  {
401    PRINTF(1)("could not create obb-tree, because no model was loaded yet\n");
402    this->obbTree = NULL;
403    return false;
404  }
405
406
407  // create the axis aligned bounding box
408  if( this->aabbNode != NULL)
409  {
410    delete this->aabbNode;
411    this->aabbNode = NULL;
412  }
413
414  if( this->models[0] != NULL)
415  {
416    this->aabbNode = new AABBTreeNode();
417    this->aabbNode->spawnBVTree(this->models[0]);
418  }
419  else
420  {
421    PRINTF(1)("could not create aabb bounding box, because no model was loaded yet\n");
422    this->aabbNode = NULL;
423    return false;
424  }
425  return true;
426}
427
428
429/**
430 * adds a mount point to the end of the list
431 * @param mountPoint point to be added
432 */
433void WorldEntity::addMountPoint(MountPoint* mountPoint)
434{
435  // add the mount point at the last position
436//   this->mountPointMap[](mountPoint);
437  assert(false);
438}
439
440/**
441 * adds a mount point to a world entity
442 * @param mountPoint point to be added
443 */
444void WorldEntity::addMountPoint(int slot, MountPoint* mountPoint)
445{
446  if( this->mountPointMap.find(slot) != this->mountPointMap.end())
447  {
448    PRINTF(2)("adding a mount point to a slot, that already is occupied! ignoring - maybe some object did not get connected well (object: %s)\n", this->getClassCName());
449  }
450
451  // just connect the mount point
452  this->mountPointMap[slot] = mountPoint;
453}
454
455
456/**
457 * mounts a world entity on a specified mount point (~socket)
458 * @param entity entity to be connected
459 */
460void WorldEntity::mount(int slot, WorldEntity* entity)
461{
462  if( this->mountPointMap.find(slot) != this->mountPointMap.end())
463  {
464    PRINTF(0)("you tried to add an entity to a mount point that doesn't exist (slot %i)\n", slot);
465    return;
466  }
467
468  // mount the entity
469  this->mountPoints[slot]->mount(entity);
470}
471
472
473/**
474 * removes a mount point from a specified mount point
475 * @param mountPoint entity to be unconnected
476 */
477void WorldEntity::unmount(int slot)
478{
479  if( this->mountPoints[slot] == NULL)
480  {
481    PRINTF(0)("you tried to remove an entity from a mount point that doesn't exist (slot %i)\n", slot);
482    return;
483  }
484
485  // unmount the entity
486  this->mountPoints[slot]->unmount();
487}
488
489
490/**
491 * subscribes this world entity to a collision reaction
492 *  @param type the type of reaction to subscribe to
493 *  @param target1 a filter target (classID)
494 */
495void WorldEntity::subscribeReaction(CoRe::CREngine::ReactionType type, const ClassID& target1)
496{
497  this->_collisionFilter.subscribeReaction(type, target1);
498}
499
500
501/**
502 * subscribes this world entity to a collision reaction
503 *  @param type the type of reaction to subscribe to
504 *  @param target1 a filter target (classID)
505 */
506void WorldEntity::subscribeReaction(CoRe::CREngine::ReactionType type, const ClassID& target1, const ClassID& target2)
507{
508  this->_collisionFilter.subscribeReaction(type, target1, target2);
509}
510
511
512/**
513 * subscribes this world entity to a collision reaction
514 *  @param type the type of reaction to subscribe to
515 *  @param target1 a filter target (classID)
516 */
517void WorldEntity::subscribeReaction(CoRe::CREngine::ReactionType type, const ClassID& target1, const ClassID& target2, const ClassID& target3)
518{
519  this->_collisionFilter.subscribeReaction(type, target1, target2, target3);
520}
521
522
523/**
524 * unsubscribes a specific reaction from the worldentity
525 *  @param type the reaction to unsubscribe
526 */
527void WorldEntity::unsubscribeReaction(CoRe::CREngine::ReactionType type)
528{
529  this->_collisionFilter.unsubscribeReaction(type);
530}
531
532
533/**
534 * unsubscribes all collision reactions
535 */
536void WorldEntity::unsubscribeReactions()
537{
538  this->_collisionFilter.unsubscribeReactions();
539}
540
541
542/**
543 * @brief moves this entity to the List OM_List
544 * @param list the list to set this Entity to.
545 *
546 * this is the same as a call to State::getObjectManager()->toList(entity , list);
547 * directly, but with an easier interface.
548 *
549 * @todo inline this (peut etre)
550 */
551void WorldEntity::toList(OM_LIST list)
552{
553  State::getObjectManager()->toList(this, list);
554}
555
556void WorldEntity::toListS(const std::string& listName)
557{
558  OM_LIST id = ObjectManager::StringToOMList(listName);
559  if (id != OM_NULL)
560    this->toList(id);
561  else
562    PRINTF(2)("List %s not found\n", listName.c_str());
563}
564
565
566void WorldEntity::toReflectionList()
567{
568  State::getObjectManager()->toReflectionList( this );
569}
570
571void removeFromReflectionList()
572{
573  /// TODO
574  ///  State::getObject
575}
576
577/**
578 * sets the character attributes of a worldentity
579 * @param character attributes
580 *
581 * these attributes don't have to be set, only use them, if you need them
582*/
583//void WorldEntity::setCharacterAttributes(CharacterAttributes* charAttr)
584//{}
585
586
587/**
588 *  this function is called, when two entities collide
589 * @param entity: the world entity with whom it collides
590 *
591 * Implement behaviour like damage application or other miscellaneous collision stuff in this function
592 */
593void WorldEntity::collidesWith(WorldEntity* entity, const Vector& location)
594{
595  /**
596   * THIS IS A DEFAULT COLLISION-Effect.
597   * IF YOU WANT TO CREATE A SPECIFIC COLLISION ON EACH OBJECT
598   * USE::
599   * if (entity->isA(CL_WHAT_YOU_ARE_LOOKING_FOR)) { printf "dothings"; };
600   *
601   * You can always define a default Action.... don't be affraid just test it :)
602   */
603  //  PRINTF(3)("collision %s vs %s @ (%f,%f,%f)\n", this->getClassCName(), entity->getClassCName(), location.x, location.y, location.z);
604}
605
606
607/**
608 *  this function is called, when two entities collide
609 * @param entity: the world entity with whom it collides
610 *
611 * Implement behaviour like damage application or other miscellaneous collision stuff in this function
612 */
613void WorldEntity::collidesWithGround(const Vector& location)
614{
615  PRINTF(0)("BSP_GROUND: %s collides \n", this->getClassCName() );
616}
617
618void WorldEntity::collidesWithGround(const Vector& feet, const Vector& ray_1, const Vector& ray_2)
619{
620
621  // PRINTF(0)("BSP_GROUND: Player collides \n", this->getClassCName() );
622
623  Vector v = this->getAbsDirX();
624  v.x *= 10.1;
625  v.y *= 10.1;
626  v.z *= 10.1;
627  Vector u = Vector(0.0,-20.0,0.0);
628
629
630  if(!(this->getAbsCoor().x == ray_2.x && this->getAbsCoor().y == ray_2.y && this->getAbsCoor().z == ray_2.z) )
631  {
632
633    this->setAbsCoor(ray_2 - v);
634
635  }
636  else
637  {
638    if(ray_1.x == this->getAbsCoor().x + v.x && ray_1.y == this->getAbsCoor().y + v.y + 0.1 && ray_1.z ==this->getAbsCoor().z + v.z)
639    {
640      this->setAbsCoor(feet -u );
641    }
642
643    this->setAbsCoor(ray_2 - v);
644
645  }
646
647
648}
649
650/**
651 *  this is called immediately after the Entity has been constructed, initialized and then Spawned into the World
652 *
653 */
654void WorldEntity::postSpawn ()
655{}
656
657
658/**
659 *  this method is called by the world if the WorldEntity leaves the game
660 */
661void WorldEntity::leaveWorld ()
662{}
663
664
665/**
666 * resets the WorldEntity to its initial values. eg. used for multiplayer games: respawning
667 */
668void WorldEntity::reset()
669{
670  this->setHealth( this->getHealthMax() );
671}
672
673/**
674 *  this method is called every frame
675 * @param time: the time in seconds that has passed since the last tick
676 *
677 * Handle all stuff that should update with time inside this method (movement, animation, etc.)
678*/
679void WorldEntity::tick(float time)
680{}
681
682
683/**
684 *  the entity is drawn onto the screen with this function
685 *
686 * This is a central function of an entity: call it to let the entity painted to the screen.
687 * Just override this function with whatever you want to be drawn.
688*/
689void WorldEntity::draw() const
690{
691  //PRINTF(0)("(%s::%s)\n", this->getClassCName(), this->getName());
692  //  assert(!unlikely(this->models.empty()));
693  {
694    glMatrixMode(GL_MODELVIEW);
695    glPushMatrix();
696
697    /* translate */
698    glTranslatef (this->getAbsCoor ().x,
699                  this->getAbsCoor ().y,
700                  this->getAbsCoor ().z);
701    Vector tmpRot = this->getAbsDir().getSpacialAxis();
702    glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
703
704
705    // This Draws the LOD's
706    float cameraDistance = State::getCamera()->distance(this);
707    if (cameraDistance > 30 && this->models.size() >= 3 && this->models[2] != NULL)
708    {
709      this->models[2]->draw();
710    }
711    else if (cameraDistance > 10 && this->models.size() >= 2 && this->models[1] != NULL)
712    {
713      this->models[1]->draw();
714    }
715    else if (this->models.size() >= 1 && this->models[0] != NULL)
716    {
717      this->models[0]->draw();
718    }
719
720    //if (this->entityTrack)
721    //this->entityTrack->drawGraph(0.02);
722
723    //     if( this->aabbNode != NULL)
724    //       this->aabbNode->drawBV(0, DRAW_BV_POLYGON, Vector(1, 0.6, 0.2), true);
725
726    glPopMatrix();
727  }
728}
729
730
731/**
732 *  the entity is drawn onto the screen with this function
733 *
734 * This is a central function of an entity: call it to let the entity painted to the screen.
735 * Just override this function with whatever you want to be drawn.
736*/
737void WorldEntity::draw(const Model* model) const
738{
739  if(bVisible)
740  {
741  glMatrixMode(GL_MODELVIEW);
742  glPushMatrix();
743
744  /* translate */
745  glTranslatef (this->getAbsCoor ().x,
746                this->getAbsCoor ().y,
747                this->getAbsCoor ().z);
748  Vector tmpRot = this->getAbsDir().getSpacialAxis();
749  glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
750
751
752  // This Draws the LOD's
753  if( model != NULL)
754    model->draw();
755
756  glPopMatrix();
757  }
758}
759
760
761/**
762 * @param health the Health to add.
763 * @returns the health left (this->healthMax - health+this->health)
764 */
765float WorldEntity::increaseHealth(float health)
766{
767  this->health += health;
768  if (this->health > this->healthMax)
769  {
770    float retHealth = this->healthMax - this->health;
771    this->health = this->healthMax;
772    this->updateHealthWidget();
773    return retHealth;
774  }
775  this->updateHealthWidget();
776  return 0.0;
777}
778
779/**
780 * @param health the Health to be removed
781 * @returns 0.0 or the rest, that was not substracted (bellow 0.0)
782 */
783float WorldEntity::decreaseHealth(float health)
784{
785  this->health -= health;
786
787  if (this->health < 0)
788  {
789    float retHealth = -this->health;
790    this->health = 0.0f;
791    this->updateHealthWidget();
792    return retHealth;
793  }
794  this->updateHealthWidget();
795  return 0.0;
796}
797
798
799/**
800 * @param maxHealth the maximal health that can be loaded onto the entity.
801 */
802void WorldEntity::setHealthMax(float healthMax)
803{
804  this->healthMax = healthMax;
805  if (this->health > this->healthMax)
806  {
807    PRINTF(3)("new maxHealth is bigger as the old health. Did you really intend to do this for (%s::%s)\n", this->getClassCName(), this->getCName());
808    this->health = this->healthMax;
809  }
810  this->updateHealthWidget();
811}
812
813
814
815/**
816 * @param shiled the Shieldstength to add.
817 * @returns the shield left (this->shieldMax - shiled + this->shield)
818 */
819float WorldEntity::increaseShield(float shiled)
820{
821  this->shield += shield;
822  if (this->shield > this->shieldTH * this->shieldMax) { this->bShieldActive = true; }
823  if (this->shield > this->shieldMax)
824  {
825    float retShield = this->shieldMax - this->shield;
826    this->shield = this->shieldMax;
827//     this->updateShieldWidget();
828    return retShield;
829  }
830//   this->updateShieldWidget();
831  return 0.0;
832}
833
834/**
835 * @param shield the Shieldstrength to be removed
836 * @returns 0.0 or the rest, if the shield drops belew 0.0
837 */
838float WorldEntity::decreaseShield(float shield)
839{
840  this->shield -= shield;
841
842  if (this->shield <= 0)
843  {
844    float retShield = -this->shield;
845//     this->updateShieldWidget();
846    this->bShieldActive = false;
847    return retShield;
848  }
849//   this->updateShieldWidget();
850  return 0.0;
851}
852
853
854
855/**
856 * @brief creates the HealthWidget
857 *
858 * since not all entities need an HealthWidget, it is only created on request.
859 */
860void WorldEntity::createHealthWidget()
861{
862  if (this->healthWidget == NULL)
863  {
864    this->healthWidget = new OrxGui::GLGuiEnergyWidgetVertical();
865    //this->healthWidget->setDisplayedName("Health");
866    //this->healthWidget->setSize2D(100,20);
867    //this->healthWidget->setAbsCoor2D(100,200);
868
869    this->updateHealthWidget();
870  }
871  else
872    PRINTF(3)("Allready created the HealthWidget for %s::%s\n", this->getClassCName(), this->getCName());
873}
874
875
876/**
877 * @brief creates the ImplantWidget
878 *
879 * since not all entities need an ImpantWidget, it is only created on request.
880 */
881void WorldEntity::createImplantWidget()
882{
883  if (this->implantWidget == NULL)
884  {
885    this->implantWidget = new OrxGui::GLGuiEnergyWidgetVertical();
886    //this->impantWidget->setDisplayedName("Implant");
887    //this->impantWidget->setSize2D(100,20);
888    //this->impantWidget->setAbsCoor2D(100,200);
889
890    //this->updateImplantWidget();
891  }
892  else
893    PRINTF(3)("Allready created the ImlpantWidget for %s::%s\n", this->getClassCName(), this->getCName());
894}
895
896
897
898void WorldEntity::createShieldWidget()
899{
900  if (this->shieldWidget == NULL)
901  {
902    this->shieldWidget = new OrxGui::GLGuiEnergyWidgetVertical();
903    this->updateShieldWidget();
904  }
905  else
906    PRINTF(3)("Allready created the ShieldWidget for %s::%s\n", this->getClassCName(), this->getCName());
907}
908
909void WorldEntity::createElectronicWidget()
910{
911  if (this->electronicWidget == NULL)
912  {
913    this->electronicWidget = new OrxGui::GLGuiEnergyWidgetVertical();
914    this->updateElectronicWidget();
915  }
916  else
917    PRINTF(3)("Allready created the ElectronicWidget for %s::%s\n", this->getClassCName(), this->getCName());
918}
919
920
921
922void WorldEntity::increaseHealthMax(float increaseHealth)
923{
924  this->healthMax += increaseHealth;
925  this->updateHealthWidget();
926}
927
928
929OrxGui::GLGuiWidget* WorldEntity::getHealthWidget()
930{
931  if ( this->healthWidget == NULL)
932    this->createHealthWidget();
933  return this->healthWidget;
934}
935
936
937
938OrxGui::GLGuiWidget* WorldEntity::getImplantWidget()
939{
940  this->createImplantWidget();
941  return this->implantWidget;
942}
943
944
945
946OrxGui::GLGuiWidget* WorldEntity::getShieldWidget()
947{
948  if ( this->shieldWidget == NULL)
949    this->createShieldWidget();
950  return this->shieldWidget;
951}
952
953
954OrxGui::GLGuiWidget* WorldEntity::getElectronicWidget()
955{
956  if ( this->electronicWidget == NULL)
957    this->createElectronicWidget();
958  return this->electronicWidget;
959}
960
961
962
963
964/**
965 * @param visibility shows or hides the health-bar
966 * (creates the widget if needed)
967 */
968void WorldEntity::setHealthWidgetVisibility(bool visibility)
969{
970  if (visibility)
971  {
972    if (this->healthWidget != NULL)
973      this->healthWidget->show();
974    else
975    {
976      this->createHealthWidget();
977      this->updateHealthWidget();
978      this->healthWidget->show();
979    }
980  }
981  else if (this->healthWidget != NULL)
982    this->healthWidget->hide();
983}
984
985
986/**
987 * hit the world entity with
988 *  @param damage damage to be dealt
989 */
990void WorldEntity::hit(float damage, WorldEntity* killer)
991{
992  PRINTF(0)("TESTS: %i %i %i\n", (forwardDamageToParent), (this->getParent() != NullParent::getNullParent()), (this->getParent()->isA( WorldEntity::staticClassID() )));
993  if ( forwardDamageToParent && this->getParent() != NullParent::getNullParent() && this->getParent()->isA( WorldEntity::staticClassID() ) )
994  {
995    WorldEntity* pa = dynamic_cast<WorldEntity*>(this->getParent());
996    pa->hit( damage, killer );
997    return;
998  }
999 
1000  bool dead = this->getHealth()<=0;
1001 
1002  if ( !damageable )
1003    return;
1004 
1005  this->decreaseHealth(damage);
1006
1007  PRINTF(0)("Hit me: %s::%s now only %f/%f health\n", this->getClassCName(), this->getCName(), this->getHealth(), this->getHealthMax());
1008
1009  if( this->getHealth() > 0)
1010  {
1011    // any small explosion animaitions
1012  }
1013  else
1014  {
1015    if ( !dead )
1016      this->destroy( killer );
1017  }
1018}
1019
1020
1021/**
1022 * destoys the world entity
1023 */
1024void WorldEntity::destroy(WorldEntity* killer)
1025{
1026  this->toList(OM_DEAD);
1027}
1028
1029
1030/**
1031 * @brief updates the HealthWidget
1032 */
1033void WorldEntity::updateHealthWidget()
1034{
1035  if (this->healthWidget != NULL)
1036  {
1037    this->healthWidget->setMaximum(this->healthMax);
1038    this->healthWidget->setValue(this->health);
1039  }
1040}
1041
1042/**
1043 * @brief updates the Electronic Widget
1044 */
1045//!< xferred from spaceship
1046void WorldEntity::updateElectronicWidget(){
1047  if (this->electronicWidget != NULL)
1048  { //if it exists already: update it
1049     this->electronicWidget->setMaximum(this->electronicMax);
1050     this->electronicWidget->setValue(this->electronic);
1051  }
1052  else
1053  { //create the widget
1054    this->electronicWidget = new OrxGui::GLGuiEnergyWidgetVertical();
1055    this->electronicWidget->getBarWidget()->setChangedValueColor(Color(1,0,0,1));
1056    //this->electronicWidget->setDisplayedName("Electronics:");
1057    //this->electronicWidget->setSize2D(100,20);
1058    //this->electronicWidget->setAbsCoor2D(150,200);
1059    this->updateElectronicWidget();
1060//     if ( dynamic_cast<SpaceShip*>(this)->hasPlayer() )
1061//       State::getPlayer()->hud().setEnergyWidget(this->electronicWidget);
1062  }
1063}
1064
1065/**
1066 * @brief updates the ShieldWidget
1067 */
1068//!< xferred from spaceship
1069void WorldEntity::updateShieldWidget()
1070{
1071  if (this->shieldWidget != NULL)
1072  {
1073    this->shieldWidget->setMaximum(this->shieldMax);
1074    this->shieldWidget->setValue(this->shield);;
1075  }
1076  else
1077  {
1078    this->shieldWidget = new OrxGui::GLGuiEnergyWidgetVertical();
1079    this->shieldWidget->getBarWidget()->setChangedValueColor(Color(1,0,0,1));
1080    //this->shieldWidget->setDisplayedName("Shield:");
1081    //his->shieldWidget->setSize2D(100,20);
1082    //this->shieldWidget->setAbsCoor2D(200,200);
1083    this->updateShieldWidget();
1084//     if (dynamic_cast<SpaceShip*>(this)->hasPlayer())
1085//       State::getPlayer()->hud().setShieldWidget(this->shieldWidget);
1086  }
1087}
1088
1089
1090
1091/**
1092 * DEBUG-DRAW OF THE BV-Tree.
1093 * @param depth What depth to draw
1094 * @param drawMode the mode to draw this entity under
1095 */
1096void WorldEntity::drawBVTree(int depth, int drawMode) const
1097{
1098  glMatrixMode(GL_MODELVIEW);
1099  glPushMatrix();
1100  /* translate */
1101  glTranslatef (this->getAbsCoor ().x,
1102                this->getAbsCoor ().y,
1103                this->getAbsCoor ().z);
1104  /* rotate */
1105  Vector tmpRot = this->getAbsDir().getSpacialAxis();
1106  glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
1107
1108
1109  if (this->obbTree)
1110    this->obbTree->drawBV(depth, drawMode);
1111
1112
1113  glPopMatrix();
1114}
1115
1116
1117
1118/**
1119 * draw the mounting points
1120 */
1121void WorldEntity::debugDrawMountPoints() const
1122{
1123
1124  std::vector<MountPoint*>::const_iterator it = this->mountPoints.begin();
1125  for( ; it < this->mountPoints.end(); it++)
1126  {
1127    if( (*it) != NULL)
1128    {
1129      (*it)->debugDraw();
1130    }
1131  }
1132}
1133
1134
1135/**
1136 * Debug the WorldEntity
1137 */
1138void WorldEntity::debugEntity() const
1139{
1140  PRINT(0)("WorldEntity %s::%s  (DEBUG)\n", this->getClassCName(), this->getCName());
1141  this->debugNode();
1142  PRINT(0)("List: %s ; ModelCount %d - ", ObjectManager::OMListToString(this->objectListNumber).c_str(), this->models.size());
1143  for (unsigned int i = 0; i < this->models.size(); i++)
1144  {
1145    if (models[i] != NULL)
1146      PRINT(0)(" : %d:%s", i, this->models[i]->getCName());
1147  }
1148  PRINT(0)("\n");
1149
1150}
1151
1152
1153/**
1154 * handler for changes on registred vars
1155 * @param id id's which changed
1156 */
1157void WorldEntity::varChangeHandler( std::list< int > & id )
1158{
1159  if ( std::find( id.begin(), id.end(), modelFileName_handle ) != id.end() ||
1160       std::find( id.begin(), id.end(), scaling_handle ) != id.end()
1161     )
1162  {
1163    loadModel( modelFileName, scaling );
1164  }
1165
1166  if ( std::find( id.begin(), id.end(), list_handle ) != id.end() )
1167  {
1168    this->toList( (OM_LIST)list_write );
1169  }
1170
1171  if ( std::find( id.begin(), id.end(), health_handle ) != id.end() )
1172  {
1173    this->setHealth( health_write );
1174  }
1175
1176  if ( std::find( id.begin(), id.end(), healthMax_handle ) != id.end() )
1177  {
1178    this->setHealthMax( healthMax_write );
1179  }
1180
1181  PNode::varChangeHandler( id );
1182}
1183
1184
1185void WorldEntity::regen(float time){
1186  static float tmp;
1187  increaseHealth(time * this->healthRegen);
1188  increaseShield(time * this->shieldRegen);
1189//   updateHealthWidget();
1190//   updateShieldWidget();
1191
1192  //this->setHealth( this->shieldCur);      // FIXME currently just to test share system
1193
1194  if (this->electronic != this->electronicMax || this->electronicRegen != 0){
1195    tmp = this->electronic + this->electronicRegen * time;
1196    if ( tmp > electronicMax)
1197      this->electronic = this->electronicMax;
1198    else
1199      this->electronic = tmp;
1200
1201    updateElectronicWidget();
1202  }
1203
1204}
Note: See TracBrowser for help on using the repository browser.