Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/core/Game.cc @ 2932

Last change on this file since 2932 was 2927, checked in by rgrieder, 16 years ago

Fixed three memory leaks and a bug.
@beni: Is deleting the "startGame" console command a problem or did we just forget to remove the comment characters?

  • Property svn:eol-style set to native
File size: 13.6 KB
RevLine 
[2805]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 <cassert>
39
40#include "util/Debug.h"
41#include "util/Exception.h"
[2850]42#include "util/SubString.h"
[2844]43#include "Clock.h"
44#include "CommandLine.h"
45#include "ConsoleCommand.h"
46#include "Core.h"
47#include "CoreIncludes.h"
48#include "ConfigValueIncludes.h"
49#include "GameState.h"
[2805]50
51namespace orxonox
52{
[2845]53    static void stop_game()
54        { Game::getInstance().stop(); }
55    SetConsoleCommandShortcutExternAlias(stop_game, "exit");
[2805]56
[2844]57    struct _CoreExport GameStateTreeNode
58    {
59        GameState*                      state_;
60        GameStateTreeNode*              parent_;
61        std::vector<GameStateTreeNode*> children_;
62    };
63
64    std::map<std::string, GameState*> Game::allStates_s;
[2805]65    Game* Game::singletonRef_s = 0;
66
67    /**
68    @brief
69        Non-initialising constructor.
70    */
71    Game::Game(int argc, char** argv)
72    {
73        assert(singletonRef_s == 0);
74        singletonRef_s = this;
75
[2844]76        this->rootStateNode_ = 0;
77        this->activeStateNode_ = 0;
78
[2805]79        this->abort_ = false;
80
[2817]81        // reset statistics
82        this->statisticsStartTime_ = 0;
83        this->statisticsTickTimes_.clear();
84        this->periodTickTime_ = 0;
85        this->periodTime_ = 0;
86        this->avgFPS_ = 0.0f;
87        this->avgTickTime_ = 0.0f;
88
[2846]89
90        // Set up a basic clock to keep time
91        this->gameClock_ = new Clock();
92
[2807]93        this->core_ = new orxonox::Core();
[2846]94        this->core_->initialise(argc, argv);
[2817]95
96        RegisterRootObject(Game);
97        this->setConfigValues();
[2805]98    }
99
100    /**
101    @brief
102    */
103    Game::~Game()
104    {
105        // Destroy pretty much everyhting left
106        delete this->core_;
107
[2927]108        // Delete all the created nodes
109        for (std::vector<GameStateTreeNode*>::const_iterator it = this->allStateNodes_.begin(); it != this->allStateNodes_.end(); ++it)
110            delete *it;
[2844]111
[2846]112        delete this->gameClock_;
113
[2805]114        assert(singletonRef_s);
115        singletonRef_s = 0;
116    }
117
[2817]118    void Game::setConfigValues()
119    {
120        SetConfigValue(statisticsRefreshCycle_, 250000)
121            .description("Sets the time in microseconds interval at which average fps, etc. get updated.");
122        SetConfigValue(statisticsAvgLength_, 1000000)
123            .description("Sets the time in microseconds interval at which average fps, etc. gets calculated.");
124    }
125
[2805]126    /**
127    @brief
128        Main loop of the orxonox game.
129    @note
130        We use the Ogre::Timer to measure time since it uses the most precise
131        method an any platform (however the windows timer lacks time when under
132        heavy kernel load!).
133    */
134    void Game::run()
135    {
[2845]136        // Always start with the ROOT state
[2844]137        this->requestedStateNodes_.push_back(this->rootStateNode_);
138        this->activeStateNode_ = this->rootStateNode_;
139        this->loadState(this->rootStateNode_->state_);
[2805]140
[2845]141        // START GAME
[2817]142        this->gameClock_->capture(); // first delta time should be about 0 seconds
[2844]143        while (!this->abort_ && !this->activeStates_.empty())
[2805]144        {
[2807]145            this->gameClock_->capture();
[2817]146            uint64_t currentTime = this->gameClock_->getMicroseconds();
[2805]147
[2817]148            // STATISTICS
149            statisticsTickInfo tickInfo = {currentTime, 0};
150            statisticsTickTimes_.push_back(tickInfo);
151            this->periodTime_ += this->gameClock_->getDeltaTimeMicroseconds();
152
[2844]153            // UPDATE STATE STACK
154            while (this->requestedStateNodes_.size() > 1)
155            {
156                // Note: this->requestedStateNodes_.front() is the currently active state node
157                std::vector<GameStateTreeNode*>::iterator it = this->requestedStateNodes_.begin() + 1;
158                if (*it == this->activeStateNode_->parent_)
159                    this->unloadState(this->activeStateNode_->state_);
160                else // has to be child
161                    this->loadState((*it)->state_);
162                this->activeStateNode_ = *it;
163                this->requestedStateNodes_.erase(this->requestedStateNodes_.begin());
164            }
[2805]165
[2844]166            // UPDATE, bottom to top in the stack
[2846]167            this->core_->update(*this->gameClock_);
[2844]168            for (std::vector<GameState*>::const_iterator it = this->activeStates_.begin();
169                it != this->activeStates_.end(); ++it)
170                (*it)->update(*this->gameClock_);
171
[2817]172            // STATISTICS
173            if (this->periodTime_ > statisticsRefreshCycle_)
174            {
175                std::list<statisticsTickInfo>::iterator it = this->statisticsTickTimes_.begin();
176                assert(it != this->statisticsTickTimes_.end());
177                int64_t lastTime = currentTime - this->statisticsAvgLength_;
178                if ((int64_t)it->tickTime < lastTime)
179                {
180                    do
181                    {
182                        assert(this->periodTickTime_ > it->tickLength);
183                        this->periodTickTime_ -= it->tickLength;
184                        ++it;
185                        assert(it != this->statisticsTickTimes_.end());
186                    } while ((int64_t)it->tickTime < lastTime);
187                    this->statisticsTickTimes_.erase(this->statisticsTickTimes_.begin(), it);
188                }
189
190                uint32_t framesPerPeriod = this->statisticsTickTimes_.size();
191                this->avgFPS_ = (float)framesPerPeriod / (currentTime - this->statisticsTickTimes_.front().tickTime) * 1000000.0;
192                this->avgTickTime_ = (float)this->periodTickTime_ / framesPerPeriod / 1000.0;
193
194                this->periodTime_ -= this->statisticsRefreshCycle_;
195            }
[2805]196        }
197
[2845]198        // UNLOAD all remaining states
[2844]199        while (!this->activeStates_.empty())
200            this->unloadState(this->activeStates_.back());
201        this->activeStateNode_ = 0;
202        this->requestedStateNodes_.clear();
[2805]203    }
204
205    void Game::stop()
206    {
207        this->abort_ = true;
208    }
[2817]209
210    void Game::addTickTime(uint32_t length)
211    {
212        assert(!this->statisticsTickTimes_.empty());
213        this->statisticsTickTimes_.back().tickLength += length;
214        this->periodTickTime_+=length;
215    }
[2844]216
217
218    /***** GameState related *****/
219
220    void Game::requestState(const std::string& name)
221    {
222        GameState* state = this->getState(name);
223        if (state == NULL || this->activeStateNode_ == NULL)
224            return;
225
226        GameStateTreeNode* requestedNode = 0;
227
228        // this->requestedStateNodes_.back() is the currently active state
229        GameStateTreeNode* lastRequestedNode = this->requestedStateNodes_.back();
230
231        // Already the active node?
232        if (state == lastRequestedNode->state_)
233        {
234            COUT(2) << "Warning: Requesting the currently active state! Ignoring." << std::endl;
235            return;
236        }
237
238        // Check children first
239        for (unsigned int i = 0; i < lastRequestedNode->children_.size(); ++i)
240        {
241            if (lastRequestedNode->children_[i]->state_ == state)
242            {
243                requestedNode = lastRequestedNode->children_[i];
244                break;
245            }
246        }
247
248        // Check parent and all its grand parents
249        GameStateTreeNode* currentNode = lastRequestedNode;
[2850]250        while (requestedNode == NULL && currentNode != NULL)
[2844]251        {
252            if (currentNode->state_ == state)
253                requestedNode = currentNode;
254            currentNode = currentNode->parent_;
255        }
256
257        if (requestedNode == NULL)
258            COUT(1) << "Error: Requested GameState transition is not allowed. Ignoring." << std::endl;
259        else
260            this->requestedStateNodes_.push_back(requestedNode);
261    }
262
[2850]263    void Game::requestStates(const std::string& names)
264    {
265        SubString tokens(names, ",;", " ");
266        for (unsigned int i = 0; i < tokens.size(); ++i)
267            this->requestState(tokens[i]);
268    }
269
[2844]270    void Game::popState()
271    {
272        if (this->activeStateNode_ != NULL && this->requestedStateNodes_.back()->parent_)
273            this->requestState(this->requestedStateNodes_.back()->parent_->state_->getName());
274        else
275            COUT(2) << "Warning: Could not pop GameState. Ignoring." << std::endl;
276    }
277
278    GameState* Game::getState(const std::string& name)
279    {
[2850]280        std::map<std::string, GameState*>::const_iterator it = allStates_s.find(getLowercase(name));
[2844]281        if (it != allStates_s.end())
282            return it->second;
283        else
284        {
285            COUT(1) << "Error: Could not find GameState '" << name << "'. Ignoring." << std::endl;
286            return 0;
287        }
288    }
289
290    void Game::setStateHierarchy(const std::string& str)
291    {
292        // Split string into pieces of the form whitespacesText
293        std::vector<std::pair<std::string, unsigned> > stateStrings;
294        size_t pos = 0;
295        size_t startPos = 0;
296        while (pos < str.size())
297        {
298            unsigned indentation = 0;
299            while(pos < str.size() && str[pos] == ' ')
300                ++indentation, ++pos;
301            startPos = pos;
302            while(pos < str.size() && str[pos] != ' ')
303                ++pos;
304            stateStrings.push_back(std::pair<std::string, unsigned>(
305                str.substr(startPos, pos - startPos), indentation));
306        }
307        unsigned int currentLevel = 0;
308        GameStateTreeNode* currentNode = 0;
309        for (std::vector<std::pair<std::string, unsigned> >::const_iterator it = stateStrings.begin(); it != stateStrings.end(); ++it)
310        {
311            std::string newStateName = it->first;
312            unsigned newLevel = it->second;
313            GameState* newState = this->getState(newStateName);
314            if (!newState)
315                ThrowException(GameState, std::string("GameState with name '") + newStateName + "' not found!");
316            if (newLevel == 0)
317            {
318                // root
319                if (this->rootStateNode_ != NULL)
320                    ThrowException(GameState, "No two root GameStates are allowed!");
321                GameStateTreeNode* newNode = new GameStateTreeNode;
[2927]322                this->allStateNodes_.push_back(newNode);
[2844]323                newNode->state_ = newState;
324                newNode->parent_ = 0;
325                this->rootStateNode_ = newNode;
326                currentNode = this->rootStateNode_;
327            }
328            else if (currentNode)
329            {
330                GameStateTreeNode* newNode = new GameStateTreeNode;
[2927]331                this->allStateNodes_.push_back(newNode);
[2844]332                newNode->state_ = newState;
333                if (newLevel < currentLevel)
334                {
335                    // Get down the hierarchy
336                    do
337                        currentNode = currentNode->parent_;
338                    while (newLevel < --currentLevel);
339                }
340                if (newLevel == currentLevel)
341                {
342                    // same level
343                    newNode->parent_ = currentNode->parent_;
344                    newNode->parent_->children_.push_back(newNode);
345                }
346                else if (newLevel == currentLevel + 1)
347                {
348                    // child
349                    newNode->parent_ = currentNode;
350                    currentNode->children_.push_back(newNode);
351                }
352                else
353                    ThrowException(GameState, "Indentation error while parsing the hierarchy.");
354                currentNode = newNode;
355                currentLevel = newLevel;
356            }
357            else
358            {
359                ThrowException(GameState, "No root GameState specified!");
360            }
361        }
362    }
363
364    /*** Internal ***/
365
366    void Game::loadState(GameState* state)
367    {
[2850]368        if (!this->activeStates_.empty())
369            this->activeStates_.back()->activity_.topState = false;
[2844]370        state->activate();
[2850]371        state->activity_.topState = true;
[2844]372        this->activeStates_.push_back(state);
373    }
374
375    void Game::unloadState(orxonox::GameState* state)
376    {
[2850]377        state->activity_.topState = false;
[2844]378        state->deactivate();
379        this->activeStates_.pop_back();
[2850]380        if (!this->activeStates_.empty())
381            this->activeStates_.back()->activity_.topState = true;
[2844]382    }
383
384    /*static*/ bool Game::addGameState(GameState* state)
385    {
[2850]386        std::map<std::string, GameState*>::const_iterator it = allStates_s.find(getLowercase(state->getName()));
[2844]387        if (it == allStates_s.end())
[2850]388            allStates_s[getLowercase(state->getName())] = state;
[2844]389        else
390            ThrowException(GameState, "Cannot add two GameStates with the same name to 'Game'.");
391
392        // just a required dummy return value
393        return true;
394    }
[2927]395
396    /*static*/ void Game::destroyStates()
397    {
398        // Delete all GameStates created by the macros
399        for (std::map<std::string, GameState*>::const_iterator it = allStates_s.begin(); it != allStates_s.end(); ++it)
400            delete it->second;
401        allStates_s.clear();
402    }
[2805]403}
Note: See TracBrowser for help on using the repository browser.