Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 8729 was 8729, checked in by rgrieder, 13 years ago

Merged unity_build branch back to trunk.

Features:

  • Implemented fully automatic build units to speed up compilation if requested
  • Added DOUT macro for quick debug output
  • Activated text colouring in the POSIX IOConsole
  • DeclareToluaInterface is not necessary anymore

Improvements:

  • Output levels now change appropriately when switch back and forth from dev mode
  • Log level for the file output is now also correct during startup
  • Removed some header file dependencies in core and tools to speed up compilation

no more file for command line options

  • Improved util::tribool by adapting some concepts from boost::tribool

Regressions:

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