Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

Synchronised sandbox with current code trunk. There should be a few bug fixes.

  • Property svn:eol-style set to native
File size: 21.7 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *      Reto Grieder
24 *   Co-authors:
25 *      ...
26 *
27 */
28
29/**
30@file
31@brief
32    Implementation of the Game class.
33*/
34
35#include "Game.h"
36
37#include <exception>
38#include <boost/weak_ptr.hpp>
39
40#include "util/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 "CommandLineParser.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::getFactories(), &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            if (currentNode == NULL)
407                requestedNodes.clear();
408        }
409
410        if (requestedNodes.empty())
411            COUT(1) << "Error: Requested GameState transition is not allowed. Ignoring." << std::endl;
412        else
413            this->requestedStateNodes_.insert(requestedStateNodes_.end(), requestedNodes.begin(), requestedNodes.end());
414    }
415
416    void Game::requestStates(const std::string& names)
417    {
418        SubString tokens(names, ",;", " ");
419        for (unsigned int i = 0; i < tokens.size(); ++i)
420            this->requestState(tokens[i]);
421    }
422
423    void Game::popState()
424    {
425        shared_ptr<GameStateTreeNode> lastRequestedNode;
426        if (this->requestedStateNodes_.empty())
427            lastRequestedNode = this->loadedTopStateNode_;
428        else
429            lastRequestedNode = this->requestedStateNodes_.back();
430        if (lastRequestedNode != this->rootStateNode_)
431            this->requestState(lastRequestedNode->parent_.lock()->name_);
432        else
433            COUT(2) << "Warning: Can't pop the internal dummy root GameState" << std::endl;
434    }
435
436    shared_ptr<GameState> Game::getState(const std::string& name)
437    {
438        GameStateMap::const_iterator it = constructedStates_.find(name);
439        if (it != constructedStates_.end())
440            return it->second;
441        else
442        {
443            std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.find(name);
444            if (it != gameStateDeclarations_s.end())
445                COUT(1) << "Error: GameState '" << name << "' has not yet been loaded." << std::endl;
446            else
447                COUT(1) << "Error: Could not find GameState '" << name << "'." << std::endl;
448            return shared_ptr<GameState>();
449        }
450    }
451
452    void Game::setStateHierarchy(const std::string& str)
453    {
454        // Split string into pieces of the form whitespacesText
455        std::vector<std::pair<std::string, int> > stateStrings;
456        size_t pos = 0;
457        size_t startPos = 0;
458        while (pos < str.size())
459        {
460            int indentation = 0;
461            while(pos < str.size() && str[pos] == ' ')
462                ++indentation, ++pos;
463            startPos = pos;
464            while(pos < str.size() && str[pos] != ' ')
465                ++pos;
466            stateStrings.push_back(std::make_pair(str.substr(startPos, pos - startPos), indentation));
467        }
468        if (stateStrings.empty())
469            ThrowException(GameState, "Emtpy GameState hierarchy provided, terminating.");
470        // Add element with large identation to detect the last with just an iterator
471        stateStrings.push_back(std::make_pair("", -1));
472
473        // Parse elements recursively
474        std::vector<std::pair<std::string, int> >::const_iterator begin = stateStrings.begin();
475        parseStates(begin, this->rootStateNode_);
476    }
477
478    /*** Internal ***/
479
480    void Game::parseStates(std::vector<std::pair<std::string, int> >::const_iterator& it, shared_ptr<GameStateTreeNode> currentNode)
481        {
482        SubString tokens(it->first, ",");
483        std::vector<std::pair<std::string, int> >::const_iterator startIt = it;
484
485        for (unsigned int i = 0; i < tokens.size(); ++i)
486        {
487            it = startIt; // Reset iterator to the beginning of the sub tree
488            if (!this->checkState(tokens[i]))
489                ThrowException(GameState, "GameState with name '" << tokens[i] << "' not found!");
490            if (tokens[i] == this->rootStateNode_->name_)
491                ThrowException(GameState, "You shouldn't use 'emptyRootGameState' in the hierarchy...");
492            shared_ptr<GameStateTreeNode> node(new GameStateTreeNode());
493            node->name_ = tokens[i];
494            node->parent_ = currentNode;
495            currentNode->children_.push_back(node);
496
497            int currentLevel = it->second;
498            ++it;
499            while (it->second != -1)
500            {
501                if (it->second <= currentLevel)
502                    break;
503                else if (it->second == currentLevel + 1)
504                    parseStates(it, node);
505            else
506                ThrowException(GameState, "Indentation error while parsing the hierarchy.");
507        }
508    }
509    }
510
511    void Game::loadGraphics()
512    {
513    }
514
515    void Game::unloadGraphics()
516    {
517    }
518
519    bool Game::checkState(const std::string& name) const
520    {
521        std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.find(name);
522        if (it == gameStateDeclarations_s.end())
523            return false;
524        else
525            return true;
526    }
527
528    void Game::loadState(const std::string& name)
529    {
530        this->bChangingState_ = true;
531        LOKI_ON_BLOCK_EXIT_OBJ(*this, &Game::resetChangingState);
532
533        // If state requires graphics, load it
534        Loki::ScopeGuard graphicsUnloader = Loki::MakeObjGuard(*this, &Game::unloadGraphics);
535        if (gameStateDeclarations_s[name].bGraphicsMode)
536            this->loadGraphics();
537        else
538            graphicsUnloader.Dismiss();
539
540        shared_ptr<GameState> state = this->getState(name);
541        state->activate();
542        if (!this->loadedStates_.empty())
543            this->loadedStates_.back()->activity_.topState = false;
544        this->loadedStates_.push_back(state);
545        state->activity_.topState = true;
546
547        graphicsUnloader.Dismiss();
548    }
549
550    void Game::unloadState(const std::string& name)
551    {
552        this->bChangingState_ = true;
553        try
554        {
555            shared_ptr<GameState> state = this->getState(name);
556            state->activity_.topState = false;
557            this->loadedStates_.pop_back();
558            if (!this->loadedStates_.empty())
559                this->loadedStates_.back()->activity_.topState = true;
560            state->deactivate();
561        }
562        catch (...)
563        {
564            COUT(2) << "Warning: Unloading GameState '" << name << "' threw an exception: " << Exception::handleMessage() << std::endl;
565            COUT(2) << "         There might be potential resource leaks involved! To avoid this, improve exception-safety." << std::endl;
566        }
567        // Check if graphics is still required
568        if (!bAbort_)
569        {
570            bool graphicsRequired = false;
571            for (unsigned i = 0; i < loadedStates_.size(); ++i)
572                graphicsRequired |= loadedStates_[i]->getInfo().bGraphicsMode;
573            if (!graphicsRequired)
574                this->unloadGraphics();
575        }
576        this->bChangingState_ = false;
577    }
578
579    /*static*/ std::map<std::string, shared_ptr<Game::GameStateFactory> >& Game::GameStateFactory::getFactories()
580    {
581        static std::map<std::string, shared_ptr<GameStateFactory> > factories;
582        return factories;
583    }
584
585    /*static*/ shared_ptr<GameState> Game::GameStateFactory::fabricate(const GameStateInfo& info)
586    {
587        std::map<std::string, shared_ptr<Game::GameStateFactory> >::const_iterator it = getFactories().find(info.className);
588        assert(it != getFactories().end());
589        return it->second->fabricateInternal(info);
590    }
591}
Note: See TracBrowser for help on using the repository browser.