Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/core7/src/libraries/core/Core.cc @ 10345

Last change on this file since 10345 was 10345, checked in by landauf, 9 years ago

wrap CommandLineArguments in StaticallyInitializedInstances

  • Property svn:eol-style set to native
File size: 20.8 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 <cstdlib>
40#include <ctime>
41#include <fstream>
42#include <vector>
43
44#ifdef ORXONOX_PLATFORM_WINDOWS
45#  ifndef WIN32_LEAN_AND_MEAN
46#    define WIN32_LEAN_AND_MEAN
47#  endif
48#  include <windows.h>
49#  undef min
50#  undef max
51#endif
52
53#include "util/Clock.h"
54#include "util/Output.h"
55#include "util/Exception.h"
56#include "util/output/LogWriter.h"
57#include "util/output/OutputManager.h"
58#include "util/Scope.h"
59#include "util/ScopedSingletonManager.h"
60#include "util/SignalHandler.h"
61#include "PathConfig.h"
62#include "commandline/CommandLineIncludes.h"
63#include "config/ConfigFileManager.h"
64#include "config/ConfigValueIncludes.h"
65#include "CoreIncludes.h"
66#include "DynLibManager.h"
67#include "GameMode.h"
68#include "GraphicsManager.h"
69#include "GUIManager.h"
70#include "class/Identifier.h"
71#include "Language.h"
72#include "LuaState.h"
73#include "command/ConsoleCommand.h"
74#include "command/IOConsole.h"
75#include "command/TclBind.h"
76#include "command/TclThreadManager.h"
77#include "input/InputManager.h"
78#include "object/ObjectList.h"
79#include "module/ModuleInstance.h"
80
81namespace orxonox
82{
83    //! Static pointer to the singleton
84    Core* Core::singletonPtr_s  = 0;
85
86    SetCommandLineArgument(settingsFile, "orxonox.ini").information("THE configuration file");
87#if !defined(ORXONOX_PLATFORM_APPLE) && !defined(ORXONOX_USE_WINMAIN)
88    SetCommandLineSwitch(noIOConsole).information("Use this if you don't want to use the IOConsole (for instance for Lua debugging)");
89#endif
90
91#ifdef ORXONOX_PLATFORM_WINDOWS
92    SetCommandLineArgument(limitToCPU, 0).information("Limits the program to one CPU/core (1, 2, 3, etc.). Default is off = 0.");
93#endif
94
95    // register Core as an abstract class to avoid problems if the class hierarchy is created within Core-constructor
96    RegisterAbstractClass(Core).inheritsFrom(Class(Configurable));
97
98    Core::Core(const std::string& cmdLine)
99        : pathConfig_(NULL)
100        , dynLibManager_(NULL)
101        , signalHandler_(NULL)
102        , configFileManager_(NULL)
103        , languageInstance_(NULL)
104        , ioConsole_(NULL)
105        , tclBind_(NULL)
106        , tclThreadManager_(NULL)
107        , rootScope_(NULL)
108        , graphicsManager_(NULL)
109        , inputManager_(NULL)
110        , guiManager_(NULL)
111        , graphicsScope_(NULL)
112        , bGraphicsLoaded_(false)
113        , bStartIOConsole_(true)
114        , lastLevelTimestamp_(0)
115        , ogreConfigTimestamp_(0)
116        , bDevMode_(false)
117        , destructionHelper_(this)
118    {
119        orxout(internal_status) << "initializing Core object..." << endl;
120
121        // Set the hard coded fixed paths
122        this->pathConfig_ = new PathConfig();
123
124        // Create a new dynamic library manager
125        this->dynLibManager_ = new DynLibManager();
126
127        // Load modules
128        orxout(internal_info) << "Loading modules:" << endl;
129        const std::vector<std::string>& modulePaths = this->pathConfig_->getModulePaths();
130        for (std::vector<std::string>::const_iterator it = modulePaths.begin(); it != modulePaths.end(); ++it)
131        {
132            try
133            {
134                this->dynLibManager_->load(*it);
135            }
136            catch (...)
137            {
138                orxout(user_error) << "Couldn't load module \"" << *it << "\": " << Exception::handleMessage() << endl;
139            }
140        }
141
142        // TODO: initialize CommandLineParser here
143        ModuleInstance::getCurrentModuleInstance()->loadAllStaticallyInitializedInstances();
144
145        // Parse command line arguments AFTER the modules have been loaded (static code!)
146        CommandLineParser::parse(cmdLine);
147
148        // Set configurable paths like log, config and media
149        this->pathConfig_->setConfigurablePaths();
150
151        orxout(internal_info) << "Root path:       " << PathConfig::getRootPathString() << endl;
152        orxout(internal_info) << "Executable path: " << PathConfig::getExecutablePathString() << endl;
153        orxout(internal_info) << "Data path:       " << PathConfig::getDataPathString() << endl;
154        orxout(internal_info) << "Ext. data path:  " << PathConfig::getExternalDataPathString() << endl;
155        orxout(internal_info) << "Config path:     " << PathConfig::getConfigPathString() << endl;
156        orxout(internal_info) << "Log path:        " << PathConfig::getLogPathString() << endl;
157        orxout(internal_info) << "Modules path:    " << PathConfig::getModulePathString() << endl;
158
159        // create a signal handler (only active for Linux)
160        // This call is placed as soon as possible, but after the directories are set
161        this->signalHandler_ = new SignalHandler();
162        this->signalHandler_->doCatch(PathConfig::getExecutablePathString(), PathConfig::getLogPathString() + "orxonox_crash.log");
163
164#ifdef ORXONOX_PLATFORM_WINDOWS
165        // limit the main thread to the first core so that QueryPerformanceCounter doesn't jump
166        // do this after ogre has initialised. Somehow Ogre changes the settings again (not through
167        // the timer though).
168        int limitToCPU = CommandLineParser::getValue("limitToCPU");
169        if (limitToCPU > 0)
170            setThreadAffinity(static_cast<unsigned int>(limitToCPU));
171#endif
172
173        // Manage ini files and set the default settings file (usually orxonox.ini)
174        orxout(internal_info) << "Loading config:" << endl;
175        this->configFileManager_ = new ConfigFileManager();
176        this->configFileManager_->setFilename(ConfigFileType::Settings,
177            CommandLineParser::getValue("settingsFile").get<std::string>());
178
179        // Required as well for the config values
180        orxout(internal_info) << "Loading language:" << endl;
181        this->languageInstance_ = new Language();
182
183        // Do this soon after the ConfigFileManager has been created to open up the
184        // possibility to configure everything below here
185        RegisterObject(Core);
186        orxout(internal_info) << "configuring Core" << endl;
187        this->setConfigValues();
188
189        // Set the correct log path and rewrite the log file with the correct log levels
190        OutputManager::getInstance().getLogWriter()->setLogDirectory(PathConfig::getLogPathString());
191
192#if !defined(ORXONOX_PLATFORM_APPLE) && !defined(ORXONOX_USE_WINMAIN)
193        // Create persistent IO console
194        if (CommandLineParser::getValue("noIOConsole").get<bool>())
195        {
196            ModifyConfigValue(bStartIOConsole_, tset, false);
197        }
198        if (this->bStartIOConsole_)
199        {
200            orxout(internal_info) << "creating IO console" << endl;
201            this->ioConsole_ = new IOConsole();
202        }
203#endif
204
205        // creates the class hierarchy for all classes with factories
206        orxout(internal_info) << "creating class hierarchy" << endl;
207        IdentifierManager::getInstance().createClassHierarchy();
208
209        // Load OGRE excluding the renderer and the render window
210        orxout(internal_info) << "creating GraphicsManager:" << endl;
211        this->graphicsManager_ = new GraphicsManager(false);
212
213        // initialise Tcl
214        this->tclBind_ = new TclBind(PathConfig::getDataPathString());
215        this->tclThreadManager_ = new TclThreadManager(tclBind_->getTclInterpreter());
216
217        // Create singletons that always exist (in other libraries)
218        orxout(internal_info) << "creating root scope:" << endl;
219        this->rootScope_ = new Scope<ScopeID::Root>();
220
221        // Generate documentation instead of normal run?
222        std::string docFilename;
223        CommandLineParser::getValue("generateDoc", &docFilename);
224        if (!docFilename.empty())
225        {
226            std::ofstream docFile(docFilename.c_str());
227            if (docFile.is_open())
228            {
229                CommandLineParser::generateDoc(docFile);
230                docFile.close();
231            }
232            else
233                orxout(internal_error) << "Could not open file for documentation writing" << endl;
234        }
235
236        orxout(internal_status) << "finished initializing Core object" << endl;
237    }
238
239    void Core::destroy()
240    {
241        orxout(internal_status) << "destroying Core object..." << endl;
242
243        // Remove us from the object lists again to avoid problems when destroying them
244        this->unregisterObject();
245
246        safeObjectDelete(&graphicsScope_);
247        safeObjectDelete(&guiManager_);
248        safeObjectDelete(&inputManager_);
249        safeObjectDelete(&graphicsManager_);
250        safeObjectDelete(&rootScope_);
251        safeObjectDelete(&tclThreadManager_);
252        safeObjectDelete(&tclBind_);
253        safeObjectDelete(&ioConsole_);
254        safeObjectDelete(&languageInstance_);
255        safeObjectDelete(&configFileManager_);
256        ConsoleCommand::destroyAll();
257        Context::setRootContext(NULL);
258        IdentifierManager::getInstance().destroyAllIdentifiers();
259        safeObjectDelete(&signalHandler_);
260        safeObjectDelete(&dynLibManager_);
261        safeObjectDelete(&pathConfig_);
262
263        orxout(internal_status) << "finished destroying Core object" << endl;
264    }
265
266    //! Function to collect the SetConfigValue-macro calls.
267    void Core::setConfigValues()
268    {
269        SetConfigValueExternal(OutputManager::getInstance().getLogWriter()->configurableMaxLevel_,
270                               OutputManager::getInstance().getLogWriter()->getConfigurableSectionName(),
271                               OutputManager::getInstance().getLogWriter()->getConfigurableMaxLevelName(),
272                               OutputManager::getInstance().getLogWriter()->configurableMaxLevel_)
273            .description("The maximum level of output shown in the log file")
274            .callback(static_cast<BaseWriter*>(OutputManager::getInstance().getLogWriter()), &BaseWriter::changedConfigurableLevel);
275        SetConfigValueExternal(OutputManager::getInstance().getLogWriter()->configurableAdditionalContextsMaxLevel_,
276                               OutputManager::getInstance().getLogWriter()->getConfigurableSectionName(),
277                               OutputManager::getInstance().getLogWriter()->getConfigurableAdditionalContextsMaxLevelName(),
278                               OutputManager::getInstance().getLogWriter()->configurableAdditionalContextsMaxLevel_)
279            .description("The maximum level of output shown in the log file for additional contexts")
280            .callback(static_cast<BaseWriter*>(OutputManager::getInstance().getLogWriter()), &BaseWriter::changedConfigurableAdditionalContextsLevel);
281        SetConfigValueExternal(OutputManager::getInstance().getLogWriter()->configurableAdditionalContexts_,
282                               OutputManager::getInstance().getLogWriter()->getConfigurableSectionName(),
283                               OutputManager::getInstance().getLogWriter()->getConfigurableAdditionalContextsName(),
284                               OutputManager::getInstance().getLogWriter()->configurableAdditionalContexts_)
285            .description("Additional output contexts shown in the log file")
286            .callback(static_cast<BaseWriter*>(OutputManager::getInstance().getLogWriter()), &BaseWriter::changedConfigurableAdditionalContexts);
287
288        SetConfigValue(bDevMode_, PathConfig::buildDirectoryRun())
289            .description("Developer mode. If not set, hides some things from the user to not confuse him.")
290            .callback(this, &Core::devModeChanged);
291        SetConfigValue(language_, Language::getInstance().defaultLanguage_)
292            .description("The language of the in game text")
293            .callback(this, &Core::languageChanged);
294        SetConfigValue(bInitRandomNumberGenerator_, true)
295            .description("If true, all random actions are different each time you start the game")
296            .callback(this, &Core::initRandomNumberGenerator);
297        SetConfigValue(bStartIOConsole_, true)
298            .description("Set to false if you don't want to use the IOConsole (for Lua debugging for instance)");
299        SetConfigValue(lastLevelTimestamp_, 0)
300            .description("Timestamp when the last level was started.");
301        SetConfigValue(ogreConfigTimestamp_, 0)
302            .description("Timestamp when the ogre config file was changed.");
303    }
304
305    /** Callback function for changes in the dev mode that affect debug levels.
306        The function behaves according to these rules:
307        - 'normal' mode is defined based on where the program was launched: if
308          the launch path was the build directory, development mode \c on is
309          normal, otherwise normal means development mode \c off.
310        - Debug levels should not be hard configured (\c config instead of
311          \c tconfig) in non 'normal' mode to avoid strange behaviour.
312        - Changing the development mode from 'normal' to the other state will
313          immediately change the debug levels to predefined values which can be
314          reconfigured with \c tconfig.
315    @note
316        The debug levels for the IOConsole and the InGameConsole can be found
317        in the Shell class. The same rules apply.
318    */
319    void Core::devModeChanged()
320    {
321        // Inform listeners
322        ObjectList<DevModeListener>::iterator it = ObjectList<DevModeListener>::begin();
323        for (; it != ObjectList<DevModeListener>::end(); ++it)
324            it->devModeChanged(bDevMode_);
325    }
326
327    //! Callback function if the language has changed.
328    void Core::languageChanged()
329    {
330        // Read the translation file after the language was configured
331        Language::getInstance().readTranslatedLanguageFile();
332    }
333
334    void Core::initRandomNumberGenerator()
335    {
336        static bool bInitialized = false;
337        if (!bInitialized && this->bInitRandomNumberGenerator_)
338        {
339            srand(static_cast<unsigned int>(time(0)));
340            rand();
341            bInitialized = true;
342        }
343    }
344
345    void Core::loadGraphics()
346    {
347        orxout(internal_info) << "loading graphics in Core" << endl;
348
349        // Any exception should trigger this, even in upgradeToGraphics (see its remarks)
350        Loki::ScopeGuard unloader = Loki::MakeObjGuard(*this, &Core::unloadGraphics);
351
352        // Upgrade OGRE to receive a render window
353        try
354        {
355            graphicsManager_->upgradeToGraphics();
356        }
357        catch (const InitialisationFailedException&)
358        {
359            // Exit the application if the Ogre config dialog was canceled
360            orxout(user_error) << Exception::handleMessage() << endl;
361            exit(EXIT_FAILURE);
362        }
363        catch (...)
364        {
365            // Recovery from this is very difficult. It requires to completely
366            // destroy Ogre related objects and load again (without graphics).
367            // However since Ogre 1.7 there seems to be a problem when Ogre
368            // throws an exception and the graphics engine then gets destroyed
369            // and reloaded between throw and catch (access violation in MSVC).
370            // That's why we abort completely and only display the exception.
371            orxout(user_error) << "An exception occurred during upgrade to graphics. "
372                               << "That is unrecoverable. The message was:" << endl
373                               << Exception::handleMessage() << endl;
374            abort();
375        }
376
377        // Calls the InputManager which sets up the input devices.
378        inputManager_ = new InputManager();
379
380        // Load the CEGUI interface
381        guiManager_ = new GUIManager(inputManager_->getMousePosition());
382
383        bGraphicsLoaded_ = true;
384        GameMode::bShowsGraphics_s = true;
385
386        // Load some sort of a debug overlay (only denoted by its name, "debug.oxo")
387        graphicsManager_->loadDebugOverlay();
388
389        // Create singletons associated with graphics (in other libraries)
390        orxout(internal_info) << "creating graphics scope:" << endl;
391        graphicsScope_ = new Scope<ScopeID::Graphics>();
392
393        unloader.Dismiss();
394
395        orxout(internal_info) << "finished loading graphics in Core" << endl;
396    }
397
398    void Core::unloadGraphics()
399    {
400        orxout(internal_info) << "unloading graphics in Core" << endl;
401
402        safeObjectDelete(&graphicsScope_);
403        safeObjectDelete(&guiManager_);
404        safeObjectDelete(&inputManager_);
405        safeObjectDelete(&graphicsManager_);
406
407        // Load Ogre::Root again, but without the render system
408        try
409            { this->graphicsManager_ = new GraphicsManager(false); }
410        catch (...)
411        {
412            orxout(user_error) << "An exception occurred during 'unloadGraphics':" << Exception::handleMessage() << endl
413                               << "Another exception might be being handled which may lead to undefined behaviour!" << endl
414                               << "Terminating the program." << endl;
415            abort();
416        }
417
418        bGraphicsLoaded_ = false;
419        GameMode::bShowsGraphics_s = false;
420    }
421
422    //! Sets the language in the config-file back to the default.
423    void Core::resetLanguage()
424    {
425        ResetConfigValue(language_);
426    }
427
428    /**
429    @note
430        The code of this function has been copied and adjusted from OGRE, an open source graphics engine.
431            (Object-oriented Graphics Rendering Engine)
432        For the latest info, see http://www.ogre3d.org/
433
434        Copyright (c) 2000-2008 Torus Knot Software Ltd
435
436        OGRE is licensed under the LGPL. For more info, see OGRE license.
437    */
438    void Core::setThreadAffinity(int limitToCPU)
439    {
440#ifdef ORXONOX_PLATFORM_WINDOWS
441
442        if (limitToCPU <= 0)
443            return;
444
445        unsigned int coreNr = limitToCPU - 1;
446        // Get the current process core mask
447        DWORD procMask;
448        DWORD sysMask;
449#  if _MSC_VER >= 1400 && defined (_M_X64)
450        GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&procMask, (PDWORD_PTR)&sysMask);
451#  else
452        GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask);
453#  endif
454
455        // If procMask is 0, consider there is only one core available
456        // (using 0 as procMask will cause an infinite loop below)
457        if (procMask == 0)
458            procMask = 1;
459
460        // if the core specified with coreNr is not available, take the lowest one
461        if (!(procMask & (1 << coreNr)))
462            coreNr = 0;
463
464        // Find the lowest core that this process uses and coreNr suggests
465        DWORD threadMask = 1;
466        while ((threadMask & procMask) == 0 || (threadMask < (1u << coreNr)))
467            threadMask <<= 1;
468
469        // Set affinity to the first core
470        SetThreadAffinityMask(GetCurrentThread(), threadMask);
471#endif
472    }
473
474    void Core::preUpdate(const Clock& time)
475    {
476        // Update singletons before general ticking
477        ScopedSingletonManager::preUpdate<ScopeID::Root>(time);
478        if (this->bGraphicsLoaded_)
479        {
480            // Process input events
481            this->inputManager_->preUpdate(time);
482            // Update GUI
483            this->guiManager_->preUpdate(time);
484            // Update singletons before general ticking
485            ScopedSingletonManager::preUpdate<ScopeID::Graphics>(time);
486        }
487        // Process console events and status line
488        if (this->ioConsole_ != NULL)
489            this->ioConsole_->preUpdate(time);
490        // Process thread commands
491        this->tclThreadManager_->preUpdate(time);
492    }
493
494    void Core::postUpdate(const Clock& time)
495    {
496        // Update singletons just before rendering
497        ScopedSingletonManager::postUpdate<ScopeID::Root>(time);
498        if (this->bGraphicsLoaded_)
499        {
500            // Update singletons just before rendering
501            ScopedSingletonManager::postUpdate<ScopeID::Graphics>(time);
502            // Render (doesn't throw)
503            this->graphicsManager_->postUpdate(time);
504        }
505    }
506
507    void Core::updateLastLevelTimestamp()
508    {
509        ModifyConfigValue(lastLevelTimestamp_, set, static_cast<long long>(time(NULL)));
510    }
511
512    void Core::updateOgreConfigTimestamp()
513    {
514        ModifyConfigValue(ogreConfigTimestamp_, set, static_cast<long long>(time(NULL)));
515    }
516
517
518    RegisterAbstractClass(DevModeListener).inheritsFrom(Class(Listable));
519
520    DevModeListener::DevModeListener()
521    {
522        RegisterObject(DevModeListener);
523    }
524}
Note: See TracBrowser for help on using the repository browser.