Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/water/src/world_entities/world_entity.cc @ 7895

Last change on this file since 7895 was 7814, checked in by stefalie, 19 years ago

branches/water: textures works now, but its at the wrong place

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