Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

moved DynLib and DynLibManager into module sub-directory

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