Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/core7/src/libraries/core/Core.cc @ 10343

Last change on this file since 10343 was 10343, checked in by landauf, 9 years ago

moved CommandLineParser into separate subfolder

  • Property svn:eol-style set to native
File size: 20.8 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/Output.h"
55#include "util/Exception.h"
56#include "util/output/LogWriter.h"
57#include "util/output/OutputManager.h"
58#include "util/Scope.h"
59#include "util/ScopedSingletonManager.h"
60#include "util/SignalHandler.h"
61#include "PathConfig.h"
62#include "commandline/CommandLineParser.h"
63#include "config/ConfigFileManager.h"
64#include "config/ConfigValueIncludes.h"
65#include "CoreIncludes.h"
66#include "DynLibManager.h"
67#include "GameMode.h"
68#include "GraphicsManager.h"
69#include "GUIManager.h"
70#include "class/Identifier.h"
71#include "Language.h"
72#include "LuaState.h"
73#include "command/ConsoleCommand.h"
74#include "command/IOConsole.h"
75#include "command/TclBind.h"
76#include "command/TclThreadManager.h"
77#include "input/InputManager.h"
78#include "object/ObjectList.h"
79#include "module/ModuleInstance.h"
80
81namespace orxonox
82{
83    //! Static pointer to the singleton
84    Core* Core::singletonPtr_s  = 0;
85
86    SetCommandLineArgument(settingsFile, "orxonox.ini").information("THE configuration file");
87#if !defined(ORXONOX_PLATFORM_APPLE) && !defined(ORXONOX_USE_WINMAIN)
88    SetCommandLineSwitch(noIOConsole).information("Use this if you don't want to use the IOConsole (for instance for Lua debugging)");
89#endif
90
91#ifdef ORXONOX_PLATFORM_WINDOWS
92    SetCommandLineArgument(limitToCPU, 0).information("Limits the program to one CPU/core (1, 2, 3, etc.). Default is off = 0.");
93#endif
94
95    // register Core as an abstract class to avoid problems if the class hierarchy is created within Core-constructor
96    RegisterAbstractClass(Core).inheritsFrom(Class(Configurable));
97
98    Core::Core(const std::string& cmdLine)
99        : pathConfig_(NULL)
100        , dynLibManager_(NULL)
101        , signalHandler_(NULL)
102        , configFileManager_(NULL)
103        , languageInstance_(NULL)
104        , ioConsole_(NULL)
105        , tclBind_(NULL)
106        , tclThreadManager_(NULL)
107        , rootScope_(NULL)
108        , graphicsManager_(NULL)
109        , inputManager_(NULL)
110        , guiManager_(NULL)
111        , graphicsScope_(NULL)
112        , bGraphicsLoaded_(false)
113        , bStartIOConsole_(true)
114        , lastLevelTimestamp_(0)
115        , ogreConfigTimestamp_(0)
116        , bDevMode_(false)
117        , destructionHelper_(this)
118    {
119        orxout(internal_status) << "initializing Core object..." << endl;
120
121        // Set the hard coded fixed paths
122        this->pathConfig_ = new PathConfig();
123
124        // Create a new dynamic library manager
125        this->dynLibManager_ = new DynLibManager();
126
127        // Load modules
128        orxout(internal_info) << "Loading modules:" << endl;
129        const std::vector<std::string>& modulePaths = this->pathConfig_->getModulePaths();
130        for (std::vector<std::string>::const_iterator it = modulePaths.begin(); it != modulePaths.end(); ++it)
131        {
132            try
133            {
134                this->dynLibManager_->load(*it);
135            }
136            catch (...)
137            {
138                orxout(user_error) << "Couldn't load module \"" << *it << "\": " << Exception::handleMessage() << endl;
139            }
140        }
141
142        ModuleInstance::getCurrentModuleInstance()->loadAllStaticallyInitializedInstances();
143
144        // Parse command line arguments AFTER the modules have been loaded (static code!)
145        CommandLineParser::parse(cmdLine);
146
147        // Set configurable paths like log, config and media
148        this->pathConfig_->setConfigurablePaths();
149
150        orxout(internal_info) << "Root path:       " << PathConfig::getRootPathString() << endl;
151        orxout(internal_info) << "Executable path: " << PathConfig::getExecutablePathString() << endl;
152        orxout(internal_info) << "Data path:       " << PathConfig::getDataPathString() << endl;
153        orxout(internal_info) << "Ext. data path:  " << PathConfig::getExternalDataPathString() << endl;
154        orxout(internal_info) << "Config path:     " << PathConfig::getConfigPathString() << endl;
155        orxout(internal_info) << "Log path:        " << PathConfig::getLogPathString() << endl;
156        orxout(internal_info) << "Modules path:    " << PathConfig::getModulePathString() << endl;
157
158        // create a signal handler (only active for Linux)
159        // This call is placed as soon as possible, but after the directories are set
160        this->signalHandler_ = new SignalHandler();
161        this->signalHandler_->doCatch(PathConfig::getExecutablePathString(), PathConfig::getLogPathString() + "orxonox_crash.log");
162
163#ifdef ORXONOX_PLATFORM_WINDOWS
164        // limit the main thread to the first core so that QueryPerformanceCounter doesn't jump
165        // do this after ogre has initialised. Somehow Ogre changes the settings again (not through
166        // the timer though).
167        int limitToCPU = CommandLineParser::getValue("limitToCPU");
168        if (limitToCPU > 0)
169            setThreadAffinity(static_cast<unsigned int>(limitToCPU));
170#endif
171
172        // Manage ini files and set the default settings file (usually orxonox.ini)
173        orxout(internal_info) << "Loading config:" << endl;
174        this->configFileManager_ = new ConfigFileManager();
175        this->configFileManager_->setFilename(ConfigFileType::Settings,
176            CommandLineParser::getValue("settingsFile").get<std::string>());
177
178        // Required as well for the config values
179        orxout(internal_info) << "Loading language:" << endl;
180        this->languageInstance_ = new Language();
181
182        // Do this soon after the ConfigFileManager has been created to open up the
183        // possibility to configure everything below here
184        RegisterObject(Core);
185        orxout(internal_info) << "configuring Core" << endl;
186        this->setConfigValues();
187
188        // Set the correct log path and rewrite the log file with the correct log levels
189        OutputManager::getInstance().getLogWriter()->setLogDirectory(PathConfig::getLogPathString());
190
191#if !defined(ORXONOX_PLATFORM_APPLE) && !defined(ORXONOX_USE_WINMAIN)
192        // Create persistent IO console
193        if (CommandLineParser::getValue("noIOConsole").get<bool>())
194        {
195            ModifyConfigValue(bStartIOConsole_, tset, false);
196        }
197        if (this->bStartIOConsole_)
198        {
199            orxout(internal_info) << "creating IO console" << endl;
200            this->ioConsole_ = new IOConsole();
201        }
202#endif
203
204        // creates the class hierarchy for all classes with factories
205        orxout(internal_info) << "creating class hierarchy" << endl;
206        IdentifierManager::getInstance().createClassHierarchy();
207
208        // Load OGRE excluding the renderer and the render window
209        orxout(internal_info) << "creating GraphicsManager:" << endl;
210        this->graphicsManager_ = new GraphicsManager(false);
211
212        // initialise Tcl
213        this->tclBind_ = new TclBind(PathConfig::getDataPathString());
214        this->tclThreadManager_ = new TclThreadManager(tclBind_->getTclInterpreter());
215
216        // Create singletons that always exist (in other libraries)
217        orxout(internal_info) << "creating root scope:" << endl;
218        this->rootScope_ = new Scope<ScopeID::Root>();
219
220        // Generate documentation instead of normal run?
221        std::string docFilename;
222        CommandLineParser::getValue("generateDoc", &docFilename);
223        if (!docFilename.empty())
224        {
225            std::ofstream docFile(docFilename.c_str());
226            if (docFile.is_open())
227            {
228                CommandLineParser::generateDoc(docFile);
229                docFile.close();
230            }
231            else
232                orxout(internal_error) << "Could not open file for documentation writing" << endl;
233        }
234
235        orxout(internal_status) << "finished initializing Core object" << endl;
236    }
237
238    void Core::destroy()
239    {
240        orxout(internal_status) << "destroying Core object..." << endl;
241
242        // Remove us from the object lists again to avoid problems when destroying them
243        this->unregisterObject();
244
245        safeObjectDelete(&graphicsScope_);
246        safeObjectDelete(&guiManager_);
247        safeObjectDelete(&inputManager_);
248        safeObjectDelete(&graphicsManager_);
249        safeObjectDelete(&rootScope_);
250        safeObjectDelete(&tclThreadManager_);
251        safeObjectDelete(&tclBind_);
252        safeObjectDelete(&ioConsole_);
253        safeObjectDelete(&languageInstance_);
254        safeObjectDelete(&configFileManager_);
255        ConsoleCommand::destroyAll();
256        Context::setRootContext(NULL);
257        IdentifierManager::getInstance().destroyAllIdentifiers();
258        safeObjectDelete(&signalHandler_);
259        safeObjectDelete(&dynLibManager_);
260        safeObjectDelete(&pathConfig_);
261
262        orxout(internal_status) << "finished destroying Core object" << endl;
263    }
264
265    //! Function to collect the SetConfigValue-macro calls.
266    void Core::setConfigValues()
267    {
268        SetConfigValueExternal(OutputManager::getInstance().getLogWriter()->configurableMaxLevel_,
269                               OutputManager::getInstance().getLogWriter()->getConfigurableSectionName(),
270                               OutputManager::getInstance().getLogWriter()->getConfigurableMaxLevelName(),
271                               OutputManager::getInstance().getLogWriter()->configurableMaxLevel_)
272            .description("The maximum level of output shown in the log file")
273            .callback(static_cast<BaseWriter*>(OutputManager::getInstance().getLogWriter()), &BaseWriter::changedConfigurableLevel);
274        SetConfigValueExternal(OutputManager::getInstance().getLogWriter()->configurableAdditionalContextsMaxLevel_,
275                               OutputManager::getInstance().getLogWriter()->getConfigurableSectionName(),
276                               OutputManager::getInstance().getLogWriter()->getConfigurableAdditionalContextsMaxLevelName(),
277                               OutputManager::getInstance().getLogWriter()->configurableAdditionalContextsMaxLevel_)
278            .description("The maximum level of output shown in the log file for additional contexts")
279            .callback(static_cast<BaseWriter*>(OutputManager::getInstance().getLogWriter()), &BaseWriter::changedConfigurableAdditionalContextsLevel);
280        SetConfigValueExternal(OutputManager::getInstance().getLogWriter()->configurableAdditionalContexts_,
281                               OutputManager::getInstance().getLogWriter()->getConfigurableSectionName(),
282                               OutputManager::getInstance().getLogWriter()->getConfigurableAdditionalContextsName(),
283                               OutputManager::getInstance().getLogWriter()->configurableAdditionalContexts_)
284            .description("Additional output contexts shown in the log file")
285            .callback(static_cast<BaseWriter*>(OutputManager::getInstance().getLogWriter()), &BaseWriter::changedConfigurableAdditionalContexts);
286
287        SetConfigValue(bDevMode_, PathConfig::buildDirectoryRun())
288            .description("Developer mode. If not set, hides some things from the user to not confuse him.")
289            .callback(this, &Core::devModeChanged);
290        SetConfigValue(language_, Language::getInstance().defaultLanguage_)
291            .description("The language of the in game text")
292            .callback(this, &Core::languageChanged);
293        SetConfigValue(bInitRandomNumberGenerator_, true)
294            .description("If true, all random actions are different each time you start the game")
295            .callback(this, &Core::initRandomNumberGenerator);
296        SetConfigValue(bStartIOConsole_, true)
297            .description("Set to false if you don't want to use the IOConsole (for Lua debugging for instance)");
298        SetConfigValue(lastLevelTimestamp_, 0)
299            .description("Timestamp when the last level was started.");
300        SetConfigValue(ogreConfigTimestamp_, 0)
301            .description("Timestamp when the ogre config file was changed.");
302    }
303
304    /** Callback function for changes in the dev mode that affect debug levels.
305        The function behaves according to these rules:
306        - 'normal' mode is defined based on where the program was launched: if
307          the launch path was the build directory, development mode \c on is
308          normal, otherwise normal means development mode \c off.
309        - Debug levels should not be hard configured (\c config instead of
310          \c tconfig) in non 'normal' mode to avoid strange behaviour.
311        - Changing the development mode from 'normal' to the other state will
312          immediately change the debug levels to predefined values which can be
313          reconfigured with \c tconfig.
314    @note
315        The debug levels for the IOConsole and the InGameConsole can be found
316        in the Shell class. The same rules apply.
317    */
318    void Core::devModeChanged()
319    {
320        // Inform listeners
321        ObjectList<DevModeListener>::iterator it = ObjectList<DevModeListener>::begin();
322        for (; it != ObjectList<DevModeListener>::end(); ++it)
323            it->devModeChanged(bDevMode_);
324    }
325
326    //! Callback function if the language has changed.
327    void Core::languageChanged()
328    {
329        // Read the translation file after the language was configured
330        Language::getInstance().readTranslatedLanguageFile();
331    }
332
333    void Core::initRandomNumberGenerator()
334    {
335        static bool bInitialized = false;
336        if (!bInitialized && this->bInitRandomNumberGenerator_)
337        {
338            srand(static_cast<unsigned int>(time(0)));
339            rand();
340            bInitialized = true;
341        }
342    }
343
344    void Core::loadGraphics()
345    {
346        orxout(internal_info) << "loading graphics in Core" << endl;
347
348        // Any exception should trigger this, even in upgradeToGraphics (see its remarks)
349        Loki::ScopeGuard unloader = Loki::MakeObjGuard(*this, &Core::unloadGraphics);
350
351        // Upgrade OGRE to receive a render window
352        try
353        {
354            graphicsManager_->upgradeToGraphics();
355        }
356        catch (const InitialisationFailedException&)
357        {
358            // Exit the application if the Ogre config dialog was canceled
359            orxout(user_error) << Exception::handleMessage() << endl;
360            exit(EXIT_FAILURE);
361        }
362        catch (...)
363        {
364            // Recovery from this is very difficult. It requires to completely
365            // destroy Ogre related objects and load again (without graphics).
366            // However since Ogre 1.7 there seems to be a problem when Ogre
367            // throws an exception and the graphics engine then gets destroyed
368            // and reloaded between throw and catch (access violation in MSVC).
369            // That's why we abort completely and only display the exception.
370            orxout(user_error) << "An exception occurred during upgrade to graphics. "
371                               << "That is unrecoverable. The message was:" << endl
372                               << Exception::handleMessage() << endl;
373            abort();
374        }
375
376        // Calls the InputManager which sets up the input devices.
377        inputManager_ = new InputManager();
378
379        // Load the CEGUI interface
380        guiManager_ = new GUIManager(inputManager_->getMousePosition());
381
382        bGraphicsLoaded_ = true;
383        GameMode::bShowsGraphics_s = true;
384
385        // Load some sort of a debug overlay (only denoted by its name, "debug.oxo")
386        graphicsManager_->loadDebugOverlay();
387
388        // Create singletons associated with graphics (in other libraries)
389        orxout(internal_info) << "creating graphics scope:" << endl;
390        graphicsScope_ = new Scope<ScopeID::Graphics>();
391
392        unloader.Dismiss();
393
394        orxout(internal_info) << "finished loading graphics in Core" << endl;
395    }
396
397    void Core::unloadGraphics()
398    {
399        orxout(internal_info) << "unloading graphics in Core" << endl;
400
401        safeObjectDelete(&graphicsScope_);
402        safeObjectDelete(&guiManager_);
403        safeObjectDelete(&inputManager_);
404        safeObjectDelete(&graphicsManager_);
405
406        // Load Ogre::Root again, but without the render system
407        try
408            { this->graphicsManager_ = new GraphicsManager(false); }
409        catch (...)
410        {
411            orxout(user_error) << "An exception occurred during 'unloadGraphics':" << Exception::handleMessage() << endl
412                               << "Another exception might be being handled which may lead to undefined behaviour!" << endl
413                               << "Terminating the program." << endl;
414            abort();
415        }
416
417        bGraphicsLoaded_ = false;
418        GameMode::bShowsGraphics_s = false;
419    }
420
421    //! Sets the language in the config-file back to the default.
422    void Core::resetLanguage()
423    {
424        ResetConfigValue(language_);
425    }
426
427    /**
428    @note
429        The code of this function has been copied and adjusted from OGRE, an open source graphics engine.
430            (Object-oriented Graphics Rendering Engine)
431        For the latest info, see http://www.ogre3d.org/
432
433        Copyright (c) 2000-2008 Torus Knot Software Ltd
434
435        OGRE is licensed under the LGPL. For more info, see OGRE license.
436    */
437    void Core::setThreadAffinity(int limitToCPU)
438    {
439#ifdef ORXONOX_PLATFORM_WINDOWS
440
441        if (limitToCPU <= 0)
442            return;
443
444        unsigned int coreNr = limitToCPU - 1;
445        // Get the current process core mask
446        DWORD procMask;
447        DWORD sysMask;
448#  if _MSC_VER >= 1400 && defined (_M_X64)
449        GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&procMask, (PDWORD_PTR)&sysMask);
450#  else
451        GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask);
452#  endif
453
454        // If procMask is 0, consider there is only one core available
455        // (using 0 as procMask will cause an infinite loop below)
456        if (procMask == 0)
457            procMask = 1;
458
459        // if the core specified with coreNr is not available, take the lowest one
460        if (!(procMask & (1 << coreNr)))
461            coreNr = 0;
462
463        // Find the lowest core that this process uses and coreNr suggests
464        DWORD threadMask = 1;
465        while ((threadMask & procMask) == 0 || (threadMask < (1u << coreNr)))
466            threadMask <<= 1;
467
468        // Set affinity to the first core
469        SetThreadAffinityMask(GetCurrentThread(), threadMask);
470#endif
471    }
472
473    void Core::preUpdate(const Clock& time)
474    {
475        // Update singletons before general ticking
476        ScopedSingletonManager::preUpdate<ScopeID::Root>(time);
477        if (this->bGraphicsLoaded_)
478        {
479            // Process input events
480            this->inputManager_->preUpdate(time);
481            // Update GUI
482            this->guiManager_->preUpdate(time);
483            // Update singletons before general ticking
484            ScopedSingletonManager::preUpdate<ScopeID::Graphics>(time);
485        }
486        // Process console events and status line
487        if (this->ioConsole_ != NULL)
488            this->ioConsole_->preUpdate(time);
489        // Process thread commands
490        this->tclThreadManager_->preUpdate(time);
491    }
492
493    void Core::postUpdate(const Clock& time)
494    {
495        // Update singletons just before rendering
496        ScopedSingletonManager::postUpdate<ScopeID::Root>(time);
497        if (this->bGraphicsLoaded_)
498        {
499            // Update singletons just before rendering
500            ScopedSingletonManager::postUpdate<ScopeID::Graphics>(time);
501            // Render (doesn't throw)
502            this->graphicsManager_->postUpdate(time);
503        }
504    }
505
506    void Core::updateLastLevelTimestamp()
507    {
508        ModifyConfigValue(lastLevelTimestamp_, set, static_cast<long long>(time(NULL)));
509    }
510
511    void Core::updateOgreConfigTimestamp()
512    {
513        ModifyConfigValue(ogreConfigTimestamp_, set, static_cast<long long>(time(NULL)));
514    }
515
516
517    RegisterAbstractClass(DevModeListener).inheritsFrom(Class(Listable));
518
519    DevModeListener::DevModeListener()
520    {
521        RegisterObject(DevModeListener);
522    }
523}
Note: See TracBrowser for help on using the repository browser.