Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/story_entities/game_world.cc @ 10344

Last change on this file since 10344 was 10340, checked in by patrick, 18 years ago

got gravity and no banking anymore

File size: 18.9 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   main-programmer: Benjamin Grauer
14   co-programmer: Christian Meyer
15
16*/
17
18#define DEBUG_SPECIAL_MODULE DEBUG_MODULE_WORLD
19
20#include "game_world.h"
21#include "game_world_data.h"
22
23#include "state.h"
24
25#include "util/loading/game_loader.h"
26#include "util/timer.h"
27
28#include "player.h"
29#include "camera.h"
30#include "environment.h"
31#include "terrain.h"
32#include "test_entity.h"
33#include "terrain.h"
34#include "playable.h"
35#include "environments/mapped_water.h"
36
37#include "light.h"
38
39#include "util/loading/factory.h"
40#include "util/loading/load_param_xml.h"
41#include "loading/fast_factory.h"
42#include "shell_command.h"
43
44#include "graphics_engine.h"
45#include "weather_effects/atmospheric_engine.h"
46#include "event_handler.h"
47#include "sound_engine.h"
48#include "cd_engine.h"
49#include "network_manager.h"
50#include "physics_engine.h"
51
52#include "glmenu_imagescreen.h"
53#include "shell.h"
54
55#include "ogg_player.h"
56#include "shader.h"
57
58#include "animation_player.h"
59
60#include "game_rules.h"
61
62#include "script_class.h"
63ObjectListDefinition(GameWorld);
64CREATE_SCRIPTABLE_CLASS(GameWorld,
65                        addMethod("setPlaymode", Executor1<GameWorld, lua_State*,const std::string&>(&GameWorld::setPlaymode))
66                        ->addMethod("setSoundtrack", Executor1<GameWorld, lua_State*, const std::string&>(&GameWorld::setSoundtrack))
67                        ->addMethod("getStoryID", Executor0ret<StoryEntity, lua_State*, int>(&StoryEntity::getStoryID))
68                        ->addMethod("setNextStoryName", Executor1ret<StoryEntity, lua_State*, bool, const std::string&>(&StoryEntity::setNextStoryName))
69                        ->addMethod("stop", Executor0ret<GameWorld, lua_State*, bool>(&GameWorld::stop))
70                       );
71
72SHELL_COMMAND(speed, GameWorld, setSpeed) ->describe("set the Speed of the Level");
73SHELL_COMMAND(playmode, GameWorld, setPlaymode)
74->describe("Set the Playmode of the current Level")
75->completionPlugin(0, OrxShell::CompletorStringArray(Playable::playmodeNames, Playable::PlaymodeCount));
76
77SHELL_COMMAND(togglePNodeVisibility, GameWorld, togglePNodeVisibility);
78SHELL_COMMAND(showBVLevel, GameWorld, toggleBVVisibility);
79SHELL_COMMAND(showMountPoints, GameWorld, toggleMPVisibility);
80
81
82GameWorld::GameWorld()
83    : StoryEntity()
84{
85  this->registerObject(this, GameWorld::_objectList);
86  this->setName("Preloaded World - no name yet");
87
88  this->gameTime = 0.0f;
89  this->setSpeed(1.0f);
90  this->shell = NULL;
91
92  this->showPNodes = false;
93  this->showBV = false;
94  this->showBVLevel = 3;
95  this->showMPV = false;
96
97  this->dataXML = NULL;
98  this->gameRules = NULL;
99}
100
101/**
102 *  remove the GameWorld from memory
103 *
104 *  delete everything explicitly, that isn't contained in the parenting tree!
105 *  things contained in the tree are deleted automaticaly
106 */
107GameWorld::~GameWorld ()
108{
109  PRINTF(4)("Deleted GameWorld\n");
110
111}
112
113
114
115/**
116 * loads the parameters of a GameWorld from an XML-element
117 * @param root the XML-element to load from
118 */
119void GameWorld::loadParams(const TiXmlElement* root)
120{
121  StoryEntity::loadParams(root);
122
123  PRINTF(4)("Loaded GameWorld specific stuff\n");
124}
125
126
127/**
128 * this is executed just before load
129 *
130 * since the load function sometimes needs data, that has been initialized
131 * before the load and after the proceeding storyentity has finished
132*/
133ErrorMessage GameWorld::init()
134{
135  /* init the world interface */
136  this->shell = new OrxShell::Shell();
137
138  State::setCurrentStoryEntity(dynamic_cast<StoryEntity*>(this));
139  this->dataTank->init();
140
141  /* initialize some engines and graphical elements */
142  AnimationPlayer::getInstance();
143  PhysicsEngine::getInstance();
144  CoRe::CREngine::getInstance();
145
146  State::setScriptManager(&this->scriptManager);
147
148  return ErrorMessage();
149}
150
151/**
152 *  loads the GameWorld by initializing all resources, and set their default values.
153 */
154ErrorMessage GameWorld::loadData()
155{
156  this->displayLoadScreen();  State::setScriptManager(&this->scriptManager);
157
158
159  PRINTF(4)("Loading the GameWorld\n");
160
161  PRINTF(3)("> Loading world: '%s'\n", getLoadFile().c_str());
162  //  TiXmlElement* element;
163  //  GameLoader* loader = GameLoader::getInstance();
164
165  if( getLoadFile().empty())
166  {
167    PRINTF(1)("GameWorld has no path specified for loading\n");
168    return (ErrorMessage(213,"Path not specified","GameWorld::load()"));
169  }
170
171  TiXmlDocument* XMLDoc = new TiXmlDocument( getLoadFile());
172  // load the xml world file for further loading
173  if( !XMLDoc->LoadFile())
174  {
175    PRINTF(1)("loading XML File: %s @ %s:l%d:c%d\n", XMLDoc->ErrorDesc(), this->getLoadFile().c_str(), XMLDoc->ErrorRow(), XMLDoc->ErrorCol());
176    delete XMLDoc;
177    return ErrorMessage(213,"XML File parsing error","GameWorld::load()");
178  }
179  // check basic validity
180  TiXmlElement* root = XMLDoc->RootElement();
181  assert( root != NULL);
182  if( root == NULL || root->Value() == NULL || strcmp( root->Value(), "WorldDataFile"))
183  {
184    // report an error
185    PRINTF(1)("Specified XML File is not an orxonox world data file (WorldDataFile element missing)\n");
186    delete XMLDoc;
187    return ErrorMessage(213,"Path not a WorldDataFile","GameWorld::load()");
188  }
189  /* the whole loading process for the GameWorld */
190  this->dataTank->loadData(root);
191  this->dataXML = (TiXmlElement*)root->Clone();
192
193  //remove this after finished testing !!!!
194  //Object* obj= new Object();
195  //obj->setName("Obj");
196  //Account* a = new Account();
197  //a->setName("a");
198  //Account *b = new Account(30);
199  //b->setName("b");
200
201
202  LoadParamXML(root, "ScriptManager", &this->scriptManager, ScriptManager, loadParams);
203
204  delete XMLDoc;
205  this->releaseLoadScreen();
206
207  return ErrorMessage();
208}
209
210
211/**
212 *  unload the data of this GameWorld
213 */
214ErrorMessage GameWorld::unloadData()
215{
216
217  PRINTF(3)("GameWorld::~GameWorld() - unloading the current GameWorld\n");
218  this->scriptManager.flush();
219
220  delete this->shell;
221
222  this->dataTank->unloadData();
223
224  this->shell = NULL;
225  delete AnimationPlayer::getInstance();
226  delete PhysicsEngine::getInstance();
227  delete CoRe::CREngine::getInstance();
228
229  State::setCurrentStoryEntity(NULL);
230  if (this->dataXML)
231    delete this->dataXML;
232
233  return ErrorMessage();
234}
235
236
237void GameWorld::setSoundtrack(const std::string& soundTrack)
238{
239  if (this->dataTank != NULL)
240  {
241    this->dataTank->setSoundTrack(soundTrack);
242    this->dataTank->music->play();
243  }
244}
245
246
247/**
248 *  starts the GameWorld
249 */
250bool GameWorld::start()
251{
252  this->bPaused = false;
253  this->bRunning = true;
254  State::setScriptManager(&this->scriptManager); //make sure we have the right script manager
255  this->run();
256
257  return true;
258}
259
260
261/**
262 *  stops the world.
263 */
264bool GameWorld::stop()
265{
266  PRINTF(3)("GameWorld::stop() - got stop signal\n");
267  State::setScriptManager(NULL);
268  return (this->bRunning = false);
269}
270
271
272/**
273 *  pauses the game
274 */
275bool GameWorld::pause()
276{
277  return (this->bPaused = true);
278}
279
280
281/**
282 *  ends the pause Phase
283 */
284bool GameWorld::resume()
285{
286  return(this->bPaused = false);
287}
288
289
290/**
291 *  main loop of the world: executing all world relevant function
292 *
293 * in this loop we synchronize (if networked), handle input events, give the heart-beat to
294 * all other member-entities of the world (tick to player, enemies etc.), checking for
295 * collisions drawing everything to the screen.
296 */
297void GameWorld::run()
298{
299  PRINTF(3)("GameWorld::mainLoop() - Entering main loop\n");
300
301  // initialize Timing
302  this->cycle = 0;
303  for (unsigned int i = 0; i < TICK_SMOOTH_VALUE; i++)
304    this->frameTimes[i] = 0.01f;
305  this->dtS = 0.0f;
306  this->lastFrame = Timer::getNow();
307
308  if (this->dataTank->music != NULL)
309    this->dataTank->music->play();
310
311  PNode::getNullParent()->updateNode(0.01);
312  PNode::getNullParent()->updateNode(0.01);
313
314  bool bNoDraw = true;
315
316  while( this->bRunning) /* @todo implement pause */
317  {
318    /* process intput */
319    this->handleInput ();
320    if( !this->bRunning)
321      break;
322
323    /* network synchronisation */
324    this->synchronize ();
325    /* process time */
326    this->tick ();
327
328
329    /* update the state */
330    //this->update (); /// LESS REDUNDANCY.
331    //      PNode::getNullParent()->updateNode(this->dtS);
332    PNode::getNullParent()->updateNode(this->dtS);
333
334    /* collision detection */
335    this->collisionDetection ();
336    /* collision reaction */
337    this->collisionReaction ();
338
339    /* check the game rules */
340    this->checkGameRules();
341
342    /* update the state */
343    this->update ();
344    /* draw everything */
345    if( bNoDraw)
346      this->display ();
347
348    bNoDraw= !bNoDraw;
349  }
350
351  PRINTF(4)("GameWorld::mainLoop() - Exiting the main loop\n");
352}
353
354
355void GameWorld::setPlaymode(Playable::Playmode playmode)
356{
357  if (this->dataTank->localPlayer &&
358      this->dataTank->localPlayer->getPlayable() &&
359      this->dataTank->localPlayer->getPlayable()->setPlaymode(playmode))
360  {
361    PRINTF(4)("Set Playmode to %d:%s\n", playmode, Playable::playmodeToString(playmode).c_str());
362  }
363  else
364  {
365    PRINTF(2)("Unable to set Playmode %d:'%s'\n", playmode, Playable::playmodeToString(playmode).c_str());
366  }
367}
368
369void GameWorld::setPlaymode(const std::string& playmode)
370{
371  this->setPlaymode(Playable::stringToPlaymode(playmode));
372}
373
374/**
375 *  synchronize local data with remote data
376*/
377void GameWorld::synchronize ()
378{}
379
380
381/**
382 *  run all input processing
383
384   the command node is the central input event dispatcher. the node uses the even-queue from
385   sdl and has its own event-passing-queue.
386*/
387void GameWorld::handleInput ()
388{
389  EventHandler::getInstance()->process();
390}
391
392
393/**
394 * @brief ticks a WorldEntity list
395 * @param entityList list of the WorldEntities
396 * @param dt time passed since last frame
397 */
398void GameWorld::tick(ObjectManager::EntityList entityList, float dt)
399{
400  ObjectManager::EntityList::iterator entity, next;
401  next = entityList.begin();
402  while (next != entityList.end())
403  {
404    entity = next++;
405    (*entity)->tick(dt);
406  }
407}
408
409
410/**
411 *  advance the timeline
412 *
413 * this calculates the time used to process one frame (with all input handling, drawing, etc)
414 * the time is mesured in ms and passed to all world-entities and other classes that need
415 * a heart-beat.
416 */
417void GameWorld::tick ()
418{
419  if( !this->bPaused)
420  {
421    // CALCULATE FRAMERATE
422    Uint32 frameTimesIndex;
423    Uint32 i;
424    double currentFrame = Timer::getNow();
425
426    if (currentFrame - this->lastFrame < .01)
427    {
428      SDL_Delay((int)(1000.0 * (0.01 - (currentFrame - lastFrame))));
429      currentFrame = Timer::getNow();
430    }
431
432
433    frameTimesIndex = this->cycle % TICK_SMOOTH_VALUE;
434    this->frameTimes[frameTimesIndex] = currentFrame - this->lastFrame;
435    this->lastFrame = currentFrame;
436    ++this->cycle;
437    this->dtS = 0.0;
438    for (i = 0; i < TICK_SMOOTH_VALUE; i++)
439      this->dtS += this->frameTimes[i];
440    this->dtS = this->dtS / TICK_SMOOTH_VALUE * speed;
441
442    // TICK everything
443    for (i = 0; i < this->dataTank->tickLists.size(); ++i)
444      this->tick(this->dataTank->objectManager->getEntityList(this->dataTank->tickLists[i]), this->dtS);
445
446    /* update tick the rest */
447    this->dataTank->localCamera->tick(this->dtS);
448    AnimationPlayer::getInstance()->tick(this->dtS);
449    PhysicsEngine::getInstance()->tick(this->dtS);
450
451    GraphicsEngine::getInstance()->tick(this->dtS);
452    AtmosphericEngine::getInstance()->tick(this->dtS);
453
454    if( likely(this->dataTank->gameRule != NULL))
455      this->dataTank->gameRule->tick(this->dtS);
456
457  }
458}
459
460
461/**
462 *  this function gives the world a consistant state
463 *
464 * after ticking (updating the world state) this will give a constistant
465 * state to the whole system.
466 */
467void GameWorld::update()
468{
469  PNode::getNullParent()->updateNode (this->dtS);
470  OrxSound::SoundEngine::getInstance()->update();
471
472  this->applyCameraSettings();
473  GraphicsEngine::getInstance()->update(this->dtS);
474}
475
476
477/**
478 * kicks the CDEngine to detect the collisions between the object groups in the world
479 */
480void GameWorld::collisionDetection()
481{
482  // object-object collision detection
483  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_00),
484      this->dataTank->objectManager->getEntityList(OM_GROUP_01_PROJ));
485  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_01),
486      this->dataTank->objectManager->getEntityList(OM_GROUP_00_PROJ));
487  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_01),
488      this->dataTank->objectManager->getEntityList(OM_GROUP_00));
489
490  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_01),
491      this->dataTank->objectManager->getEntityList(OM_GROUP_02));
492  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_02),
493      this->dataTank->objectManager->getEntityList(OM_GROUP_01_PROJ));
494
495
496  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_00),
497      this->dataTank->objectManager->getEntityList(OM_COMMON));
498  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_01),
499      this->dataTank->objectManager->getEntityList(OM_COMMON));
500
501  // ground collision detection: BSP Model
502  CDEngine::getInstance()->checkCollisionGround(this->dataTank->objectManager->getEntityList(OM_GROUP_00));
503  CDEngine::getInstance()->checkCollisionGround(this->dataTank->objectManager->getEntityList(OM_GROUP_01));
504}
505
506
507void GameWorld::collisionReaction()
508{
509  CoRe::CREngine::getInstance()->handleCollisions();
510}
511
512
513/**
514 *  check the game rules: winning conditions, etc.
515 *
516 */
517void GameWorld::checkGameRules()
518{
519  if( this->gameRules)
520    this->gameRules->tick(this->dtS);
521}
522
523
524/**
525 *  render the current frame
526 *
527 * clear all buffers and draw the world
528 */
529void GameWorld::display ()
530{
531
532  // if this server is a dedicated server the game workd does not need to be drawn
533  if( !GraphicsEngine::getInstance()->isDedicated())
534  {
535    // render the reflection texture
536    this->renderPassReflection();
537    // redner the refraction texture
538    this->renderPassRefraction();
539  }
540  // render all
541  this->renderPassAll();
542
543  // flip buffers
544  GraphicsEngine::swapBuffers();
545}
546
547
548/**
549 * @brief draws all entities in the list drawList
550 * @param drawList the List of entities to draw.
551 */
552void GameWorld::drawEntityList(const ObjectManager::EntityList& drawList) const
553{
554  ObjectManager::EntityList::const_iterator entity;
555  for (entity = drawList.begin(); entity != drawList.end(); entity++)
556  {
557    if ((*entity)->isVisible())
558      (*entity)->draw();
559
560    if( unlikely( this->showMPV))
561      (*entity)->debugDrawMountPoints();
562  }
563}
564
565
566void GameWorld::applyCameraSettings()
567{
568  this->dataTank->localCamera->apply ();
569  this->dataTank->localCamera->project ();
570  GraphicsEngine::storeMatrices();
571}
572
573
574
575/**
576 * reflection rendering for water surfaces
577 */
578void GameWorld::renderPassReflection()
579{
580  // clear buffer
581  glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
582  //  glLoadIdentity();
583
584  MappedWater* mw;
585
586  for (ObjectList<MappedWater>::const_iterator it = MappedWater::objectList().begin();
587       it != MappedWater::objectList().end();
588       ++it)
589  {
590    mw =  (*it);
591
592    //camera and light
593    //this->dataTank->localCamera->apply ();
594    //this->dataTank->localCamera->project ();
595
596    LightManager::getInstance()->draw();
597
598
599    // prepare for reflection rendering
600    mw->activateReflection();
601
602    // draw everything to be included in the reflection
603    this->drawEntityList(State::getObjectManager()->getReflectionList());
604    //       for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i)
605    //         this->drawEntityList(State::getObjectManager()->getEntityList(this->dataTank->drawLists[i]));
606
607    // clean up from reflection rendering
608    mw->deactivateReflection();
609  }
610
611}
612
613
614/**
615 *  refraction rendering for water surfaces
616 */
617void GameWorld::renderPassRefraction()
618{
619  // clear buffer
620  glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
621  //glLoadIdentity();
622
623  MappedWater* mw;
624
625  for (ObjectList<MappedWater>::const_iterator it = MappedWater::objectList().begin();
626       it != MappedWater::objectList().end();
627       ++it)
628  {
629    mw =  dynamic_cast<MappedWater*>(*it);
630
631    //camera and light
632    //this->dataTank->localCamera->apply ();
633    //this->dataTank->localCamera->project ();
634    // prepare for reflection rendering
635    mw->activateRefraction();
636
637
638    LightManager::getInstance()->draw();
639    // draw everything to be included in the reflection
640    this->drawEntityList(State::getObjectManager()->getReflectionList());
641    //       for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i)
642    //         this->drawEntityList(State::getObjectManager()->getEntityList(this->dataTank->drawLists[i]));
643
644    // clean up from reflection rendering
645    mw->deactivateRefraction();
646  }
647}
648
649
650/**
651 *  this render pass renders the whole wolrd
652 */
653void GameWorld::renderPassAll()
654{
655  // clear buffer
656  glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
657  GraphicsEngine* engine = GraphicsEngine::getInstance();
658
659
660  // glEnable(GL_DEPTH_TEST);
661  // glEnable(GL_LIGHTING);
662
663  // set Lighting
664  LightManager::getInstance()->draw();
665
666  // only render the world if its not dedicated mode
667  if( !GraphicsEngine::getInstance()->isDedicated())
668  {
669    /* Draw the BackGround */
670    this->drawEntityList(State::getObjectManager()->getEntityList(OM_BACKGROUND));
671    engine->drawBackgroundElements();
672
673    /* draw all WorldEntiy groups */
674    for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i)
675      this->drawEntityList(State::getObjectManager()->getEntityList(this->dataTank->drawLists[i]));
676
677    AtmosphericEngine::getInstance()->draw();
678
679    if( unlikely( this->showBV))
680    {
681      CDEngine* engine = CDEngine::getInstance();
682      for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i)
683        engine->drawBV(State::getObjectManager()->getEntityList(this->dataTank->drawLists[i]), this->showBVLevel);
684    }
685
686
687    if( unlikely(this->showPNodes))
688      PNode::getNullParent()->debugDraw(0);
689
690    // draw the game ruls
691    if( likely(this->dataTank->gameRule != NULL))
692      this->dataTank->gameRule->draw();
693  }
694
695  engine->draw();
696}
697
698
699/**
700 *  shows the loading screen
701 */
702void GameWorld::displayLoadScreen ()
703{
704  PRINTF(3)("GameWorld::displayLoadScreen - start\n");
705  this->dataTank->glmis = new GLMenuImageScreen();
706  this->dataTank->glmis->setMaximum(8);
707  PRINTF(3)("GameWorld::displayLoadScreen - end\n");
708}
709
710
711/**
712 *  removes the loadscreen, and changes over to the game
713 */
714void GameWorld::releaseLoadScreen()
715{
716  PRINTF(3)("GameWorld::releaseLoadScreen - start\n");
717  this->dataTank->glmis->setValue(this->dataTank->glmis->getMaximum());
718  PRINTF(3)("GameWorld::releaseLoadScreen - end\n");
719}
720
721
722
723/**
724 * @brief toggles the PNode visibility in the world (drawn as boxes)
725 */
726void GameWorld::togglePNodeVisibility()
727{
728  this->showPNodes = !this->showPNodes;
729};
730
731
732/**
733 * @brief toggles the bounding volume (BV) visibility
734*/
735void GameWorld::toggleBVVisibility(int level)
736{
737  if( level < 1)
738    this->showBV = false;
739  else
740  {
741    this->showBV = true;
742    this->showBVLevel = level;
743  }
744
745};
746
Note: See TracBrowser for help on using the repository browser.