Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/terrain/src/story_entities/game_world.cc @ 10642

Last change on this file since 10642 was 10013, checked in by patrick, 18 years ago

merged the collision reaction branche back to trunk

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