Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/libraries/core/Core.cc @ 10264

Last change on this file since 10264 was 9667, checked in by landauf, 11 years ago

merged core6 back to trunk

  • Property svn:eol-style set to native
File size: 20.6 KB
RevLine 
[1505]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
[2896]24 *      Reto Grieder
[1505]25 *   Co-authors:
[2896]26 *      ...
[1505]27 *
28 */
29
30/**
[3196]31@file
32@brief
33    Implementation of the Core singleton with its global variables (avoids boost include)
[1505]34*/
35
[1524]36#include "Core.h"
[2710]37
[1756]38#include <cassert>
[7427]39#include <cstdlib>
40#include <ctime>
[7401]41#include <fstream>
[5929]42#include <vector>
[2710]43
44#ifdef ORXONOX_PLATFORM_WINDOWS
[2896]45#  ifndef WIN32_LEAN_AND_MEAN
46#    define WIN32_LEAN_AND_MEAN
47#  endif
[2710]48#  include <windows.h>
[3214]49#  undef min
50#  undef max
[2710]51#endif
52
[5929]53#include "util/Clock.h"
[8858]54#include "util/Output.h"
[2710]55#include "util/Exception.h"
[8858]56#include "util/output/LogWriter.h"
[9550]57#include "util/output/OutputManager.h"
[6417]58#include "util/Scope.h"
[7284]59#include "util/ScopedSingletonManager.h"
[2896]60#include "util/SignalHandler.h"
[5929]61#include "PathConfig.h"
[9667]62#include "config/CommandLineParser.h"
63#include "config/ConfigFileManager.h"
64#include "config/ConfigValueIncludes.h"
[2896]65#include "CoreIncludes.h"
[5693]66#include "DynLibManager.h"
[5781]67#include "GameMode.h"
68#include "GraphicsManager.h"
69#include "GUIManager.h"
[9667]70#include "class/Identifier.h"
[1505]71#include "Language.h"
[5695]72#include "LuaState.h"
[7284]73#include "command/ConsoleCommand.h"
74#include "command/IOConsole.h"
75#include "command/TclBind.h"
76#include "command/TclThreadManager.h"
[5781]77#include "input/InputManager.h"
[9667]78#include "object/ObjectList.h"
[1505]79
80namespace orxonox
81{
[3196]82    //! Static pointer to the singleton
[3370]83    Core* Core::singletonPtr_s  = 0;
[2662]84
[3280]85    SetCommandLineArgument(settingsFile, "orxonox.ini").information("THE configuration file");
[8351]86#if !defined(ORXONOX_PLATFORM_APPLE) && !defined(ORXONOX_USE_WINMAIN)
[6746]87    SetCommandLineSwitch(noIOConsole).information("Use this if you don't want to use the IOConsole (for instance for Lua debugging)");
[8351]88#endif
[7163]89
[3280]90#ifdef ORXONOX_PLATFORM_WINDOWS
[8505]91    SetCommandLineArgument(limitToCPU, 0).information("Limits the program to one CPU/core (1, 2, 3, etc.). Default is off = 0.");
[3280]92#endif
[2710]93
[9667]94    // register Core as an abstract class to avoid problems if the class hierarchy is created within Core-constructor
95    RegisterAbstractClass(Core).inheritsFrom(Class(Configurable));
96
[3323]97    Core::Core(const std::string& cmdLine)
[8423]98        : pathConfig_(NULL)
99        , dynLibManager_(NULL)
100        , signalHandler_(NULL)
101        , configFileManager_(NULL)
102        , languageInstance_(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)
[5781]111        , bGraphicsLoaded_(false)
[6746]112        , bStartIOConsole_(true)
[7870]113        , lastLevelTimestamp_(0)
114        , ogreConfigTimestamp_(0)
[8366]115        , bDevMode_(false)
[8423]116        , destructionHelper_(this)
[3280]117    {
[8858]118        orxout(internal_status) << "initializing Core object..." << endl;
119
[5693]120        // Set the hard coded fixed paths
[8423]121        this->pathConfig_ = new PathConfig();
[3280]122
[5693]123        // Create a new dynamic library manager
[8423]124        this->dynLibManager_ = new DynLibManager();
[2896]125
[5693]126        // Load modules
[8858]127        orxout(internal_info) << "Loading modules:" << endl;
[5929]128        const std::vector<std::string>& modulePaths = this->pathConfig_->getModulePaths();
129        for (std::vector<std::string>::const_iterator it = modulePaths.begin(); it != modulePaths.end(); ++it)
[5693]130        {
[5929]131            try
[5693]132            {
[5929]133                this->dynLibManager_->load(*it);
[5693]134            }
[5929]135            catch (...)
136            {
[8858]137                orxout(user_error) << "Couldn't load module \"" << *it << "\": " << Exception::handleMessage() << endl;
[5929]138            }
[5693]139        }
140
141        // Parse command line arguments AFTER the modules have been loaded (static code!)
[8729]142        CommandLineParser::parse(cmdLine);
[5693]143
144        // Set configurable paths like log, config and media
[5929]145        this->pathConfig_->setConfigurablePaths();
[5693]146
[8858]147        orxout(internal_info) << "Root path:       " << PathConfig::getRootPathString() << endl;
148        orxout(internal_info) << "Executable path: " << PathConfig::getExecutablePathString() << endl;
149        orxout(internal_info) << "Data path:       " << PathConfig::getDataPathString() << endl;
150        orxout(internal_info) << "Ext. data path:  " << PathConfig::getExternalDataPathString() << endl;
151        orxout(internal_info) << "Config path:     " << PathConfig::getConfigPathString() << endl;
152        orxout(internal_info) << "Log path:        " << PathConfig::getLogPathString() << endl;
153        orxout(internal_info) << "Modules path:    " << PathConfig::getModulePathString() << endl;
154
[6105]155        // create a signal handler (only active for Linux)
[2896]156        // This call is placed as soon as possible, but after the directories are set
[8423]157        this->signalHandler_ = new SignalHandler();
[5929]158        this->signalHandler_->doCatch(PathConfig::getExecutablePathString(), PathConfig::getLogPathString() + "orxonox_crash.log");
[2896]159
[3280]160#ifdef ORXONOX_PLATFORM_WINDOWS
161        // limit the main thread to the first core so that QueryPerformanceCounter doesn't jump
162        // do this after ogre has initialised. Somehow Ogre changes the settings again (not through
163        // the timer though).
[6021]164        int limitToCPU = CommandLineParser::getValue("limitToCPU");
[3280]165        if (limitToCPU > 0)
166            setThreadAffinity(static_cast<unsigned int>(limitToCPU));
167#endif
168
[2896]169        // Manage ini files and set the default settings file (usually orxonox.ini)
[8858]170        orxout(internal_info) << "Loading config:" << endl;
[8423]171        this->configFileManager_ = new ConfigFileManager();
[2896]172        this->configFileManager_->setFilename(ConfigFileType::Settings,
[9550]173            CommandLineParser::getValue("settingsFile").get<std::string>());
[2896]174
[3280]175        // Required as well for the config values
[8858]176        orxout(internal_info) << "Loading language:" << endl;
[8423]177        this->languageInstance_ = new Language();
[2896]178
[6417]179        // Do this soon after the ConfigFileManager has been created to open up the
180        // possibility to configure everything below here
[9667]181        RegisterObject(Core);
[8858]182        orxout(internal_info) << "configuring Core" << endl;
[6417]183        this->setConfigValues();
184
[8858]185        // Set the correct log path and rewrite the log file with the correct log levels
[9550]186        OutputManager::getInstance().getLogWriter()->setLogDirectory(PathConfig::getLogPathString());
[8858]187
[8351]188#if !defined(ORXONOX_PLATFORM_APPLE) && !defined(ORXONOX_USE_WINMAIN)
189        // Create persistent IO console
[9550]190        if (CommandLineParser::getValue("noIOConsole").get<bool>())
[6746]191        {
192            ModifyConfigValue(bStartIOConsole_, tset, false);
193        }
194        if (this->bStartIOConsole_)
[8858]195        {
196            orxout(internal_info) << "creating IO console" << endl;
[8423]197            this->ioConsole_ = new IOConsole();
[8858]198        }
[8351]199#endif
[6105]200
[5695]201        // creates the class hierarchy for all classes with factories
[8858]202        orxout(internal_info) << "creating class hierarchy" << endl;
[9667]203        IdentifierManager::getInstance().createClassHierarchy();
[5695]204
[5781]205        // Load OGRE excluding the renderer and the render window
[8858]206        orxout(internal_info) << "creating GraphicsManager:" << endl;
[8423]207        this->graphicsManager_ = new GraphicsManager(false);
[5781]208
209        // initialise Tcl
[8423]210        this->tclBind_ = new TclBind(PathConfig::getDataPathString());
211        this->tclThreadManager_ = new TclThreadManager(tclBind_->getTclInterpreter());
[5781]212
[5929]213        // Create singletons that always exist (in other libraries)
[8858]214        orxout(internal_info) << "creating root scope:" << endl;
[8423]215        this->rootScope_ = new Scope<ScopeID::Root>();
[7401]216
217        // Generate documentation instead of normal run?
218        std::string docFilename;
219        CommandLineParser::getValue("generateDoc", &docFilename);
220        if (!docFilename.empty())
221        {
222            std::ofstream docFile(docFilename.c_str());
223            if (docFile.is_open())
224            {
225                CommandLineParser::generateDoc(docFile);
226                docFile.close();
227            }
228            else
[8858]229                orxout(internal_error) << "Could not open file for documentation writing" << endl;
[7401]230        }
[8858]231
232        orxout(internal_status) << "finished initializing Core object" << endl;
[1505]233    }
234
[8423]235    void Core::destroy()
[1505]236    {
[8858]237        orxout(internal_status) << "destroying Core object..." << endl;
238
[6417]239        // Remove us from the object lists again to avoid problems when destroying them
240        this->unregisterObject();
[8423]241
242        safeObjectDelete(&graphicsScope_);
243        safeObjectDelete(&guiManager_);
244        safeObjectDelete(&inputManager_);
245        safeObjectDelete(&graphicsManager_);
246        safeObjectDelete(&rootScope_);
247        safeObjectDelete(&tclThreadManager_);
248        safeObjectDelete(&tclBind_);
249        safeObjectDelete(&ioConsole_);
250        safeObjectDelete(&languageInstance_);
251        safeObjectDelete(&configFileManager_);
252        ConsoleCommand::destroyAll();
[9667]253        Context::setRootContext(NULL);
254        IdentifierManager::getInstance().destroyAllIdentifiers();
[8423]255        safeObjectDelete(&signalHandler_);
256        safeObjectDelete(&dynLibManager_);
257        safeObjectDelete(&pathConfig_);
[2896]258
[8858]259        orxout(internal_status) << "finished destroying Core object" << endl;
[8729]260    }
261
[6417]262    //! Function to collect the SetConfigValue-macro calls.
263    void Core::setConfigValues()
264    {
[9550]265        SetConfigValueExternal(OutputManager::getInstance().getLogWriter()->configurableMaxLevel_,
266                               OutputManager::getInstance().getLogWriter()->getConfigurableSectionName(),
267                               OutputManager::getInstance().getLogWriter()->getConfigurableMaxLevelName(),
268                               OutputManager::getInstance().getLogWriter()->configurableMaxLevel_)
[8858]269            .description("The maximum level of output shown in the log file")
[9550]270            .callback(static_cast<BaseWriter*>(OutputManager::getInstance().getLogWriter()), &BaseWriter::changedConfigurableLevel);
271        SetConfigValueExternal(OutputManager::getInstance().getLogWriter()->configurableAdditionalContextsMaxLevel_,
272                               OutputManager::getInstance().getLogWriter()->getConfigurableSectionName(),
273                               OutputManager::getInstance().getLogWriter()->getConfigurableAdditionalContextsMaxLevelName(),
274                               OutputManager::getInstance().getLogWriter()->configurableAdditionalContextsMaxLevel_)
[8858]275            .description("The maximum level of output shown in the log file for additional contexts")
[9550]276            .callback(static_cast<BaseWriter*>(OutputManager::getInstance().getLogWriter()), &BaseWriter::changedConfigurableAdditionalContextsLevel);
277        SetConfigValueExternal(OutputManager::getInstance().getLogWriter()->configurableAdditionalContexts_,
278                               OutputManager::getInstance().getLogWriter()->getConfigurableSectionName(),
279                               OutputManager::getInstance().getLogWriter()->getConfigurableAdditionalContextsName(),
280                               OutputManager::getInstance().getLogWriter()->configurableAdditionalContexts_)
[8858]281            .description("Additional output contexts shown in the log file")
[9550]282            .callback(static_cast<BaseWriter*>(OutputManager::getInstance().getLogWriter()), &BaseWriter::changedConfigurableAdditionalContexts);
[6417]283
[8366]284        SetConfigValue(bDevMode_, PathConfig::buildDirectoryRun())
[8729]285            .description("Developer mode. If not set, hides some things from the user to not confuse him.")
286            .callback(this, &Core::devModeChanged);
[6417]287        SetConfigValue(language_, Language::getInstance().defaultLanguage_)
288            .description("The language of the in game text")
289            .callback(this, &Core::languageChanged);
290        SetConfigValue(bInitRandomNumberGenerator_, true)
291            .description("If true, all random actions are different each time you start the game")
292            .callback(this, &Core::initRandomNumberGenerator);
[6746]293        SetConfigValue(bStartIOConsole_, true)
294            .description("Set to false if you don't want to use the IOConsole (for Lua debugging for instance)");
[7870]295        SetConfigValue(lastLevelTimestamp_, 0)
296            .description("Timestamp when the last level was started.");
297        SetConfigValue(ogreConfigTimestamp_, 0)
298            .description("Timestamp when the ogre config file was changed.");
[6417]299    }
300
[8729]301    /** Callback function for changes in the dev mode that affect debug levels.
302        The function behaves according to these rules:
303        - 'normal' mode is defined based on where the program was launched: if
304          the launch path was the build directory, development mode \c on is
305          normal, otherwise normal means development mode \c off.
306        - Debug levels should not be hard configured (\c config instead of
307          \c tconfig) in non 'normal' mode to avoid strange behaviour.
308        - Changing the development mode from 'normal' to the other state will
309          immediately change the debug levels to predefined values which can be
310          reconfigured with \c tconfig.
311    @note
312        The debug levels for the IOConsole and the InGameConsole can be found
313        in the Shell class. The same rules apply.
314    */
315    void Core::devModeChanged()
316    {
317        // Inform listeners
318        ObjectList<DevModeListener>::iterator it = ObjectList<DevModeListener>::begin();
319        for (; it != ObjectList<DevModeListener>::end(); ++it)
320            it->devModeChanged(bDevMode_);
321    }
322
[6417]323    //! Callback function if the language has changed.
324    void Core::languageChanged()
325    {
326        // Read the translation file after the language was configured
327        Language::getInstance().readTranslatedLanguageFile();
328    }
329
330    void Core::initRandomNumberGenerator()
331    {
332        static bool bInitialized = false;
333        if (!bInitialized && this->bInitRandomNumberGenerator_)
334        {
335            srand(static_cast<unsigned int>(time(0)));
336            rand();
337            bInitialized = true;
338        }
339    }
340
[5781]341    void Core::loadGraphics()
342    {
[8858]343        orxout(internal_info) << "loading graphics in Core" << endl;
[9550]344
[5781]345        // Any exception should trigger this, even in upgradeToGraphics (see its remarks)
346        Loki::ScopeGuard unloader = Loki::MakeObjGuard(*this, &Core::unloadGraphics);
347
348        // Upgrade OGRE to receive a render window
[7175]349        try
350        {
351            graphicsManager_->upgradeToGraphics();
352        }
[7872]353        catch (const InitialisationFailedException&)
[7868]354        {
355            // Exit the application if the Ogre config dialog was canceled
[8858]356            orxout(user_error) << Exception::handleMessage() << endl;
[7868]357            exit(EXIT_FAILURE);
358        }
[7175]359        catch (...)
360        {
361            // Recovery from this is very difficult. It requires to completely
362            // destroy Ogre related objects and load again (without graphics).
363            // However since Ogre 1.7 there seems to be a problem when Ogre
364            // throws an exception and the graphics engine then gets destroyed
365            // and reloaded between throw and catch (access violation in MSVC).
366            // That's why we abort completely and only display the exception.
[8858]367            orxout(user_error) << "An exception occurred during upgrade to graphics. "
368                               << "That is unrecoverable. The message was:" << endl
369                               << Exception::handleMessage() << endl;
[7175]370            abort();
371        }
[5781]372
373        // Calls the InputManager which sets up the input devices.
[8423]374        inputManager_ = new InputManager();
[5781]375
[5929]376        // Load the CEGUI interface
[8423]377        guiManager_ = new GUIManager(inputManager_->getMousePosition());
[5781]378
[5929]379        bGraphicsLoaded_ = true;
380        GameMode::bShowsGraphics_s = true;
381
382        // Load some sort of a debug overlay (only denoted by its name, "debug.oxo")
383        graphicsManager_->loadDebugOverlay();
384
385        // Create singletons associated with graphics (in other libraries)
[8858]386        orxout(internal_info) << "creating graphics scope:" << endl;
[8423]387        graphicsScope_ = new Scope<ScopeID::Graphics>();
[5929]388
[5781]389        unloader.Dismiss();
[8858]390
391        orxout(internal_info) << "finished loading graphics in Core" << endl;
[5781]392    }
393
394    void Core::unloadGraphics()
395    {
[8858]396        orxout(internal_info) << "unloading graphics in Core" << endl;
397
[8423]398        safeObjectDelete(&graphicsScope_);
399        safeObjectDelete(&guiManager_);
400        safeObjectDelete(&inputManager_);
401        safeObjectDelete(&graphicsManager_);
[5781]402
403        // Load Ogre::Root again, but without the render system
404        try
[8423]405            { this->graphicsManager_ = new GraphicsManager(false); }
[5781]406        catch (...)
407        {
[8858]408            orxout(user_error) << "An exception occurred during 'unloadGraphics':" << Exception::handleMessage() << endl
409                               << "Another exception might be being handled which may lead to undefined behaviour!" << endl
410                               << "Terminating the program." << endl;
[5781]411            abort();
412        }
413
414        bGraphicsLoaded_ = false;
[5929]415        GameMode::bShowsGraphics_s = false;
[5781]416    }
417
[6417]418    //! Sets the language in the config-file back to the default.
419    void Core::resetLanguage()
[1505]420    {
[6417]421        ResetConfigValue(language_);
[1505]422    }
423
424    /**
[2896]425    @note
426        The code of this function has been copied and adjusted from OGRE, an open source graphics engine.
427            (Object-oriented Graphics Rendering Engine)
428        For the latest info, see http://www.ogre3d.org/
429
430        Copyright (c) 2000-2008 Torus Knot Software Ltd
431
432        OGRE is licensed under the LGPL. For more info, see OGRE license.
[2710]433    */
[2896]434    void Core::setThreadAffinity(int limitToCPU)
[2710]435    {
[3280]436#ifdef ORXONOX_PLATFORM_WINDOWS
437
[2896]438        if (limitToCPU <= 0)
439            return;
[2710]440
[2896]441        unsigned int coreNr = limitToCPU - 1;
442        // Get the current process core mask
443        DWORD procMask;
444        DWORD sysMask;
445#  if _MSC_VER >= 1400 && defined (_M_X64)
446        GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&procMask, (PDWORD_PTR)&sysMask);
447#  else
448        GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask);
449#  endif
[2710]450
[2896]451        // If procMask is 0, consider there is only one core available
452        // (using 0 as procMask will cause an infinite loop below)
453        if (procMask == 0)
454            procMask = 1;
455
456        // if the core specified with coreNr is not available, take the lowest one
457        if (!(procMask & (1 << coreNr)))
458            coreNr = 0;
459
460        // Find the lowest core that this process uses and coreNr suggests
461        DWORD threadMask = 1;
462        while ((threadMask & procMask) == 0 || (threadMask < (1u << coreNr)))
463            threadMask <<= 1;
464
465        // Set affinity to the first core
466        SetThreadAffinityMask(GetCurrentThread(), threadMask);
467#endif
[2710]468    }
469
[5695]470    void Core::preUpdate(const Clock& time)
[2896]471    {
[6417]472        // Update singletons before general ticking
473        ScopedSingletonManager::preUpdate<ScopeID::Root>(time);
[5781]474        if (this->bGraphicsLoaded_)
475        {
[6417]476            // Process input events
477            this->inputManager_->preUpdate(time);
478            // Update GUI
479            this->guiManager_->preUpdate(time);
480            // Update singletons before general ticking
481            ScopedSingletonManager::preUpdate<ScopeID::Graphics>(time);
[5781]482        }
[6417]483        // Process console events and status line
[6746]484        if (this->ioConsole_ != NULL)
485            this->ioConsole_->preUpdate(time);
[6417]486        // Process thread commands
487        this->tclThreadManager_->preUpdate(time);
[2896]488    }
[3370]489
[5695]490    void Core::postUpdate(const Clock& time)
[3370]491    {
[6417]492        // Update singletons just before rendering
493        ScopedSingletonManager::postUpdate<ScopeID::Root>(time);
[5781]494        if (this->bGraphicsLoaded_)
495        {
[6417]496            // Update singletons just before rendering
497            ScopedSingletonManager::postUpdate<ScopeID::Graphics>(time);
[5781]498            // Render (doesn't throw)
[6417]499            this->graphicsManager_->postUpdate(time);
[5781]500        }
[3370]501    }
[7870]502
503    void Core::updateLastLevelTimestamp()
504    {
505        ModifyConfigValue(lastLevelTimestamp_, set, static_cast<long long>(time(NULL)));
506    }
507
508    void Core::updateOgreConfigTimestamp()
509    {
510        ModifyConfigValue(ogreConfigTimestamp_, set, static_cast<long long>(time(NULL)));
511    }
[8729]512
513
[9667]514    RegisterAbstractClass(DevModeListener).inheritsFrom(Class(Listable));
515
[8729]516    DevModeListener::DevModeListener()
517    {
[9667]518        RegisterObject(DevModeListener);
[8729]519    }
[1505]520}
Note: See TracBrowser for help on using the repository browser.