Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/ggz2/src/libraries/core/Game.cc @ 8740

Last change on this file since 8740 was 5738, checked in by landauf, 15 years ago

merged libraries2 back to trunk

  • Property svn:eol-style set to native
File size: 23.5 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *      Reto Grieder
24 *   Co-authors:
25 *      ...
26 *
27 */
28
29/**
30@file
31@brief
32    Implementation of the Game class.
33*/
34
35#include "Game.h"
36
37#include <exception>
38#include <boost/weak_ptr.hpp>
39#include <CEGUIExceptions.h>
40
41#include "util/Debug.h"
42#include "util/Exception.h"
43#include "util/ScopeGuard.h"
44#include "util/Sleep.h"
45#include "util/SubString.h"
46#include "Clock.h"
47#include "CommandLine.h"
48#include "ConsoleCommand.h"
49#include "Core.h"
50#include "CoreIncludes.h"
51#include "ConfigValueIncludes.h"
52#include "GameMode.h"
53#include "GameState.h"
54
55namespace orxonox
56{
57    static void stop_game()
58        { Game::getInstance().stop(); }
59    SetConsoleCommandShortcutExternAlias(stop_game, "exit");
60
61    std::map<std::string, GameStateInfo> Game::gameStateDeclarations_s;
62    Game* Game::singletonPtr_s = 0;
63
64
65    /**
66    @brief
67        Represents one node of the game state tree.
68    */
69    struct GameStateTreeNode
70    {
71        std::string name_;
72        weak_ptr<GameStateTreeNode> parent_;
73        std::vector<shared_ptr<GameStateTreeNode> > children_;
74    };
75
76
77    /**
78    @brief
79        Another helper class for the Game singleton: we cannot derive
80        Game from OrxonoxClass because we need to handle the Identifier
81        destruction in the Core destructor.
82    */
83    class GameConfiguration : public OrxonoxClass
84    {
85    public:
86        GameConfiguration()
87        {
88            RegisterRootObject(GameConfiguration);
89            this->setConfigValues();
90        }
91
92        void setConfigValues()
93        {
94            SetConfigValue(statisticsRefreshCycle_, 250000)
95                .description("Sets the time in microseconds interval at which average fps, etc. get updated.");
96            SetConfigValue(statisticsAvgLength_, 1000000)
97                .description("Sets the time in microseconds interval at which average fps, etc. gets calculated.");
98            SetConfigValue(fpsLimit_, 50)
99                .description("Sets the desired framerate (0 for no limit).");
100        }
101
102        unsigned int statisticsRefreshCycle_;
103        unsigned int statisticsAvgLength_;
104        unsigned int fpsLimit_;
105    };
106
107
108    /**
109    @brief
110        Non-initialising constructor.
111    */
112    Game::Game(const std::string& cmdLine)
113        // Destroy factories before the Core!
114        : gsFactoryDestroyer_(Game::GameStateFactory::factories_s, &std::map<std::string, shared_ptr<GameStateFactory> >::clear)
115    {
116        this->bAbort_ = false;
117        bChangingState_ = false;
118
119#ifdef ORXONOX_PLATFORM_WINDOWS
120        minimumSleepTime_ = 1000/*us*/;
121#else
122        minimumSleepTime_ = 0/*us*/;
123#endif
124
125        // Create an empty root state
126        this->declareGameState<GameState>("GameState", "emptyRootGameState", true, false);
127
128        // Set up a basic clock to keep time
129        this->gameClock_.reset(new Clock());
130
131        // Create the Core
132        this->core_.reset(new Core(cmdLine));
133
134        // After the core has been created, we can safely instantiate the GameStates that don't require graphics
135        for (std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.begin();
136            it != gameStateDeclarations_s.end(); ++it)
137        {
138            if (!it->second.bGraphicsMode)
139                constructedStates_[it->second.stateName] = GameStateFactory::fabricate(it->second);
140        }
141
142        // The empty root state is ALWAYS loaded!
143        this->rootStateNode_ = shared_ptr<GameStateTreeNode>(new GameStateTreeNode());
144        this->rootStateNode_->name_ = "emptyRootGameState";
145        this->loadedTopStateNode_ = this->rootStateNode_;
146        this->loadedStates_.push_back(this->getState(rootStateNode_->name_));
147
148        // Do this after the Core creation!
149        this->configuration_.reset(new GameConfiguration());
150    }
151
152    /**
153    @brief
154        All destruction code is handled by scoped_ptrs and SimpleScopeGuards.
155    */
156    Game::~Game()
157    {
158    }
159
160    /**
161    @brief
162        Main loop of the orxonox game.
163    @note
164        We use the Ogre::Timer to measure time since it uses the most precise
165        method an any platform (however the windows timer lacks time when under
166        heavy kernel load!).
167    */
168    void Game::run()
169    {
170        if (this->requestedStateNodes_.empty())
171            COUT(0) << "Warning: Starting game without requesting GameState. This automatically terminates the program." << std::endl;
172
173        // reset statistics
174        this->statisticsStartTime_ = 0;
175        this->statisticsTickTimes_.clear();
176        this->periodTickTime_ = 0;
177        this->periodTime_ = 0;
178        this->avgFPS_ = 0.0f;
179        this->avgTickTime_ = 0.0f;
180        this->excessSleepTime_ = 0;
181
182        // START GAME
183        // first delta time should be about 0 seconds
184        this->gameClock_->capture();
185        // A first item is required for the fps limiter
186        StatisticsTickInfo tickInfo = {0, 0};
187        statisticsTickTimes_.push_back(tickInfo);
188        while (!this->bAbort_ && (!this->loadedStates_.empty() || this->requestedStateNodes_.size() > 0))
189        {
190            // Generate the dt
191            this->gameClock_->capture();
192
193            // Statistics init
194            StatisticsTickInfo tickInfo = {gameClock_->getMicroseconds(), 0};
195            statisticsTickTimes_.push_back(tickInfo);
196            this->periodTime_ += this->gameClock_->getDeltaTimeMicroseconds();
197
198            // Update the GameState stack if required
199            this->updateGameStateStack();
200
201            // Core preUpdate (doesn't throw)
202            try
203                { this->core_->preUpdate(*this->gameClock_); }
204            catch (...)
205            {
206                COUT(0) << "An exception occurred in the Core preUpdate: " << Game::getExceptionMessage() << std::endl;
207                COUT(0) << "This should really never happen! Closing the program." << std::endl;
208                this->stop();
209                break;
210            }
211
212            // Update the GameStates bottom up in the stack
213            this->updateGameStates();
214
215            // Core postUpdate (doesn't throw)
216            try
217                { this->core_->postUpdate(*this->gameClock_); }
218            catch (...)
219            {
220            COUT(0) << "An exception occurred in the Core postUpdate: " << Game::getExceptionMessage() << std::endl;
221            COUT(0) << "This should really never happen! Closing the program." << std::endl;
222                this->stop();
223                break;
224            }
225
226            // Evaluate statistics
227            this->updateStatistics();
228
229            // Limit framerate
230            this->updateFPSLimiter();
231        }
232
233        // UNLOAD all remaining states
234        while (this->loadedStates_.size() > 1)
235            this->unloadState(this->loadedStates_.back()->getName());
236        this->loadedTopStateNode_ = this->rootStateNode_;
237        this->requestedStateNodes_.clear();
238    }
239
240    void Game::updateGameStateStack()
241    {
242        while (this->requestedStateNodes_.size() > 0)
243        {
244            shared_ptr<GameStateTreeNode> requestedStateNode = this->requestedStateNodes_.front();
245            assert(this->loadedTopStateNode_);
246            if (!this->loadedTopStateNode_->parent_.expired() && requestedStateNode == this->loadedTopStateNode_->parent_.lock())
247                this->unloadState(loadedTopStateNode_->name_);
248            else // has to be child
249            {
250                try
251                {
252                    this->loadState(requestedStateNode->name_);
253                }
254                catch (...)
255                {
256                    COUT(1) << "Error: Loading GameState '" << requestedStateNode->name_ << "' failed: " << Game::getExceptionMessage() << std::endl;
257                    // All scheduled operations have now been rendered inert --> flush them and issue a warning
258                    if (this->requestedStateNodes_.size() > 1)
259                        COUT(4) << "All " << this->requestedStateNodes_.size() - 1 << " scheduled transitions have been ignored." << std::endl;
260                    this->requestedStateNodes_.clear();
261                    break;
262                }
263            }
264            this->loadedTopStateNode_ = requestedStateNode;
265            this->requestedStateNodes_.erase(this->requestedStateNodes_.begin());
266        }
267    }
268
269    void Game::updateGameStates()
270    {
271        // Note: The first element is the empty root state, which doesn't need ticking
272        for (GameStateVector::const_iterator it = this->loadedStates_.begin() + 1;
273            it != this->loadedStates_.end(); ++it)
274        {
275            try
276            {
277                // Add tick time for most of the states
278                uint64_t timeBeforeTick = 0;
279                if ((*it)->getInfo().bIgnoreTickTime)
280                    timeBeforeTick = this->gameClock_->getRealMicroseconds();
281                (*it)->update(*this->gameClock_);
282                if ((*it)->getInfo().bIgnoreTickTime)
283                    this->subtractTickTime(static_cast<int32_t>(this->gameClock_->getRealMicroseconds() - timeBeforeTick));
284            }
285            catch (...)
286            {
287                COUT(1) << "An exception occurred while updating '" << (*it)->getName() << "': " << Game::getExceptionMessage() << std::endl;
288                COUT(1) << "This should really never happen!" << std::endl;
289                COUT(1) << "Unloading all GameStates depending on the one that crashed." << std::endl;
290                shared_ptr<GameStateTreeNode> current = this->loadedTopStateNode_;
291                while (current->name_ != (*it)->getName() && current)
292                    current = current->parent_.lock();
293                if (current && current->parent_.lock())
294                    this->requestState(current->parent_.lock()->name_);
295                else
296                    this->stop();
297                break;
298            }
299        }
300    }
301
302    void Game::updateStatistics()
303    {
304        // Add the tick time of this frame (rendering time has already been subtracted)
305        uint64_t currentTime = gameClock_->getMicroseconds();
306        uint64_t currentRealTime = gameClock_->getRealMicroseconds();
307        this->statisticsTickTimes_.back().tickLength += currentRealTime - currentTime;
308        this->periodTickTime_ += currentRealTime - currentTime;
309        if (this->periodTime_ > this->configuration_->statisticsRefreshCycle_)
310        {
311            std::list<StatisticsTickInfo>::iterator it = this->statisticsTickTimes_.begin();
312            assert(it != this->statisticsTickTimes_.end());
313            int64_t lastTime = currentTime - this->configuration_->statisticsAvgLength_;
314            if (static_cast<int64_t>(it->tickTime) < lastTime)
315            {
316                do
317                {
318                    assert(this->periodTickTime_ >= it->tickLength);
319                    this->periodTickTime_ -= it->tickLength;
320                    ++it;
321                    assert(it != this->statisticsTickTimes_.end());
322                } while (static_cast<int64_t>(it->tickTime) < lastTime);
323                this->statisticsTickTimes_.erase(this->statisticsTickTimes_.begin(), it);
324            }
325
326            uint32_t framesPerPeriod = this->statisticsTickTimes_.size();
327            this->avgFPS_ = static_cast<float>(framesPerPeriod) / (currentTime - this->statisticsTickTimes_.front().tickTime) * 1000000.0f;
328            this->avgTickTime_ = static_cast<float>(this->periodTickTime_) / framesPerPeriod / 1000.0f;
329
330            this->periodTime_ -= this->configuration_->statisticsRefreshCycle_;
331        }
332    }
333
334    void Game::updateFPSLimiter()
335    {
336        // Why configuration_->fpsLimit_ - 1? No idea, but otherwise the fps rate is always (from 10 to 200!) one frame too high
337        uint32_t nextTime = gameClock_->getMicroseconds() - excessSleepTime_ + static_cast<uint32_t>(1000000.0f / (configuration_->fpsLimit_ - 1));
338        uint64_t currentRealTime = gameClock_->getRealMicroseconds();
339        while (currentRealTime < nextTime - minimumSleepTime_)
340        {
341            usleep(nextTime - currentRealTime);
342            currentRealTime = gameClock_->getRealMicroseconds();
343        }
344        // Integrate excess to avoid steady state error
345        excessSleepTime_ = currentRealTime - nextTime;
346        // Anti windup
347        if (excessSleepTime_ > 50000) // 20ms is about the maximum time Windows would sleep for too long
348            excessSleepTime_ = 50000;
349    }
350
351    void Game::stop()
352    {
353        this->bAbort_ = true;
354    }
355
356    void Game::subtractTickTime(int32_t length)
357    {
358        assert(!this->statisticsTickTimes_.empty());
359        this->statisticsTickTimes_.back().tickLength -= length;
360        this->periodTickTime_ -= length;
361    }
362
363
364    /***** GameState related *****/
365
366    void Game::requestState(const std::string& name)
367    {
368        if (!this->checkState(name))
369        {
370            COUT(2) << "Warning: GameState named '" << name << "' doesn't exist!" << std::endl;
371            return;
372        }
373
374        if (this->bChangingState_)
375        {
376            COUT(2) << "Warning: Requesting GameStates while loading/unloading a GameState is illegal! Ignoring." << std::endl;
377            return;
378        }
379
380        shared_ptr<GameStateTreeNode> lastRequestedNode;
381        if (this->requestedStateNodes_.empty())
382            lastRequestedNode = this->loadedTopStateNode_;
383        else
384            lastRequestedNode = this->requestedStateNodes_.back();
385        if (name == lastRequestedNode->name_)
386        {
387            COUT(2) << "Warning: Requesting the currently active state! Ignoring." << std::endl;
388            return;
389        }
390
391        // Check children first
392        std::vector<shared_ptr<GameStateTreeNode> > requestedNodes;
393        for (unsigned int i = 0; i < lastRequestedNode->children_.size(); ++i)
394        {
395            if (lastRequestedNode->children_[i]->name_ == name)
396            {
397                requestedNodes.push_back(lastRequestedNode->children_[i]);
398                break;
399            }
400        }
401
402        if (requestedNodes.empty())
403        {
404            // Check parent and all its grand parents
405            shared_ptr<GameStateTreeNode> currentNode = lastRequestedNode;
406            while (currentNode != NULL)
407            {
408                if (currentNode->name_ == name)
409                    break;
410                currentNode = currentNode->parent_.lock();
411                requestedNodes.push_back(currentNode);
412            }
413        }
414
415        if (requestedNodes.empty())
416            COUT(1) << "Error: Requested GameState transition is not allowed. Ignoring." << std::endl;
417        else
418            this->requestedStateNodes_.insert(requestedStateNodes_.end(), requestedNodes.begin(), requestedNodes.end());
419    }
420
421    void Game::requestStates(const std::string& names)
422    {
423        SubString tokens(names, ",;", " ");
424        for (unsigned int i = 0; i < tokens.size(); ++i)
425            this->requestState(tokens[i]);
426    }
427
428    void Game::popState()
429    {
430        shared_ptr<GameStateTreeNode> lastRequestedNode;
431        if (this->requestedStateNodes_.empty())
432            lastRequestedNode = this->loadedTopStateNode_;
433        else
434            lastRequestedNode = this->requestedStateNodes_.back();
435        if (lastRequestedNode != this->rootStateNode_)
436            this->requestState(lastRequestedNode->parent_.lock()->name_);
437        else
438            COUT(2) << "Warning: Can't pop the internal dummy root GameState" << std::endl;
439    }
440
441    shared_ptr<GameState> Game::getState(const std::string& name)
442    {
443        GameStateMap::const_iterator it = constructedStates_.find(name);
444        if (it != constructedStates_.end())
445            return it->second;
446        else
447        {
448            std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.find(name);
449            if (it != gameStateDeclarations_s.end())
450                COUT(1) << "Error: GameState '" << name << "' has not yet been loaded." << std::endl;
451            else
452                COUT(1) << "Error: Could not find GameState '" << name << "'." << std::endl;
453            return shared_ptr<GameState>();
454        }
455    }
456
457    void Game::setStateHierarchy(const std::string& str)
458    {
459        // Split string into pieces of the form whitespacesText
460        std::vector<std::pair<std::string, unsigned> > stateStrings;
461        size_t pos = 0;
462        size_t startPos = 0;
463        while (pos < str.size())
464        {
465            unsigned indentation = 0;
466            while(pos < str.size() && str[pos] == ' ')
467                ++indentation, ++pos;
468            startPos = pos;
469            while(pos < str.size() && str[pos] != ' ')
470                ++pos;
471            stateStrings.push_back(std::make_pair(str.substr(startPos, pos - startPos), indentation));
472        }
473        unsigned int currentLevel = 0;
474        shared_ptr<GameStateTreeNode> currentNode = this->rootStateNode_;
475        for (std::vector<std::pair<std::string, unsigned> >::const_iterator it = stateStrings.begin(); it != stateStrings.end(); ++it)
476        {
477            std::string newStateName = it->first;
478            unsigned newLevel = it->second + 1; // empty root is 0
479            if (!this->checkState(newStateName))
480                ThrowException(GameState, "GameState with name '" << newStateName << "' not found!");
481            if (newStateName == this->rootStateNode_->name_)
482                ThrowException(GameState, "You shouldn't use 'emptyRootGameState' in the hierarchy...");
483            shared_ptr<GameStateTreeNode> newNode(new GameStateTreeNode);
484            newNode->name_ = newStateName;
485
486            if (newLevel <= currentLevel)
487            {
488                do
489                    currentNode = currentNode->parent_.lock();
490                while (newLevel <= --currentLevel);
491            }
492            if (newLevel == currentLevel + 1)
493            {
494                // Add the child
495                newNode->parent_ = currentNode;
496                currentNode->children_.push_back(newNode);
497            }
498            else
499                ThrowException(GameState, "Indentation error while parsing the hierarchy.");
500            currentNode = newNode;
501            currentLevel = newLevel;
502        }
503    }
504
505    /*** Internal ***/
506
507    void Game::loadGraphics()
508    {
509        if (!GameMode::bShowsGraphics_s)
510        {
511            core_->loadGraphics();
512            Loki::ScopeGuard graphicsUnloader = Loki::MakeObjGuard(*this, &Game::unloadGraphics);
513            GameMode::bShowsGraphics_s = true;
514
515            // Construct all the GameStates that require graphics
516            for (std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.begin();
517                it != gameStateDeclarations_s.end(); ++it)
518            {
519                if (it->second.bGraphicsMode)
520                {
521                    // Game state loading failure is serious --> don't catch
522                    shared_ptr<GameState> gameState = GameStateFactory::fabricate(it->second);
523                    if (!constructedStates_.insert(std::make_pair(
524                        it->second.stateName, gameState)).second)
525                        assert(false); // GameState was already created!
526                }
527            }
528            graphicsUnloader.Dismiss();
529        }
530    }
531
532    void Game::unloadGraphics()
533    {
534        if (GameMode::bShowsGraphics_s)
535        {
536            // Destroy all the GameStates that require graphics
537            for (GameStateMap::iterator it = constructedStates_.begin(); it != constructedStates_.end();)
538            {
539                if (it->second->getInfo().bGraphicsMode)
540                    constructedStates_.erase(it++);
541                else
542                    ++it;
543            }
544
545            core_->unloadGraphics();
546            GameMode::bShowsGraphics_s = false;
547        }
548    }
549
550    bool Game::checkState(const std::string& name) const
551    {
552        std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.find(name);
553        if (it == gameStateDeclarations_s.end())
554            return false;
555        else
556            return true;
557    }
558
559    void Game::loadState(const std::string& name)
560    {
561        this->bChangingState_ = true;
562        LOKI_ON_BLOCK_EXIT_OBJ(*this, &Game::resetChangingState);
563
564        // If state requires graphics, load it
565        Loki::ScopeGuard graphicsUnloader = Loki::MakeObjGuard(*this, &Game::unloadGraphics);
566        if (gameStateDeclarations_s[name].bGraphicsMode && !GameMode::showsGraphics())
567            this->loadGraphics();
568        else
569            graphicsUnloader.Dismiss();
570
571        shared_ptr<GameState> state = this->getState(name);
572        state->activate();
573        if (!this->loadedStates_.empty())
574            this->loadedStates_.back()->activity_.topState = false;
575        this->loadedStates_.push_back(state);
576        state->activity_.topState = true;
577
578        graphicsUnloader.Dismiss();
579    }
580
581    void Game::unloadState(const std::string& name)
582    {
583        this->bChangingState_ = true;
584        try
585        {
586            shared_ptr<GameState> state = this->getState(name);
587            state->activity_.topState = false;
588            this->loadedStates_.pop_back();
589            if (!this->loadedStates_.empty())
590                this->loadedStates_.back()->activity_.topState = true;
591            state->deactivate();
592        }
593        catch (...)
594        {
595            COUT(2) << "Warning: Unloading GameState '" << name << "' threw an exception: " << Game::getExceptionMessage() << std::endl;
596            COUT(2) << "         There might be potential resource leaks involved! To avoid this, improve exception-safety." << std::endl;
597        }
598        // Check if graphics is still required
599        if (!bAbort_)
600        {
601            bool graphicsRequired = false;
602            for (unsigned i = 0; i < loadedStates_.size(); ++i)
603                graphicsRequired |= loadedStates_[i]->getInfo().bGraphicsMode;
604            if (!graphicsRequired)
605                this->unloadGraphics();
606        }
607        this->bChangingState_ = false;
608    }
609
610    /*static*/ std::string Game::getExceptionMessage()
611    {
612        std::string exceptionMessage;
613        try
614        {
615            // rethrow
616            throw;
617        }
618        catch (const std::exception& ex)
619        {
620            return ex.what();
621        }
622        catch (const CEGUI::Exception& ex)
623        {
624#if CEGUI_VERSION_MAJOR == 0 && CEGUI_VERSION_MINOR < 6
625            return GeneralException(ex.getMessage().c_str()).getDescription();
626#else
627            return GeneralException(ex.getMessage().c_str(), ex.getLine(),
628                ex.getFileName().c_str(), ex.getName().c_str()).getDescription();
629#endif
630        }
631        catch (...)
632        {
633            return "Unknown exception";
634        }
635    }
636
637    std::map<std::string, shared_ptr<Game::GameStateFactory> > Game::GameStateFactory::factories_s;
638
639    /*static*/ shared_ptr<GameState> Game::GameStateFactory::fabricate(const GameStateInfo& info)
640    {
641        std::map<std::string, shared_ptr<Game::GameStateFactory> >::const_iterator it = factories_s.find(info.className);
642        assert(it != factories_s.end());
643        return it->second->fabricateInternal(info);
644    }
645}
Note: See TracBrowser for help on using the repository browser.