Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/cd/src/world_entities/world_entity.cc @ 7365

Last change on this file since 7365 was 7365, checked in by bensch, 18 years ago

orxonox/branches/cd: merged the new collision-detection back.
merged and collissions resolved.

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