Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: sandbox/src/libraries/core/Core.cc @ 6497

Last change on this file since 6497 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: 13.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>
[6038]39#include <vector>
[2710]40
41#ifdef ORXONOX_PLATFORM_WINDOWS
[2896]42#  ifndef WIN32_LEAN_AND_MEAN
43#    define WIN32_LEAN_AND_MEAN
44#  endif
[2710]45#  include <windows.h>
[3214]46#  undef min
47#  undef max
[2710]48#endif
49
[6038]50#include "util/Clock.h"
[2896]51#include "util/Debug.h"
[2710]52#include "util/Exception.h"
[2896]53#include "util/SignalHandler.h"
[6038]54#include "PathConfig.h"
55#include "CommandLineParser.h"
[2896]56#include "ConfigFileManager.h"
57#include "ConfigValueIncludes.h"
58#include "CoreIncludes.h"
[5693]59#include "DynLibManager.h"
[2896]60#include "Identifier.h"
[1505]61#include "Language.h"
[5695]62#include "LuaState.h"
[1505]63
64namespace orxonox
65{
[3196]66    //! Static pointer to the singleton
[3370]67    Core* Core::singletonPtr_s  = 0;
[2662]68
[3280]69    SetCommandLineArgument(settingsFile, "orxonox.ini").information("THE configuration file");
70#ifdef ORXONOX_PLATFORM_WINDOWS
71    SetCommandLineArgument(limitToCPU, 0).information("Limits the program to one cpu/core (1, 2, 3, etc.). 0 turns it off (default)");
72#endif
[2710]73
[3280]74    /**
75    @brief
76        Helper class for the Core singleton: we cannot derive
77        Core from OrxonoxClass because we need to handle the Identifier
78        destruction in the Core destructor.
79    */
80    class CoreConfiguration : public OrxonoxClass
[1505]81    {
[3280]82    public:
83        CoreConfiguration()
84        {
85        }
[2662]86
[3280]87        void initialise()
88        {
89            RegisterRootObject(CoreConfiguration);
90            this->setConfigValues();
91        }
92
93        /**
94            @brief Function to collect the SetConfigValue-macro calls.
95        */
96        void setConfigValues()
[2896]97        {
[3280]98#ifdef NDEBUG
99            const unsigned int defaultLevelConsole = 1;
100            const unsigned int defaultLevelLogfile = 3;
101            const unsigned int defaultLevelShell   = 1;
102#else
103            const unsigned int defaultLevelConsole = 3;
104            const unsigned int defaultLevelLogfile = 4;
105            const unsigned int defaultLevelShell   = 3;
106#endif
107            SetConfigValue(softDebugLevelConsole_, defaultLevelConsole)
108                .description("The maximal level of debug output shown in the console")
109                .callback(this, &CoreConfiguration::debugLevelChanged);
110            SetConfigValue(softDebugLevelLogfile_, defaultLevelLogfile)
111                .description("The maximal level of debug output shown in the logfile")
112                .callback(this, &CoreConfiguration::debugLevelChanged);
113            SetConfigValue(softDebugLevelShell_, defaultLevelShell)
114                .description("The maximal level of debug output shown in the ingame shell")
115                .callback(this, &CoreConfiguration::debugLevelChanged);
116
[3370]117            SetConfigValue(language_, Language::getInstance().defaultLanguage_)
[3280]118                .description("The language of the ingame text")
119                .callback(this, &CoreConfiguration::languageChanged);
120            SetConfigValue(bInitializeRandomNumberGenerator_, true)
121                .description("If true, all random actions are different each time you start the game")
122                .callback(this, &CoreConfiguration::initializeRandomNumberGenerator);
[2896]123        }
[3280]124
125        /**
126            @brief Callback function if the debug level has changed.
127        */
128        void debugLevelChanged()
[2896]129        {
[3280]130            // softDebugLevel_ is the maximum of the 3 variables
131            this->softDebugLevel_ = this->softDebugLevelConsole_;
132            if (this->softDebugLevelLogfile_ > this->softDebugLevel_)
133                this->softDebugLevel_ = this->softDebugLevelLogfile_;
134            if (this->softDebugLevelShell_ > this->softDebugLevel_)
135                this->softDebugLevel_ = this->softDebugLevelShell_;
136
137            OutputHandler::setSoftDebugLevel(OutputHandler::LD_All,     this->softDebugLevel_);
138            OutputHandler::setSoftDebugLevel(OutputHandler::LD_Console, this->softDebugLevelConsole_);
139            OutputHandler::setSoftDebugLevel(OutputHandler::LD_Logfile, this->softDebugLevelLogfile_);
140            OutputHandler::setSoftDebugLevel(OutputHandler::LD_Shell,   this->softDebugLevelShell_);
[2896]141        }
[2662]142
[3280]143        /**
144            @brief Callback function if the language has changed.
145        */
146        void languageChanged()
147        {
148            // Read the translation file after the language was configured
[3370]149            Language::getInstance().readTranslatedLanguageFile();
[3280]150        }
[2896]151
[3280]152        /**
153            @brief Sets the language in the config-file back to the default.
154        */
155        void resetLanguage()
156        {
157            ResetConfigValue(language_);
158        }
159
160        void initializeRandomNumberGenerator()
161        {
162            static bool bInitialized = false;
163            if (!bInitialized && this->bInitializeRandomNumberGenerator_)
164            {
165                srand(static_cast<unsigned int>(time(0)));
166                rand();
167                bInitialized = true;
168            }
169        }
170
171        int softDebugLevel_;                            //!< The debug level
172        int softDebugLevelConsole_;                     //!< The debug level for the console
173        int softDebugLevelLogfile_;                     //!< The debug level for the logfile
174        int softDebugLevelShell_;                       //!< The debug level for the ingame shell
175        std::string language_;                          //!< The language
176        bool bInitializeRandomNumberGenerator_;         //!< If true, srand(time(0)) is called
177    };
178
179
[3323]180    Core::Core(const std::string& cmdLine)
[3370]181        // Cleanup guard for identifier destruction (incl. XMLPort, configValues, consoleCommands)
182        : identifierDestroyer_(Identifier::destroyAllIdentifiers)
183        , configuration_(new CoreConfiguration()) // Don't yet create config values!
[3280]184    {
[5693]185        // Set the hard coded fixed paths
[6038]186        this->pathConfig_.reset(new PathConfig());
[3280]187
[5693]188        // Create a new dynamic library manager
189        this->dynLibManager_.reset(new DynLibManager());
[2896]190
[5693]191        // Load modules
[6038]192        const std::vector<std::string>& modulePaths = this->pathConfig_->getModulePaths();
193        for (std::vector<std::string>::const_iterator it = modulePaths.begin(); it != modulePaths.end(); ++it)
[5693]194        {
[6038]195            try
[5693]196            {
[6038]197                this->dynLibManager_->load(*it);
[5693]198            }
[6038]199            catch (...)
200            {
201                COUT(1) << "Couldn't load module \"" << *it << "\": " << Exception::handleMessage() << std::endl;
202            }
[5693]203        }
204
205        // Parse command line arguments AFTER the modules have been loaded (static code!)
[6038]206        CommandLineParser::parseCommandLine(cmdLine);
[5693]207
208        // Set configurable paths like log, config and media
[6038]209        this->pathConfig_->setConfigurablePaths();
[5693]210
[2896]211        // create a signal handler (only active for linux)
212        // This call is placed as soon as possible, but after the directories are set
[3370]213        this->signalHandler_.reset(new SignalHandler());
[6038]214        this->signalHandler_->doCatch(PathConfig::getExecutablePathString(), PathConfig::getLogPathString() + "orxonox_crash.log");
[2896]215
[2710]216        // Set the correct log path. Before this call, /tmp (Unix) or %TEMP% was used
[6038]217        OutputHandler::getOutStream().setLogPath(PathConfig::getLogPathString());
[2710]218
[3280]219        // Parse additional options file now that we know its path
[6038]220        CommandLineParser::parseFile();
[3280]221
222#ifdef ORXONOX_PLATFORM_WINDOWS
223        // limit the main thread to the first core so that QueryPerformanceCounter doesn't jump
224        // do this after ogre has initialised. Somehow Ogre changes the settings again (not through
225        // the timer though).
[6038]226        int limitToCPU = CommandLineParser::getValue("limitToCPU");
[3280]227        if (limitToCPU > 0)
228            setThreadAffinity(static_cast<unsigned int>(limitToCPU));
229#endif
230
[2896]231        // Manage ini files and set the default settings file (usually orxonox.ini)
[3370]232        this->configFileManager_.reset(new ConfigFileManager());
[2896]233        this->configFileManager_->setFilename(ConfigFileType::Settings,
[6038]234            CommandLineParser::getValue("settingsFile").getString());
[2896]235
[3280]236        // Required as well for the config values
[3370]237        this->languageInstance_.reset(new Language());
[2896]238
[5695]239        // creates the class hierarchy for all classes with factories
[6038]240        Identifier::createClassHierarchy();
[5695]241
[2896]242        // Do this soon after the ConfigFileManager has been created to open up the
243        // possibility to configure everything below here
[3280]244        this->configuration_->initialise();
[1505]245    }
246
247    /**
[3370]248    @brief
[5695]249        All destruction code is handled by scoped_ptrs and ScopeGuards.
[1505]250    */
[1524]251    Core::~Core()
[1505]252    {
[3370]253    }
[2896]254
[1747]255    /**
[3280]256        @brief Returns the softDebugLevel for the given device (returns a default-value if the class is right about to be created).
[1505]257        @param device The device
258        @return The softDebugLevel
259    */
[3280]260    /*static*/ int Core::getSoftDebugLevel(OutputHandler::OutputDevice device)
[1505]261    {
[2662]262        switch (device)
[1505]263        {
[2662]264        case OutputHandler::LD_All:
[3280]265            return Core::getInstance().configuration_->softDebugLevel_;
[2662]266        case OutputHandler::LD_Console:
[3280]267            return Core::getInstance().configuration_->softDebugLevelConsole_;
[2662]268        case OutputHandler::LD_Logfile:
[3280]269            return Core::getInstance().configuration_->softDebugLevelLogfile_;
[2662]270        case OutputHandler::LD_Shell:
[3280]271            return Core::getInstance().configuration_->softDebugLevelShell_;
[2662]272        default:
273            assert(0);
274            return 2;
[1505]275        }
276    }
277
278     /**
279        @brief Sets the softDebugLevel for the given device. Please use this only temporary and restore the value afterwards, as it overrides the configured value.
280        @param device The device
281        @param level The level
282    */
[3280]283    /*static*/ void Core::setSoftDebugLevel(OutputHandler::OutputDevice device, int level)
284    {
[2662]285        if (device == OutputHandler::LD_All)
[3280]286            Core::getInstance().configuration_->softDebugLevel_ = level;
[2662]287        else if (device == OutputHandler::LD_Console)
[3280]288            Core::getInstance().configuration_->softDebugLevelConsole_ = level;
[2662]289        else if (device == OutputHandler::LD_Logfile)
[3280]290            Core::getInstance().configuration_->softDebugLevelLogfile_ = level;
[2662]291        else if (device == OutputHandler::LD_Shell)
[3280]292            Core::getInstance().configuration_->softDebugLevelShell_ = level;
[1747]293
[2662]294        OutputHandler::setSoftDebugLevel(device, level);
[3280]295    }
[1505]296
297    /**
298        @brief Returns the configured language.
299    */
[3280]300    /*static*/ const std::string& Core::getLanguage()
[1505]301    {
[3280]302        return Core::getInstance().configuration_->language_;
[1505]303    }
304
305    /**
306        @brief Sets the language in the config-file back to the default.
307    */
[3280]308    /*static*/ void Core::resetLanguage()
[1505]309    {
[3280]310        Core::getInstance().configuration_->resetLanguage();
[1505]311    }
312
[2710]313    /**
[2896]314    @note
315        The code of this function has been copied and adjusted from OGRE, an open source graphics engine.
316            (Object-oriented Graphics Rendering Engine)
317        For the latest info, see http://www.ogre3d.org/
318
319        Copyright (c) 2000-2008 Torus Knot Software Ltd
320
321        OGRE is licensed under the LGPL. For more info, see OGRE license.
[2710]322    */
[2896]323    void Core::setThreadAffinity(int limitToCPU)
[2710]324    {
[3280]325#ifdef ORXONOX_PLATFORM_WINDOWS
326
[2896]327        if (limitToCPU <= 0)
328            return;
[2710]329
[2896]330        unsigned int coreNr = limitToCPU - 1;
331        // Get the current process core mask
332        DWORD procMask;
333        DWORD sysMask;
334#  if _MSC_VER >= 1400 && defined (_M_X64)
335        GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&procMask, (PDWORD_PTR)&sysMask);
336#  else
337        GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask);
338#  endif
[2710]339
[2896]340        // If procMask is 0, consider there is only one core available
341        // (using 0 as procMask will cause an infinite loop below)
342        if (procMask == 0)
343            procMask = 1;
344
345        // if the core specified with coreNr is not available, take the lowest one
346        if (!(procMask & (1 << coreNr)))
347            coreNr = 0;
348
349        // Find the lowest core that this process uses and coreNr suggests
350        DWORD threadMask = 1;
351        while ((threadMask & procMask) == 0 || (threadMask < (1u << coreNr)))
352            threadMask <<= 1;
353
354        // Set affinity to the first core
355        SetThreadAffinityMask(GetCurrentThread(), threadMask);
356#endif
[2710]357    }
358
[5695]359    void Core::preUpdate(const Clock& time)
[2896]360    {
361    }
[3370]362
[5695]363    void Core::postUpdate(const Clock& time)
[3370]364    {
365    }
[1505]366}
Note: See TracBrowser for help on using the repository browser.