Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 7936 was 7933, checked in by patrick, 19 years ago

cr: more registration framework

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