Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/mount_points/src/story_entities/game_world.cc @ 10228

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

some more work on the mounting points. should soon be finished

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