Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/kicklib/src/libraries/core/Core.cc @ 8071

Last change on this file since 8071 was 8071, checked in by rgrieder, 14 years ago

Merged ois_update branch (before it was renamed to mac_osx) into kicklib branch.

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