Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 10768 was 10624, checked in by landauf, 9 years ago

merged branch core7 back to trunk

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