Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

clean and explicit setup/shutdown of singletons that are used by statically initialized instances

  • Property svn:eol-style set to native
File size: 17.9 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"
[10540]56#include "util/SignalHandler.h"
[8858]57#include "util/output/LogWriter.h"
[9550]58#include "util/output/OutputManager.h"
[10407]59#include "core/singleton/Scope.h"
[10509]60#include "ApplicationPaths.h"
61#include "ConfigurablePaths.h"
[10345]62#include "commandline/CommandLineIncludes.h"
[9667]63#include "config/ConfigFileManager.h"
[5781]64#include "GameMode.h"
65#include "GraphicsManager.h"
66#include "GUIManager.h"
[1505]67#include "Language.h"
[10392]68#include "Loader.h"
[5695]69#include "LuaState.h"
[7284]70#include "command/IOConsole.h"
71#include "command/TclBind.h"
72#include "command/TclThreadManager.h"
[5781]73#include "input/InputManager.h"
[9667]74#include "object/ObjectList.h"
[10540]75#include "module/DynLibManager.h"
[10342]76#include "module/ModuleInstance.h"
[10532]77#include "module/StaticInitializationManager.h"
78#include "CoreStaticInitializationHandler.h"
[10413]79#include "UpdateListener.h"
[1505]80
81namespace orxonox
82{
[3196]83    //! Static pointer to the singleton
[3370]84    Core* Core::singletonPtr_s  = 0;
[2662]85
[3280]86    SetCommandLineArgument(settingsFile, "orxonox.ini").information("THE configuration file");
[8351]87#if !defined(ORXONOX_PLATFORM_APPLE) && !defined(ORXONOX_USE_WINMAIN)
[6746]88    SetCommandLineSwitch(noIOConsole).information("Use this if you don't want to use the IOConsole (for instance for Lua debugging)");
[8351]89#endif
[7163]90
[3280]91#ifdef ORXONOX_PLATFORM_WINDOWS
[8505]92    SetCommandLineArgument(limitToCPU, 0).information("Limits the program to one CPU/core (1, 2, 3, etc.). Default is off = 0.");
[3280]93#endif
[2710]94
[3323]95    Core::Core(const std::string& cmdLine)
[10509]96        : applicationPaths_(NULL)
97        , configurablePaths_(NULL)
[8423]98        , dynLibManager_(NULL)
99        , signalHandler_(NULL)
100        , configFileManager_(NULL)
101        , languageInstance_(NULL)
[10392]102        , loaderInstance_(NULL)
[8423]103        , ioConsole_(NULL)
104        , tclBind_(NULL)
105        , tclThreadManager_(NULL)
106        , rootScope_(NULL)
107        , graphicsManager_(NULL)
108        , inputManager_(NULL)
109        , guiManager_(NULL)
110        , graphicsScope_(NULL)
[5781]111        , bGraphicsLoaded_(false)
[10532]112        , staticInitHandler_(NULL)
[10518]113        , rootModule_(NULL)
[10479]114        , config_(NULL)
[8423]115        , destructionHelper_(this)
[3280]116    {
[8858]117        orxout(internal_status) << "initializing Core object..." << endl;
118
[5693]119        // Set the hard coded fixed paths
[10509]120        this->applicationPaths_ = new ApplicationPaths();
[3280]121
[5693]122        // Create a new dynamic library manager
[8423]123        this->dynLibManager_ = new DynLibManager();
[2896]124
[10483]125        // TODO: initialize Root-Context
[10542]126        new StaticInitializationManager(); // create singleton
[10535]127        this->staticInitHandler_ = new CoreStaticInitializationHandler();
128        StaticInitializationManager::getInstance().addHandler(this->staticInitHandler_);
129
[10518]130        this->rootModule_ = ModuleInstance::getCurrentModuleInstance();
[10535]131        StaticInitializationManager::getInstance().loadModule(this->rootModule_);
[10342]132
[5693]133        // Parse command line arguments AFTER the modules have been loaded (static code!)
[8729]134        CommandLineParser::parse(cmdLine);
[5693]135
136        // Set configurable paths like log, config and media
[10509]137        this->configurablePaths_ = new ConfigurablePaths();
138        this->configurablePaths_->setConfigurablePaths(ApplicationPaths::getInstance());
[5693]139
[10509]140        orxout(internal_info) << "Root path:       " << ApplicationPaths::getRootPathString() << endl;
141        orxout(internal_info) << "Executable path: " << ApplicationPaths::getExecutablePathString() << endl;
142        orxout(internal_info) << "Modules path:    " << ApplicationPaths::getModulePathString() << endl;
[8858]143
[10509]144        orxout(internal_info) << "Data path:       " << ConfigurablePaths::getDataPathString() << endl;
145        orxout(internal_info) << "Ext. data path:  " << ConfigurablePaths::getExternalDataPathString() << endl;
146        orxout(internal_info) << "Config path:     " << ConfigurablePaths::getConfigPathString() << endl;
147        orxout(internal_info) << "Log path:        " << ConfigurablePaths::getLogPathString() << endl;
148
149        // create a signal handler
[2896]150        // This call is placed as soon as possible, but after the directories are set
[8423]151        this->signalHandler_ = new SignalHandler();
[10509]152        this->signalHandler_->doCatch(ApplicationPaths::getExecutablePathString(), ConfigurablePaths::getLogPathString() + "orxonox_crash.log");
[2896]153
[3280]154#ifdef ORXONOX_PLATFORM_WINDOWS
155        // limit the main thread to the first core so that QueryPerformanceCounter doesn't jump
156        // do this after ogre has initialised. Somehow Ogre changes the settings again (not through
157        // the timer though).
[6021]158        int limitToCPU = CommandLineParser::getValue("limitToCPU");
[3280]159        if (limitToCPU > 0)
160            setThreadAffinity(static_cast<unsigned int>(limitToCPU));
161#endif
162
[2896]163        // Manage ini files and set the default settings file (usually orxonox.ini)
[8858]164        orxout(internal_info) << "Loading config:" << endl;
[8423]165        this->configFileManager_ = new ConfigFileManager();
[2896]166        this->configFileManager_->setFilename(ConfigFileType::Settings,
[9550]167            CommandLineParser::getValue("settingsFile").get<std::string>());
[2896]168
[3280]169        // Required as well for the config values
[8858]170        orxout(internal_info) << "Loading language:" << endl;
[8423]171        this->languageInstance_ = new Language();
[2896]172
[6417]173        // Do this soon after the ConfigFileManager has been created to open up the
174        // possibility to configure everything below here
[8858]175        orxout(internal_info) << "configuring Core" << endl;
[10479]176        this->config_ = new CoreConfig();
[6417]177
[8858]178        // Set the correct log path and rewrite the log file with the correct log levels
[10509]179        OutputManager::getInstance().getLogWriter()->setLogDirectory(ConfigurablePaths::getLogPathString());
[8858]180
[8351]181#if !defined(ORXONOX_PLATFORM_APPLE) && !defined(ORXONOX_USE_WINMAIN)
182        // Create persistent IO console
[10479]183        if (CommandLineParser::getValue("noIOConsole").get<bool>() == false && this->config_->getStartIOConsole())
[6746]184        {
[8858]185            orxout(internal_info) << "creating IO console" << endl;
[8423]186            this->ioConsole_ = new IOConsole();
[8858]187        }
[8351]188#endif
[6105]189
[5695]190        // creates the class hierarchy for all classes with factories
[8858]191        orxout(internal_info) << "creating class hierarchy" << endl;
[10535]192        this->staticInitHandler_->initInstances(this->rootModule_);
193        this->staticInitHandler_->setInitInstances(true);
[5695]194
[10392]195        // Loader
196        this->loaderInstance_ = new Loader();
197
[5781]198        // Load OGRE excluding the renderer and the render window
[8858]199        orxout(internal_info) << "creating GraphicsManager:" << endl;
[8423]200        this->graphicsManager_ = new GraphicsManager(false);
[5781]201
202        // initialise Tcl
[10509]203        this->tclBind_ = new TclBind(ConfigurablePaths::getDataPathString());
[8423]204        this->tclThreadManager_ = new TclThreadManager(tclBind_->getTclInterpreter());
[5781]205
[5929]206        // Create singletons that always exist (in other libraries)
[8858]207        orxout(internal_info) << "creating root scope:" << endl;
[10464]208        this->rootScope_ = new Scope<ScopeID::ROOT>();
[7401]209
210        // Generate documentation instead of normal run?
211        std::string docFilename;
212        CommandLineParser::getValue("generateDoc", &docFilename);
213        if (!docFilename.empty())
214        {
215            std::ofstream docFile(docFilename.c_str());
216            if (docFile.is_open())
217            {
218                CommandLineParser::generateDoc(docFile);
219                docFile.close();
220            }
221            else
[8858]222                orxout(internal_error) << "Could not open file for documentation writing" << endl;
[7401]223        }
[8858]224
225        orxout(internal_status) << "finished initializing Core object" << endl;
[1505]226    }
227
[8423]228    void Core::destroy()
[1505]229    {
[8858]230        orxout(internal_status) << "destroying Core object..." << endl;
231
[8423]232        safeObjectDelete(&graphicsScope_);
233        safeObjectDelete(&guiManager_);
234        safeObjectDelete(&inputManager_);
235        safeObjectDelete(&graphicsManager_);
236        safeObjectDelete(&rootScope_);
237        safeObjectDelete(&tclThreadManager_);
238        safeObjectDelete(&tclBind_);
239        safeObjectDelete(&ioConsole_);
[10392]240        safeObjectDelete(&loaderInstance_);
[10479]241        safeObjectDelete(&config_);
[8423]242        safeObjectDelete(&languageInstance_);
243        safeObjectDelete(&configFileManager_);
[10527]244        safeObjectDelete(&signalHandler_);
245        Context::getRootContext()->unregisterObject(); // unregister context from object lists - otherwise the root context would be destroyed while unloading the root module
246        if (this->rootModule_)
247        {
[10535]248            StaticInitializationManager::getInstance().unloadModule(this->rootModule_);
[10527]249            this->rootModule_->deleteAllStaticallyInitializedInstances();
250        }
[10532]251        if (this->staticInitHandler_)
252            StaticInitializationManager::getInstance().removeHandler(this->staticInitHandler_);
[9667]253        Context::setRootContext(NULL);
[10527]254        safeObjectDelete(&rootModule_);
[10532]255        safeObjectDelete(&staticInitHandler_);
[10542]256        delete &StaticInitializationManager::getInstance();
[8423]257        safeObjectDelete(&dynLibManager_);
[10509]258        safeObjectDelete(&configurablePaths_);
259        safeObjectDelete(&applicationPaths_);
[2896]260
[8858]261        orxout(internal_status) << "finished destroying Core object" << endl;
[8729]262    }
263
[10518]264    void Core::loadModules()
265    {
266        orxout(internal_info) << "Loading modules:" << endl;
267
268        const std::vector<std::string>& modulePaths = ApplicationPaths::getInstance().getModulePaths();
269        for (std::vector<std::string>::const_iterator it = modulePaths.begin(); it != modulePaths.end(); ++it)
270        {
271            try
272            {
273                ModuleInstance* module = new ModuleInstance(*it);
274                this->loadModule(module);
275                this->modules_.push_back(module);
276            }
277            catch (...)
278            {
279                orxout(user_error) << "Couldn't load module \"" << *it << "\": " << Exception::handleMessage() << endl;
280            }
281        }
282
283        orxout(internal_info) << "finished loading modules" << endl;
284    }
285
286    void Core::loadModule(ModuleInstance* module)
287    {
[10527]288        orxout(internal_info) << "Loading module " << module->getName() << "..." << endl;
289
[10518]290        ModuleInstance::setCurrentModuleInstance(module);
291        DynLib* dynLib = this->dynLibManager_->load(module->getName());
292        module->setDynLib(dynLib);
[10532]293
294        StaticInitializationManager::getInstance().loadModule(module);
[10518]295    }
296
297    void Core::unloadModules()
298    {
299        for (std::list<ModuleInstance*>::iterator it = this->modules_.begin(); it != this->modules_.end(); ++it)
300        {
301            ModuleInstance* module = (*it);
302            this->unloadModule(module);
303            delete module;
304        }
305        this->modules_.clear();
306    }
307
308    void Core::unloadModule(ModuleInstance* module)
309    {
[10527]310        orxout(internal_info) << "Unloading module " << module->getName() << "..." << endl;
311
[10532]312        StaticInitializationManager::getInstance().unloadModule(module);
313
[10518]314        module->deleteAllStaticallyInitializedInstances();
315        this->dynLibManager_->unload(module->getDynLib());
316        module->setDynLib(NULL);
317    }
318
[5781]319    void Core::loadGraphics()
320    {
[8858]321        orxout(internal_info) << "loading graphics in Core" << endl;
[9550]322
[5781]323        // Any exception should trigger this, even in upgradeToGraphics (see its remarks)
[10524]324        Loki::ScopeGuard unloader = Loki::MakeObjGuard(*this, &Core::unloadGraphics, true);
[5781]325
326        // Upgrade OGRE to receive a render window
[7175]327        try
328        {
329            graphicsManager_->upgradeToGraphics();
330        }
[7872]331        catch (const InitialisationFailedException&)
[7868]332        {
333            // Exit the application if the Ogre config dialog was canceled
[8858]334            orxout(user_error) << Exception::handleMessage() << endl;
[7868]335            exit(EXIT_FAILURE);
336        }
[7175]337        catch (...)
338        {
339            // Recovery from this is very difficult. It requires to completely
340            // destroy Ogre related objects and load again (without graphics).
341            // However since Ogre 1.7 there seems to be a problem when Ogre
342            // throws an exception and the graphics engine then gets destroyed
343            // and reloaded between throw and catch (access violation in MSVC).
344            // That's why we abort completely and only display the exception.
[8858]345            orxout(user_error) << "An exception occurred during upgrade to graphics. "
346                               << "That is unrecoverable. The message was:" << endl
347                               << Exception::handleMessage() << endl;
[7175]348            abort();
349        }
[5781]350
351        // Calls the InputManager which sets up the input devices.
[8423]352        inputManager_ = new InputManager();
[5781]353
[5929]354        // Load the CEGUI interface
[8423]355        guiManager_ = new GUIManager(inputManager_->getMousePosition());
[5781]356
[5929]357        bGraphicsLoaded_ = true;
358        GameMode::bShowsGraphics_s = true;
359
360        // Load some sort of a debug overlay (only denoted by its name, "debug.oxo")
361        graphicsManager_->loadDebugOverlay();
362
363        // Create singletons associated with graphics (in other libraries)
[8858]364        orxout(internal_info) << "creating graphics scope:" << endl;
[10464]365        graphicsScope_ = new Scope<ScopeID::GRAPHICS>();
[5929]366
[5781]367        unloader.Dismiss();
[8858]368
369        orxout(internal_info) << "finished loading graphics in Core" << endl;
[5781]370    }
371
[10524]372    void Core::unloadGraphics(bool loadGraphicsManagerWithoutRenderer)
[5781]373    {
[8858]374        orxout(internal_info) << "unloading graphics in Core" << endl;
375
[10525]376        if (this->graphicsManager_)
377            this->graphicsManager_->unloadDebugOverlay();
378
[8423]379        safeObjectDelete(&graphicsScope_);
380        safeObjectDelete(&guiManager_);
381        safeObjectDelete(&inputManager_);
382        safeObjectDelete(&graphicsManager_);
[5781]383
384        // Load Ogre::Root again, but without the render system
385        try
[10524]386        {
387            if (loadGraphicsManagerWithoutRenderer)
388                this->graphicsManager_ = new GraphicsManager(false);
389        }
[5781]390        catch (...)
391        {
[8858]392            orxout(user_error) << "An exception occurred during 'unloadGraphics':" << Exception::handleMessage() << endl
393                               << "Another exception might be being handled which may lead to undefined behaviour!" << endl
394                               << "Terminating the program." << endl;
[5781]395            abort();
396        }
397
398        bGraphicsLoaded_ = false;
[5929]399        GameMode::bShowsGraphics_s = false;
[5781]400    }
401
[1505]402    /**
[2896]403    @note
404        The code of this function has been copied and adjusted from OGRE, an open source graphics engine.
405            (Object-oriented Graphics Rendering Engine)
406        For the latest info, see http://www.ogre3d.org/
407
408        Copyright (c) 2000-2008 Torus Knot Software Ltd
409
410        OGRE is licensed under the LGPL. For more info, see OGRE license.
[2710]411    */
[2896]412    void Core::setThreadAffinity(int limitToCPU)
[2710]413    {
[3280]414#ifdef ORXONOX_PLATFORM_WINDOWS
415
[2896]416        if (limitToCPU <= 0)
417            return;
[2710]418
[2896]419        unsigned int coreNr = limitToCPU - 1;
420        // Get the current process core mask
421        DWORD procMask;
422        DWORD sysMask;
423#  if _MSC_VER >= 1400 && defined (_M_X64)
424        GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&procMask, (PDWORD_PTR)&sysMask);
425#  else
426        GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask);
427#  endif
[2710]428
[2896]429        // If procMask is 0, consider there is only one core available
430        // (using 0 as procMask will cause an infinite loop below)
431        if (procMask == 0)
432            procMask = 1;
433
434        // if the core specified with coreNr is not available, take the lowest one
435        if (!(procMask & (1 << coreNr)))
436            coreNr = 0;
437
438        // Find the lowest core that this process uses and coreNr suggests
439        DWORD threadMask = 1;
440        while ((threadMask & procMask) == 0 || (threadMask < (1u << coreNr)))
441            threadMask <<= 1;
442
443        // Set affinity to the first core
444        SetThreadAffinityMask(GetCurrentThread(), threadMask);
445#endif
[2710]446    }
447
[5695]448    void Core::preUpdate(const Clock& time)
[2896]449    {
[10413]450        // Update UpdateListeners before general ticking
451        for (ObjectList<UpdateListener>::iterator it = ObjectList<UpdateListener>::begin(); it != ObjectList<UpdateListener>::end(); ++it)
452            it->preUpdate(time);
[5781]453        if (this->bGraphicsLoaded_)
454        {
[6417]455            // Process input events
456            this->inputManager_->preUpdate(time);
457            // Update GUI
458            this->guiManager_->preUpdate(time);
[5781]459        }
[6417]460        // Process console events and status line
[6746]461        if (this->ioConsole_ != NULL)
462            this->ioConsole_->preUpdate(time);
[6417]463        // Process thread commands
464        this->tclThreadManager_->preUpdate(time);
[2896]465    }
[3370]466
[5695]467    void Core::postUpdate(const Clock& time)
[3370]468    {
[10413]469        // Update UpdateListeners just before rendering
470        for (ObjectList<UpdateListener>::iterator it = ObjectList<UpdateListener>::begin(); it != ObjectList<UpdateListener>::end(); ++it)
471            it->postUpdate(time);
[5781]472        if (this->bGraphicsLoaded_)
473        {
474            // Render (doesn't throw)
[6417]475            this->graphicsManager_->postUpdate(time);
[5781]476        }
[3370]477    }
[1505]478}
Note: See TracBrowser for help on using the repository browser.