Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

ai fix, mp fix

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