Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

renamed ScopedSingletonManager to ScopedSingletonWrapper. removed static maps.

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