Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 7373 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
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 <fstream>
40#include <vector>
41
42#ifdef ORXONOX_PLATFORM_WINDOWS
43#  ifndef WIN32_LEAN_AND_MEAN
44#    define WIN32_LEAN_AND_MEAN
45#  endif
46#  include <windows.h>
47#  undef min
48#  undef max
49#endif
50
51#include "util/Clock.h"
52#include "util/Debug.h"
53#include "util/Exception.h"
54#include "util/Scope.h"
55#include "util/ScopedSingletonManager.h"
56#include "util/SignalHandler.h"
57#include "PathConfig.h"
58#include "CommandLineParser.h"
59#include "ConfigFileManager.h"
60#include "ConfigValueIncludes.h"
61#include "CoreIncludes.h"
62#include "DynLibManager.h"
63#include "GameMode.h"
64#include "GraphicsManager.h"
65#include "GUIManager.h"
66#include "Identifier.h"
67#include "Language.h"
68#include "LuaState.h"
69#include "command/ConsoleCommand.h"
70#include "command/IOConsole.h"
71#include "command/TclBind.h"
72#include "command/TclThreadManager.h"
73#include "input/InputManager.h"
74
75namespace orxonox
76{
77    //! Static pointer to the singleton
78    Core* Core::singletonPtr_s  = 0;
79
80    SetCommandLineArgument(settingsFile, "orxonox.ini").information("THE configuration file");
81    SetCommandLineSwitch(noIOConsole).information("Use this if you don't want to use the IOConsole (for instance for Lua debugging)");
82
83#ifdef ORXONOX_PLATFORM_WINDOWS
84    SetCommandLineArgument(limitToCPU, 1).information("Limits the program to one CPU/core (1, 2, 3, etc.). Default is the first core (faster than off)");
85#endif
86
87    Core::Core(const std::string& cmdLine)
88        // Cleanup guard for identifier destruction (incl. XMLPort, configValues, consoleCommands)
89        : identifierDestroyer_(Identifier::destroyAllIdentifiers)
90        // Cleanup guard for external console commands that don't belong to an Identifier
91        , consoleCommandDestroyer_(ConsoleCommand::destroyAll)
92        , bGraphicsLoaded_(false)
93        , bStartIOConsole_(true)
94    {
95        // Set the hard coded fixed paths
96        this->pathConfig_.reset(new PathConfig());
97
98        // Create a new dynamic library manager
99        this->dynLibManager_.reset(new DynLibManager());
100
101        // Load modules
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)
104        {
105            try
106            {
107                this->dynLibManager_->load(*it);
108            }
109            catch (...)
110            {
111                COUT(1) << "Couldn't load module \"" << *it << "\": " << Exception::handleMessage() << std::endl;
112            }
113        }
114
115        // Parse command line arguments AFTER the modules have been loaded (static code!)
116        CommandLineParser::parseCommandLine(cmdLine);
117
118        // Set configurable paths like log, config and media
119        this->pathConfig_->setConfigurablePaths();
120
121        // create a signal handler (only active for Linux)
122        // This call is placed as soon as possible, but after the directories are set
123        this->signalHandler_.reset(new SignalHandler());
124        this->signalHandler_->doCatch(PathConfig::getExecutablePathString(), PathConfig::getLogPathString() + "orxonox_crash.log");
125
126        // Set the correct log path. Before this call, /tmp (Unix) or %TEMP% (Windows) was used
127        OutputHandler::getInstance().setLogPath(PathConfig::getLogPathString());
128
129        // Parse additional options file now that we know its path
130        CommandLineParser::parseFile();
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).
136        int limitToCPU = CommandLineParser::getValue("limitToCPU");
137        if (limitToCPU > 0)
138            setThreadAffinity(static_cast<unsigned int>(limitToCPU));
139#endif
140
141        // Manage ini files and set the default settings file (usually orxonox.ini)
142        this->configFileManager_.reset(new ConfigFileManager());
143        this->configFileManager_->setFilename(ConfigFileType::Settings,
144            CommandLineParser::getValue("settingsFile").getString());
145
146        // Required as well for the config values
147        this->languageInstance_.reset(new Language());
148
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
154        // create persistent io console
155        if (CommandLineParser::getValue("noIOConsole").getBool())
156        {
157            ModifyConfigValue(bStartIOConsole_, tset, false);
158        }
159        if (this->bStartIOConsole_)
160            this->ioConsole_.reset(new IOConsole());
161
162        // creates the class hierarchy for all classes with factories
163        Identifier::createClassHierarchy();
164
165        // Load OGRE excluding the renderer and the render window
166        this->graphicsManager_.reset(new GraphicsManager(false));
167
168        // initialise Tcl
169        this->tclBind_.reset(new TclBind(PathConfig::getDataPathString()));
170        this->tclThreadManager_.reset(new TclThreadManager(tclBind_->getTclInterpreter()));
171
172        // Create singletons that always exist (in other libraries)
173        this->rootScope_.reset(new Scope<ScopeID::Root>());
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        }
189    }
190
191    /**
192    @brief
193        All destruction code is handled by scoped_ptrs and ScopeGuards.
194    */
195    Core::~Core()
196    {
197        // Remove us from the object lists again to avoid problems when destroying them
198        this->unregisterObject();
199    }
200
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
209        SetConfigValueExternal(softDebugLevelLogFile_, "OutputHandler", "softDebugLevelLogFile", defaultLevelLogFile)
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);
219        SetConfigValue(bStartIOConsole_, true)
220            .description("Set to false if you don't want to use the IOConsole (for Lua debugging for instance)");
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
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
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        }
264
265        // Calls the InputManager which sets up the input devices.
266        inputManager_.reset(new InputManager());
267
268        // Load the CEGUI interface
269        guiManager_.reset(new GUIManager(inputManager_->getMousePosition()));
270
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
280        unloader.Dismiss();
281    }
282
283    void Core::unloadGraphics()
284    {
285        this->graphicsScope_.reset();
286        this->guiManager_.reset();
287        this->inputManager_.reset();
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;
302        GameMode::bShowsGraphics_s = false;
303    }
304
305    //! Sets the language in the config-file back to the default.
306    void Core::resetLanguage()
307    {
308        ResetConfigValue(language_);
309    }
310
311    /**
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.
320    */
321    void Core::setThreadAffinity(int limitToCPU)
322    {
323#ifdef ORXONOX_PLATFORM_WINDOWS
324
325        if (limitToCPU <= 0)
326            return;
327
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
337
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
355    }
356
357    void Core::preUpdate(const Clock& time)
358    {
359        // Update singletons before general ticking
360        ScopedSingletonManager::preUpdate<ScopeID::Root>(time);
361        if (this->bGraphicsLoaded_)
362        {
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);
369        }
370        // Process console events and status line
371        if (this->ioConsole_ != NULL)
372            this->ioConsole_->preUpdate(time);
373        // Process thread commands
374        this->tclThreadManager_->preUpdate(time);
375    }
376
377    void Core::postUpdate(const Clock& time)
378    {
379        // Update singletons just before rendering
380        ScopedSingletonManager::postUpdate<ScopeID::Root>(time);
381        if (this->bGraphicsLoaded_)
382        {
383            // Update singletons just before rendering
384            ScopedSingletonManager::postUpdate<ScopeID::Graphics>(time);
385            // Render (doesn't throw)
386            this->graphicsManager_->postUpdate(time);
387        }
388    }
389}
Note: See TracBrowser for help on using the repository browser.