Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

huge diff
cleaned the individual weapons, moved stuff to weapon.{cc,h}
and some minor fixes which popped up then and when

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