Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/christmas_branche/src/story_entities/world.cc @ 6194

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

branches/christmas removed many include 'list.h'

File size: 18.2 KB
Line 
1/*
2   orxonox - the future of 3D-vertical-scrollers
3
4   Copyright (C) 2004 orx
5
6   This program is free software; you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation; either version 2, or (at your option)
9   any later version.
10
11   ### File Specific:
12   main-programmer: Patrick Boenzli
13   co-programmer: Christian Meyer
14   co-programmer: Benjamin Grauer
15*/
16
17#define DEBUG_SPECIAL_MODULE DEBUG_MODULE_WORLD
18
19#include "world.h"
20
21#include "shell_command.h"
22#include "resource_manager.h"
23#include "state.h"
24
25#include "p_node.h"
26#include "world_entity.h"
27#include "player.h"
28#include "camera.h"
29#include "environment.h"
30#include "terrain.h"
31
32#include "test_entity.h"
33#include "terrain.h"
34#include "light.h"
35#include "load_param.h"
36#include "shell.h"
37
38#include "fast_factory.h"
39#include "animation_player.h"
40#include "particle_engine.h"
41#include "graphics_engine.h"
42#include "physics_engine.h"
43#include "fields.h"
44
45#include "md2Model.h"
46
47#include "glmenu_imagescreen.h"
48#include "game_loader.h"
49
50#include "animation3d.h"
51
52#include "substring.h"
53
54#include "factory.h"
55
56#include "weapons/projectile.h"
57#include "event_handler.h"
58#include "sound_engine.h"
59#include "ogg_player.h"
60
61#include "class_list.h"
62
63#include "cd_engine.h"
64#include "npcs/npc_test1.h"
65#include "shader.h"
66
67#include "playable.h"
68#include "network_manager.h"
69#include "playable.h"
70
71
72SHELL_COMMAND(speed, World, setSpeed);
73SHELL_COMMAND(togglePNodeVisibility, World, togglePNodeVisibility);
74SHELL_COMMAND(toggleBVVisibility, World, toggleBVVisibility);
75
76using namespace std;
77
78//! This creates a Factory to fabricate a World
79CREATE_FACTORY(World, CL_WORLD);
80
81World::World(const TiXmlElement* root)
82{
83  this->constuctorInit("", -1);
84  this->path = NULL;
85
86  this->loadParams(root);
87}
88
89/**
90 *  remove the World from memory
91 *
92 *  delete everything explicitly, that isn't contained in the parenting tree!
93 *  things contained in the tree are deleted automaticaly
94 */
95World::~World ()
96{
97  delete this->shell;
98  PRINTF(3)("World::~World() - deleting current world\n");
99
100  delete this->localPlayer;
101
102  // delete all the initialized Engines.
103  FastFactory::flushAll(true);
104  delete LightManager::getInstance();
105  delete ParticleEngine::getInstance();
106  delete AnimationPlayer::getInstance();
107  delete PhysicsEngine::getInstance();
108
109  // external engines initialized by the orxonox-class get deleted
110  SoundEngine::getInstance()->flushAllBuffers();
111  SoundEngine::getInstance()->flushAllSources();
112
113  if (State::getObjectManager() == &this->objectManager)
114    State::setObjectManager(NULL);
115  // erease everything that is left.
116  delete PNode::getNullParent();
117
118  //secondary cleanup of PNodes;
119  const std::list<BaseObject*>* nodeList = ClassList::getList(CL_PARENT_NODE);
120  if (nodeList != NULL)
121    while (!nodeList->empty())
122      delete nodeList->front();
123
124  Shader::suspendShader();
125
126  // unload the resources !!
127  ResourceManager::getInstance()->unloadAllByPriority(RP_LEVEL);
128}
129
130/**
131 * initializes the world.
132 * @param name the name of the world
133 * @param worldID the ID of this world
134 *
135 * set all stuff here that is world generic and does not use to much memory
136 * because the real init() function StoryEntity::init() will be called
137 * shortly before start of the game.
138 * since all worlds are initiated/referenced before they will be started.
139 * NO LEVEL LOADING HERE - NEVER!
140*/
141void World::constuctorInit(const char* name, int worldID)
142{
143  this->setClassID(CL_WORLD, "World");
144
145  this->setName(name);
146  this->gameTime = 0.0f;
147  this->setSpeed(1.0);
148  this->music = NULL;
149  this->shell = NULL;
150  this->localPlayer = NULL;
151  this->localCamera = NULL;
152
153  this->showPNodes = false;
154  this->showBV = false;
155}
156
157/**
158 * loads the parameters of a World from an XML-element
159 * @param root the XML-element to load from
160 */
161void World::loadParams(const TiXmlElement* root)
162{
163  PRINTF(4)("Creating a World\n");
164
165  LoadParam(root, "identifier", this, World, setStoryID)
166    .describe("Sets the StoryID of this world");
167
168  LoadParam(root, "nextid", this, World, setNextStoryID)
169    .describe("Sets the ID of the next world");
170
171  LoadParam(root, "path", this, World, setPath)
172    .describe("The Filename of this World (relative from the data-dir)");
173}
174
175/**
176 * this is executed just before load
177 *
178 * since the load function sometimes needs data, that has been initialized
179 * before the load and after the proceeding storyentity has finished
180*/
181ErrorMessage World::preLoad()
182{
183  State::setObjectManager(&this->objectManager);
184  this->cycle = 0;
185
186  /* init the world interface */
187  this->shell = new Shell();
188
189  LightManager::getInstance();
190  PNode::getNullParent();
191
192  AnimationPlayer::getInstance(); // initializes the animationPlayer
193  ParticleEngine::getInstance();
194  PhysicsEngine::getInstance();
195
196  this->localCamera = new Camera();
197  this->localCamera->setName ("World-Camera");
198
199  State::setCamera(this->localCamera, this->localCamera->getTarget());
200
201  GraphicsEngine::getInstance()->displayFPS(true);
202  this->displayLoadScreen();
203}
204
205
206/**
207 *  loads the World by initializing all resources, and set their default values.
208 */
209ErrorMessage World::load()
210{
211  PRINTF(3)("> Loading world: '%s'\n", getPath());
212  TiXmlElement* element;
213  GameLoader* loader = GameLoader::getInstance();
214
215  if( getPath() == NULL)
216    {
217      PRINTF(1)("World has no path specified for loading");
218      return (ErrorMessage){213,"Path not specified","World::load()"};
219    }
220
221  TiXmlDocument* XMLDoc = new TiXmlDocument( getPath());
222  // load the campaign document
223  if( !XMLDoc->LoadFile())
224  {
225    // report an error
226    PRINTF(1)("loading XML File: %s @ %s:l%d:c%d\n", XMLDoc->ErrorDesc(), this->getPath(), XMLDoc->ErrorRow(), XMLDoc->ErrorCol());
227    delete XMLDoc;
228    return (ErrorMessage){213,"XML File parsing error","World::load()"};
229  }
230
231  // check basic validity
232  TiXmlElement* root = XMLDoc->RootElement();
233  assert( root != NULL);
234
235  if( root == NULL || root->Value() == NULL || strcmp( root->Value(), "WorldDataFile"))
236    {
237      // report an error
238      PRINTF(1)("Specified XML File is not an orxonox world data file (WorldDataFile element missing)\n");
239      delete XMLDoc;
240      return (ErrorMessage){213,"Path not a WorldDataFile","World::load()"};
241    }
242
243  // load the parameters
244  // name
245  const char* string = grabParameter( root, "name");
246  if( string == NULL)
247    {
248      PRINTF(2)("World is missing a proper 'name'\n");
249      this->setName("Unknown");
250    }
251  else
252    {
253      this->setName(string);
254    }
255
256  ////////////////
257  // LOADSCREEN //
258  ////////////////
259  element = root->FirstChildElement("LoadScreen");
260  if (element == NULL)
261    {
262      PRINTF(2)("no LoadScreen specified, loading default\n");
263
264      glmis->setBackgroundImage("pictures/load_screen.jpg");
265      this->glmis->setMaximum(8);
266      this->glmis->draw();
267    }
268  else
269    {
270      this->glmis->loadParams(element);
271      this->glmis->draw();
272    }
273  this->glmis->draw();
274
275  ////////////////////////
276  // find WorldEntities //
277  ////////////////////////
278
279  element = root->FirstChildElement("WorldEntities");
280
281  if( element == NULL)
282    {
283      PRINTF(1)("World is missing 'WorldEntities'\n");
284    }
285  else
286    {
287      element = element->FirstChildElement();
288      // load Players/Objects/Whatever
289      PRINTF(4)("Loading WorldEntities\n");
290      while( element != NULL)
291        {
292          BaseObject* created = Factory::fabricate(element);
293          if( created != NULL )
294          {
295            if(created->isA(CL_WORLD_ENTITY))
296              this->spawn(dynamic_cast<WorldEntity*>(created));
297            printf("Created a %s: %s\n", created->getClassName(), created->getName());
298          }
299
300          // if we load a 'Player' we use it as localPlayer
301
302
303          //todo do this more elegant
304          if( element->Value() != NULL && !strcmp( element->Value(), "SkyBox"))
305            this->sky = dynamic_cast<WorldEntity*>(created);
306          if( element->Value() != NULL && !strcmp( element->Value(), "Terrain"))
307          {
308            terrain = dynamic_cast<Terrain*>(created);
309            CDEngine::getInstance()->setTerrain(terrain);
310          }
311          element = element->NextSiblingElement();
312          glmis->step(); //! @todo temporary
313        }
314      PRINTF(4)("Done loading WorldEntities\n");
315    }
316
317    //////////////////////////////
318    // LOADING ADDITIONAL STUFF //
319    //////////////////////////////
320
321    LoadParamXML(root, "LightManager", LightManager::getInstance(), LightManager, loadParams);
322
323   LoadParamXML(root, "ParticleEngine", ParticleEngine::getInstance(), ParticleEngine, loadParams);
324//   LoadParamXML(root, "PhysicsEngine", PhysicsEngine::getInstance(), PhysicsEngine, loadParams);
325
326  // free the XML data
327
328  delete XMLDoc;
329  /* GENERIC LOADING PROCESS FINISHED */
330
331
332  // Create a Player
333  this->localPlayer = new Player();
334
335  Playable* playable;
336  const list<BaseObject*>* playableList = ClassList::getList(CL_PLAYABLE);
337  if (playableList != NULL)
338  {
339    playable = dynamic_cast<Playable*>(playableList->front());
340    this->localPlayer->setControllable(playable);
341  }
342
343  // bind camera
344  playable->addChild (this->localCamera);
345
346//   //localCamera->setParent(TrackNode::getInstance());
347//  tn->addChild(this->localCamera);
348  localCamera->setClipRegion(1, 10000.0);
349  localCamera->lookAt(playable);
350//  this->localPlayer->setParentMode(PNODE_ALL);
351  if (sky != NULL)
352  {
353    this->sky->setParent(this->localCamera);
354    this->sky->setParentMode(PNODE_MOVEMENT);
355  }
356
357  SoundEngine::getInstance()->setListener(this->localCamera);
358
359
360
361  ////////////
362  // STATIC //
363  ////////////
364
365
366//   TestEntity* testEntity = new TestEntity();
367//   testEntity->setRelCoor(Vector(570, 10, -15));
368//   testEntity->setRelDir(Quaternion(M_PI, Vector(0, 1, 0)));
369//   this->spawn(testEntity);
370
371  for(int i = 0; i < 100; i++)
372  {
373    WorldEntity* tmp = new NPCTest1();
374    char npcChar[10];
375    sprintf (npcChar, "NPC_%d", i);
376        tmp->setName(npcChar);
377    tmp->setAbsCoor(((float)rand()/RAND_MAX) * 5000, 50/*+ (float)rand()/RAND_MAX*20*/, ((float)rand()/RAND_MAX -.5) *30);
378    this->spawn(tmp);
379  }
380
381  this->music = NULL;
382  //(OggPlayer*)ResourceManager::getInstance()->load("sound/00-luke_grey_-_hypermode.ogg", OGG, RP_LEVEL);
383  //music->playback();
384}
385
386ErrorMessage World::postLoad()
387{
388  this->releaseLoadScreen();
389}
390
391
392/**
393 *  initializes a new World shortly before start
394 *
395 * this is the function, that will be loaded shortly before the world is
396 * started
397*/
398ErrorMessage World::preStart()
399{
400  this->bPause = false;
401
402  /* update the object position before game start - so there are no wrong coordinates used in the first processing */
403  PNode::getNullParent()->updateNode (0.001f);
404  PNode::getNullParent()->updateNode (0.001f);
405}
406
407
408/**
409 *  starts the World
410 */
411ErrorMessage World::start()
412{
413  this->bQuitWorld = false;
414  this->mainLoop();
415}
416
417/**
418 *  stops the world.
419
420   This happens, when the player decides to end the Level.
421*/
422ErrorMessage World::stop()
423{
424  PRINTF(3)("World::stop() - got stop signal\n");
425  this->bQuitWorld= true;
426}
427
428/**
429 *  pauses the Game
430*/
431ErrorMessage World::pause()
432{
433  this->isPaused = true;
434}
435
436/**
437 *  ends the pause Phase
438*/
439ErrorMessage World::resume()
440{
441  this->isPaused = false;
442}
443
444/**
445 *  destroys the World
446*/
447ErrorMessage World::destroy()
448{
449
450}
451
452/**
453 *  shows the loading screen
454*/
455void World::displayLoadScreen ()
456{
457  PRINTF(3)("World::displayLoadScreen - start\n");
458
459  //GLMenuImageScreen*
460  this->glmis = new GLMenuImageScreen();
461  this->glmis->setMaximum(8);
462
463  PRINTF(3)("World::displayLoadScreen - end\n");
464}
465
466/**
467 * @brief removes the loadscreen, and changes over to the game
468 *
469 * @todo take out the delay
470*/
471void World::releaseLoadScreen ()
472{
473  PRINTF(3)("World::releaseLoadScreen - start\n");
474  this->glmis->setValue(this->glmis->getMaximum());
475  PRINTF(3)("World::releaseLoadScreen - end\n");
476  delete this->glmis;
477}
478
479
480/**
481 *  this returns the current game time
482 * @returns elapsed game time
483*/
484double World::getGameTime()
485{
486  return this->gameTime;
487}
488
489
490
491/**
492 *  synchronize local data with remote data
493*/
494void World::synchronize ()
495{
496  // Get remote input
497  // Update synchronizables
498/*  NetworkManager::getInstance()->synchronize();*/
499}
500
501
502/**
503 *  run all input processing
504
505   the command node is the central input event dispatcher. the node uses the even-queue from
506   sdl and has its own event-passing-queue.
507*/
508void World::handleInput ()
509{
510  EventHandler::getInstance()->process();
511
512  // remoteinput
513}
514
515void World::tick(std::list<WorldEntity*> entityList, float dt)
516{
517  std::list<WorldEntity*>::iterator entity;
518  for (entity = entityList.begin(); entity != entityList.end(); entity++)
519    (*entity)->tick(dt);
520
521}
522
523/**
524 *  advance the timeline
525
526   this calculates the time used to process one frame (with all input handling, drawing, etc)
527   the time is mesured in ms and passed to all world-entities and other classes that need
528   a heart-beat.
529*/
530void World::tick ()
531{
532  Uint32 currentFrame = SDL_GetTicks();
533  if(!this->bPause)
534    {
535      this->dt = currentFrame - this->lastFrame;
536
537      if( this->dt > 10)
538        {
539          float fps = 1000/dt;
540
541          // temporary, only for showing how fast the text-engine is
542          char tmpChar[20];
543          sprintf(tmpChar, "fps: %4.0f", fps);
544        }
545      else
546        {
547          /* the frame-rate is limited to 100 frames per second, all other things are for
548             nothing.
549          */
550          PRINTF(3)("fps = 1000 - frame rate is adjusted\n");
551          SDL_Delay(10-dt);
552          this->dt = 10;
553        }
554
555      this->dtS = (float)this->dt / 1000.0 * this->speed;
556      this->gameTime += this->dtS;
557
558      this->tick(this->objectManager.getObjectList(OM_DEAD_TICK), this->dtS);
559      this->tick(this->objectManager.getObjectList(OM_COMMON), this->dtS);
560      this->tick(this->objectManager.getObjectList(OM_GROUP_00), this->dtS);
561      this->tick(this->objectManager.getObjectList(OM_GROUP_01), this->dtS);
562      this->tick(this->objectManager.getObjectList(OM_GROUP_01_PROJ), this->dtS);
563
564      /* update tick the rest */
565      this->localCamera->tick(this->dtS);
566      // tick the engines
567      AnimationPlayer::getInstance()->tick(this->dtS);
568//      if (this->cycle > 5)
569        PhysicsEngine::getInstance()->tick(this->dtS);
570
571      ParticleEngine::getInstance()->tick(this->dtS);
572
573
574      /** actualy the Graphics Engine should tick the world not the other way around...
575         but since we like the things not too complicated we got it this way around
576         until there is need or time to do it the other way around.
577         @todo: GraphicsEngine ticks world: separation of processes and data...
578
579        bensch: in my opinion the GraphicsEngine could draw the world, but not tick it,
580         beceause graphics have nothing(or at least not much) to do with Motion.
581      */
582      GraphicsEngine::getInstance()->tick(this->dtS);
583    }
584  this->lastFrame = currentFrame;
585}
586
587
588/**
589 *  this function gives the world a consistant state
590
591   after ticking (updating the world state) this will give a constistant
592   state to the whole system.
593*/
594void World::update()
595{
596  GraphicsEngine::getInstance()->update(this->dtS);
597  PNode::getNullParent()->updateNode (this->dtS);
598  SoundEngine::getInstance()->update();
599  //music->update();
600}
601
602
603void World::collide()
604{
605  CDEngine::getInstance()->checkCollisions(this->objectManager.getObjectList(OM_GROUP_00),
606                                            this->objectManager.getObjectList(OM_GROUP_01_PROJ));
607  CDEngine::getInstance()->checkCollisions(this->objectManager.getObjectList(OM_GROUP_01),
608                                            this->objectManager.getObjectList(OM_COMMON));
609}
610
611/**
612 *  render the current frame
613
614   clear all buffers and draw the world
615*/
616void World::display ()
617{
618  // clear buffer
619  glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
620  // set camera
621  this->localCamera->apply ();
622  // draw world
623  this->draw();
624  // draw HUD
625  /** @todo draw HUD */
626  // flip buffers
627  GraphicsEngine::swapBuffers();
628  //SDL_Surface* screen = Orxonox::getInstance()->getScreen ();
629  //SDL_Flip (screen);
630}
631
632
633/**
634 *  runs through all entities calling their draw() methods
635 */
636void World::draw ()
637{
638  GraphicsEngine* engine = GraphicsEngine::getInstance();
639  engine->draw(State::getObjectManager()->getObjectList(OM_ENVIRON_NOTICK));
640  engine->draw(State::getObjectManager()->getObjectList(OM_ENVIRON));
641  engine->draw(State::getObjectManager()->getObjectList(OM_COMMON));
642  engine->draw(State::getObjectManager()->getObjectList(OM_GROUP_00));
643  engine->draw(State::getObjectManager()->getObjectList(OM_GROUP_01));
644  engine->draw(State::getObjectManager()->getObjectList(OM_GROUP_01_PROJ));
645
646//   {
647//     if( entity->isVisible() ) entity->draw();
648  //FIXME
649//     if( unlikely( this->showBV)) entity->drawBVTree(3, 226);  // to draw the bounding boxes of the objects at level 2 for debug purp
650//     entity = iterator->nextElement();
651//   }
652
653  ParticleEngine::getInstance()->draw();
654
655  if (unlikely(this->showPNodes))
656    PNode::getNullParent()->debugDraw(0);
657
658  engine->draw();
659  //TextEngine::getInstance()->draw();
660}
661
662
663/**
664 * \brief main loop of the world: executing all world relevant function
665 *
666 * in this loop we synchronize (if networked), handle input events, give the heart-beat to
667 * all other member-entities of the world (tick to player, enemies etc.), checking for
668 * collisions drawing everything to the screen.
669 */
670void World::mainLoop()
671{
672  this->lastFrame = SDL_GetTicks ();
673  PRINTF(3)("World::mainLoop() - Entering main loop\n");
674
675  while(!this->bQuitWorld) /* @todo implement pause */
676  {
677    ++this->cycle;
678      // Network
679    this->synchronize ();
680      // Process input
681    this->handleInput ();
682    if( this->bQuitWorld)
683      break;
684      // Process time
685    this->tick ();
686      // Process collision
687    this->collide ();
688      // Update the state
689    this->update ();
690      // Draw
691    this->display ();
692  }
693
694  PRINTF(3)("World::mainLoop() - Exiting the main loop\n");
695}
696
697
698
699/**
700 *  add and spawn a new entity to this world
701 * @param entity to be added
702*/
703void World::spawn(WorldEntity* entity)
704{
705//   this->entities->add (entity);
706  entity->postSpawn ();
707}
708
709void World::setPath( const char* name)
710{
711  if (this->path)
712    delete this->path;
713  if (ResourceManager::isFile(name))
714  {
715    this->path = new char[strlen(name)+1];
716    strcpy(this->path, name);
717  }
718  else
719    {
720      this->path = new char[strlen(ResourceManager::getInstance()->getDataDir()) + strlen(name) +1];
721      sprintf(this->path, "%s%s", ResourceManager::getInstance()->getDataDir(), name);
722    }
723}
724
725const char* World::getPath( void)
726{
727  return path;
728}
Note: See TracBrowser for help on using the repository browser.