Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/archive/tutorialHS09/src/libraries/core/Game.cc @ 12373

Last change on this file since 12373 was 5747, checked in by rgrieder, 15 years ago

Added Exception::handleMessage() (copy from Game::getExceptionMessage) function that returns the exception message (if retrievable) when catching with "…"
and adjusted some exception handlers.

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