Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

Moved Clock from core to util (used in Scope anyway).

  • Property svn:eol-style set to native
File size: 16.2 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/Clock.h"
51#include "util/Debug.h"
52#include "util/Exception.h"
53#include "util/SignalHandler.h"
54#include "PathConfig.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        const 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        // Create singletons that always exist (in other libraries)
268        this->rootScope_.reset(new Scope<ScopeID::Root>());
269    }
270
271    /**
272    @brief
273        All destruction code is handled by scoped_ptrs and ScopeGuards.
274    */
275    Core::~Core()
276    {
277    }
278
279    void Core::loadGraphics()
280    {
281        // Any exception should trigger this, even in upgradeToGraphics (see its remarks)
282        Loki::ScopeGuard unloader = Loki::MakeObjGuard(*this, &Core::unloadGraphics);
283
284        // Upgrade OGRE to receive a render window
285        graphicsManager_->upgradeToGraphics();
286
287        // Calls the InputManager which sets up the input devices.
288        inputManager_.reset(new InputManager());
289
290        // load the CEGUI interface
291        guiManager_.reset(new GUIManager(graphicsManager_->getRenderWindow(),
292            inputManager_->getMousePosition(), graphicsManager_->isFullScreen()));
293
294        // Create singletons associated with graphics (in other libraries)
295        graphicsScope_.reset(new Scope<ScopeID::Graphics>());
296
297        unloader.Dismiss();
298
299        bGraphicsLoaded_ = true;
300    }
301
302    void Core::unloadGraphics()
303    {
304        this->graphicsScope_.reset();
305        this->guiManager_.reset();
306        this->inputManager_.reset();
307        this->graphicsManager_.reset();
308
309        // Load Ogre::Root again, but without the render system
310        try
311            { this->graphicsManager_.reset(new GraphicsManager(false)); }
312        catch (...)
313        {
314            COUT(0) << "An exception occurred during 'unloadGraphics':" << Exception::handleMessage() << std::endl
315                    << "Another exception might be being handled which may lead to undefined behaviour!" << std::endl
316                    << "Terminating the program." << std::endl;
317            abort();
318        }
319
320        bGraphicsLoaded_ = false;
321    }
322
323    /**
324        @brief Returns the softDebugLevel for the given device (returns a default-value if the class is right about to be created).
325        @param device The device
326        @return The softDebugLevel
327    */
328    /*static*/ int Core::getSoftDebugLevel(OutputHandler::OutputDevice device)
329    {
330        switch (device)
331        {
332        case OutputHandler::LD_All:
333            return Core::getInstance().configuration_->softDebugLevel_;
334        case OutputHandler::LD_Console:
335            return Core::getInstance().configuration_->softDebugLevelConsole_;
336        case OutputHandler::LD_Logfile:
337            return Core::getInstance().configuration_->softDebugLevelLogfile_;
338        case OutputHandler::LD_Shell:
339            return Core::getInstance().configuration_->softDebugLevelShell_;
340        default:
341            assert(0);
342            return 2;
343        }
344    }
345
346     /**
347        @brief Sets the softDebugLevel for the given device. Please use this only temporary and restore the value afterwards, as it overrides the configured value.
348        @param device The device
349        @param level The level
350    */
351    /*static*/ void Core::setSoftDebugLevel(OutputHandler::OutputDevice device, int level)
352    {
353        if (device == OutputHandler::LD_All)
354            Core::getInstance().configuration_->softDebugLevel_ = level;
355        else if (device == OutputHandler::LD_Console)
356            Core::getInstance().configuration_->softDebugLevelConsole_ = level;
357        else if (device == OutputHandler::LD_Logfile)
358            Core::getInstance().configuration_->softDebugLevelLogfile_ = level;
359        else if (device == OutputHandler::LD_Shell)
360            Core::getInstance().configuration_->softDebugLevelShell_ = level;
361
362        OutputHandler::setSoftDebugLevel(device, level);
363    }
364
365    /**
366        @brief Returns the configured language.
367    */
368    /*static*/ const std::string& Core::getLanguage()
369    {
370        return Core::getInstance().configuration_->language_;
371    }
372
373    /**
374        @brief Sets the language in the config-file back to the default.
375    */
376    /*static*/ void Core::resetLanguage()
377    {
378        Core::getInstance().configuration_->resetLanguage();
379    }
380
381    /**
382    @note
383        The code of this function has been copied and adjusted from OGRE, an open source graphics engine.
384            (Object-oriented Graphics Rendering Engine)
385        For the latest info, see http://www.ogre3d.org/
386
387        Copyright (c) 2000-2008 Torus Knot Software Ltd
388
389        OGRE is licensed under the LGPL. For more info, see OGRE license.
390    */
391    void Core::setThreadAffinity(int limitToCPU)
392    {
393#ifdef ORXONOX_PLATFORM_WINDOWS
394
395        if (limitToCPU <= 0)
396            return;
397
398        unsigned int coreNr = limitToCPU - 1;
399        // Get the current process core mask
400        DWORD procMask;
401        DWORD sysMask;
402#  if _MSC_VER >= 1400 && defined (_M_X64)
403        GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&procMask, (PDWORD_PTR)&sysMask);
404#  else
405        GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask);
406#  endif
407
408        // If procMask is 0, consider there is only one core available
409        // (using 0 as procMask will cause an infinite loop below)
410        if (procMask == 0)
411            procMask = 1;
412
413        // if the core specified with coreNr is not available, take the lowest one
414        if (!(procMask & (1 << coreNr)))
415            coreNr = 0;
416
417        // Find the lowest core that this process uses and coreNr suggests
418        DWORD threadMask = 1;
419        while ((threadMask & procMask) == 0 || (threadMask < (1u << coreNr)))
420            threadMask <<= 1;
421
422        // Set affinity to the first core
423        SetThreadAffinityMask(GetCurrentThread(), threadMask);
424#endif
425    }
426
427    void Core::preUpdate(const Clock& time)
428    {
429        // singletons from other libraries
430        Scope<ScopeID::Root>::update(time);
431        if (this->bGraphicsLoaded_)
432        {
433            // process input events
434            this->inputManager_->update(time);
435            // process gui events
436            this->guiManager_->update(time);
437            // graphics singletons from other libraries
438            Scope<ScopeID::Graphics>::update(time);
439        }
440        // process thread commands
441        this->tclThreadManager_->update(time);
442    }
443
444    void Core::postUpdate(const Clock& time)
445    {
446        if (this->bGraphicsLoaded_)
447        {
448            // Render (doesn't throw)
449            this->graphicsManager_->update(time);
450        }
451    }
452}
Note: See TracBrowser for help on using the repository browser.