Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 10319 was 10319, checked in by patrick, 17 years ago

injected silvans patch

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
315  while( this->bRunning) /* @todo implement pause */
316  {
317    /* process intput */
318    this->handleInput ();
319    if( !this->bRunning)
320      break;
321
322    /* network synchronisation */
323    this->synchronize ();
324    /* process time */
325    this->tick ();
326
327
328    /* update the state */
329    //this->update (); /// LESS REDUNDANCY.
330    //      PNode::getNullParent()->updateNode(this->dtS);
331    PNode::getNullParent()->updateNode(this->dtS);
332
333    /* collision detection */
334    this->collisionDetection ();
335    /* collision reaction */
336    this->collisionReaction ();
337
338    /* check the game rules */
339    this->checkGameRules();
340
341    /* update the state */
342    this->update ();
343    /* draw everything */
344    this->display ();
345
346  }
347
348  PRINTF(4)("GameWorld::mainLoop() - Exiting the main loop\n");
349}
350
351
352void GameWorld::setPlaymode(Playable::Playmode playmode)
353{
354  if (this->dataTank->localPlayer &&
355      this->dataTank->localPlayer->getPlayable() &&
356      this->dataTank->localPlayer->getPlayable()->setPlaymode(playmode))
357  {
358    PRINTF(4)("Set Playmode to %d:%s\n", playmode, Playable::playmodeToString(playmode).c_str());
359  }
360  else
361  {
362    PRINTF(2)("Unable to set Playmode %d:'%s'\n", playmode, Playable::playmodeToString(playmode).c_str());
363  }
364}
365
366void GameWorld::setPlaymode(const std::string& playmode)
367{
368  this->setPlaymode(Playable::stringToPlaymode(playmode));
369}
370
371/**
372 *  synchronize local data with remote data
373*/
374void GameWorld::synchronize ()
375{}
376
377
378/**
379 *  run all input processing
380
381   the command node is the central input event dispatcher. the node uses the even-queue from
382   sdl and has its own event-passing-queue.
383*/
384void GameWorld::handleInput ()
385{
386  EventHandler::getInstance()->process();
387}
388
389
390/**
391 * @brief ticks a WorldEntity list
392 * @param entityList list of the WorldEntities
393 * @param dt time passed since last frame
394 */
395void GameWorld::tick(ObjectManager::EntityList entityList, float dt)
396{
397  ObjectManager::EntityList::iterator entity, next;
398  next = entityList.begin();
399  while (next != entityList.end())
400  {
401    entity = next++;
402    (*entity)->tick(dt);
403  }
404}
405
406
407/**
408 *  advance the timeline
409 *
410 * this calculates the time used to process one frame (with all input handling, drawing, etc)
411 * the time is mesured in ms and passed to all world-entities and other classes that need
412 * a heart-beat.
413 */
414void GameWorld::tick ()
415{
416  if( !this->bPaused)
417  {
418    // CALCULATE FRAMERATE
419    Uint32 frameTimesIndex;
420    Uint32 i;
421    double currentFrame = Timer::getNow();
422
423    if (currentFrame - this->lastFrame < .01)
424    {
425      SDL_Delay((int)(1000.0 * (0.01 - (currentFrame - lastFrame))));
426      currentFrame = Timer::getNow();
427    }
428
429
430    frameTimesIndex = this->cycle % TICK_SMOOTH_VALUE;
431    this->frameTimes[frameTimesIndex] = currentFrame - this->lastFrame;
432    this->lastFrame = currentFrame;
433    ++this->cycle;
434    this->dtS = 0.0;
435    for (i = 0; i < TICK_SMOOTH_VALUE; i++)
436      this->dtS += this->frameTimes[i];
437    this->dtS = this->dtS / TICK_SMOOTH_VALUE * speed;
438
439    // TICK everything
440    for (i = 0; i < this->dataTank->tickLists.size(); ++i)
441      this->tick(this->dataTank->objectManager->getEntityList(this->dataTank->tickLists[i]), this->dtS);
442
443    /* update tick the rest */
444    this->dataTank->localCamera->tick(this->dtS);
445    AnimationPlayer::getInstance()->tick(this->dtS);
446    PhysicsEngine::getInstance()->tick(this->dtS);
447
448    GraphicsEngine::getInstance()->tick(this->dtS);
449    AtmosphericEngine::getInstance()->tick(this->dtS);
450
451    if( likely(this->dataTank->gameRule != NULL))
452      this->dataTank->gameRule->tick(this->dtS);
453
454  }
455}
456
457
458/**
459 *  this function gives the world a consistant state
460 *
461 * after ticking (updating the world state) this will give a constistant
462 * state to the whole system.
463 */
464void GameWorld::update()
465{
466  PNode::getNullParent()->updateNode (this->dtS);
467  OrxSound::SoundEngine::getInstance()->update();
468
469  this->applyCameraSettings();
470  GraphicsEngine::getInstance()->update(this->dtS);
471}
472
473
474/**
475 * kicks the CDEngine to detect the collisions between the object groups in the world
476 */
477void GameWorld::collisionDetection()
478{
479  // object-object collision detection
480  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_00),
481      this->dataTank->objectManager->getEntityList(OM_GROUP_01_PROJ));
482  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_01),
483      this->dataTank->objectManager->getEntityList(OM_GROUP_00_PROJ));
484  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_01),
485      this->dataTank->objectManager->getEntityList(OM_GROUP_00));
486
487  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_01),
488      this->dataTank->objectManager->getEntityList(OM_GROUP_02));
489  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_02),
490      this->dataTank->objectManager->getEntityList(OM_GROUP_01_PROJ));
491
492
493  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_00),
494      this->dataTank->objectManager->getEntityList(OM_COMMON));
495  CDEngine::getInstance()->checkCollisions(this->dataTank->objectManager->getEntityList(OM_GROUP_01),
496      this->dataTank->objectManager->getEntityList(OM_COMMON));
497
498  // ground collision detection: BSP Model
499  CDEngine::getInstance()->checkCollisionGround(this->dataTank->objectManager->getEntityList(OM_GROUP_00));
500  CDEngine::getInstance()->checkCollisionGround(this->dataTank->objectManager->getEntityList(OM_GROUP_01));
501}
502
503
504void GameWorld::collisionReaction()
505{
506  CoRe::CREngine::getInstance()->handleCollisions();
507}
508
509
510/**
511 *  check the game rules: winning conditions, etc.
512 *
513 */
514void GameWorld::checkGameRules()
515{
516  if( this->gameRules)
517    this->gameRules->tick(this->dtS);
518}
519
520
521/**
522 *  render the current frame
523 *
524 * clear all buffers and draw the world
525 */
526void GameWorld::display ()
527{
528
529  // if this server is a dedicated server the game workd does not need to be drawn
530  if( !GraphicsEngine::getInstance()->isDedicated())
531  {
532    // render the reflection texture
533    this->renderPassReflection();
534    // redner the refraction texture
535    this->renderPassRefraction();
536  }
537  // render all
538  this->renderPassAll();
539
540  // flip buffers
541  GraphicsEngine::swapBuffers();
542}
543
544
545/**
546 * @brief draws all entities in the list drawList
547 * @param drawList the List of entities to draw.
548 */
549void GameWorld::drawEntityList(const ObjectManager::EntityList& drawList) const
550{
551  ObjectManager::EntityList::const_iterator entity;
552  for (entity = drawList.begin(); entity != drawList.end(); entity++)
553  {
554    if ((*entity)->isVisible())
555      (*entity)->draw();
556
557    if( unlikely( this->showMPV))
558      (*entity)->debugDrawMountPoints();
559  }
560}
561
562
563void GameWorld::applyCameraSettings()
564{
565  this->dataTank->localCamera->apply ();
566  this->dataTank->localCamera->project ();
567  GraphicsEngine::storeMatrices();
568}
569
570
571
572/**
573 * reflection rendering for water surfaces
574 */
575void GameWorld::renderPassReflection()
576{
577  // clear buffer
578  glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
579  //  glLoadIdentity();
580
581  MappedWater* mw;
582
583  for (ObjectList<MappedWater>::const_iterator it = MappedWater::objectList().begin();
584       it != MappedWater::objectList().end();
585       ++it)
586  {
587    mw =  (*it);
588
589    //camera and light
590    //this->dataTank->localCamera->apply ();
591    //this->dataTank->localCamera->project ();
592
593    LightManager::getInstance()->draw();
594
595
596    // prepare for reflection rendering
597    mw->activateReflection();
598
599    // draw everything to be included in the reflection
600    this->drawEntityList(State::getObjectManager()->getReflectionList());
601    //       for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i)
602    //         this->drawEntityList(State::getObjectManager()->getEntityList(this->dataTank->drawLists[i]));
603
604    // clean up from reflection rendering
605    mw->deactivateReflection();
606  }
607
608}
609
610
611/**
612 *  refraction rendering for water surfaces
613 */
614void GameWorld::renderPassRefraction()
615{
616  // clear buffer
617  glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
618  //glLoadIdentity();
619
620  MappedWater* mw;
621
622  for (ObjectList<MappedWater>::const_iterator it = MappedWater::objectList().begin();
623       it != MappedWater::objectList().end();
624       ++it)
625  {
626    mw =  dynamic_cast<MappedWater*>(*it);
627
628    //camera and light
629    //this->dataTank->localCamera->apply ();
630    //this->dataTank->localCamera->project ();
631    // prepare for reflection rendering
632    mw->activateRefraction();
633
634
635    LightManager::getInstance()->draw();
636    // draw everything to be included in the reflection
637    this->drawEntityList(State::getObjectManager()->getReflectionList());
638    //       for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i)
639    //         this->drawEntityList(State::getObjectManager()->getEntityList(this->dataTank->drawLists[i]));
640
641    // clean up from reflection rendering
642    mw->deactivateRefraction();
643  }
644}
645
646
647/**
648 *  this render pass renders the whole wolrd
649 */
650void GameWorld::renderPassAll()
651{
652  // clear buffer
653  glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
654  GraphicsEngine* engine = GraphicsEngine::getInstance();
655
656
657  // glEnable(GL_DEPTH_TEST);
658  // glEnable(GL_LIGHTING);
659
660  // set Lighting
661  LightManager::getInstance()->draw();
662
663  // only render the world if its not dedicated mode
664  if( !GraphicsEngine::getInstance()->isDedicated())
665  {
666    /* Draw the BackGround */
667    this->drawEntityList(State::getObjectManager()->getEntityList(OM_BACKGROUND));
668    engine->drawBackgroundElements();
669
670    /* draw all WorldEntiy groups */
671    for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i)
672      this->drawEntityList(State::getObjectManager()->getEntityList(this->dataTank->drawLists[i]));
673
674    AtmosphericEngine::getInstance()->draw();
675
676    if( unlikely( this->showBV))
677    {
678      CDEngine* engine = CDEngine::getInstance();
679      for (unsigned int i = 0; i < this->dataTank->drawLists.size(); ++i)
680        engine->drawBV(State::getObjectManager()->getEntityList(this->dataTank->drawLists[i]), this->showBVLevel);
681    }
682
683
684    if( unlikely(this->showPNodes))
685      PNode::getNullParent()->debugDraw(0);
686
687    // draw the game ruls
688    if( likely(this->dataTank->gameRule != NULL))
689      this->dataTank->gameRule->draw();
690  }
691
692  engine->draw();
693}
694
695
696/**
697 *  shows the loading screen
698 */
699void GameWorld::displayLoadScreen ()
700{
701  PRINTF(3)("GameWorld::displayLoadScreen - start\n");
702  this->dataTank->glmis = new GLMenuImageScreen();
703  this->dataTank->glmis->setMaximum(8);
704  PRINTF(3)("GameWorld::displayLoadScreen - end\n");
705}
706
707
708/**
709 *  removes the loadscreen, and changes over to the game
710 */
711void GameWorld::releaseLoadScreen()
712{
713  PRINTF(3)("GameWorld::releaseLoadScreen - start\n");
714  this->dataTank->glmis->setValue(this->dataTank->glmis->getMaximum());
715  PRINTF(3)("GameWorld::releaseLoadScreen - end\n");
716}
717
718
719
720/**
721 * @brief toggles the PNode visibility in the world (drawn as boxes)
722 */
723void GameWorld::togglePNodeVisibility()
724{
725  this->showPNodes = !this->showPNodes;
726};
727
728
729/**
730 * @brief toggles the bounding volume (BV) visibility
731*/
732void GameWorld::toggleBVVisibility(int level)
733{
734  if( level < 1)
735    this->showBV = false;
736  else
737  {
738    this->showBV = true;
739    this->showBVLevel = level;
740  }
741
742};
743
Note: See TracBrowser for help on using the repository browser.