Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 11993 was 11692, checked in by landauf, 7 years ago

with the latest CMake there are a lot of warnings about the usage of CMP0026. therefore the naming and content of the module/plugin-files had to be changed:
old: <library-filename>.module with content <target-name>
new: <target-name>.module with content <library-filename>
this seems to comply better with cmake and works equally well in c++ (with some small adjustments).
reference: https://cmake.org/cmake/help/v3.0/policy/CMP0026.html

  • Property svn:eol-style set to native
File size: 18.5 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/SignalHandler.h"
57#include "util/output/LogWriter.h"
58#include "util/output/OutputManager.h"
59#include "core/singleton/Scope.h"
60#include "ApplicationPaths.h"
61#include "ConfigurablePaths.h"
62#include "commandline/CommandLineIncludes.h"
63#include "config/ConfigFileManager.h"
64#include "GameMode.h"
65#include "GraphicsManager.h"
66#include "GUIManager.h"
67#include "Language.h"
68#include "Loader.h"
69#include "LuaState.h"
70#include "command/IOConsole.h"
71#include "command/TclBind.h"
72#include "command/TclThreadManager.h"
73#include "input/InputManager.h"
74#include "object/ObjectList.h"
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"
81
82namespace orxonox
83{
84    //! Static pointer to the singleton
85    Core* Core::singletonPtr_s  = nullptr;
86
87    SetCommandLineArgument(settingsFile, "orxonox.ini").information("THE configuration file");
88#if !defined(ORXONOX_PLATFORM_APPLE) && !defined(ORXONOX_USE_WINMAIN)
89    SetCommandLineSwitch(noIOConsole).information("Use this if you don't want to use the IOConsole (for instance for Lua debugging)");
90#endif
91
92#ifdef ORXONOX_PLATFORM_WINDOWS
93    SetCommandLineArgument(limitToCPU, 0).information("Limits the program to one CPU/core (1, 2, 3, etc.). Default is off = 0.");
94#endif
95
96    SetCommandLineArgument(generateDoc, "")
97        .information("Generates a Doxygen file from things like SetConsoleCommand");
98
99    Core::Core(const std::string& cmdLine)
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)
115        , bGraphicsLoaded_(false)
116        , staticInitHandler_(nullptr)
117        , pluginManager_(nullptr)
118        , rootModule_(nullptr)
119        , config_(nullptr)
120        , destructionHelper_(this)
121    {
122        orxout(internal_status) << "initializing Core object..." << endl;
123
124        // Set the hard coded fixed paths
125        this->applicationPaths_ = new ApplicationPaths();
126
127        // Create a new dynamic library manager
128        this->dynLibManager_ = new DynLibManager();
129
130        // create handler for static initialization
131        new StaticInitializationManager(); // create singleton
132        this->staticInitHandler_ = new CoreStaticInitializationHandler();
133        StaticInitializationManager::getInstance().addHandler(this->staticInitHandler_);
134
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
139        // Parse command line arguments AFTER the modules have been loaded (static code!)
140        CommandLineParser::parse(cmdLine);
141
142        // Set configurable paths like log, config and media
143        this->configurablePaths_ = new ConfigurablePaths();
144        this->configurablePaths_->setConfigurablePaths(ApplicationPaths::getInstance());
145
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;
150
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
157        // This call is placed as soon as possible, but after the directories are set
158        this->signalHandler_ = new SignalHandler();
159        this->signalHandler_->doCatch(ApplicationPaths::getExecutablePathString(), ConfigurablePaths::getLogPathString() + "orxonox_crash.log");
160
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).
165        int limitToCPU = CommandLineParser::getValue("limitToCPU");
166        if (limitToCPU > 0)
167            setThreadAffinity(static_cast<unsigned int>(limitToCPU));
168#endif
169
170        // Manage ini files and set the default settings file (usually orxonox.ini)
171        orxout(internal_info) << "Loading config:" << endl;
172        this->configFileManager_ = new ConfigFileManager();
173        this->configFileManager_->setFilename(ConfigFileType::Settings,
174            CommandLineParser::getValue("settingsFile").get<std::string>());
175
176        // Required as well for the config values
177        orxout(internal_info) << "Loading language:" << endl;
178        this->languageInstance_ = new Language();
179
180        // initialize root context
181        Context::setRootContext(new Context(nullptr));
182
183        // Do this soon after the ConfigFileManager has been created to open up the
184        // possibility to configure everything below here
185        orxout(internal_info) << "configuring Core" << endl;
186        this->config_ = new CoreConfig();
187
188        // Set the correct log path and rewrite the log file with the correct log levels
189        OutputManager::getInstance().getLogWriter()->setLogDirectory(ConfigurablePaths::getLogPathString());
190
191#if !defined(ORXONOX_PLATFORM_APPLE) && !defined(ORXONOX_USE_WINMAIN)
192        // Create persistent IO console
193        if (CommandLineParser::getValue("noIOConsole").get<bool>() == false && this->config_->getStartIOConsole())
194        {
195            orxout(internal_info) << "creating IO console" << endl;
196            this->ioConsole_ = new IOConsole();
197        }
198#endif
199
200        // creates the class hierarchy for all classes with factories
201        orxout(internal_info) << "creating class hierarchy" << endl;
202        this->staticInitHandler_->initInstances(this->rootModule_);
203        this->staticInitHandler_->setInitInstances(true);
204
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
212        // Load OGRE excluding the renderer and the render window
213        orxout(internal_info) << "creating GraphicsManager:" << endl;
214        this->graphicsManager_ = new GraphicsManager(false);
215
216        // initialise Tcl
217        this->tclBind_ = new TclBind(ConfigurablePaths::getDataPathString());
218        this->tclThreadManager_ = new TclThreadManager(tclBind_->getTclInterpreter());
219
220        // Create singletons that always exist (in other libraries)
221        orxout(internal_info) << "creating root scope:" << endl;
222        this->rootScope_ = new Scope<ScopeID::ROOT>();
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
236                orxout(internal_error) << "Could not open file for documentation writing" << endl;
237        }
238
239        orxout(internal_status) << "finished initializing Core object" << endl;
240    }
241
242    void Core::destroy()
243    {
244        orxout(internal_status) << "destroying Core object..." << endl;
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(&loaderInstance_);
255        safeObjectDelete(&config_);
256        safeObjectDelete(&languageInstance_);
257        safeObjectDelete(&configFileManager_);
258        safeObjectDelete(&signalHandler_);
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();
272        safeObjectDelete(&dynLibManager_);
273        safeObjectDelete(&configurablePaths_);
274        safeObjectDelete(&applicationPaths_);
275
276        orxout(internal_status) << "finished destroying Core object" << endl;
277    }
278
279    void Core::loadModules()
280    {
281        orxout(internal_info) << "Loading modules:" << endl;
282
283        const std::map<std::string, std::string>& modulePaths = ApplicationPaths::getInstance().getModulePaths();
284        for (const std::pair<std::string, std::string>& modulePath : modulePaths)
285        {
286            ModuleInstance* module = new ModuleInstance(modulePath.second);
287            this->loadModule(module);
288            this->modules_.push_back(module);
289        }
290
291        orxout(internal_info) << "finished loading modules" << endl;
292    }
293
294    void Core::loadModule(ModuleInstance* module)
295    {
296        orxout(internal_info) << "Loading module " << module->getLibraryName() << "..." << endl;
297
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        }
310    }
311
312    void Core::unloadModules()
313    {
314        for (ModuleInstance* module : this->modules_)
315        {
316            this->unloadModule(module);
317            delete module;
318        }
319        this->modules_.clear();
320    }
321
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        if (module->getDynLib()) {
330            this->dynLibManager_->unload(module->getDynLib());
331            module->setDynLib(nullptr);
332        }
333    }
334
335    void Core::loadGraphics()
336    {
337        orxout(internal_info) << "loading graphics in Core" << endl;
338
339        // Any exception should trigger this, even in upgradeToGraphics (see its remarks)
340        Loki::ScopeGuard unloader = Loki::MakeObjGuard(*this, &Core::unloadGraphics, true);
341
342        // Upgrade OGRE to receive a render window
343        try
344        {
345            graphicsManager_->upgradeToGraphics();
346        }
347        catch (const InitialisationFailedException&)
348        {
349            // Exit the application if the Ogre config dialog was canceled
350            orxout(user_error) << Exception::handleMessage() << endl;
351            exit(EXIT_FAILURE);
352        }
353        catch (...)
354        {
355            // Recovery from this is very difficult. It requires to completely
356            // destroy Ogre related objects and load again (without graphics).
357            // However since Ogre 1.7 there seems to be a problem when Ogre
358            // throws an exception and the graphics engine then gets destroyed
359            // and reloaded between throw and catch (access violation in MSVC).
360            // That's why we abort completely and only display the exception.
361            orxout(user_error) << "An exception occurred during upgrade to graphics. "
362                               << "That is unrecoverable. The message was:" << endl
363                               << Exception::handleMessage() << endl;
364            abort();
365        }
366
367        // Calls the InputManager which sets up the input devices.
368        inputManager_ = new InputManager();
369
370        // Load the CEGUI interface
371        guiManager_ = new GUIManager(inputManager_->getMousePosition());
372
373        bGraphicsLoaded_ = true;
374        GameMode::bShowsGraphics_s = true;
375
376        // Load some sort of a debug overlay (only denoted by its name, "debug.oxo")
377        graphicsManager_->loadDebugOverlay();
378
379        // Create singletons associated with graphics (in other libraries)
380        orxout(internal_info) << "creating graphics scope:" << endl;
381        graphicsScope_ = new Scope<ScopeID::GRAPHICS>();
382
383        unloader.Dismiss();
384
385        orxout(internal_info) << "finished loading graphics in Core" << endl;
386    }
387
388    void Core::unloadGraphics(bool loadGraphicsManagerWithoutRenderer)
389    {
390        orxout(internal_info) << "unloading graphics in Core" << endl;
391
392        if (this->graphicsManager_)
393            this->graphicsManager_->unloadDebugOverlay();
394
395        safeObjectDelete(&graphicsScope_);
396        safeObjectDelete(&guiManager_);
397        safeObjectDelete(&inputManager_);
398        safeObjectDelete(&graphicsManager_);
399
400        // Load Ogre::Root again, but without the render system
401        try
402        {
403            if (loadGraphicsManagerWithoutRenderer)
404                this->graphicsManager_ = new GraphicsManager(false);
405        }
406        catch (...)
407        {
408            orxout(user_error) << "An exception occurred during 'unloadGraphics':" << Exception::handleMessage() << endl
409                               << "Another exception might be being handled which may lead to undefined behaviour!" << endl
410                               << "Terminating the program." << endl;
411            abort();
412        }
413
414        bGraphicsLoaded_ = false;
415        GameMode::bShowsGraphics_s = false;
416    }
417
418    /**
419    @note
420        The code of this function has been copied and adjusted from OGRE, an open source graphics engine.
421            (Object-oriented Graphics Rendering Engine)
422        For the latest info, see http://www.ogre3d.org/
423
424        Copyright (c) 2000-2008 Torus Knot Software Ltd
425
426        OGRE is licensed under the LGPL. For more info, see OGRE license.
427    */
428    void Core::setThreadAffinity(int limitToCPU)
429    {
430#ifdef ORXONOX_PLATFORM_WINDOWS
431
432        if (limitToCPU <= 0)
433            return;
434
435        unsigned int coreNr = limitToCPU - 1;
436        // Get the current process core mask
437        ULONG_PTR procMask;
438        ULONG_PTR sysMask;
439#  if _MSC_VER >= 1400 && defined (_M_X64)
440        GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&procMask, (PDWORD_PTR)&sysMask);
441#  else
442        GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask);
443#  endif
444
445        // If procMask is 0, consider there is only one core available
446        // (using 0 as procMask will cause an infinite loop below)
447        if (procMask == 0)
448            procMask = 1;
449
450        // if the core specified with coreNr is not available, take the lowest one
451        if (!(procMask & (1 << coreNr)))
452            coreNr = 0;
453
454        // Find the lowest core that this process uses and coreNr suggests
455        DWORD threadMask = 1;
456        while ((threadMask & procMask) == 0 || (threadMask < (1u << coreNr)))
457            threadMask <<= 1;
458
459        // Set affinity to the first core
460        SetThreadAffinityMask(GetCurrentThread(), threadMask);
461#endif
462    }
463
464    void Core::preUpdate(const Clock& time)
465    {
466        // Update UpdateListeners before general ticking
467        for (UpdateListener* listener : ObjectList<UpdateListener>())
468            listener->preUpdate(time);
469        if (this->bGraphicsLoaded_)
470        {
471            // Process input events
472            this->inputManager_->preUpdate(time);
473            // Update GUI
474            this->guiManager_->preUpdate(time);
475        }
476        // Process console events and status line
477        if (this->ioConsole_ != nullptr)
478            this->ioConsole_->preUpdate(time);
479        // Process thread commands
480        this->tclThreadManager_->preUpdate(time);
481    }
482
483    void Core::postUpdate(const Clock& time)
484    {
485        // Update UpdateListeners just before rendering
486        for (UpdateListener* listener : ObjectList<UpdateListener>())
487            listener->postUpdate(time);
488        if (this->bGraphicsLoaded_)
489        {
490            // Render (doesn't throw)
491            this->graphicsManager_->postUpdate(time);
492        }
493    }
494}
Note: See TracBrowser for help on using the repository browser.