| 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 <loki/ScopeGuard.h> |
|---|
| 39 | |
|---|
| 40 | #include "util/Clock.h" |
|---|
| 41 | #include "util/Output.h" |
|---|
| 42 | #include "util/Exception.h" |
|---|
| 43 | #include "util/Sleep.h" |
|---|
| 44 | #include "util/SubString.h" |
|---|
| 45 | #include "Core.h" |
|---|
| 46 | #include "commandline/CommandLineParser.h" |
|---|
| 47 | #include "GameConfig.h" |
|---|
| 48 | #include "GameMode.h" |
|---|
| 49 | #include "GameState.h" |
|---|
| 50 | #include "GraphicsManager.h" |
|---|
| 51 | #include "GUIManager.h" |
|---|
| 52 | #include "command/ConsoleCommandIncludes.h" |
|---|
| 53 | |
|---|
| 54 | namespace orxonox |
|---|
| 55 | { |
|---|
| 56 | static void stop_game() |
|---|
| 57 | { Game::getInstance().stop(); } |
|---|
| 58 | SetConsoleCommand("exit", &stop_game); |
|---|
| 59 | static void printFPS() |
|---|
| 60 | { orxout(message) << Game::getInstance().getAvgFPS() << endl; } |
|---|
| 61 | SetConsoleCommand("Stats", "printFPS", &printFPS); |
|---|
| 62 | static void printTickTime() |
|---|
| 63 | { orxout(message) << Game::getInstance().getAvgTickTime() << endl; } |
|---|
| 64 | SetConsoleCommand("Stats", "printTickTime", &printTickTime); |
|---|
| 65 | |
|---|
| 66 | std::map<std::string, GameStateInfo> Game::gameStateDeclarations_s; |
|---|
| 67 | Game* Game::singletonPtr_s = nullptr; |
|---|
| 68 | |
|---|
| 69 | //! Represents one node of the game state tree. |
|---|
| 70 | struct GameStateTreeNode |
|---|
| 71 | { |
|---|
| 72 | std::string name_; |
|---|
| 73 | std::weak_ptr<GameStateTreeNode> parent_; |
|---|
| 74 | std::vector<std::shared_ptr<GameStateTreeNode>> children_; |
|---|
| 75 | }; |
|---|
| 76 | |
|---|
| 77 | Game::Game(const std::string& cmdLine) |
|---|
| 78 | : gameClock_(nullptr) |
|---|
| 79 | , core_(nullptr) |
|---|
| 80 | , bChangingState_(false) |
|---|
| 81 | , bAbort_(false) |
|---|
| 82 | , config_(nullptr) |
|---|
| 83 | , destructionHelper_(this) |
|---|
| 84 | { |
|---|
| 85 | orxout(internal_status) << "initializing Game object..." << endl; |
|---|
| 86 | |
|---|
| 87 | #ifdef ORXONOX_PLATFORM_WINDOWS |
|---|
| 88 | minimumSleepTime_ = 1000/*us*/; |
|---|
| 89 | #else |
|---|
| 90 | minimumSleepTime_ = 0/*us*/; |
|---|
| 91 | #endif |
|---|
| 92 | |
|---|
| 93 | // reset statistics |
|---|
| 94 | this->statisticsStartTime_ = 0; |
|---|
| 95 | this->statisticsTickTimes_.clear(); |
|---|
| 96 | this->periodTickTime_ = 0; |
|---|
| 97 | this->periodTime_ = 0; |
|---|
| 98 | this->avgFPS_ = 0.0f; |
|---|
| 99 | this->avgTickTime_ = 0.0f; |
|---|
| 100 | this->excessSleepTime_ = 0; |
|---|
| 101 | |
|---|
| 102 | // Create an empty root state |
|---|
| 103 | this->declareGameState<GameState>("GameState", "emptyRootGameState", true, false); |
|---|
| 104 | |
|---|
| 105 | // Set up a basic clock to keep time |
|---|
| 106 | this->gameClock_ = new Clock(); |
|---|
| 107 | |
|---|
| 108 | // Create the Core |
|---|
| 109 | orxout(internal_info) << "creating Core object:" << endl; |
|---|
| 110 | this->core_ = new Core(cmdLine); |
|---|
| 111 | this->core_->loadModules(); |
|---|
| 112 | |
|---|
| 113 | // Do this after the Core creation! |
|---|
| 114 | this->config_ = new GameConfig(); |
|---|
| 115 | |
|---|
| 116 | // After the core has been created, we can safely instantiate the GameStates that don't require graphics |
|---|
| 117 | for (std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.begin(); |
|---|
| 118 | it != gameStateDeclarations_s.end(); ++it) |
|---|
| 119 | { |
|---|
| 120 | if (!it->second.bGraphicsMode) |
|---|
| 121 | constructedStates_[it->second.stateName] = GameStateFactory::fabricate(it->second); |
|---|
| 122 | } |
|---|
| 123 | |
|---|
| 124 | // The empty root state is ALWAYS loaded! |
|---|
| 125 | this->rootStateNode_ = std::shared_ptr<GameStateTreeNode>(std::make_shared<GameStateTreeNode>()); |
|---|
| 126 | this->rootStateNode_->name_ = "emptyRootGameState"; |
|---|
| 127 | this->loadedTopStateNode_ = this->rootStateNode_; |
|---|
| 128 | this->loadedStates_.push_back(this->getState(rootStateNode_->name_)); |
|---|
| 129 | |
|---|
| 130 | orxout(internal_status) << "finished initializing Game object" << endl; |
|---|
| 131 | } |
|---|
| 132 | |
|---|
| 133 | void Game::destroy() |
|---|
| 134 | { |
|---|
| 135 | orxout(internal_status) << "destroying Game object..." << endl; |
|---|
| 136 | |
|---|
| 137 | assert(loadedStates_.size() <= 1); // Just empty root GameState |
|---|
| 138 | // Destroy all GameStates (std::shared_ptrs take care of actual destruction) |
|---|
| 139 | constructedStates_.clear(); |
|---|
| 140 | |
|---|
| 141 | GameStateFactory::getFactories().clear(); |
|---|
| 142 | safeObjectDelete(&config_); |
|---|
| 143 | if (this->core_) |
|---|
| 144 | this->core_->unloadModules(); |
|---|
| 145 | safeObjectDelete(&core_); |
|---|
| 146 | safeObjectDelete(&gameClock_); |
|---|
| 147 | |
|---|
| 148 | orxout(internal_status) << "finished destroying Game object..." << endl; |
|---|
| 149 | } |
|---|
| 150 | |
|---|
| 151 | /** |
|---|
| 152 | @brief |
|---|
| 153 | Main loop of the orxonox game. |
|---|
| 154 | @note |
|---|
| 155 | We use the Ogre::Timer to measure time since it uses the most precise |
|---|
| 156 | method an any platform (however the windows timer lacks time when under |
|---|
| 157 | heavy kernel load!). |
|---|
| 158 | */ |
|---|
| 159 | void Game::run() |
|---|
| 160 | { |
|---|
| 161 | if (this->requestedStateNodes_.empty()) |
|---|
| 162 | orxout(user_error) << "Starting game without requesting GameState. This automatically terminates the program." << endl; |
|---|
| 163 | |
|---|
| 164 | // Update the GameState stack if required. We do this already here to have a properly initialized game before entering the main loop |
|---|
| 165 | this->updateGameStateStack(); |
|---|
| 166 | |
|---|
| 167 | orxout(user_status) << "Game loaded" << endl; |
|---|
| 168 | orxout(internal_status) << "-------------------- starting main loop --------------------" << endl; |
|---|
| 169 | |
|---|
| 170 | // START GAME |
|---|
| 171 | // first delta time should be about 0 seconds |
|---|
| 172 | this->gameClock_->capture(); |
|---|
| 173 | // A first item is required for the fps limiter |
|---|
| 174 | StatisticsTickInfo tickInfo = {0, 0}; |
|---|
| 175 | statisticsTickTimes_.push_back(tickInfo); |
|---|
| 176 | while (!this->bAbort_ && (!this->loadedStates_.empty() || this->requestedStateNodes_.size() > 0)) |
|---|
| 177 | { |
|---|
| 178 | // Generate the dt |
|---|
| 179 | this->gameClock_->capture(); |
|---|
| 180 | |
|---|
| 181 | // Statistics init |
|---|
| 182 | StatisticsTickInfo tickInfo = {gameClock_->getMicroseconds(), 0}; |
|---|
| 183 | statisticsTickTimes_.push_back(tickInfo); |
|---|
| 184 | this->periodTime_ += this->gameClock_->getDeltaTimeMicroseconds(); |
|---|
| 185 | |
|---|
| 186 | // Update the GameState stack if required |
|---|
| 187 | this->updateGameStateStack(); |
|---|
| 188 | |
|---|
| 189 | // Core preUpdate |
|---|
| 190 | try |
|---|
| 191 | { this->core_->preUpdate(*this->gameClock_); } |
|---|
| 192 | catch (...) |
|---|
| 193 | { |
|---|
| 194 | orxout(user_error) << "An exception occurred in the Core preUpdate: " << Exception::handleMessage() << endl; |
|---|
| 195 | orxout(user_error) << "This should really never happen! Closing the program." << endl; |
|---|
| 196 | this->stop(); |
|---|
| 197 | break; |
|---|
| 198 | } |
|---|
| 199 | |
|---|
| 200 | // Update the GameStates bottom up in the stack |
|---|
| 201 | this->updateGameStates(); |
|---|
| 202 | |
|---|
| 203 | // Core postUpdate |
|---|
| 204 | try |
|---|
| 205 | { this->core_->postUpdate(*this->gameClock_); } |
|---|
| 206 | catch (...) |
|---|
| 207 | { |
|---|
| 208 | orxout(user_error) << "An exception occurred in the Core postUpdate: " << Exception::handleMessage() << endl; |
|---|
| 209 | orxout(user_error) << "This should really never happen! Closing the program." << endl; |
|---|
| 210 | this->stop(); |
|---|
| 211 | break; |
|---|
| 212 | } |
|---|
| 213 | |
|---|
| 214 | // Evaluate statistics |
|---|
| 215 | this->updateStatistics(); |
|---|
| 216 | |
|---|
| 217 | // Limit frame rate |
|---|
| 218 | static bool hasVSync = GameMode::showsGraphics() && GraphicsManager::getInstance().hasVSyncEnabled(); // can be static since changes of VSync currently require a restart |
|---|
| 219 | if (this->config_->getFpsLimit() > 0 && !hasVSync) |
|---|
| 220 | this->updateFPSLimiter(); |
|---|
| 221 | } |
|---|
| 222 | |
|---|
| 223 | orxout(internal_status) << "-------------------- finished main loop --------------------" << endl; |
|---|
| 224 | |
|---|
| 225 | // UNLOAD all remaining states |
|---|
| 226 | while (this->loadedStates_.size() > 1) |
|---|
| 227 | this->unloadState(this->loadedStates_.back()->getName()); |
|---|
| 228 | this->loadedTopStateNode_ = this->rootStateNode_; |
|---|
| 229 | this->requestedStateNodes_.clear(); |
|---|
| 230 | } |
|---|
| 231 | |
|---|
| 232 | void Game::updateGameStateStack() |
|---|
| 233 | { |
|---|
| 234 | while (this->requestedStateNodes_.size() > 0) |
|---|
| 235 | { |
|---|
| 236 | std::shared_ptr<GameStateTreeNode> requestedStateNode = this->requestedStateNodes_.front(); |
|---|
| 237 | assert(this->loadedTopStateNode_); |
|---|
| 238 | if (!this->loadedTopStateNode_->parent_.expired() && requestedStateNode == this->loadedTopStateNode_->parent_.lock()) |
|---|
| 239 | this->unloadState(loadedTopStateNode_->name_); |
|---|
| 240 | else // has to be child |
|---|
| 241 | { |
|---|
| 242 | try |
|---|
| 243 | { |
|---|
| 244 | this->loadState(requestedStateNode->name_); |
|---|
| 245 | } |
|---|
| 246 | catch (...) |
|---|
| 247 | { |
|---|
| 248 | orxout(user_error) << "Loading GameState '" << requestedStateNode->name_ << "' failed: " << Exception::handleMessage() << endl; |
|---|
| 249 | // All scheduled operations have now been rendered inert --> flush them and issue a warning |
|---|
| 250 | if (this->requestedStateNodes_.size() > 1) |
|---|
| 251 | orxout(internal_info) << "All " << this->requestedStateNodes_.size() - 1 << " scheduled transitions have been ignored." << endl; |
|---|
| 252 | this->requestedStateNodes_.clear(); |
|---|
| 253 | break; |
|---|
| 254 | } |
|---|
| 255 | } |
|---|
| 256 | this->loadedTopStateNode_ = requestedStateNode; |
|---|
| 257 | this->requestedStateNodes_.erase(this->requestedStateNodes_.begin()); |
|---|
| 258 | } |
|---|
| 259 | } |
|---|
| 260 | |
|---|
| 261 | void Game::updateGameStates() |
|---|
| 262 | { |
|---|
| 263 | // Note: The first element is the empty root state, which doesn't need ticking |
|---|
| 264 | for (GameStateVector::const_iterator it = this->loadedStates_.begin() + 1; |
|---|
| 265 | it != this->loadedStates_.end(); ++it) |
|---|
| 266 | { |
|---|
| 267 | try |
|---|
| 268 | { |
|---|
| 269 | // Add tick time for most of the states |
|---|
| 270 | uint64_t timeBeforeTick = 0; |
|---|
| 271 | if ((*it)->getInfo().bIgnoreTickTime) |
|---|
| 272 | timeBeforeTick = this->gameClock_->getRealMicroseconds(); |
|---|
| 273 | (*it)->update(*this->gameClock_); |
|---|
| 274 | if ((*it)->getInfo().bIgnoreTickTime) |
|---|
| 275 | this->subtractTickTime(static_cast<int32_t>(this->gameClock_->getRealMicroseconds() - timeBeforeTick)); |
|---|
| 276 | } |
|---|
| 277 | catch (...) |
|---|
| 278 | { |
|---|
| 279 | orxout(user_error) << "An exception occurred while updating '" << (*it)->getName() << "': " << Exception::handleMessage() << endl; |
|---|
| 280 | orxout(user_error) << "This should really never happen!" << endl; |
|---|
| 281 | orxout(user_error) << "Unloading all GameStates depending on the one that crashed." << endl; |
|---|
| 282 | std::shared_ptr<GameStateTreeNode> current = this->loadedTopStateNode_; |
|---|
| 283 | while (current->name_ != (*it)->getName() && current) |
|---|
| 284 | current = current->parent_.lock(); |
|---|
| 285 | if (current && current->parent_.lock()) |
|---|
| 286 | this->requestState(current->parent_.lock()->name_); |
|---|
| 287 | else |
|---|
| 288 | this->stop(); |
|---|
| 289 | break; |
|---|
| 290 | } |
|---|
| 291 | } |
|---|
| 292 | } |
|---|
| 293 | |
|---|
| 294 | void Game::updateStatistics() |
|---|
| 295 | { |
|---|
| 296 | // Add the tick time of this frame (rendering time has already been subtracted) |
|---|
| 297 | uint64_t currentTime = gameClock_->getMicroseconds(); |
|---|
| 298 | uint64_t currentRealTime = gameClock_->getRealMicroseconds(); |
|---|
| 299 | this->statisticsTickTimes_.back().tickLength += (uint32_t)(currentRealTime - currentTime); |
|---|
| 300 | this->periodTickTime_ += (uint32_t)(currentRealTime - currentTime); |
|---|
| 301 | if (this->periodTime_ > this->config_->getStatisticsRefreshCycle()) |
|---|
| 302 | { |
|---|
| 303 | std::list<StatisticsTickInfo>::iterator it = this->statisticsTickTimes_.begin(); |
|---|
| 304 | assert(it != this->statisticsTickTimes_.end()); |
|---|
| 305 | int64_t lastTime = currentTime - this->config_->getStatisticsAvgLength(); |
|---|
| 306 | if (static_cast<int64_t>(it->tickTime) < lastTime) |
|---|
| 307 | { |
|---|
| 308 | do |
|---|
| 309 | { |
|---|
| 310 | assert(this->periodTickTime_ >= it->tickLength); |
|---|
| 311 | this->periodTickTime_ -= it->tickLength; |
|---|
| 312 | ++it; |
|---|
| 313 | assert(it != this->statisticsTickTimes_.end()); |
|---|
| 314 | } while (static_cast<int64_t>(it->tickTime) < lastTime); |
|---|
| 315 | this->statisticsTickTimes_.erase(this->statisticsTickTimes_.begin(), it); |
|---|
| 316 | } |
|---|
| 317 | |
|---|
| 318 | uint32_t framesPerPeriod = this->statisticsTickTimes_.size(); |
|---|
| 319 | // Why minus 1? No idea, but otherwise the fps rate is always (from 10 to 200!) one frame too low |
|---|
| 320 | this->avgFPS_ = -1 + 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->config_->getStatisticsRefreshCycle(); |
|---|
| 324 | } |
|---|
| 325 | } |
|---|
| 326 | |
|---|
| 327 | void Game::updateFPSLimiter() |
|---|
| 328 | { |
|---|
| 329 | uint64_t nextTime = gameClock_->getMicroseconds() - excessSleepTime_ + static_cast<uint32_t>(1000000.0f / this->config_->getFpsLimit()); |
|---|
| 330 | uint64_t currentRealTime = gameClock_->getRealMicroseconds(); |
|---|
| 331 | while (currentRealTime < nextTime - minimumSleepTime_) |
|---|
| 332 | { |
|---|
| 333 | usleep((unsigned long)(nextTime - currentRealTime)); |
|---|
| 334 | currentRealTime = gameClock_->getRealMicroseconds(); |
|---|
| 335 | } |
|---|
| 336 | // Integrate excess to avoid steady state error |
|---|
| 337 | excessSleepTime_ = (int)(currentRealTime - nextTime); |
|---|
| 338 | // Anti windup |
|---|
| 339 | if (excessSleepTime_ > 50000) // 20ms is about the maximum time Windows would sleep for too long |
|---|
| 340 | excessSleepTime_ = 50000; |
|---|
| 341 | } |
|---|
| 342 | |
|---|
| 343 | void Game::stop() |
|---|
| 344 | { |
|---|
| 345 | orxout(user_status) << "Exit" << endl; |
|---|
| 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 | orxout(user_warning) << "GameState named '" << name << "' doesn't exist!" << endl; |
|---|
| 364 | return; |
|---|
| 365 | } |
|---|
| 366 | |
|---|
| 367 | if (this->bChangingState_) |
|---|
| 368 | { |
|---|
| 369 | orxout(user_warning) << "Requesting GameStates while loading/unloading a GameState is illegal! Ignoring." << endl; |
|---|
| 370 | return; |
|---|
| 371 | } |
|---|
| 372 | |
|---|
| 373 | std::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 | orxout(user_warning) << "Requesting the currently active state! Ignoring." << endl; |
|---|
| 381 | return; |
|---|
| 382 | } |
|---|
| 383 | |
|---|
| 384 | // Check children first |
|---|
| 385 | std::vector<std::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 | std::shared_ptr<GameStateTreeNode> currentNode = lastRequestedNode; |
|---|
| 399 | while (currentNode != nullptr) |
|---|
| 400 | { |
|---|
| 401 | if (currentNode->name_ == name) |
|---|
| 402 | break; |
|---|
| 403 | currentNode = currentNode->parent_.lock(); |
|---|
| 404 | requestedNodes.push_back(currentNode); |
|---|
| 405 | } |
|---|
| 406 | if (currentNode == nullptr) |
|---|
| 407 | requestedNodes.clear(); |
|---|
| 408 | } |
|---|
| 409 | |
|---|
| 410 | if (requestedNodes.empty()) |
|---|
| 411 | orxout(user_error) << "Requested GameState transition is not allowed. Ignoring." << 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 | std::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 | orxout(internal_warning) << "Can't pop the internal dummy root GameState" << endl; |
|---|
| 434 | } |
|---|
| 435 | |
|---|
| 436 | std::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 | orxout(internal_error) << "GameState '" << name << "' has not yet been loaded." << endl; |
|---|
| 446 | else |
|---|
| 447 | orxout(internal_error) << "Could not find GameState '" << name << "'." << endl; |
|---|
| 448 | return std::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(std::string(), -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, std::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 | std::shared_ptr<GameStateTreeNode> node(std::make_shared<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 | if (!GameMode::showsGraphics()) |
|---|
| 514 | { |
|---|
| 515 | orxout(user_status) << "Loading graphics" << endl; |
|---|
| 516 | orxout(internal_info) << "loading graphics in Game" << endl; |
|---|
| 517 | |
|---|
| 518 | core_->loadGraphics(); |
|---|
| 519 | Loki::ScopeGuard graphicsUnloader = Loki::MakeObjGuard(*this, &Game::unloadGraphics, true); |
|---|
| 520 | |
|---|
| 521 | // Construct all the GameStates that require graphics |
|---|
| 522 | for (std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.begin(); |
|---|
| 523 | it != gameStateDeclarations_s.end(); ++it) |
|---|
| 524 | { |
|---|
| 525 | if (it->second.bGraphicsMode) |
|---|
| 526 | { |
|---|
| 527 | // Game state loading failure is serious --> don't catch |
|---|
| 528 | std::shared_ptr<GameState> gameState = GameStateFactory::fabricate(it->second); |
|---|
| 529 | if (!constructedStates_.insert(std::make_pair( |
|---|
| 530 | it->second.stateName, gameState)).second) |
|---|
| 531 | assert(false); // GameState was already created! |
|---|
| 532 | } |
|---|
| 533 | } |
|---|
| 534 | graphicsUnloader.Dismiss(); |
|---|
| 535 | |
|---|
| 536 | orxout(internal_info) << "finished loading graphics in Game" << endl; |
|---|
| 537 | } |
|---|
| 538 | } |
|---|
| 539 | |
|---|
| 540 | void Game::unloadGraphics(bool loadGraphicsManagerWithoutRenderer) |
|---|
| 541 | { |
|---|
| 542 | if (GameMode::showsGraphics()) |
|---|
| 543 | { |
|---|
| 544 | orxout(user_status) << "Unloading graphics" << endl; |
|---|
| 545 | orxout(internal_info) << "unloading graphics in Game" << endl; |
|---|
| 546 | |
|---|
| 547 | // Destroy all the GameStates that require graphics |
|---|
| 548 | for (GameStateMap::iterator it = constructedStates_.begin(); it != constructedStates_.end();) |
|---|
| 549 | { |
|---|
| 550 | if (it->second->getInfo().bGraphicsMode) |
|---|
| 551 | constructedStates_.erase(it++); |
|---|
| 552 | else |
|---|
| 553 | ++it; |
|---|
| 554 | } |
|---|
| 555 | |
|---|
| 556 | core_->unloadGraphics(loadGraphicsManagerWithoutRenderer); |
|---|
| 557 | } |
|---|
| 558 | } |
|---|
| 559 | |
|---|
| 560 | bool Game::checkState(const std::string& name) const |
|---|
| 561 | { |
|---|
| 562 | std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.find(name); |
|---|
| 563 | if (it == gameStateDeclarations_s.end()) |
|---|
| 564 | return false; |
|---|
| 565 | else |
|---|
| 566 | return true; |
|---|
| 567 | } |
|---|
| 568 | |
|---|
| 569 | void Game::loadState(const std::string& name) |
|---|
| 570 | { |
|---|
| 571 | orxout(internal_status) << "loading state '" << name << "'" << endl; |
|---|
| 572 | |
|---|
| 573 | this->bChangingState_ = true; |
|---|
| 574 | LOKI_ON_BLOCK_EXIT_OBJ(*this, &Game::resetChangingState); (void)LOKI_ANONYMOUS_VARIABLE(scopeGuard); |
|---|
| 575 | |
|---|
| 576 | // If state requires graphics, load it |
|---|
| 577 | Loki::ScopeGuard graphicsUnloader = Loki::MakeObjGuard(*this, &Game::unloadGraphics, true); |
|---|
| 578 | if (gameStateDeclarations_s[name].bGraphicsMode && !GameMode::showsGraphics()) |
|---|
| 579 | this->loadGraphics(); |
|---|
| 580 | else |
|---|
| 581 | graphicsUnloader.Dismiss(); |
|---|
| 582 | |
|---|
| 583 | std::shared_ptr<GameState> state = this->getState(name); |
|---|
| 584 | state->activateInternal(); |
|---|
| 585 | if (!this->loadedStates_.empty()) |
|---|
| 586 | this->loadedStates_.back()->activity_.topState = false; |
|---|
| 587 | this->loadedStates_.push_back(state); |
|---|
| 588 | state->activity_.topState = true; |
|---|
| 589 | |
|---|
| 590 | graphicsUnloader.Dismiss(); |
|---|
| 591 | } |
|---|
| 592 | |
|---|
| 593 | void Game::unloadState(const std::string& name) |
|---|
| 594 | { |
|---|
| 595 | orxout(internal_status) << "unloading state '" << name << "'" << endl; |
|---|
| 596 | |
|---|
| 597 | this->bChangingState_ = true; |
|---|
| 598 | try |
|---|
| 599 | { |
|---|
| 600 | std::shared_ptr<GameState> state = this->getState(name); |
|---|
| 601 | state->activity_.topState = false; |
|---|
| 602 | this->loadedStates_.pop_back(); |
|---|
| 603 | if (!this->loadedStates_.empty()) |
|---|
| 604 | this->loadedStates_.back()->activity_.topState = true; |
|---|
| 605 | state->deactivateInternal(); |
|---|
| 606 | } |
|---|
| 607 | catch (...) |
|---|
| 608 | { |
|---|
| 609 | orxout(internal_warning) << "Unloading GameState '" << name << "' threw an exception: " << Exception::handleMessage() << endl; |
|---|
| 610 | orxout(internal_warning) << "There might be potential resource leaks involved! To avoid this, improve exception-safety." << endl; |
|---|
| 611 | } |
|---|
| 612 | // Check if graphics is still required |
|---|
| 613 | bool graphicsRequired = false; |
|---|
| 614 | for (auto & elem : loadedStates_) |
|---|
| 615 | graphicsRequired |= elem->getInfo().bGraphicsMode; |
|---|
| 616 | if (!graphicsRequired) |
|---|
| 617 | this->unloadGraphics(!this->bAbort_); // if abort is false, that means the game is still running while unloading graphics. in this case we load a graphics manager without renderer (to keep all necessary ogre instances alive) |
|---|
| 618 | this->bChangingState_ = false; |
|---|
| 619 | } |
|---|
| 620 | |
|---|
| 621 | /*static*/ std::map<std::string, std::shared_ptr<Game::GameStateFactory>>& Game::GameStateFactory::getFactories() |
|---|
| 622 | { |
|---|
| 623 | static std::map<std::string, std::shared_ptr<GameStateFactory>> factories; |
|---|
| 624 | return factories; |
|---|
| 625 | } |
|---|
| 626 | |
|---|
| 627 | /*static*/ std::shared_ptr<GameState> Game::GameStateFactory::fabricate(const GameStateInfo& info) |
|---|
| 628 | { |
|---|
| 629 | std::map<std::string, std::shared_ptr<Game::GameStateFactory>>::const_iterator it = getFactories().find(info.className); |
|---|
| 630 | assert(it != getFactories().end()); |
|---|
| 631 | return it->second->fabricateInternal(info); |
|---|
| 632 | } |
|---|
| 633 | } |
|---|