Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 10763 was 10763, checked in by nicolasc, 17 years ago

moved loadShield (XML), some minor cleanup

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