Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/resource/src/core/Game.cc @ 3355

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

Loading and unloading graphics automatically: As soon as a GameState requires graphics (defined at the GameState declaration with a bool) it gets loaded. And vice versa.

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