Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/cr/src/world_entities/world_entity.cc @ 7944

Last change on this file since 7944 was 7944, checked in by patrick, 18 years ago

cr: collision registration work

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