Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/core4/src/core/Core.cc @ 3253

Last change on this file since 3253 was 3253, checked in by rgrieder, 15 years ago

Minor fixes and changes.

  • Property svn:eol-style set to native
File size: 22.4 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 <cstdlib>
41#include <cstdio>
42#include <boost/filesystem.hpp>
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#elif defined(ORXONOX_PLATFORM_APPLE)
52#  include <sys/param.h>
53#  include <mach-o/dyld.h>
54#else /* Linux */
55#  include <sys/types.h>
56#  include <unistd.h>
57#endif
58
59#include "SpecialConfig.h"
60#include "util/Debug.h"
61#include "util/Exception.h"
62#include "util/SignalHandler.h"
63#include "Clock.h"
64#include "CommandExecutor.h"
65#include "CommandLine.h"
66#include "ConfigFileManager.h"
67#include "ConfigValueIncludes.h"
68#include "CoreIncludes.h"
69#include "Factory.h"
70#include "Identifier.h"
71#include "Language.h"
72#include "LuaBind.h"
73#include "Shell.h"
74#include "TclBind.h"
75#include "TclThreadManager.h"
76
77namespace orxonox
78{
79    //! Static pointer to the singleton
80    Core* Core::singletonRef_s  = 0;
81
82    SetCommandLineArgument(mediaPath, "").information("PATH");
83    SetCommandLineOnlyArgument(writingPathSuffix, "").information("DIR");
84    SetCommandLineArgument(settingsFile, "orxonox.ini");
85    SetCommandLineArgument(limitToCPU, 0).information("0: off | #cpu");
86
87    /**
88    @brief
89        Helper class for the Core singleton: we cannot derive
90        Core from OrxonoxClass because we need to handle the Identifier
91        destruction in the Core destructor.
92    */
93    class CoreConfiguration : public OrxonoxClass
94    {
95    public:
96        CoreConfiguration()
97        {
98        }
99
100        void initialise()
101        {
102            RegisterRootObject(CoreConfiguration);
103            this->setConfigValues();
104
105            // Possible media path override by the command line
106            if (!CommandLine::getArgument("mediaPath")->hasDefaultValue())
107                tsetMediaPath(CommandLine::getValue("mediaPath"));
108        }
109
110        /**
111            @brief Function to collect the SetConfigValue-macro calls.
112        */
113        void setConfigValues()
114        {
115#ifdef NDEBUG
116            const unsigned int defaultLevelConsole = 1;
117            const unsigned int defaultLevelLogfile = 3;
118            const unsigned int defaultLevelShell   = 1;
119#else
120            const unsigned int defaultLevelConsole = 3;
121            const unsigned int defaultLevelLogfile = 4;
122            const unsigned int defaultLevelShell   = 3;
123#endif
124            SetConfigValue(softDebugLevelConsole_, defaultLevelConsole)
125                .description("The maximal level of debug output shown in the console")
126                .callback(this, &CoreConfiguration::debugLevelChanged);
127            SetConfigValue(softDebugLevelLogfile_, defaultLevelLogfile)
128                .description("The maximal level of debug output shown in the logfile")
129                .callback(this, &CoreConfiguration::debugLevelChanged);
130            SetConfigValue(softDebugLevelShell_, defaultLevelShell)
131                .description("The maximal level of debug output shown in the ingame shell")
132                .callback(this, &CoreConfiguration::debugLevelChanged);
133
134            SetConfigValue(language_, Language::getLanguage().defaultLanguage_)
135                .description("The language of the ingame text")
136                .callback(this, &CoreConfiguration::languageChanged);
137            SetConfigValue(bInitializeRandomNumberGenerator_, true)
138                .description("If true, all random actions are different each time you start the game")
139                .callback(this, &CoreConfiguration::initializeRandomNumberGenerator);
140
141            SetConfigValue(mediaPathString_, mediaPath_.string())
142                .description("Relative path to the game data.")
143                .callback(this, &CoreConfiguration::mediaPathChanged);
144        }
145
146        /**
147            @brief Callback function if the debug level has changed.
148        */
149        void debugLevelChanged()
150        {
151            // softDebugLevel_ is the maximum of the 3 variables
152            this->softDebugLevel_ = this->softDebugLevelConsole_;
153            if (this->softDebugLevelLogfile_ > this->softDebugLevel_)
154                this->softDebugLevel_ = this->softDebugLevelLogfile_;
155            if (this->softDebugLevelShell_ > this->softDebugLevel_)
156                this->softDebugLevel_ = this->softDebugLevelShell_;
157
158            OutputHandler::setSoftDebugLevel(OutputHandler::LD_All,     this->softDebugLevel_);
159            OutputHandler::setSoftDebugLevel(OutputHandler::LD_Console, this->softDebugLevelConsole_);
160            OutputHandler::setSoftDebugLevel(OutputHandler::LD_Logfile, this->softDebugLevelLogfile_);
161            OutputHandler::setSoftDebugLevel(OutputHandler::LD_Shell,   this->softDebugLevelShell_);
162        }
163
164        /**
165            @brief Callback function if the language has changed.
166        */
167        void languageChanged()
168        {
169            // Read the translation file after the language was configured
170            Language::getLanguage().readTranslatedLanguageFile();
171        }
172
173        /**
174        @brief
175            Callback function if the media path has changed.
176        */
177        void mediaPathChanged()
178        {
179            mediaPath_ = boost::filesystem::path(this->mediaPathString_);
180        }
181
182        /**
183            @brief Sets the language in the config-file back to the default.
184        */
185        void resetLanguage()
186        {
187            ResetConfigValue(language_);
188        }
189
190        /**
191        @brief
192            Temporary sets the media path
193        @param path
194            The new media path
195        */
196        void tsetMediaPath(const std::string& path)
197        {
198            ModifyConfigValue(mediaPathString_, tset, path);
199        }
200
201        void initializeRandomNumberGenerator()
202        {
203            static bool bInitialized = false;
204            if (!bInitialized && this->bInitializeRandomNumberGenerator_)
205            {
206                srand(static_cast<unsigned int>(time(0)));
207                rand();
208                bInitialized = true;
209            }
210        }
211
212        int softDebugLevel_;                            //!< The debug level
213        int softDebugLevelConsole_;                     //!< The debug level for the console
214        int softDebugLevelLogfile_;                     //!< The debug level for the logfile
215        int softDebugLevelShell_;                       //!< The debug level for the ingame shell
216        std::string language_;                          //!< The language
217        bool bInitializeRandomNumberGenerator_;         //!< If true, srand(time(0)) is called
218        std::string mediaPathString_;                   //!< Path to the data/media file folder as string
219
220        //! Path to the parent directory of the ones above if program was installed with relativ pahts
221        boost::filesystem::path rootPath_;
222        boost::filesystem::path executablePath_;        //!< Path to the executable
223        boost::filesystem::path mediaPath_;             //!< Path to the media file folder
224        boost::filesystem::path configPath_;            //!< Path to the config file folder
225        boost::filesystem::path logPath_;               //!< Path to the log file folder
226    };
227
228
229    Core::Core(int argc, char** argv)
230    {
231        if (singletonRef_s != 0)
232        {
233            COUT(0) << "Error: The Core singleton cannot be recreated! Shutting down." << std::endl;
234            abort();
235        }
236        Core::singletonRef_s = this;
237
238        // We need the variables very soon. But don't configure them yet!
239        this->configuration_ = new CoreConfiguration();
240
241        // Parse command line arguments first
242        CommandLine::parseCommandLine(argc, argv);
243
244        // Determine and set the location of the executable
245        setExecutablePath();
246
247        // Determine whether we have an installed or a binary dir run
248        // The latter occurs when simply running from the build directory
249        checkDevBuild();
250
251        // Make sure the directories we write in exist or else make them
252        createDirectories();
253
254        // create a signal handler (only active for linux)
255        // This call is placed as soon as possible, but after the directories are set
256        this->signalHandler_ = new SignalHandler();
257        this->signalHandler_->doCatch(configuration_->executablePath_.string(), Core::getLogPathString() + "orxonox_crash.log");
258
259        // Set the correct log path. Before this call, /tmp (Unix) or %TEMP% was used
260        OutputHandler::getOutStream().setLogPath(Core::getLogPathString());
261
262        // Parse additional options file now that we know its path
263        CommandLine::parseFile();
264
265        // limit the main thread to the first core so that QueryPerformanceCounter doesn't jump
266        // do this after ogre has initialised. Somehow Ogre changes the settings again (not through
267        // the timer though).
268        int limitToCPU = CommandLine::getValue("limitToCPU");
269        if (limitToCPU > 0)
270            setThreadAffinity(static_cast<unsigned int>(limitToCPU));
271
272        // Manage ini files and set the default settings file (usually orxonox.ini)
273        this->configFileManager_ = new ConfigFileManager();
274        this->configFileManager_->setFilename(ConfigFileType::Settings,
275            CommandLine::getValue("settingsFile").getString());
276
277        // Required as well for the config values
278        this->languageInstance_ = new Language();
279
280        // Do this soon after the ConfigFileManager has been created to open up the
281        // possibility to configure everything below here
282        this->configuration_->initialise();
283
284        // Create the lua interface
285        this->luaBind_ = new LuaBind();
286
287        // initialise Tcl
288        this->tclBind_ = new TclBind(Core::getMediaPathString());
289        this->tclThreadManager_ = new TclThreadManager(tclBind_->getTclInterpreter());
290
291        // create a shell
292        this->shell_ = new Shell();
293
294        // creates the class hierarchy for all classes with factories
295        Factory::createClassHierarchy();
296    }
297
298    /**
299        @brief Sets the bool to true to avoid static functions accessing a deleted object.
300    */
301    Core::~Core()
302    {
303        delete this->shell_;
304        delete this->tclThreadManager_;
305        delete this->tclBind_;
306        delete this->luaBind_;
307        delete this->configuration_;
308        delete this->languageInstance_;
309        delete this->configFileManager_;
310
311        // Destroy command line arguments
312        CommandLine::destroyAllArguments();
313        // Also delete external console command that don't belong to an Identifier
314        CommandExecutor::destroyExternalCommands();
315        // Clean up class hierarchy stuff (identifiers, XMLPort, configValues, consoleCommand)
316        Identifier::destroyAllIdentifiers();
317
318        delete this->signalHandler_;
319
320        // Don't assign singletonRef_s with NULL! Recreation is not supported
321    }
322
323    /**
324        @brief Returns the softDebugLevel for the given device (returns a default-value if the class is right about to be created).
325        @param device The device
326        @return The softDebugLevel
327    */
328    /*static*/ int Core::getSoftDebugLevel(OutputHandler::OutputDevice device)
329    {
330        switch (device)
331        {
332        case OutputHandler::LD_All:
333            return Core::getInstance().configuration_->softDebugLevel_;
334        case OutputHandler::LD_Console:
335            return Core::getInstance().configuration_->softDebugLevelConsole_;
336        case OutputHandler::LD_Logfile:
337            return Core::getInstance().configuration_->softDebugLevelLogfile_;
338        case OutputHandler::LD_Shell:
339            return Core::getInstance().configuration_->softDebugLevelShell_;
340        default:
341            assert(0);
342            return 2;
343        }
344    }
345
346     /**
347        @brief Sets the softDebugLevel for the given device. Please use this only temporary and restore the value afterwards, as it overrides the configured value.
348        @param device The device
349        @param level The level
350    */
351    /*static*/ void Core::setSoftDebugLevel(OutputHandler::OutputDevice device, int level)
352    {
353        if (device == OutputHandler::LD_All)
354            Core::getInstance().configuration_->softDebugLevel_ = level;
355        else if (device == OutputHandler::LD_Console)
356            Core::getInstance().configuration_->softDebugLevelConsole_ = level;
357        else if (device == OutputHandler::LD_Logfile)
358            Core::getInstance().configuration_->softDebugLevelLogfile_ = level;
359        else if (device == OutputHandler::LD_Shell)
360            Core::getInstance().configuration_->softDebugLevelShell_ = level;
361
362        OutputHandler::setSoftDebugLevel(device, level);
363    }
364
365    /**
366        @brief Returns the configured language.
367    */
368    /*static*/ const std::string& Core::getLanguage()
369    {
370        return Core::getInstance().configuration_->language_;
371    }
372
373    /**
374        @brief Sets the language in the config-file back to the default.
375    */
376    /*static*/ void Core::resetLanguage()
377    {
378        Core::getInstance().configuration_->resetLanguage();
379    }
380
381    /*static*/ void Core::tsetMediaPath(const std::string& path)
382    {
383        getInstance().configuration_->tsetMediaPath(path);
384    }
385
386    /*static*/ const boost::filesystem::path& Core::getMediaPath()
387    {
388        return getInstance().configuration_->mediaPath_;
389    }
390    /*static*/ std::string Core::getMediaPathString()
391    {
392        return getInstance().configuration_->mediaPath_.string() + '/';
393    }
394
395    /*static*/ const boost::filesystem::path& Core::getConfigPath()
396    {
397        return getInstance().configuration_->configPath_;
398    }
399    /*static*/ std::string Core::getConfigPathString()
400    {
401        return getInstance().configuration_->configPath_.string() + '/';
402    }
403
404    /*static*/ const boost::filesystem::path& Core::getLogPath()
405    {
406        return getInstance().configuration_->logPath_;
407    }
408    /*static*/ std::string Core::getLogPathString()
409    {
410        return getInstance().configuration_->logPath_.string() + '/';
411    }
412
413    /**
414    @note
415        The code of this function has been copied and adjusted from OGRE, an open source graphics engine.
416            (Object-oriented Graphics Rendering Engine)
417        For the latest info, see http://www.ogre3d.org/
418
419        Copyright (c) 2000-2008 Torus Knot Software Ltd
420
421        OGRE is licensed under the LGPL. For more info, see OGRE license.
422    */
423    void Core::setThreadAffinity(int limitToCPU)
424    {
425        if (limitToCPU <= 0)
426            return;
427
428#ifdef ORXONOX_PLATFORM_WINDOWS
429        unsigned int coreNr = limitToCPU - 1;
430        // Get the current process core mask
431        DWORD procMask;
432        DWORD sysMask;
433#  if _MSC_VER >= 1400 && defined (_M_X64)
434        GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&procMask, (PDWORD_PTR)&sysMask);
435#  else
436        GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask);
437#  endif
438
439        // If procMask is 0, consider there is only one core available
440        // (using 0 as procMask will cause an infinite loop below)
441        if (procMask == 0)
442            procMask = 1;
443
444        // if the core specified with coreNr is not available, take the lowest one
445        if (!(procMask & (1 << coreNr)))
446            coreNr = 0;
447
448        // Find the lowest core that this process uses and coreNr suggests
449        DWORD threadMask = 1;
450        while ((threadMask & procMask) == 0 || (threadMask < (1u << coreNr)))
451            threadMask <<= 1;
452
453        // Set affinity to the first core
454        SetThreadAffinityMask(GetCurrentThread(), threadMask);
455#endif
456    }
457
458    /**
459    @brief
460        Compares the executable path with the working directory
461    */
462    void Core::setExecutablePath()
463    {
464#ifdef ORXONOX_PLATFORM_WINDOWS
465        // get executable module
466        TCHAR buffer[1024];
467        if (GetModuleFileName(NULL, buffer, 1024) == 0)
468            ThrowException(General, "Could not retrieve executable path.");
469
470#elif defined(ORXONOX_PLATFORM_APPLE)
471        char buffer[1024];
472        unsigned long path_len = 1023;
473        if (_NSGetExecutablePath(buffer, &path_len))
474            ThrowException(General, "Could not retrieve executable path.");
475
476#else /* Linux */
477        /* written by Nicolai Haehnle <prefect_@gmx.net> */
478
479        /* Get our PID and build the name of the link in /proc */
480        char linkname[64]; /* /proc/<pid>/exe */
481        if (snprintf(linkname, sizeof(linkname), "/proc/%i/exe", getpid()) < 0)
482        {
483            /* This should only happen on large word systems. I'm not sure
484               what the proper response is here.
485               Since it really is an assert-like condition, aborting the
486               program seems to be in order. */
487            assert(false);
488        }
489
490        /* Now read the symbolic link */
491        char buffer[1024];
492        int ret;
493        ret = readlink(linkname, buffer, 1024);
494        /* In case of an error, leave the handling up to the caller */
495        if (ret == -1)
496            ThrowException(General, "Could not retrieve executable path.");
497
498        /* Ensure proper NUL termination */
499        buffer[ret] = 0;
500#endif
501
502        configuration_->executablePath_ = boost::filesystem::path(buffer);
503#ifndef ORXONOX_PLATFORM_APPLE
504        configuration_->executablePath_ = configuration_->executablePath_.branch_path(); // remove executable name
505#endif
506    }
507
508    /**
509    @brief
510        Checks for "orxonox_dev_build.keep_me" in the executable diretory.
511        If found it means that this is not an installed run, hence we
512        don't write the logs and config files to ~/.orxonox
513    @throws
514        GeneralException
515    */
516    void Core::checkDevBuild()
517    {
518        if (boost::filesystem::exists(configuration_->executablePath_ / "orxonox_dev_build.keep_me"))
519        {
520            COUT(1) << "Running from the build tree." << std::endl;
521            Core::isDevBuild_ = true;
522            configuration_->mediaPath_  = ORXONOX_MEDIA_DEV_PATH;
523            configuration_->configPath_ = ORXONOX_CONFIG_DEV_PATH;
524            configuration_->logPath_    = ORXONOX_LOG_DEV_PATH;
525        }
526        else
527        {
528#ifdef INSTALL_COPYABLE // --> relative paths
529            // Also set the root path
530            boost::filesystem::path relativeExecutablePath(ORXONOX_RUNTIME_INSTALL_PATH);
531            configuration_->rootPath_ = configuration_->executablePath_;
532            while (!boost::filesystem::equivalent(configuration_->rootPath_ / relativeExecutablePath, configuration_->executablePath_)
533                   && !configuration_->rootPath_.empty())
534                configuration_->rootPath_ = configuration_->rootPath_.branch_path();
535            if (configuration_->rootPath_.empty())
536                ThrowException(General, "Could not derive a root directory. Might the binary installation directory contain '..' when taken relative to the installation prefix path?");
537
538            // Using paths relative to the install prefix, complete them
539            configuration_->mediaPath_  = configuration_->rootPath_ / ORXONOX_MEDIA_INSTALL_PATH;
540            configuration_->configPath_ = configuration_->rootPath_ / ORXONOX_CONFIG_INSTALL_PATH;
541            configuration_->logPath_    = configuration_->rootPath_ / ORXONOX_LOG_INSTALL_PATH;
542#else
543            // There is no root path, so don't set it at all
544
545            configuration_->mediaPath_  = ORXONOX_MEDIA_INSTALL_PATH;
546
547            // Get user directory
548#  ifdef ORXONOX_PLATFORM_UNIX /* Apple? */
549            char* userDataPathPtr(getenv("HOME"));
550#  else
551            char* userDataPathPtr(getenv("APPDATA"));
552#  endif
553            if (userDataPathPtr == NULL)
554                ThrowException(General, "Could not retrieve user data path.");
555            boost::filesystem::path userDataPath(userDataPathPtr);
556            userDataPath /= ".orxonox";
557
558            configuration_->configPath_ = userDataPath / ORXONOX_CONFIG_INSTALL_PATH;
559            configuration_->logPath_    = userDataPath / ORXONOX_LOG_INSTALL_PATH;
560#endif
561        }
562
563        // Option to put all the config and log files in a separate folder
564        if (!CommandLine::getArgument("writingPathSuffix")->hasDefaultValue())
565        {
566            std::string directory(CommandLine::getValue("writingPathSuffix").getString());
567            configuration_->configPath_ = configuration_->configPath_ / directory;
568            configuration_->logPath_    = configuration_->logPath_    / directory;
569        }
570    }
571
572    /*
573    @brief
574        Checks for the log and the config directory and creates them
575        if necessary. Otherwise me might have problems opening those files.
576    @throws
577        orxonox::GeneralException if the directory to be created is a file.
578    */
579    void Core::createDirectories()
580    {
581        std::vector<std::pair<boost::filesystem::path, std::string> > directories;
582        directories.push_back(std::make_pair(boost::filesystem::path(configuration_->configPath_), "config"));
583        directories.push_back(std::make_pair(boost::filesystem::path(configuration_->logPath_), "log"));
584
585        for (std::vector<std::pair<boost::filesystem::path, std::string> >::iterator it = directories.begin();
586            it != directories.end(); ++it)
587        {
588            if (boost::filesystem::exists(it->first) && !boost::filesystem::is_directory(it->first))
589            {
590                ThrowException(General, std::string("The ") + it->second + " directory has been preoccupied by a file! \
591                                         Please remove " + it->first.string());
592            }
593            if (boost::filesystem::create_directories(it->first)) // function may not return true at all (bug?)
594            {
595                COUT(4) << "Created " << it->second << " directory" << std::endl;
596            }
597        }
598    }
599
600    void Core::update(const Clock& time)
601    {
602        this->tclThreadManager_->update(time);
603    }
604}
Note: See TracBrowser for help on using the repository browser.