Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/world_entities/world_entity.cc @ 8142

Last change on this file since 8142 was 8037, checked in by bensch, 19 years ago

trunk: merged the water back
merged with command
svn merge -r7798:HEAD https://svn.orxonox.net/orxonox/branches/water .

conflicts are all resolved

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