Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/menu/src/libraries/core/Game.cc @ 6329

Last change on this file since 6329 was 6048, checked in by scheusso, 15 years ago

ESC handling in ingame menu: if theres already an opened GUI sheet then hide it, if not open the ingame menu
in mainmenu everything should remain the same

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