Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/resource2/src/core/Game.cc @ 5654

Last change on this file since 5654 was 5651, checked in by rgrieder, 15 years ago

Added using declaration for boost::shared_ptr, weak_ptr and scoped_ptr to OrxonoxConfig.h

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