Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: sandbox/src/libraries/core/Game.cc @ 5788

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

Applied changes to the real sandbox this time.

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