Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/libraries/core/Core.cc @ 8366

Last change on this file since 8366 was 8366, checked in by rgrieder, 13 years ago

Renamed PathConfig::isDevelopmentRun() to PathConfig::buildDirectoryRun() because that fits better and there is no confusion with Core::inDevMode().
Also used isDevelopmentRun() as default value for Core::inDevMode() instead of ORXONOX_RELEASE.

  • Property svn:eol-style set to native
File size: 15.2 KB
RevLine 
[1505]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 *      Fabian 'x3n' Landau
[2896]24 *      Reto Grieder
[1505]25 *   Co-authors:
[2896]26 *      ...
[1505]27 *
28 */
29
30/**
[3196]31@file
32@brief
33    Implementation of the Core singleton with its global variables (avoids boost include)
[1505]34*/
35
[1524]36#include "Core.h"
[2710]37
[1756]38#include <cassert>
[7427]39#include <cstdlib>
40#include <ctime>
[7401]41#include <fstream>
[5929]42#include <vector>
[2710]43
44#ifdef ORXONOX_PLATFORM_WINDOWS
[2896]45#  ifndef WIN32_LEAN_AND_MEAN
46#    define WIN32_LEAN_AND_MEAN
47#  endif
[2710]48#  include <windows.h>
[3214]49#  undef min
50#  undef max
[2710]51#endif
52
[5929]53#include "util/Clock.h"
[2896]54#include "util/Debug.h"
[2710]55#include "util/Exception.h"
[6417]56#include "util/Scope.h"
[7284]57#include "util/ScopedSingletonManager.h"
[2896]58#include "util/SignalHandler.h"
[5929]59#include "PathConfig.h"
[6021]60#include "CommandLineParser.h"
[2896]61#include "ConfigFileManager.h"
62#include "ConfigValueIncludes.h"
63#include "CoreIncludes.h"
[5693]64#include "DynLibManager.h"
[5781]65#include "GameMode.h"
66#include "GraphicsManager.h"
67#include "GUIManager.h"
[2896]68#include "Identifier.h"
[1505]69#include "Language.h"
[5695]70#include "LuaState.h"
[7284]71#include "command/ConsoleCommand.h"
72#include "command/IOConsole.h"
73#include "command/TclBind.h"
74#include "command/TclThreadManager.h"
[5781]75#include "input/InputManager.h"
[1505]76
77namespace orxonox
78{
[3196]79    //! Static pointer to the singleton
[3370]80    Core* Core::singletonPtr_s  = 0;
[2662]81
[3280]82    SetCommandLineArgument(settingsFile, "orxonox.ini").information("THE configuration file");
[8351]83#if !defined(ORXONOX_PLATFORM_APPLE) && !defined(ORXONOX_USE_WINMAIN)
[6746]84    SetCommandLineSwitch(noIOConsole).information("Use this if you don't want to use the IOConsole (for instance for Lua debugging)");
[8351]85#endif
[7163]86
[3280]87#ifdef ORXONOX_PLATFORM_WINDOWS
[6417]88    SetCommandLineArgument(limitToCPU, 1).information("Limits the program to one CPU/core (1, 2, 3, etc.). Default is the first core (faster than off)");
[3280]89#endif
[2710]90
[3323]91    Core::Core(const std::string& cmdLine)
[3370]92        // Cleanup guard for identifier destruction (incl. XMLPort, configValues, consoleCommands)
93        : identifierDestroyer_(Identifier::destroyAllIdentifiers)
[5781]94        // Cleanup guard for external console commands that don't belong to an Identifier
[7284]95        , consoleCommandDestroyer_(ConsoleCommand::destroyAll)
[5781]96        , bGraphicsLoaded_(false)
[6746]97        , bStartIOConsole_(true)
[7870]98        , lastLevelTimestamp_(0)
99        , ogreConfigTimestamp_(0)
[8366]100        , bDevMode_(false)
[3280]101    {
[5693]102        // Set the hard coded fixed paths
[5929]103        this->pathConfig_.reset(new PathConfig());
[3280]104
[5693]105        // Create a new dynamic library manager
106        this->dynLibManager_.reset(new DynLibManager());
[2896]107
[5693]108        // Load modules
[5929]109        const std::vector<std::string>& modulePaths = this->pathConfig_->getModulePaths();
110        for (std::vector<std::string>::const_iterator it = modulePaths.begin(); it != modulePaths.end(); ++it)
[5693]111        {
[5929]112            try
[5693]113            {
[5929]114                this->dynLibManager_->load(*it);
[5693]115            }
[5929]116            catch (...)
117            {
118                COUT(1) << "Couldn't load module \"" << *it << "\": " << Exception::handleMessage() << std::endl;
119            }
[5693]120        }
121
122        // Parse command line arguments AFTER the modules have been loaded (static code!)
[6021]123        CommandLineParser::parseCommandLine(cmdLine);
[5693]124
125        // Set configurable paths like log, config and media
[5929]126        this->pathConfig_->setConfigurablePaths();
[5693]127
[6105]128        // create a signal handler (only active for Linux)
[2896]129        // This call is placed as soon as possible, but after the directories are set
[3370]130        this->signalHandler_.reset(new SignalHandler());
[5929]131        this->signalHandler_->doCatch(PathConfig::getExecutablePathString(), PathConfig::getLogPathString() + "orxonox_crash.log");
[2896]132
[6105]133        // Set the correct log path. Before this call, /tmp (Unix) or %TEMP% (Windows) was used
134        OutputHandler::getInstance().setLogPath(PathConfig::getLogPathString());
[2710]135
[3280]136        // Parse additional options file now that we know its path
[6021]137        CommandLineParser::parseFile();
[3280]138
139#ifdef ORXONOX_PLATFORM_WINDOWS
140        // limit the main thread to the first core so that QueryPerformanceCounter doesn't jump
141        // do this after ogre has initialised. Somehow Ogre changes the settings again (not through
142        // the timer though).
[6021]143        int limitToCPU = CommandLineParser::getValue("limitToCPU");
[3280]144        if (limitToCPU > 0)
145            setThreadAffinity(static_cast<unsigned int>(limitToCPU));
146#endif
147
[2896]148        // Manage ini files and set the default settings file (usually orxonox.ini)
[3370]149        this->configFileManager_.reset(new ConfigFileManager());
[2896]150        this->configFileManager_->setFilename(ConfigFileType::Settings,
[6021]151            CommandLineParser::getValue("settingsFile").getString());
[2896]152
[3280]153        // Required as well for the config values
[3370]154        this->languageInstance_.reset(new Language());
[2896]155
[6417]156        // Do this soon after the ConfigFileManager has been created to open up the
157        // possibility to configure everything below here
158        ClassIdentifier<Core>::getIdentifier("Core")->initialiseObject(this, "Core", true);
159        this->setConfigValues();
160
[8351]161#if !defined(ORXONOX_PLATFORM_APPLE) && !defined(ORXONOX_USE_WINMAIN)
162        // Create persistent IO console
[6746]163        if (CommandLineParser::getValue("noIOConsole").getBool())
164        {
165            ModifyConfigValue(bStartIOConsole_, tset, false);
166        }
167        if (this->bStartIOConsole_)
168            this->ioConsole_.reset(new IOConsole());
[8351]169#endif
[6105]170
[5695]171        // creates the class hierarchy for all classes with factories
[5929]172        Identifier::createClassHierarchy();
[5695]173
[5781]174        // Load OGRE excluding the renderer and the render window
175        this->graphicsManager_.reset(new GraphicsManager(false));
176
177        // initialise Tcl
[5929]178        this->tclBind_.reset(new TclBind(PathConfig::getDataPathString()));
[5781]179        this->tclThreadManager_.reset(new TclThreadManager(tclBind_->getTclInterpreter()));
180
[5929]181        // Create singletons that always exist (in other libraries)
182        this->rootScope_.reset(new Scope<ScopeID::Root>());
[7401]183
184        // Generate documentation instead of normal run?
185        std::string docFilename;
186        CommandLineParser::getValue("generateDoc", &docFilename);
187        if (!docFilename.empty())
188        {
189            std::ofstream docFile(docFilename.c_str());
190            if (docFile.is_open())
191            {
192                CommandLineParser::generateDoc(docFile);
193                docFile.close();
194            }
195            else
196                COUT(0) << "Error: Could not open file for documentation writing" << endl;
197        }
[1505]198    }
199
200    /**
[3370]201    @brief
[5695]202        All destruction code is handled by scoped_ptrs and ScopeGuards.
[1505]203    */
[1524]204    Core::~Core()
[1505]205    {
[6417]206        // Remove us from the object lists again to avoid problems when destroying them
207        this->unregisterObject();
[3370]208    }
[2896]209
[6417]210    //! Function to collect the SetConfigValue-macro calls.
211    void Core::setConfigValues()
212    {
213#ifdef ORXONOX_RELEASE
214        const unsigned int defaultLevelLogFile = 3;
215#else
216        const unsigned int defaultLevelLogFile = 4;
217#endif
[7167]218        SetConfigValueExternal(softDebugLevelLogFile_, "OutputHandler", "softDebugLevelLogFile", defaultLevelLogFile)
[6417]219            .description("The maximum level of debug output shown in the log file");
220        OutputHandler::getInstance().setSoftDebugLevel(OutputHandler::logFileOutputListenerName_s, this->softDebugLevelLogFile_);
221
[8366]222        SetConfigValue(bDevMode_, PathConfig::buildDirectoryRun())
223            .description("Developer mode. If not set, hides some things from the user to not confuse him.");
[6417]224        SetConfigValue(language_, Language::getInstance().defaultLanguage_)
225            .description("The language of the in game text")
226            .callback(this, &Core::languageChanged);
227        SetConfigValue(bInitRandomNumberGenerator_, true)
228            .description("If true, all random actions are different each time you start the game")
229            .callback(this, &Core::initRandomNumberGenerator);
[6746]230        SetConfigValue(bStartIOConsole_, true)
231            .description("Set to false if you don't want to use the IOConsole (for Lua debugging for instance)");
[7870]232        SetConfigValue(lastLevelTimestamp_, 0)
233            .description("Timestamp when the last level was started.");
234        SetConfigValue(ogreConfigTimestamp_, 0)
235            .description("Timestamp when the ogre config file was changed.");
[6417]236    }
237
238    //! Callback function if the language has changed.
239    void Core::languageChanged()
240    {
241        // Read the translation file after the language was configured
242        Language::getInstance().readTranslatedLanguageFile();
243    }
244
245    void Core::initRandomNumberGenerator()
246    {
247        static bool bInitialized = false;
248        if (!bInitialized && this->bInitRandomNumberGenerator_)
249        {
250            srand(static_cast<unsigned int>(time(0)));
251            rand();
252            bInitialized = true;
253        }
254    }
255
[5781]256    void Core::loadGraphics()
257    {
258        // Any exception should trigger this, even in upgradeToGraphics (see its remarks)
259        Loki::ScopeGuard unloader = Loki::MakeObjGuard(*this, &Core::unloadGraphics);
260
261        // Upgrade OGRE to receive a render window
[7175]262        try
263        {
264            graphicsManager_->upgradeToGraphics();
265        }
[7872]266        catch (const InitialisationFailedException&)
[7868]267        {
268            // Exit the application if the Ogre config dialog was canceled
269            COUT(1) << Exception::handleMessage() << std::endl;
270            exit(EXIT_FAILURE);
271        }
[7175]272        catch (...)
273        {
274            // Recovery from this is very difficult. It requires to completely
275            // destroy Ogre related objects and load again (without graphics).
276            // However since Ogre 1.7 there seems to be a problem when Ogre
277            // throws an exception and the graphics engine then gets destroyed
278            // and reloaded between throw and catch (access violation in MSVC).
279            // That's why we abort completely and only display the exception.
[7868]280            COUT(1) << "An exception occurred during upgrade to graphics. "
[7175]281                    << "That is unrecoverable. The message was:" << endl
282                    << Exception::handleMessage() << endl;
283            abort();
284        }
[5781]285
286        // Calls the InputManager which sets up the input devices.
287        inputManager_.reset(new InputManager());
288
[5929]289        // Load the CEGUI interface
[6746]290        guiManager_.reset(new GUIManager(inputManager_->getMousePosition()));
[5781]291
[5929]292        bGraphicsLoaded_ = true;
293        GameMode::bShowsGraphics_s = true;
294
295        // Load some sort of a debug overlay (only denoted by its name, "debug.oxo")
296        graphicsManager_->loadDebugOverlay();
297
298        // Create singletons associated with graphics (in other libraries)
299        graphicsScope_.reset(new Scope<ScopeID::Graphics>());
300
[5781]301        unloader.Dismiss();
302    }
303
304    void Core::unloadGraphics()
305    {
[5929]306        this->graphicsScope_.reset();
307        this->guiManager_.reset();
308        this->inputManager_.reset();
[5781]309        this->graphicsManager_.reset();
310
311        // Load Ogre::Root again, but without the render system
312        try
313            { this->graphicsManager_.reset(new GraphicsManager(false)); }
314        catch (...)
315        {
316            COUT(0) << "An exception occurred during 'unloadGraphics':" << Exception::handleMessage() << std::endl
317                    << "Another exception might be being handled which may lead to undefined behaviour!" << std::endl
318                    << "Terminating the program." << std::endl;
319            abort();
320        }
321
322        bGraphicsLoaded_ = false;
[5929]323        GameMode::bShowsGraphics_s = false;
[5781]324    }
325
[6417]326    //! Sets the language in the config-file back to the default.
327    void Core::resetLanguage()
[1505]328    {
[6417]329        ResetConfigValue(language_);
[1505]330    }
331
332    /**
[2896]333    @note
334        The code of this function has been copied and adjusted from OGRE, an open source graphics engine.
335            (Object-oriented Graphics Rendering Engine)
336        For the latest info, see http://www.ogre3d.org/
337
338        Copyright (c) 2000-2008 Torus Knot Software Ltd
339
340        OGRE is licensed under the LGPL. For more info, see OGRE license.
[2710]341    */
[2896]342    void Core::setThreadAffinity(int limitToCPU)
[2710]343    {
[3280]344#ifdef ORXONOX_PLATFORM_WINDOWS
345
[2896]346        if (limitToCPU <= 0)
347            return;
[2710]348
[2896]349        unsigned int coreNr = limitToCPU - 1;
350        // Get the current process core mask
351        DWORD procMask;
352        DWORD sysMask;
353#  if _MSC_VER >= 1400 && defined (_M_X64)
354        GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&procMask, (PDWORD_PTR)&sysMask);
355#  else
356        GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask);
357#  endif
[2710]358
[2896]359        // If procMask is 0, consider there is only one core available
360        // (using 0 as procMask will cause an infinite loop below)
361        if (procMask == 0)
362            procMask = 1;
363
364        // if the core specified with coreNr is not available, take the lowest one
365        if (!(procMask & (1 << coreNr)))
366            coreNr = 0;
367
368        // Find the lowest core that this process uses and coreNr suggests
369        DWORD threadMask = 1;
370        while ((threadMask & procMask) == 0 || (threadMask < (1u << coreNr)))
371            threadMask <<= 1;
372
373        // Set affinity to the first core
374        SetThreadAffinityMask(GetCurrentThread(), threadMask);
375#endif
[2710]376    }
377
[5695]378    void Core::preUpdate(const Clock& time)
[2896]379    {
[6417]380        // Update singletons before general ticking
381        ScopedSingletonManager::preUpdate<ScopeID::Root>(time);
[5781]382        if (this->bGraphicsLoaded_)
383        {
[6417]384            // Process input events
385            this->inputManager_->preUpdate(time);
386            // Update GUI
387            this->guiManager_->preUpdate(time);
388            // Update singletons before general ticking
389            ScopedSingletonManager::preUpdate<ScopeID::Graphics>(time);
[5781]390        }
[6417]391        // Process console events and status line
[6746]392        if (this->ioConsole_ != NULL)
393            this->ioConsole_->preUpdate(time);
[6417]394        // Process thread commands
395        this->tclThreadManager_->preUpdate(time);
[2896]396    }
[3370]397
[5695]398    void Core::postUpdate(const Clock& time)
[3370]399    {
[6417]400        // Update singletons just before rendering
401        ScopedSingletonManager::postUpdate<ScopeID::Root>(time);
[5781]402        if (this->bGraphicsLoaded_)
403        {
[6417]404            // Update singletons just before rendering
405            ScopedSingletonManager::postUpdate<ScopeID::Graphics>(time);
[5781]406            // Render (doesn't throw)
[6417]407            this->graphicsManager_->postUpdate(time);
[5781]408        }
[3370]409    }
[7870]410
411    void Core::updateLastLevelTimestamp()
412    {
413        ModifyConfigValue(lastLevelTimestamp_, set, static_cast<long long>(time(NULL)));
414    }
415
416    void Core::updateOgreConfigTimestamp()
417    {
418        ModifyConfigValue(ogreConfigTimestamp_, set, static_cast<long long>(time(NULL)));
419    }
[1505]420}
Note: See TracBrowser for help on using the repository browser.