Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

trunk: new algorithm for the Camera-Distance

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