Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/masterserver/src/libraries/core/Core.cc @ 7659

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

Applied fixes from sandbox_qt to trunk.

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