Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

Renamed PathConfig::isDevelopmentRun() to PathConfig::buildDirectoryRun() because that fits better and there is no confusion with Core::inDevMode().
Also used isDevelopmentRun() as default value for Core::inDevMode() instead of ORXONOX_RELEASE.

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