Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 8716 was 8711, checked in by bensch, 18 years ago

merged the script_engine back here

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