Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

load modules AFTER core was initialized. load each module with a separate ModuleInstance. unloading is not yet implemented…

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