Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

StaticallyInitializedInstances are now responsible to delete the wrapped object.

  • Property svn:eol-style set to native
File size: 17.0 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        Context::setRootContext(NULL);
244        safeObjectDelete(&signalHandler_);
245//        if (this->rootModule_)
246//            this->rootModule_->unloadAllStaticallyInitializedInstances();
247//        safeObjectDelete(&rootModule_);
248        safeObjectDelete(&dynLibManager_);
249        safeObjectDelete(&configurablePaths_);
250        safeObjectDelete(&applicationPaths_);
251
252        orxout(internal_status) << "finished destroying Core object" << endl;
253    }
254
255    void Core::loadModules()
256    {
257        orxout(internal_info) << "Loading modules:" << endl;
258
259        const std::vector<std::string>& modulePaths = ApplicationPaths::getInstance().getModulePaths();
260        for (std::vector<std::string>::const_iterator it = modulePaths.begin(); it != modulePaths.end(); ++it)
261        {
262            try
263            {
264                ModuleInstance* module = new ModuleInstance(*it);
265                this->loadModule(module);
266                this->modules_.push_back(module);
267            }
268            catch (...)
269            {
270                orxout(user_error) << "Couldn't load module \"" << *it << "\": " << Exception::handleMessage() << endl;
271            }
272        }
273
274        orxout(internal_info) << "finished loading modules" << endl;
275    }
276
277    void Core::loadModule(ModuleInstance* module)
278    {
279        ModuleInstance::setCurrentModuleInstance(module);
280        DynLib* dynLib = this->dynLibManager_->load(module->getName());
281        module->setDynLib(dynLib);
282        module->loadAllStaticallyInitializedInstances();
283        IdentifierManager::getInstance().createClassHierarchy();
284        ScopeManager::getInstance().updateListeners();
285    }
286
287    void Core::unloadModules()
288    {
289        for (std::list<ModuleInstance*>::iterator it = this->modules_.begin(); it != this->modules_.end(); ++it)
290        {
291            ModuleInstance* module = (*it);
292            this->unloadModule(module);
293            delete module;
294        }
295        this->modules_.clear();
296    }
297
298    void Core::unloadModule(ModuleInstance* module)
299    {
300        module->unloadAllStaticallyInitializedInstances();
301        module->deleteAllStaticallyInitializedInstances();
302        this->dynLibManager_->unload(module->getDynLib());
303        module->setDynLib(NULL);
304    }
305
306    void Core::loadGraphics()
307    {
308        orxout(internal_info) << "loading graphics in Core" << endl;
309
310        // Any exception should trigger this, even in upgradeToGraphics (see its remarks)
311        Loki::ScopeGuard unloader = Loki::MakeObjGuard(*this, &Core::unloadGraphics);
312
313        // Upgrade OGRE to receive a render window
314        try
315        {
316            graphicsManager_->upgradeToGraphics();
317        }
318        catch (const InitialisationFailedException&)
319        {
320            // Exit the application if the Ogre config dialog was canceled
321            orxout(user_error) << Exception::handleMessage() << endl;
322            exit(EXIT_FAILURE);
323        }
324        catch (...)
325        {
326            // Recovery from this is very difficult. It requires to completely
327            // destroy Ogre related objects and load again (without graphics).
328            // However since Ogre 1.7 there seems to be a problem when Ogre
329            // throws an exception and the graphics engine then gets destroyed
330            // and reloaded between throw and catch (access violation in MSVC).
331            // That's why we abort completely and only display the exception.
332            orxout(user_error) << "An exception occurred during upgrade to graphics. "
333                               << "That is unrecoverable. The message was:" << endl
334                               << Exception::handleMessage() << endl;
335            abort();
336        }
337
338        // Calls the InputManager which sets up the input devices.
339        inputManager_ = new InputManager();
340
341        // Load the CEGUI interface
342        guiManager_ = new GUIManager(inputManager_->getMousePosition());
343
344        bGraphicsLoaded_ = true;
345        GameMode::bShowsGraphics_s = true;
346
347        // Load some sort of a debug overlay (only denoted by its name, "debug.oxo")
348        graphicsManager_->loadDebugOverlay();
349
350        // Create singletons associated with graphics (in other libraries)
351        orxout(internal_info) << "creating graphics scope:" << endl;
352        graphicsScope_ = new Scope<ScopeID::GRAPHICS>();
353
354        unloader.Dismiss();
355
356        orxout(internal_info) << "finished loading graphics in Core" << endl;
357    }
358
359    void Core::unloadGraphics()
360    {
361        orxout(internal_info) << "unloading graphics in Core" << endl;
362
363        safeObjectDelete(&graphicsScope_);
364        safeObjectDelete(&guiManager_);
365        safeObjectDelete(&inputManager_);
366        safeObjectDelete(&graphicsManager_);
367
368        // Load Ogre::Root again, but without the render system
369        try
370            { this->graphicsManager_ = new GraphicsManager(false); }
371        catch (...)
372        {
373            orxout(user_error) << "An exception occurred during 'unloadGraphics':" << Exception::handleMessage() << endl
374                               << "Another exception might be being handled which may lead to undefined behaviour!" << endl
375                               << "Terminating the program." << endl;
376            abort();
377        }
378
379        bGraphicsLoaded_ = false;
380        GameMode::bShowsGraphics_s = false;
381    }
382
383    /**
384    @note
385        The code of this function has been copied and adjusted from OGRE, an open source graphics engine.
386            (Object-oriented Graphics Rendering Engine)
387        For the latest info, see http://www.ogre3d.org/
388
389        Copyright (c) 2000-2008 Torus Knot Software Ltd
390
391        OGRE is licensed under the LGPL. For more info, see OGRE license.
392    */
393    void Core::setThreadAffinity(int limitToCPU)
394    {
395#ifdef ORXONOX_PLATFORM_WINDOWS
396
397        if (limitToCPU <= 0)
398            return;
399
400        unsigned int coreNr = limitToCPU - 1;
401        // Get the current process core mask
402        DWORD procMask;
403        DWORD sysMask;
404#  if _MSC_VER >= 1400 && defined (_M_X64)
405        GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&procMask, (PDWORD_PTR)&sysMask);
406#  else
407        GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask);
408#  endif
409
410        // If procMask is 0, consider there is only one core available
411        // (using 0 as procMask will cause an infinite loop below)
412        if (procMask == 0)
413            procMask = 1;
414
415        // if the core specified with coreNr is not available, take the lowest one
416        if (!(procMask & (1 << coreNr)))
417            coreNr = 0;
418
419        // Find the lowest core that this process uses and coreNr suggests
420        DWORD threadMask = 1;
421        while ((threadMask & procMask) == 0 || (threadMask < (1u << coreNr)))
422            threadMask <<= 1;
423
424        // Set affinity to the first core
425        SetThreadAffinityMask(GetCurrentThread(), threadMask);
426#endif
427    }
428
429    void Core::preUpdate(const Clock& time)
430    {
431        // Update UpdateListeners before general ticking
432        for (ObjectList<UpdateListener>::iterator it = ObjectList<UpdateListener>::begin(); it != ObjectList<UpdateListener>::end(); ++it)
433            it->preUpdate(time);
434        if (this->bGraphicsLoaded_)
435        {
436            // Process input events
437            this->inputManager_->preUpdate(time);
438            // Update GUI
439            this->guiManager_->preUpdate(time);
440        }
441        // Process console events and status line
442        if (this->ioConsole_ != NULL)
443            this->ioConsole_->preUpdate(time);
444        // Process thread commands
445        this->tclThreadManager_->preUpdate(time);
446    }
447
448    void Core::postUpdate(const Clock& time)
449    {
450        // Update UpdateListeners just before rendering
451        for (ObjectList<UpdateListener>::iterator it = ObjectList<UpdateListener>::begin(); it != ObjectList<UpdateListener>::end(); ++it)
452            it->postUpdate(time);
453        if (this->bGraphicsLoaded_)
454        {
455            // Render (doesn't throw)
456            this->graphicsManager_->postUpdate(time);
457        }
458    }
459}
Note: See TracBrowser for help on using the repository browser.