Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/core4/src/core/Game.cc @ 5649

Last change on this file since 5649 was 3278, checked in by rgrieder, 15 years ago

Bugfix: When requesting a game that that wasn't child or parent but grad parent the unloading didn't work properly.

  • Property svn:eol-style set to native
File size: 18.7 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
40#include "util/Debug.h"
41#include "util/Exception.h"
42#include "util/SubString.h"
43#include "Clock.h"
44#include "CommandLine.h"
45#include "ConsoleCommand.h"
46#include "Core.h"
47#include "CoreIncludes.h"
48#include "ConfigValueIncludes.h"
49#include "GameState.h"
50
51namespace orxonox
52{
53    using boost::shared_ptr;
54    using boost::weak_ptr;
55
56    static void stop_game()
57        { Game::getInstance().stop(); }
58    SetConsoleCommandShortcutExternAlias(stop_game, "exit");
59
60    std::map<std::string, Game::GameStateInfo> Game::gameStateDeclarations_s;
61    Game* Game::singletonRef_s = 0;
62
63
64    /**
65    @brief
66        Represents one node of the game state tree.
67    */
68    struct GameStateTreeNode
69    {
70        GameState* state_;
71        weak_ptr<GameStateTreeNode> parent_;
72        std::vector<shared_ptr<GameStateTreeNode> > children_;
73    };
74
75
76    /**
77    @brief
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.");
97        }
98
99        unsigned int statisticsRefreshCycle_;
100        unsigned int statisticsAvgLength_;
101    };
102
103
104    /**
105    @brief
106        Non-initialising constructor.
107    */
108    Game::Game(int argc, char** argv)
109    {
110        if (singletonRef_s != 0)
111        {
112            COUT(0) << "Error: The Game singleton cannot be recreated! Shutting down." << std::endl;
113            abort();
114        }
115        singletonRef_s = this;
116
117        this->bAbort_ = false;
118        bChangingState_ = false;
119
120        // Create an empty root state
121        declareGameState<GameState>("GameState", "emptyRootGameState", true, false);
122
123        // reset statistics
124        this->statisticsStartTime_ = 0;
125        this->statisticsTickTimes_.clear();
126        this->periodTickTime_ = 0;
127        this->periodTime_ = 0;
128        this->avgFPS_ = 0.0f;
129        this->avgTickTime_ = 0.0f;
130
131        // Set up a basic clock to keep time
132        this->gameClock_ = new Clock();
133
134        // Create the Core
135        this->core_ = new Core(argc, argv);
136
137        // After the core has been created, we can safely instantiate the GameStates
138        for (std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.begin();
139            it != gameStateDeclarations_s.end(); ++it)
140        {
141            // Only create the states appropriate for the game mode
142            //if (GameMode::showsGraphics || !it->second.bGraphicsMode)
143            GameStateConstrParams params = { it->second.stateName, it->second.bIgnoreTickTime };
144            gameStates_[getLowercase(it->second.stateName)] = GameStateFactory::fabricate(it->second.className, params);
145        }
146
147        // The empty root state is ALWAYS loaded!
148        this->rootStateNode_ = shared_ptr<GameStateTreeNode>(new GameStateTreeNode());
149        this->rootStateNode_->state_ = getState("emptyRootGameState");
150        this->activeStateNode_ = this->rootStateNode_;
151        this->activeStates_.push_back(this->rootStateNode_->state_);
152
153        // Do this after the Core creation!
154        this->configuration_ = new GameConfiguration();
155    }
156
157    /**
158    @brief
159    */
160    Game::~Game()
161    {
162        // Destroy the configuration helper class instance
163        delete this->configuration_;
164
165        // Destroy the GameStates (note that the nodes still point to them, but doesn't matter)
166        for (std::map<std::string, GameState*>::const_iterator it = gameStates_.begin();
167            it != gameStates_.end(); ++it)
168            delete it->second;
169
170        // Destroy the Core and with it almost everything
171        delete this->core_;
172        delete this->gameClock_;
173
174        // Take care of the GameStateFactories
175        GameStateFactory::destroyFactories();
176
177        // Don't assign singletonRef_s with NULL! Recreation is not supported
178    }
179
180    /**
181    @brief
182        Main loop of the orxonox game.
183    @note
184        We use the Ogre::Timer to measure time since it uses the most precise
185        method an any platform (however the windows timer lacks time when under
186        heavy kernel load!).
187    */
188    void Game::run()
189    {
190        if (this->requestedStateNodes_.empty())
191            COUT(0) << "Warning: Starting game without requesting GameState. This automatically terminates the program." << std::endl;
192
193        // START GAME
194        this->gameClock_->capture(); // first delta time should be about 0 seconds
195        while (!this->bAbort_ && (!this->activeStates_.empty() || this->requestedStateNodes_.size() > 0))
196        {
197            this->gameClock_->capture();
198            uint64_t currentTime = this->gameClock_->getMicroseconds();
199
200            // STATISTICS
201            StatisticsTickInfo tickInfo = {currentTime, 0};
202            statisticsTickTimes_.push_back(tickInfo);
203            this->periodTime_ += this->gameClock_->getDeltaTimeMicroseconds();
204
205            // UPDATE STATE STACK
206            while (this->requestedStateNodes_.size() > 0)
207            {
208                shared_ptr<GameStateTreeNode> requestedStateNode = this->requestedStateNodes_.front();
209                assert(this->activeStateNode_);
210                if (!this->activeStateNode_->parent_.expired() && requestedStateNode == this->activeStateNode_->parent_.lock())
211                    this->unloadState(this->activeStateNode_->state_);
212                else // has to be child
213                {
214                    try
215                    {
216                        this->loadState(requestedStateNode->state_);
217                    }
218                    catch (const std::exception& ex)
219                    {
220                        COUT(1) << "Error: Loading GameState '" << requestedStateNode->state_->getName() << "' failed: " << ex.what() << std::endl;
221                        // All scheduled operations have now been rendered inert --> flush them and issue a warning
222                        if (this->requestedStateNodes_.size() > 1)
223                            COUT(1) << "All " << this->requestedStateNodes_.size() - 1 << " scheduled transitions have been ignored." << std::endl;
224                        this->requestedStateNodes_.clear();
225                        break;
226                    }
227                }
228                this->activeStateNode_ = requestedStateNode;
229                this->requestedStateNodes_.erase(this->requestedStateNodes_.begin());
230            }
231
232            // UPDATE, Core first
233            try
234            {
235                this->core_->update(*this->gameClock_);
236            }
237            catch (...)
238            {
239                COUT(0) << "An exception occured while ticking the Core. This should really never happen!" << std::endl;
240                COUT(0) << "Closing the program." << std::endl;
241                this->stop();
242                break;
243            }
244
245            // UPDATE, GameStates bottom to top in the stack
246            // Note: The first element is the empty root state, which doesn't need ticking
247            for (std::vector<GameState*>::const_iterator it = this->activeStates_.begin() + 1;
248                it != this->activeStates_.end(); ++it)
249            {
250                bool threwException = false;
251                try
252                {
253                    // Add tick time for most of the states
254                    uint64_t timeBeforeTick;
255                    if (!(*it)->ignoreTickTime())
256                        timeBeforeTick = this->gameClock_->getRealMicroseconds();
257                    (*it)->update(*this->gameClock_);
258                    if (!(*it)->ignoreTickTime())
259                        this->addTickTime(static_cast<uint32_t>(this->gameClock_->getRealMicroseconds() - timeBeforeTick));
260                }
261                catch (const std::exception& ex)
262                {
263                    threwException = true;
264                    COUT(0) << "Exception while ticking: " << ex.what() << std::endl;
265                }
266                catch (...)
267                {
268                    threwException = true;
269                }
270                if (threwException)
271                {
272                    COUT(1) << "An exception occured while ticking GameState '" << (*it)->getName() << "'. This should really never happen!" << std::endl;
273                    COUT(1) << "Unloading all GameStates depending on the one that crashed." << std::endl;
274                    if ((*it)->getParent() != NULL)
275                        this->requestState((*it)->getParent()->getName());
276                    else
277                        this->stop();
278                    break;
279                }
280
281            }
282
283            // STATISTICS
284            if (this->periodTime_ > this->configuration_->statisticsRefreshCycle_)
285            {
286                std::list<StatisticsTickInfo>::iterator it = this->statisticsTickTimes_.begin();
287                assert(it != this->statisticsTickTimes_.end());
288                int64_t lastTime = currentTime - this->configuration_->statisticsAvgLength_;
289                if ((int64_t)it->tickTime < lastTime)
290                {
291                    do
292                    {
293                        assert(this->periodTickTime_ >= it->tickLength);
294                        this->periodTickTime_ -= it->tickLength;
295                        ++it;
296                        assert(it != this->statisticsTickTimes_.end());
297                    } while ((int64_t)it->tickTime < lastTime);
298                    this->statisticsTickTimes_.erase(this->statisticsTickTimes_.begin(), it);
299                }
300
301                uint32_t framesPerPeriod = this->statisticsTickTimes_.size();
302                this->avgFPS_ = static_cast<float>(framesPerPeriod) / (currentTime - this->statisticsTickTimes_.front().tickTime) * 1000000.0f;
303                this->avgTickTime_ = static_cast<float>(this->periodTickTime_) / framesPerPeriod / 1000.0f;
304
305                this->periodTime_ -= this->configuration_->statisticsRefreshCycle_;
306            }
307        }
308
309        // UNLOAD all remaining states
310        while (this->activeStates_.size() > 1)
311            this->unloadState(this->activeStates_.back());
312        this->activeStateNode_ = this->rootStateNode_;
313        this->requestedStateNodes_.clear();
314    }
315
316    void Game::stop()
317    {
318        this->bAbort_ = true;
319    }
320
321    void Game::addTickTime(uint32_t length)
322    {
323        assert(!this->statisticsTickTimes_.empty());
324        this->statisticsTickTimes_.back().tickLength += length;
325        this->periodTickTime_+=length;
326    }
327
328
329    /***** GameState related *****/
330
331    void Game::requestState(const std::string& name)
332    {
333        GameState* state = this->getState(name);
334        if (state == NULL)
335            return;
336
337        //if (this->bChangingState_)
338        //{
339        //    COUT(2) << "Warning: Requesting GameStates while loading/unloading a GameState is illegal! Ignoring." << std::endl;
340        //    return;
341        //}
342
343        shared_ptr<GameStateTreeNode> lastRequestedNode;
344        if (this->requestedStateNodes_.empty())
345            lastRequestedNode = this->activeStateNode_;
346        else
347            lastRequestedNode = this->requestedStateNodes_.back();
348        if (state == lastRequestedNode->state_)
349        {
350            COUT(2) << "Warning: Requesting the currently active state! Ignoring." << std::endl;
351            return;
352        }
353
354        // Check children first
355        std::vector<shared_ptr<GameStateTreeNode> > requestedNodes;
356        for (unsigned int i = 0; i < lastRequestedNode->children_.size(); ++i)
357        {
358            if (lastRequestedNode->children_[i]->state_ == state)
359            {
360                requestedNodes.push_back(lastRequestedNode->children_[i]);
361                break;
362            }
363        }
364
365        if (requestedNodes.empty())
366        {
367            // Check parent and all its grand parents
368            shared_ptr<GameStateTreeNode> currentNode = lastRequestedNode;
369            while (currentNode != NULL)
370            {
371                if (currentNode->state_ == state)
372                    break;
373                currentNode = currentNode->parent_.lock();
374                requestedNodes.push_back(currentNode);
375            }
376        }
377
378        if (requestedNodes.empty())
379            COUT(1) << "Error: Requested GameState transition is not allowed. Ignoring." << std::endl;
380        else
381            this->requestedStateNodes_.insert(requestedStateNodes_.end(), requestedNodes.begin(), requestedNodes.end());
382    }
383
384    void Game::requestStates(const std::string& names)
385    {
386        SubString tokens(names, ",;", " ");
387        for (unsigned int i = 0; i < tokens.size(); ++i)
388            this->requestState(tokens[i]);
389    }
390
391    void Game::popState()
392    {
393        shared_ptr<GameStateTreeNode> lastRequestedNode;
394        if (this->requestedStateNodes_.empty())
395            lastRequestedNode = this->activeStateNode_;
396        else
397            lastRequestedNode = this->requestedStateNodes_.back();
398        if (lastRequestedNode != this->rootStateNode_)
399            this->requestState(lastRequestedNode->parent_.lock()->state_->getName());
400        else
401            COUT(2) << "Warning: Can't pop the internal dummy root GameState" << std::endl;
402    }
403
404    GameState* Game::getState(const std::string& name)
405    {
406        std::map<std::string, GameState*>::const_iterator it = gameStates_.find(getLowercase(name));
407        if (it != gameStates_.end())
408            return it->second;
409        else
410        {
411            COUT(1) << "Error: Could not find GameState '" << name << "'. Ignoring." << std::endl;
412            return 0;
413        }
414    }
415
416    void Game::setStateHierarchy(const std::string& str)
417    {
418        // Split string into pieces of the form whitespacesText
419        std::vector<std::pair<std::string, unsigned> > stateStrings;
420        size_t pos = 0;
421        size_t startPos = 0;
422        while (pos < str.size())
423        {
424            unsigned indentation = 0;
425            while(pos < str.size() && str[pos] == ' ')
426                ++indentation, ++pos;
427            startPos = pos;
428            while(pos < str.size() && str[pos] != ' ')
429                ++pos;
430            stateStrings.push_back(std::make_pair(str.substr(startPos, pos - startPos), indentation));
431        }
432        unsigned int currentLevel = 0;
433        shared_ptr<GameStateTreeNode> currentNode = this->rootStateNode_;
434        for (std::vector<std::pair<std::string, unsigned> >::const_iterator it = stateStrings.begin(); it != stateStrings.end(); ++it)
435        {
436            std::string newStateName = it->first;
437            unsigned newLevel = it->second + 1; // empty root is 0
438            GameState* newState = this->getState(newStateName);
439            if (!newState)
440                ThrowException(GameState, "GameState with name '" << newStateName << "' not found!");
441            if (newState == this->rootStateNode_->state_)
442                ThrowException(GameState, "You shouldn't use 'emptyRootGameState' in the hierarchy...");
443            shared_ptr<GameStateTreeNode> newNode(new GameStateTreeNode);
444            newNode->state_ = newState;
445
446            if (newLevel <= currentLevel)
447            {
448                do
449                    currentNode = currentNode->parent_.lock();
450                while (newLevel <= --currentLevel);
451            }
452            if (newLevel == currentLevel + 1)
453            {
454                // Add the child
455                newNode->parent_ = currentNode;
456                currentNode->children_.push_back(newNode);
457                currentNode->state_->addChild(newNode->state_);
458            }
459            else
460                ThrowException(GameState, "Indentation error while parsing the hierarchy.");
461            currentNode = newNode;
462            currentLevel = newLevel;
463        }
464    }
465
466    /*** Internal ***/
467
468    void Game::loadState(GameState* state)
469    {
470        this->bChangingState_ = true;
471        state->activate();
472        if (!this->activeStates_.empty())
473            this->activeStates_.back()->activity_.topState = false;
474        this->activeStates_.push_back(state);
475        state->activity_.topState = true;
476        this->bChangingState_ = false;
477    }
478
479    void Game::unloadState(orxonox::GameState* state)
480    {
481        this->bChangingState_ = true;
482        state->activity_.topState = false;
483        this->activeStates_.pop_back();
484        if (!this->activeStates_.empty())
485            this->activeStates_.back()->activity_.topState = true;
486        try
487        {
488            state->deactivate();
489        }
490        catch (const std::exception& ex)
491        {
492            COUT(2) << "Warning: Unloading GameState '" << state->getName() << "' threw an exception: " << ex.what() << std::endl;
493            COUT(2) << "         There might be potential resource leaks involved! To avoid this, improve exception-safety." << std::endl;
494        }
495        this->bChangingState_ = false;
496    }
497
498    std::map<std::string, Game::GameStateFactory*> Game::GameStateFactory::factories_s;
499
500    /*static*/ GameState* Game::GameStateFactory::fabricate(const std::string& className, const GameStateConstrParams& params)
501    {
502        std::map<std::string, GameStateFactory*>::const_iterator it = factories_s.find(className);
503        assert(it != factories_s.end());
504        return it->second->fabricate(params);
505    }
506
507    /*static*/ void Game::GameStateFactory::destroyFactories()
508    {
509        for (std::map<std::string, GameStateFactory*>::const_iterator it = factories_s.begin(); it != factories_s.end(); ++it)
510            delete it->second;
511        factories_s.clear();
512    }
513}
Note: See TracBrowser for help on using the repository browser.