Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

statically initialized instances may contain a type. currently not used.

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