Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/libraries/core/Game.cc @ 11851

Last change on this file since 11851 was 11071, checked in by landauf, 9 years ago

merged branch cpp11_v3 back to trunk

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