Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 6883 was 6815, checked in by bensch, 19 years ago

orxonox/trunk: merged branches/network back to the trunk.
merged with command:
svn merge https://svn.orxonox.net/orxonox/branches/network . -r6774:HEAD

no conflicts…
thats what i call orthogonal work

File size: 15.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 "resource_manager.h"
25#include "load_param.h"
26#include "vector.h"
27#include "obb_tree.h"
28
29#include "glgui_bar.h"
30
31#include "state.h"
32
33using namespace std;
34
35SHELL_COMMAND(model, WorldEntity, loadModel)
36->describe("sets the Model of the WorldEntity")
37->defaultValues(2, "models/ships/fighter.obj", 1.0);
38
39SHELL_COMMAND(debugEntity, WorldEntity, debugWE);
40
41/**
42 *  Loads the WordEntity-specific Part of any derived Class
43 *
44 * @param root: Normally NULL, as the Derived Entities define a loadParams Function themeselves,
45 *              that can calls WorldEntities loadParams for itself.
46 */
47WorldEntity::WorldEntity()
48    : Synchronizeable()
49{
50  this->setClassID(CL_WORLD_ENTITY, "WorldEntity");
51
52  this->obbTree = NULL;
53  this->healthWidget = NULL;
54  this->healthMax = 1.0f;
55  this->health = 1.0f;
56  this->scaling = 1.0f;
57
58  /* OSOLETE */
59  this->bVisible = true;
60  this->bCollide = true;
61
62  this->md2TextureFileName = NULL;
63
64  this->objectListNumber = OM_INIT;
65  this->objectListIterator = NULL;
66
67  this->toList(OM_NULL);
68}
69
70/**
71 *  standard destructor
72*/
73WorldEntity::~WorldEntity ()
74{
75  // Delete the obbTree
76  if( this->obbTree != NULL)
77    delete this->obbTree;
78
79  if (this->healthWidget != NULL)
80    delete this->healthWidget;
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  State::getObjectManager()->toList(this, OM_INIT);
87}
88
89/**
90 * loads the WorldEntity Specific Parameters.
91 * @param root: the XML-Element to load the Data From
92 */
93void WorldEntity::loadParams(const TiXmlElement* root)
94{
95  // Do the PNode loading stuff
96  PNode::loadParams(root);
97
98  LoadParam(root, "md2texture", this, WorldEntity, loadMD2Texture)
99  .describe("the fileName of the texture, that should be loaded onto this world-entity. (must be relative to the data-dir)")
100  .defaultValues(1, NULL);
101
102  // Model Loading
103  LoadParam(root, "model", this, WorldEntity, loadModel)
104  .describe("the fileName of the model, that should be loaded onto this world-entity. (must be relative to the data-dir)")
105  .defaultValues(3, NULL, 1.0f, 0);
106
107  LoadParam(root, "maxHealth", this, WorldEntity, setHealthMax)
108  .describe("The Maximum health that can be loaded onto this entity")
109  .defaultValues(1, 1.0f);
110
111  LoadParam(root, "health", this, WorldEntity, setHealth)
112  .describe("The Health the WorldEntity has at this moment")
113  .defaultValues(1, 1.0f);
114}
115
116
117/**
118 * loads a Model onto a WorldEntity
119 * @param fileName the name of the model to load
120 * @param scaling the Scaling of the model
121 *
122 * @todo fix this, so it only has one loadModel-Function.
123*/
124void WorldEntity::loadModel(const char* fileName, float scaling, unsigned int modelNumber)
125{
126  this->modelLODName = fileName;
127  this->scaling = scaling;
128  if ( fileName != NULL && strcmp(fileName, "") )
129  {
130    // search for the special character # in the LoadParam
131    if (strchr(fileName, '#') != NULL)
132    {
133      PRINTF(4)("Found # in %s... searching for LOD's\n", fileName);
134      char* lodFile = new char[strlen(fileName)+1];
135      strcpy(lodFile, fileName);
136      char* depth = strchr(lodFile, '#');
137      for (unsigned int i = 0; i < 3; i++)
138      {
139        *depth = 48+(int)i;
140        if (ResourceManager::isInDataDir(lodFile))
141          this->loadModel(lodFile, scaling, i);
142      }
143      return;
144    }
145    if (this->scaling <= 0.0)
146    {
147      this->scaling = 1.0;
148      PRINTF(1)("YOU GAVE ME A CRAPY SCALE resetting to 1\n");
149    }
150    if(strstr(fileName, ".obj"))
151    {
152      PRINTF(4)("fetching OBJ file: %s\n", fileName);
153      if (this->scaling == 1.0)
154        this->setModel((Model*)ResourceManager::getInstance()->load(fileName, OBJ, RP_CAMPAIGN), modelNumber);
155      else
156        this->setModel((Model*)ResourceManager::getInstance()->load(fileName, OBJ, RP_CAMPAIGN, this->scaling), modelNumber);
157
158      if( modelNumber == 0)
159        this->buildObbTree(4);
160    }
161    else if(strstr(fileName, ".md2"))
162    {
163      PRINTF(4)("fetching MD2 file: %s\n", fileName);
164      Model* m = new MD2Model(fileName, this->md2TextureFileName);
165      //this->setModel((Model*)ResourceManager::getInstance()->load(fileName, MD2, RP_CAMPAIGN), 0);
166      this->setModel(m, 0);
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(this->models[modelNumber]);
188    //     if (resource != NULL)
189    ResourceManager::getInstance()->unload(resource, RP_LEVEL);
190  }
191  else
192    delete this->models[modelNumber];
193
194  this->models[modelNumber] = model;
195
196
197  //   if (this->model != NULL)
198  //     this->buildObbTree(4);
199}
200
201
202/**
203 * builds the obb-tree
204 * @param depth the depth to calculate
205 */
206bool WorldEntity::buildObbTree(unsigned int depth)
207{
208  if (this->obbTree)
209    delete this->obbTree;
210
211  if (this->models[0] != NULL)
212  {
213    PRINTF(4)("creating obb tree\n");
214
215
216    this->obbTree = new OBBTree(depth, (sVec3D*)this->models[0]->getVertexArray(), this->models[0]->getVertexCount());
217    return true;
218  }
219  else
220  {
221    PRINTF(2)("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 valid gamespace
283 *
284 * For free entities this means it left the Track boundaries. With bound entities it means its Location adresses a
285 * place that is not in the world anymore. In both cases you might have to take extreme measures (a.k.a. call destroy).
286 *
287 * NOT YET IMPLEMENTED
288 */
289void WorldEntity::leftWorld ()
290{}
291
292
293/**
294 *  this method is called every frame
295 * @param time: the time in seconds that has passed since the last tick
296 *
297 * Handle all stuff that should update with time inside this method (movement, animation, etc.)
298*/
299void WorldEntity::tick(float time)
300{}
301
302
303/**
304 *  the entity is drawn onto the screen with this function
305 *
306 * This is a central function of an entity: call it to let the entity painted to the screen.
307 * Just override this function with whatever you want to be drawn.
308*/
309void WorldEntity::draw() const
310{
311  //PRINTF(0)("(%s::%s)\n", this->getClassName(), this->getName());
312  //  assert(!unlikely(this->models.empty()));
313  {
314    glMatrixMode(GL_MODELVIEW);
315    glPushMatrix();
316
317    /* translate */
318    glTranslatef (this->getAbsCoor ().x,
319                  this->getAbsCoor ().y,
320                  this->getAbsCoor ().z);
321    Vector tmpRot = this->getAbsDir().getSpacialAxis();
322    glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
323
324
325    // This Draws the LOD's
326    float cameraDistance = (State::getCamera()->getAbsCoor() - this->getAbsCoor()).len();
327    if (cameraDistance > 30 && this->models.size() >= 3 && this->models[2] != NULL)
328    {
329      this->models[2]->draw();
330    }
331    else if (cameraDistance > 10 && this->models.size() >= 2 && this->models[1] != NULL)
332    {
333      this->models[1]->draw();
334    }
335    else if (this->models.size() >= 1 && this->models[0] != NULL)
336    {
337      this->models[0]->draw();
338    }
339    glPopMatrix();
340  }
341}
342
343/**
344 * @param health the Health to add.
345 * @returns the health left (this->healthMax - health+this->health)
346 */
347float WorldEntity::increaseHealth(float health)
348{
349  this->health += health;
350  if (this->health > this->healthMax)
351  {
352    float retHealth = this->healthMax - this->health;
353    this->health = this->healthMax;
354    this->updateHealthWidget();
355    return retHealth;
356  }
357  this->updateHealthWidget();
358  return 0.0;
359}
360
361/**
362 * @param health the Health to be removed
363 * @returns 0.0 or the rest, that was not substracted (bellow 0.0)
364 */
365float WorldEntity::decreaseHealth(float health)
366{
367  this->health -= health;
368
369  if (this->health < 0)
370  {
371    float retHealth = -this->health;
372    this->health = 0.0f;
373    this->updateHealthWidget();
374    return retHealth;
375  }
376  this->updateHealthWidget();
377  return 0.0;
378
379}
380
381/**
382 * @param maxHealth the maximal health that can be loaded onto the entity.
383 */
384void WorldEntity::setHealthMax(float healthMax)
385{
386  this->healthMax = healthMax;
387  if (this->health > this->healthMax)
388  {
389    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());
390    this->health = this->healthMax;
391  }
392  this->updateHealthWidget();
393}
394
395/**
396 * @brief creates the HealthWidget
397 *
398 * since not all entities need an HealthWidget, it is only created on request.
399 */
400void WorldEntity::createHealthWidget()
401{
402  if (this->healthWidget == NULL)
403  {
404    this->healthWidget = new GLGuiBar();
405    this->healthWidget->setSize2D(30,400);
406    this->healthWidget->setAbsCoor2D(10,100);
407
408    this->updateHealthWidget();
409  }
410  else
411    PRINTF(3)("Allready created the HealthWidget for %s::%s\n", this->getClassName(), this->getName());
412}
413
414void WorldEntity::increaseHealthMax(float increaseHealth)
415{
416  this->healthMax += increaseHealth;
417  this->updateHealthWidget();
418}
419
420
421GLGuiWidget* WorldEntity::getHealthWidget()
422{
423  this->createHealthWidget();
424  return this->healthWidget;
425}
426
427/**
428 * @param visibility shows or hides the health-bar
429 * (creates the widget if needed)
430 */
431void WorldEntity::setHealthWidgetVisibilit(bool visibility)
432{
433    if (visibility)
434    {
435      if (this->healthWidget != NULL)
436        this->healthWidget->show();
437      else
438      {
439        this->createHealthWidget();
440        this->updateHealthWidget();
441        this->healthWidget->show();
442      }
443    }
444    else if (this->healthWidget != NULL)
445      this->healthWidget->hide();
446}
447
448/**
449 * @brief updates the HealthWidget
450 */
451void WorldEntity::updateHealthWidget()
452{
453  if (this->healthWidget != NULL)
454  {
455    this->healthWidget->setMaximum(this->healthMax);
456    this->healthWidget->setValue(this->health);
457  }
458}
459
460
461/**
462 * DEBUG-DRAW OF THE BV-Tree.
463 * @param depth What depth to draw
464 * @param drawMode the mode to draw this entity under
465 */
466void WorldEntity::drawBVTree(unsigned int depth, int drawMode) const
467{
468  glMatrixMode(GL_MODELVIEW);
469  glPushMatrix();
470  /* translate */
471  glTranslatef (this->getAbsCoor ().x,
472                this->getAbsCoor ().y,
473                this->getAbsCoor ().z);
474  /* rotate */
475  Vector tmpRot = this->getAbsDir().getSpacialAxis();
476  glRotatef (this->getAbsDir().getSpacialAxisAngle(), tmpRot.x, tmpRot.y, tmpRot.z );
477
478  if (this->obbTree)
479    this->obbTree->drawBV(depth, drawMode);
480  glPopMatrix();
481}
482
483
484/**
485 * Debug the WorldEntity
486 */
487void WorldEntity::debugEntity() const
488{
489  PRINT(0)("WorldEntity %s::%s  (DEBUG)\n", this->getClassName(), this->getName());
490  this->debugNode();
491  PRINT(0)("List: %s ; ModelCount %d - ", ObjectManager::OMListToString(this->objectListNumber) , this->models.size());
492  for (unsigned int i = 0; i < this->models.size(); i++)
493  {
494    if (models[i] != NULL)
495      PRINT(0)(" : %d:%s", i, this->models[i]->getName());
496  }
497  PRINT(0)("\n");
498
499}
500
501
502
503
504/********************************************************************************************
505 NETWORK STUFF
506 ********************************************************************************************/
507
508
509/**
510 * Writes data from network containing information about the state
511 * @param data pointer to data
512 * @param length length of data
513 * @param sender hostID of sender
514 */
515int WorldEntity::writeState( const byte * data, int length, int sender )
516{
517  char* modelFileName;
518  SYNCHELP_READ_BEGIN();
519
520  SYNCHELP_READ_FKT( PNode::writeState, NWT_WE_PN_WRITESTATE );
521
522  SYNCHELP_READ_STRINGM( modelFileName, NWT_WE_PN_MODELFILENAME );
523  SYNCHELP_READ_FLOAT( scaling, NWT_WE_PN_SCALING );
524  //check if modelFileName is relative to datadir or absolute
525
526
527  PRINTF(0)("================ LOADING MODEL %s, %f\n", modelFileName, scaling);
528
529  if ( strcmp(modelFileName, "") )
530  {
531    loadModel( modelFileName, scaling);
532    PRINTF(0)("modelfilename: %s\n", getModel( 0 )->getName());
533  }
534  delete[] modelFileName;
535
536  /*SYNCHELP_READ_STRINGM( modelFileName );
537
538  if ( strcmp(modelFileName, "") )
539    if ( strstr(modelFileName, ResourceManager::getInstance()->getDataDir()) )
540    {
541      this->md2TextureFileName = new char[strlen(modelFileName)-strlen(ResourceManager::getInstance()->getDataDir())+1];
542      strcpy((char*)this->md2TextureFileName, modelFileName+strlen(ResourceManager::getInstance()->getDataDir()));
543    }
544    else
545    {
546      this->md2TextureFileName = modelFileName;
547    }
548  */
549
550  return SYNCHELP_READ_N;
551}
552
553
554/**
555 * data copied in data will bee sent to another host
556 * @param data pointer to data
557 * @param maxLength max length of data
558 * @return the number of bytes writen
559 */
560int WorldEntity::readState( byte * data, int maxLength )
561{
562  SYNCHELP_WRITE_BEGIN();
563
564  SYNCHELP_WRITE_FKT( PNode::readState, NWT_WE_PN_WRITESTATE );
565
566  if ( getModel(0) && getModel(0)->getName() )
567  {
568    char* name = (char*)(getModel( 0 )->getName());
569
570    if ( strstr(name, ResourceManager::getInstance()->getDataDir()) )
571    {
572      name += strlen(ResourceManager::getInstance()->getDataDir());
573    }
574
575    SYNCHELP_WRITE_STRING( name, NWT_WE_PN_MODELFILENAME );
576  }
577  else
578  {
579    SYNCHELP_WRITE_STRING("", NWT_WE_PN_MODELFILENAME);
580  }
581
582  SYNCHELP_WRITE_FLOAT( scaling, NWT_WE_PN_SCALING );
583  /*if ( this->md2TextureFileName!=NULL && strcmp(this->md2TextureFileName, "") )
584  {
585    SYNCHELP_WRITE_STRING(this->md2TextureFileName);
586  }
587  else
588  {
589    SYNCHELP_WRITE_STRING("");
590}*/
591
592  return SYNCHELP_WRITE_N;
593}
Note: See TracBrowser for help on using the repository browser.