Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/core5/src/libraries/core/Core.cc @ 5836

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

Extracted path related parts of Core into a new PathConfig class. This should decrease the mess in Core.cc a little bit.

  • Property svn:eol-style set to native
File size: 15.7 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 *      Fabian 'x3n' Landau
24 *      Reto Grieder
25 *   Co-authors:
26 *      ...
27 *
28 */
29
30/**
31@file
32@brief
33    Implementation of the Core singleton with its global variables (avoids boost include)
34*/
35
36#include "Core.h"
37
38#include <cassert>
39#include <vector>
40
41#ifdef ORXONOX_PLATFORM_WINDOWS
42#  ifndef WIN32_LEAN_AND_MEAN
43#    define WIN32_LEAN_AND_MEAN
44#  endif
45#  include <windows.h>
46#  undef min
47#  undef max
48#endif
49
50#include "util/Debug.h"
51#include "util/Exception.h"
52#include "util/SignalHandler.h"
53#include "PathConfig.h"
54#include "Clock.h"
55#include "CommandExecutor.h"
56#include "CommandLine.h"
57#include "ConfigFileManager.h"
58#include "ConfigValueIncludes.h"
59#include "CoreIncludes.h"
60#include "DynLibManager.h"
61#include "GameMode.h"
62#include "GraphicsManager.h"
63#include "GUIManager.h"
64#include "Identifier.h"
65#include "Language.h"
66#include "LuaState.h"
67#include "Shell.h"
68#include "TclBind.h"
69#include "TclThreadManager.h"
70#include "input/InputManager.h"
71
72namespace orxonox
73{
74    //! Static pointer to the singleton
75    Core* Core::singletonPtr_s  = 0;
76
77    SetCommandLineArgument(settingsFile, "orxonox.ini").information("THE configuration file");
78#ifdef ORXONOX_PLATFORM_WINDOWS
79    SetCommandLineArgument(limitToCPU, 0).information("Limits the program to one cpu/core (1, 2, 3, etc.). 0 turns it off (default)");
80#endif
81
82    /**
83    @brief
84        Helper class for the Core singleton: we cannot derive
85        Core from OrxonoxClass because we need to handle the Identifier
86        destruction in the Core destructor.
87    */
88    class CoreConfiguration : public OrxonoxClass
89    {
90    public:
91        CoreConfiguration()
92        {
93        }
94
95        void initialise()
96        {
97            RegisterRootObject(CoreConfiguration);
98            this->setConfigValues();
99        }
100
101        /**
102            @brief Function to collect the SetConfigValue-macro calls.
103        */
104        void setConfigValues()
105        {
106#ifdef NDEBUG
107            const unsigned int defaultLevelConsole = 1;
108            const unsigned int defaultLevelLogfile = 3;
109            const unsigned int defaultLevelShell   = 1;
110#else
111            const unsigned int defaultLevelConsole = 3;
112            const unsigned int defaultLevelLogfile = 4;
113            const unsigned int defaultLevelShell   = 3;
114#endif
115            SetConfigValue(softDebugLevelConsole_, defaultLevelConsole)
116                .description("The maximal level of debug output shown in the console")
117                .callback(this, &CoreConfiguration::debugLevelChanged);
118            SetConfigValue(softDebugLevelLogfile_, defaultLevelLogfile)
119                .description("The maximal level of debug output shown in the logfile")
120                .callback(this, &CoreConfiguration::debugLevelChanged);
121            SetConfigValue(softDebugLevelShell_, defaultLevelShell)
122                .description("The maximal level of debug output shown in the ingame shell")
123                .callback(this, &CoreConfiguration::debugLevelChanged);
124
125            SetConfigValue(language_, Language::getInstance().defaultLanguage_)
126                .description("The language of the ingame text")
127                .callback(this, &CoreConfiguration::languageChanged);
128            SetConfigValue(bInitializeRandomNumberGenerator_, true)
129                .description("If true, all random actions are different each time you start the game")
130                .callback(this, &CoreConfiguration::initializeRandomNumberGenerator);
131        }
132
133        /**
134            @brief Callback function if the debug level has changed.
135        */
136        void debugLevelChanged()
137        {
138            // softDebugLevel_ is the maximum of the 3 variables
139            this->softDebugLevel_ = this->softDebugLevelConsole_;
140            if (this->softDebugLevelLogfile_ > this->softDebugLevel_)
141                this->softDebugLevel_ = this->softDebugLevelLogfile_;
142            if (this->softDebugLevelShell_ > this->softDebugLevel_)
143                this->softDebugLevel_ = this->softDebugLevelShell_;
144
145            OutputHandler::setSoftDebugLevel(OutputHandler::LD_All,     this->softDebugLevel_);
146            OutputHandler::setSoftDebugLevel(OutputHandler::LD_Console, this->softDebugLevelConsole_);
147            OutputHandler::setSoftDebugLevel(OutputHandler::LD_Logfile, this->softDebugLevelLogfile_);
148            OutputHandler::setSoftDebugLevel(OutputHandler::LD_Shell,   this->softDebugLevelShell_);
149        }
150
151        /**
152            @brief Callback function if the language has changed.
153        */
154        void languageChanged()
155        {
156            // Read the translation file after the language was configured
157            Language::getInstance().readTranslatedLanguageFile();
158        }
159
160        /**
161            @brief Sets the language in the config-file back to the default.
162        */
163        void resetLanguage()
164        {
165            ResetConfigValue(language_);
166        }
167
168        void initializeRandomNumberGenerator()
169        {
170            static bool bInitialized = false;
171            if (!bInitialized && this->bInitializeRandomNumberGenerator_)
172            {
173                srand(static_cast<unsigned int>(time(0)));
174                rand();
175                bInitialized = true;
176            }
177        }
178
179        int softDebugLevel_;                            //!< The debug level
180        int softDebugLevelConsole_;                     //!< The debug level for the console
181        int softDebugLevelLogfile_;                     //!< The debug level for the logfile
182        int softDebugLevelShell_;                       //!< The debug level for the ingame shell
183        std::string language_;                          //!< The language
184        bool bInitializeRandomNumberGenerator_;         //!< If true, srand(time(0)) is called
185    };
186
187
188    Core::Core(const std::string& cmdLine)
189        // Cleanup guard for identifier destruction (incl. XMLPort, configValues, consoleCommands)
190        : identifierDestroyer_(Identifier::destroyAllIdentifiers)
191        // Cleanup guard for external console commands that don't belong to an Identifier
192        , consoleCommandDestroyer_(CommandExecutor::destroyExternalCommands)
193        , configuration_(new CoreConfiguration()) // Don't yet create config values!
194        , bGraphicsLoaded_(false)
195    {
196        // Set the hard coded fixed paths
197        this->pathConfig_.reset(new PathConfig());
198
199        // Create a new dynamic library manager
200        this->dynLibManager_.reset(new DynLibManager());
201
202        // Load modules
203        std::vector<std::string>& modulePaths = this->pathConfig_->getModulePaths();
204        for (std::vector<std::string>::const_iterator it = modulePaths.begin(); it != modulePaths.end(); ++it)
205        {
206            try
207            {
208                this->dynLibManager_->load(*it);
209            }
210            catch (...)
211            {
212                COUT(1) << "Couldn't load module \"" << *it << "\": " << Exception::handleMessage() << std::endl;
213            }
214        }
215
216        // Parse command line arguments AFTER the modules have been loaded (static code!)
217        CommandLine::parseCommandLine(cmdLine);
218
219        // Set configurable paths like log, config and media
220        this->pathConfig_->setConfigurablePaths();
221
222        // create a signal handler (only active for linux)
223        // This call is placed as soon as possible, but after the directories are set
224        this->signalHandler_.reset(new SignalHandler());
225        this->signalHandler_->doCatch(PathConfig::getExecutablePathString(), PathConfig::getLogPathString() + "orxonox_crash.log");
226
227        // Set the correct log path. Before this call, /tmp (Unix) or %TEMP% was used
228        OutputHandler::getOutStream().setLogPath(PathConfig::getLogPathString());
229
230        // Parse additional options file now that we know its path
231        CommandLine::parseFile();
232
233#ifdef ORXONOX_PLATFORM_WINDOWS
234        // limit the main thread to the first core so that QueryPerformanceCounter doesn't jump
235        // do this after ogre has initialised. Somehow Ogre changes the settings again (not through
236        // the timer though).
237        int limitToCPU = CommandLine::getValue("limitToCPU");
238        if (limitToCPU > 0)
239            setThreadAffinity(static_cast<unsigned int>(limitToCPU));
240#endif
241
242        // Manage ini files and set the default settings file (usually orxonox.ini)
243        this->configFileManager_.reset(new ConfigFileManager());
244        this->configFileManager_->setFilename(ConfigFileType::Settings,
245            CommandLine::getValue("settingsFile").getString());
246
247        // Required as well for the config values
248        this->languageInstance_.reset(new Language());
249
250        // creates the class hierarchy for all classes with factories
251        Identifier::createClassHierarchy();
252
253        // Do this soon after the ConfigFileManager has been created to open up the
254        // possibility to configure everything below here
255        this->configuration_->initialise();
256
257        // Load OGRE excluding the renderer and the render window
258        this->graphicsManager_.reset(new GraphicsManager(false));
259
260        // initialise Tcl
261        this->tclBind_.reset(new TclBind(PathConfig::getDataPathString()));
262        this->tclThreadManager_.reset(new TclThreadManager(tclBind_->getTclInterpreter()));
263
264        // create a shell
265        this->shell_.reset(new Shell());
266    }
267
268    /**
269    @brief
270        All destruction code is handled by scoped_ptrs and ScopeGuards.
271    */
272    Core::~Core()
273    {
274    }
275
276    void Core::loadGraphics()
277    {
278        // Any exception should trigger this, even in upgradeToGraphics (see its remarks)
279        Loki::ScopeGuard unloader = Loki::MakeObjGuard(*this, &Core::unloadGraphics);
280
281        // Upgrade OGRE to receive a render window
282        graphicsManager_->upgradeToGraphics();
283
284        // Calls the InputManager which sets up the input devices.
285        inputManager_.reset(new InputManager());
286
287        // load the CEGUI interface
288        guiManager_.reset(new GUIManager(graphicsManager_->getRenderWindow(),
289            inputManager_->getMousePosition(), graphicsManager_->isFullScreen()));
290
291        unloader.Dismiss();
292
293        bGraphicsLoaded_ = true;
294    }
295
296    void Core::unloadGraphics()
297    {
298        this->guiManager_.reset();;
299        this->inputManager_.reset();;
300        this->graphicsManager_.reset();
301
302        // Load Ogre::Root again, but without the render system
303        try
304            { this->graphicsManager_.reset(new GraphicsManager(false)); }
305        catch (...)
306        {
307            COUT(0) << "An exception occurred during 'unloadGraphics':" << Exception::handleMessage() << std::endl
308                    << "Another exception might be being handled which may lead to undefined behaviour!" << std::endl
309                    << "Terminating the program." << std::endl;
310            abort();
311        }
312
313        bGraphicsLoaded_ = false;
314    }
315
316    /**
317        @brief Returns the softDebugLevel for the given device (returns a default-value if the class is right about to be created).
318        @param device The device
319        @return The softDebugLevel
320    */
321    /*static*/ int Core::getSoftDebugLevel(OutputHandler::OutputDevice device)
322    {
323        switch (device)
324        {
325        case OutputHandler::LD_All:
326            return Core::getInstance().configuration_->softDebugLevel_;
327        case OutputHandler::LD_Console:
328            return Core::getInstance().configuration_->softDebugLevelConsole_;
329        case OutputHandler::LD_Logfile:
330            return Core::getInstance().configuration_->softDebugLevelLogfile_;
331        case OutputHandler::LD_Shell:
332            return Core::getInstance().configuration_->softDebugLevelShell_;
333        default:
334            assert(0);
335            return 2;
336        }
337    }
338
339     /**
340        @brief Sets the softDebugLevel for the given device. Please use this only temporary and restore the value afterwards, as it overrides the configured value.
341        @param device The device
342        @param level The level
343    */
344    /*static*/ void Core::setSoftDebugLevel(OutputHandler::OutputDevice device, int level)
345    {
346        if (device == OutputHandler::LD_All)
347            Core::getInstance().configuration_->softDebugLevel_ = level;
348        else if (device == OutputHandler::LD_Console)
349            Core::getInstance().configuration_->softDebugLevelConsole_ = level;
350        else if (device == OutputHandler::LD_Logfile)
351            Core::getInstance().configuration_->softDebugLevelLogfile_ = level;
352        else if (device == OutputHandler::LD_Shell)
353            Core::getInstance().configuration_->softDebugLevelShell_ = level;
354
355        OutputHandler::setSoftDebugLevel(device, level);
356    }
357
358    /**
359        @brief Returns the configured language.
360    */
361    /*static*/ const std::string& Core::getLanguage()
362    {
363        return Core::getInstance().configuration_->language_;
364    }
365
366    /**
367        @brief Sets the language in the config-file back to the default.
368    */
369    /*static*/ void Core::resetLanguage()
370    {
371        Core::getInstance().configuration_->resetLanguage();
372    }
373
374    /**
375    @note
376        The code of this function has been copied and adjusted from OGRE, an open source graphics engine.
377            (Object-oriented Graphics Rendering Engine)
378        For the latest info, see http://www.ogre3d.org/
379
380        Copyright (c) 2000-2008 Torus Knot Software Ltd
381
382        OGRE is licensed under the LGPL. For more info, see OGRE license.
383    */
384    void Core::setThreadAffinity(int limitToCPU)
385    {
386#ifdef ORXONOX_PLATFORM_WINDOWS
387
388        if (limitToCPU <= 0)
389            return;
390
391        unsigned int coreNr = limitToCPU - 1;
392        // Get the current process core mask
393        DWORD procMask;
394        DWORD sysMask;
395#  if _MSC_VER >= 1400 && defined (_M_X64)
396        GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&procMask, (PDWORD_PTR)&sysMask);
397#  else
398        GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask);
399#  endif
400
401        // If procMask is 0, consider there is only one core available
402        // (using 0 as procMask will cause an infinite loop below)
403        if (procMask == 0)
404            procMask = 1;
405
406        // if the core specified with coreNr is not available, take the lowest one
407        if (!(procMask & (1 << coreNr)))
408            coreNr = 0;
409
410        // Find the lowest core that this process uses and coreNr suggests
411        DWORD threadMask = 1;
412        while ((threadMask & procMask) == 0 || (threadMask < (1u << coreNr)))
413            threadMask <<= 1;
414
415        // Set affinity to the first core
416        SetThreadAffinityMask(GetCurrentThread(), threadMask);
417#endif
418    }
419
420    void Core::preUpdate(const Clock& time)
421    {
422        if (this->bGraphicsLoaded_)
423        {
424            // process input events
425            this->inputManager_->update(time);
426            // process gui events
427            this->guiManager_->update(time);
428        }
429        // process thread commands
430        this->tclThreadManager_->update(time);
431    }
432
433    void Core::postUpdate(const Clock& time)
434    {
435        if (this->bGraphicsLoaded_)
436        {
437            // Render (doesn't throw)
438            this->graphicsManager_->update(time);
439        }
440    }
441}
Note: See TracBrowser for help on using the repository browser.