Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 10702 was 10698, checked in by snellen, 17 years ago

merged adm, hud, vs-enhancements : beni's responsible for this commit. blame him!

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