Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/doc/src/libraries/core/Core.cc @ 7361

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

Changed command line arguments reference to a simple Doxygen page containing the usage information text.

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