Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/resource2/src/core/Game.cc @ 5683

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

Fixed build and a few issues and removed a warning.

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