Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/vs-enhencements/src/story_entities/game_world.cc @ 10646

Last change on this file since 10646 was 10618, checked in by bknecht, 18 years ago

merged cleanup into trunk (only improvements)

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