Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/libraries/core/Core.cc @ 11071

Last change on this file since 11071 was 11071, checked in by landauf, 8 years ago

merged branch cpp11_v3 back to trunk

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