Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

fixed tests

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