Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 5647 was 5647, checked in by landauf, 15 years ago

protected the plugin loader from single-plugin-exceptions (for example caused by invalid .plugin files)

  • Property svn:eol-style set to native
File size: 28.6 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/version.hpp>
43#include <boost/filesystem.hpp>
44#include <OgreRenderWindow.h>
45
46#ifdef ORXONOX_PLATFORM_WINDOWS
47#  ifndef WIN32_LEAN_AND_MEAN
48#    define WIN32_LEAN_AND_MEAN
49#  endif
50#  include <windows.h>
51#  undef min
52#  undef max
53#elif defined(ORXONOX_PLATFORM_APPLE)
54#  include <sys/param.h>
55#  include <mach-o/dyld.h>
56#else /* Linux */
57#  include <sys/types.h>
58#  include <unistd.h>
59#endif
60
61#include "SpecialConfig.h"
62#include "util/Debug.h"
63#include "util/Exception.h"
64#include "util/SignalHandler.h"
65#include "Clock.h"
66#include "CommandExecutor.h"
67#include "CommandLine.h"
68#include "ConfigFileManager.h"
69#include "ConfigValueIncludes.h"
70#include "CoreIncludes.h"
71#include "DynLibManager.h"
72#include "Factory.h"
73#include "GameMode.h"
74#include "GraphicsManager.h"
75#include "GUIManager.h"
76#include "Identifier.h"
77#include "Language.h"
78#include "LuaBind.h"
79#include "Shell.h"
80#include "TclBind.h"
81#include "TclThreadManager.h"
82#include "input/InputManager.h"
83
84// Boost 1.36 has some issues with deprecated functions that have been omitted
85#if (BOOST_VERSION == 103600)
86#  define BOOST_LEAF_FUNCTION filename
87#else
88#  define BOOST_LEAF_FUNCTION leaf
89#endif
90
91namespace orxonox
92{
93    //! Static pointer to the singleton
94    Core* Core::singletonPtr_s  = 0;
95
96    SetCommandLineArgument(mediaPath, "").information("Path to the media/data files");
97    SetCommandLineOnlyArgument(writingPathSuffix, "").information("Additional subfolder for config and log files");
98    SetCommandLineArgument(settingsFile, "orxonox.ini").information("THE configuration file");
99#ifdef ORXONOX_PLATFORM_WINDOWS
100    SetCommandLineArgument(limitToCPU, 0).information("Limits the program to one cpu/core (1, 2, 3, etc.). 0 turns it off (default)");
101#endif
102
103    /**
104    @brief
105        Helper class for the Core singleton: we cannot derive
106        Core from OrxonoxClass because we need to handle the Identifier
107        destruction in the Core destructor.
108    */
109    class CoreConfiguration : public OrxonoxClass
110    {
111    public:
112        CoreConfiguration()
113        {
114        }
115
116        void initialise()
117        {
118            RegisterRootObject(CoreConfiguration);
119            this->setConfigValues();
120
121            // Possible media path override by the command line
122            if (!CommandLine::getArgument("mediaPath")->hasDefaultValue())
123                tsetMediaPath(CommandLine::getValue("mediaPath"));
124        }
125
126        /**
127            @brief Function to collect the SetConfigValue-macro calls.
128        */
129        void setConfigValues()
130        {
131#ifdef NDEBUG
132            const unsigned int defaultLevelConsole = 1;
133            const unsigned int defaultLevelLogfile = 3;
134            const unsigned int defaultLevelShell   = 1;
135#else
136            const unsigned int defaultLevelConsole = 3;
137            const unsigned int defaultLevelLogfile = 4;
138            const unsigned int defaultLevelShell   = 3;
139#endif
140            SetConfigValue(softDebugLevelConsole_, defaultLevelConsole)
141                .description("The maximal level of debug output shown in the console")
142                .callback(this, &CoreConfiguration::debugLevelChanged);
143            SetConfigValue(softDebugLevelLogfile_, defaultLevelLogfile)
144                .description("The maximal level of debug output shown in the logfile")
145                .callback(this, &CoreConfiguration::debugLevelChanged);
146            SetConfigValue(softDebugLevelShell_, defaultLevelShell)
147                .description("The maximal level of debug output shown in the ingame shell")
148                .callback(this, &CoreConfiguration::debugLevelChanged);
149
150            SetConfigValue(language_, Language::getInstance().defaultLanguage_)
151                .description("The language of the ingame text")
152                .callback(this, &CoreConfiguration::languageChanged);
153            SetConfigValue(bInitializeRandomNumberGenerator_, true)
154                .description("If true, all random actions are different each time you start the game")
155                .callback(this, &CoreConfiguration::initializeRandomNumberGenerator);
156
157            // Only show this config value for development builds
158            if (Core::isDevelopmentRun())
159            {
160                SetConfigValue(mediaPathString_, mediaPath_.string())
161                    .description("Relative path to the game data.")
162                    .callback(this, &CoreConfiguration::mediaPathChanged);
163            }
164        }
165
166        /**
167            @brief Callback function if the debug level has changed.
168        */
169        void debugLevelChanged()
170        {
171            // softDebugLevel_ is the maximum of the 3 variables
172            this->softDebugLevel_ = this->softDebugLevelConsole_;
173            if (this->softDebugLevelLogfile_ > this->softDebugLevel_)
174                this->softDebugLevel_ = this->softDebugLevelLogfile_;
175            if (this->softDebugLevelShell_ > this->softDebugLevel_)
176                this->softDebugLevel_ = this->softDebugLevelShell_;
177
178            OutputHandler::setSoftDebugLevel(OutputHandler::LD_All,     this->softDebugLevel_);
179            OutputHandler::setSoftDebugLevel(OutputHandler::LD_Console, this->softDebugLevelConsole_);
180            OutputHandler::setSoftDebugLevel(OutputHandler::LD_Logfile, this->softDebugLevelLogfile_);
181            OutputHandler::setSoftDebugLevel(OutputHandler::LD_Shell,   this->softDebugLevelShell_);
182        }
183
184        /**
185            @brief Callback function if the language has changed.
186        */
187        void languageChanged()
188        {
189            // Read the translation file after the language was configured
190            Language::getInstance().readTranslatedLanguageFile();
191        }
192
193        /**
194        @brief
195            Callback function if the media path has changed.
196        */
197        void mediaPathChanged()
198        {
199            mediaPath_ = boost::filesystem::path(this->mediaPathString_);
200        }
201
202        /**
203            @brief Sets the language in the config-file back to the default.
204        */
205        void resetLanguage()
206        {
207            ResetConfigValue(language_);
208        }
209
210        /**
211        @brief
212            Temporary sets the media path
213        @param path
214            The new media path
215        */
216        void tsetMediaPath(const std::string& path)
217        {
218            if (Core::isDevelopmentRun())
219            {
220                ModifyConfigValue(mediaPathString_, tset, path);
221            }
222            else
223            {
224                // Manual 'config' value without the file entry
225                mediaPathString_ = path;
226                this->mediaPathChanged();
227            }
228        }
229
230        void initializeRandomNumberGenerator()
231        {
232            static bool bInitialized = false;
233            if (!bInitialized && this->bInitializeRandomNumberGenerator_)
234            {
235                srand(static_cast<unsigned int>(time(0)));
236                rand();
237                bInitialized = true;
238            }
239        }
240
241        int softDebugLevel_;                            //!< The debug level
242        int softDebugLevelConsole_;                     //!< The debug level for the console
243        int softDebugLevelLogfile_;                     //!< The debug level for the logfile
244        int softDebugLevelShell_;                       //!< The debug level for the ingame shell
245        std::string language_;                          //!< The language
246        bool bInitializeRandomNumberGenerator_;         //!< If true, srand(time(0)) is called
247        std::string mediaPathString_;                   //!< Path to the data/media file folder as string
248
249        //! Path to the parent directory of the ones above if program was installed with relativ pahts
250        boost::filesystem::path rootPath_;
251        boost::filesystem::path executablePath_;        //!< Path to the executable
252        boost::filesystem::path pluginPath_;            //!< Path to the plugins
253        boost::filesystem::path mediaPath_;             //!< Path to the media file folder
254        boost::filesystem::path configPath_;            //!< Path to the config file folder
255        boost::filesystem::path logPath_;               //!< Path to the log file folder
256    };
257
258
259    Core::Core(const std::string& cmdLine)
260        // Cleanup guard for identifier destruction (incl. XMLPort, configValues, consoleCommands)
261        : identifierDestroyer_(Identifier::destroyAllIdentifiers)
262        // Cleanup guard for external console commands that don't belong to an Identifier
263        , consoleCommandDestroyer_(CommandExecutor::destroyExternalCommands)
264        , configuration_(new CoreConfiguration()) // Don't yet create config values!
265        , bDevRun_(false)
266        , bGraphicsLoaded_(false)
267    {
268        // Set the hard coded fixed paths
269        this->setFixedPaths();
270
271        // Create a new dynamic library manager
272        this->dynLibManager_.reset(new DynLibManager());
273
274        // Load plugins
275        try
276        {
277            // We search for helper files with the following extension
278            std::string pluginextension = ".plugin";
279            size_t pluginextensionlength = pluginextension.size();
280
281            // Search in the directory of our executable
282            boost::filesystem::path searchpath = this->configuration_->pluginPath_;
283
284            boost::filesystem::directory_iterator file(searchpath);
285            boost::filesystem::directory_iterator end;
286
287            // Iterate through all files
288            while (file != end)
289            {
290                std::string filename = file->BOOST_LEAF_FUNCTION();
291
292                // Check if the file ends with the exension in question
293                if (filename.size() > pluginextensionlength)
294                {
295                    if (filename.substr(filename.size() - pluginextensionlength) == pluginextension)
296                    {
297                        // We've found a helper file - now load the library with the same name
298                        std::string library = filename.substr(0, filename.size() - pluginextensionlength);
299                        boost::filesystem::path librarypath = searchpath / library;
300
301                        try
302                        {
303                            DynLibManager::getInstance().load(librarypath.string());
304                        }
305                        catch (const std::exception& e)
306                        {
307                            COUT(1) << "Couldn't load plugin \"" << librarypath.string() << "\": " << e.what() << std::endl;
308                        }
309                        catch (...)
310                        {
311                            COUT(1) << "Couldn't load plugin \"" << librarypath.string() << "\"" << std::endl;
312                        }
313                    }
314                }
315
316                ++file;
317            }
318        }
319        catch (const std::exception& e)
320        {
321            COUT(1) << "An error occurred while loading plugins: " << e.what() << std::endl;
322        }
323        catch (...)
324        {
325            COUT(1) << "An error occurred while loading plugins." << std::endl;
326        }
327
328        // Parse command line arguments AFTER the plugins have been loaded (static code!)
329        CommandLine::parseCommandLine(cmdLine);
330
331        // Set configurable paths like log, config and media
332        this->setConfigurablePaths();
333
334        // create a signal handler (only active for linux)
335        // This call is placed as soon as possible, but after the directories are set
336        this->signalHandler_.reset(new SignalHandler());
337        this->signalHandler_->doCatch(configuration_->executablePath_.string(), Core::getLogPathString() + "orxonox_crash.log");
338
339        // Set the correct log path. Before this call, /tmp (Unix) or %TEMP% was used
340        OutputHandler::getOutStream().setLogPath(Core::getLogPathString());
341
342        // Parse additional options file now that we know its path
343        CommandLine::parseFile();
344
345#ifdef ORXONOX_PLATFORM_WINDOWS
346        // limit the main thread to the first core so that QueryPerformanceCounter doesn't jump
347        // do this after ogre has initialised. Somehow Ogre changes the settings again (not through
348        // the timer though).
349        int limitToCPU = CommandLine::getValue("limitToCPU");
350        if (limitToCPU > 0)
351            setThreadAffinity(static_cast<unsigned int>(limitToCPU));
352#endif
353
354        // Manage ini files and set the default settings file (usually orxonox.ini)
355        this->configFileManager_.reset(new ConfigFileManager());
356        this->configFileManager_->setFilename(ConfigFileType::Settings,
357            CommandLine::getValue("settingsFile").getString());
358
359        // Required as well for the config values
360        this->languageInstance_.reset(new Language());
361
362        // Do this soon after the ConfigFileManager has been created to open up the
363        // possibility to configure everything below here
364        this->configuration_->initialise();
365
366        // Create the lua interface
367        this->luaBind_.reset(new LuaBind());
368
369        // initialise Tcl
370        this->tclBind_.reset(new TclBind(Core::getMediaPathString()));
371        this->tclThreadManager_.reset(new TclThreadManager(tclBind_->getTclInterpreter()));
372
373        // create a shell
374        this->shell_.reset(new Shell());
375
376        // creates the class hierarchy for all classes with factories
377        Factory::createClassHierarchy();
378    }
379
380    /**
381    @brief
382        All destruction code is handled by scoped_ptrs and SimpleScopeGuards.
383    */
384    Core::~Core()
385    {
386    }
387
388    void Core::loadGraphics()
389    {
390        if (bGraphicsLoaded_)
391            return;
392
393        // Load OGRE including the render window
394        scoped_ptr<GraphicsManager> graphicsManager(new GraphicsManager());
395
396        // The render window width and height are used to set up the mouse movement.
397        size_t windowHnd = 0;
398        graphicsManager->getRenderWindow()->getCustomAttribute("WINDOW", &windowHnd);
399
400        // Calls the InputManager which sets up the input devices.
401        scoped_ptr<InputManager> inputManager(new InputManager(windowHnd));
402
403        // load the CEGUI interface
404        guiManager_.reset(new GUIManager(graphicsManager->getRenderWindow()));
405
406        // Dismiss scoped pointers
407        graphicsManager_.swap(graphicsManager);
408        inputManager_.swap(inputManager);
409
410        bGraphicsLoaded_ = true;
411    }
412
413    void Core::unloadGraphics()
414    {
415        if (!bGraphicsLoaded_)
416            return;
417
418        this->guiManager_.reset();;
419        this->inputManager_.reset();;
420        this->graphicsManager_.reset();
421
422        bGraphicsLoaded_ = false;
423    }
424
425    /**
426        @brief Returns the softDebugLevel for the given device (returns a default-value if the class is right about to be created).
427        @param device The device
428        @return The softDebugLevel
429    */
430    /*static*/ int Core::getSoftDebugLevel(OutputHandler::OutputDevice device)
431    {
432        switch (device)
433        {
434        case OutputHandler::LD_All:
435            return Core::getInstance().configuration_->softDebugLevel_;
436        case OutputHandler::LD_Console:
437            return Core::getInstance().configuration_->softDebugLevelConsole_;
438        case OutputHandler::LD_Logfile:
439            return Core::getInstance().configuration_->softDebugLevelLogfile_;
440        case OutputHandler::LD_Shell:
441            return Core::getInstance().configuration_->softDebugLevelShell_;
442        default:
443            assert(0);
444            return 2;
445        }
446    }
447
448     /**
449        @brief Sets the softDebugLevel for the given device. Please use this only temporary and restore the value afterwards, as it overrides the configured value.
450        @param device The device
451        @param level The level
452    */
453    /*static*/ void Core::setSoftDebugLevel(OutputHandler::OutputDevice device, int level)
454    {
455        if (device == OutputHandler::LD_All)
456            Core::getInstance().configuration_->softDebugLevel_ = level;
457        else if (device == OutputHandler::LD_Console)
458            Core::getInstance().configuration_->softDebugLevelConsole_ = level;
459        else if (device == OutputHandler::LD_Logfile)
460            Core::getInstance().configuration_->softDebugLevelLogfile_ = level;
461        else if (device == OutputHandler::LD_Shell)
462            Core::getInstance().configuration_->softDebugLevelShell_ = level;
463
464        OutputHandler::setSoftDebugLevel(device, level);
465    }
466
467    /**
468        @brief Returns the configured language.
469    */
470    /*static*/ const std::string& Core::getLanguage()
471    {
472        return Core::getInstance().configuration_->language_;
473    }
474
475    /**
476        @brief Sets the language in the config-file back to the default.
477    */
478    /*static*/ void Core::resetLanguage()
479    {
480        Core::getInstance().configuration_->resetLanguage();
481    }
482
483    /*static*/ void Core::tsetMediaPath(const std::string& path)
484    {
485        getInstance().configuration_->tsetMediaPath(path);
486    }
487
488    /*static*/ const boost::filesystem::path& Core::getMediaPath()
489    {
490        return getInstance().configuration_->mediaPath_;
491    }
492    /*static*/ std::string Core::getMediaPathString()
493    {
494        return getInstance().configuration_->mediaPath_.string() + '/';
495    }
496
497    /*static*/ const boost::filesystem::path& Core::getConfigPath()
498    {
499        return getInstance().configuration_->configPath_;
500    }
501    /*static*/ std::string Core::getConfigPathString()
502    {
503        return getInstance().configuration_->configPath_.string() + '/';
504    }
505
506    /*static*/ const boost::filesystem::path& Core::getLogPath()
507    {
508        return getInstance().configuration_->logPath_;
509    }
510    /*static*/ std::string Core::getLogPathString()
511    {
512        return getInstance().configuration_->logPath_.string() + '/';
513    }
514
515    /*static*/ const boost::filesystem::path& Core::getRootPath()
516    {
517        return getInstance().configuration_->rootPath_;
518    }
519    /*static*/ std::string Core::getRootPathString()
520    {
521        return getInstance().configuration_->rootPath_.string() + '/';
522    }
523
524    /**
525    @note
526        The code of this function has been copied and adjusted from OGRE, an open source graphics engine.
527            (Object-oriented Graphics Rendering Engine)
528        For the latest info, see http://www.ogre3d.org/
529
530        Copyright (c) 2000-2008 Torus Knot Software Ltd
531
532        OGRE is licensed under the LGPL. For more info, see OGRE license.
533    */
534    void Core::setThreadAffinity(int limitToCPU)
535    {
536#ifdef ORXONOX_PLATFORM_WINDOWS
537
538        if (limitToCPU <= 0)
539            return;
540
541        unsigned int coreNr = limitToCPU - 1;
542        // Get the current process core mask
543        DWORD procMask;
544        DWORD sysMask;
545#  if _MSC_VER >= 1400 && defined (_M_X64)
546        GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&procMask, (PDWORD_PTR)&sysMask);
547#  else
548        GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask);
549#  endif
550
551        // If procMask is 0, consider there is only one core available
552        // (using 0 as procMask will cause an infinite loop below)
553        if (procMask == 0)
554            procMask = 1;
555
556        // if the core specified with coreNr is not available, take the lowest one
557        if (!(procMask & (1 << coreNr)))
558            coreNr = 0;
559
560        // Find the lowest core that this process uses and coreNr suggests
561        DWORD threadMask = 1;
562        while ((threadMask & procMask) == 0 || (threadMask < (1u << coreNr)))
563            threadMask <<= 1;
564
565        // Set affinity to the first core
566        SetThreadAffinityMask(GetCurrentThread(), threadMask);
567#endif
568    }
569
570    /**
571    @brief
572        Retrievs the executable path and sets all hard coded fixed path (currently only plugin path)
573        Also checks for "orxonox_dev_build.keep_me" in the executable diretory.
574        If found it means that this is not an installed run, hence we
575        don't write the logs and config files to ~/.orxonox
576    @throw
577        GeneralException
578    */
579    void Core::setFixedPaths()
580    {
581        //////////////////////////
582        // FIND EXECUTABLE PATH //
583        //////////////////////////
584
585#ifdef ORXONOX_PLATFORM_WINDOWS
586        // get executable module
587        TCHAR buffer[1024];
588        if (GetModuleFileName(NULL, buffer, 1024) == 0)
589            ThrowException(General, "Could not retrieve executable path.");
590
591#elif defined(ORXONOX_PLATFORM_APPLE)
592        char buffer[1024];
593        unsigned long path_len = 1023;
594        if (_NSGetExecutablePath(buffer, &path_len))
595            ThrowException(General, "Could not retrieve executable path.");
596
597#else /* Linux */
598        /* written by Nicolai Haehnle <prefect_@gmx.net> */
599
600        /* Get our PID and build the name of the link in /proc */
601        char linkname[64]; /* /proc/<pid>/exe */
602        if (snprintf(linkname, sizeof(linkname), "/proc/%i/exe", getpid()) < 0)
603        {
604            /* This should only happen on large word systems. I'm not sure
605               what the proper response is here.
606               Since it really is an assert-like condition, aborting the
607               program seems to be in order. */
608            assert(false);
609        }
610
611        /* Now read the symbolic link */
612        char buffer[1024];
613        int ret;
614        ret = readlink(linkname, buffer, 1024);
615        /* In case of an error, leave the handling up to the caller */
616        if (ret == -1)
617            ThrowException(General, "Could not retrieve executable path.");
618
619        /* Ensure proper NUL termination */
620        buffer[ret] = 0;
621#endif
622
623        configuration_->executablePath_ = boost::filesystem::path(buffer);
624#ifndef ORXONOX_PLATFORM_APPLE
625        configuration_->executablePath_ = configuration_->executablePath_.branch_path(); // remove executable name
626#endif
627
628        /////////////////////
629        // SET PLUGIN PATH //
630        /////////////////////
631
632        if (boost::filesystem::exists(configuration_->executablePath_ / "orxonox_dev_build.keep_me"))
633        {
634            COUT(1) << "Running from the build tree." << std::endl;
635            Core::bDevRun_ = true;
636            configuration_->pluginPath_ = ORXONOX_PLUGIN_DEV_PATH;
637        }
638        else
639        {
640
641#ifdef INSTALL_COPYABLE // --> relative paths
642
643            // Also set the root path
644            boost::filesystem::path relativeExecutablePath(ORXONOX_RUNTIME_INSTALL_PATH);
645            configuration_->rootPath_ = configuration_->executablePath_;
646            while (!boost::filesystem::equivalent(configuration_->rootPath_ / relativeExecutablePath, configuration_->executablePath_)
647                   && !configuration_->rootPath_.empty())
648                configuration_->rootPath_ = configuration_->rootPath_.branch_path();
649            if (configuration_->rootPath_.empty())
650                ThrowException(General, "Could not derive a root directory. Might the binary installation directory contain '..' when taken relative to the installation prefix path?");
651
652            // Plugin path is fixed as well
653            configuration_->pluginPath_ = configuration_->rootPath_ / ORXONOX_PLUGIN_INSTALL_PATH;
654
655#else
656
657            // There is no root path, so don't set it at all
658            // Plugin path is fixed as well
659            configuration_->pluginPath_ = ORXONOX_PLUGIN_INSTALL_PATH;
660
661#endif
662        }
663    }
664
665    /**
666    @brief
667        Sets config, log and media path and creates folders if necessary.
668    @throws
669        GeneralException
670    */
671    void Core::setConfigurablePaths()
672    {
673        if (Core::isDevelopmentRun())
674        {
675            configuration_->mediaPath_  = ORXONOX_MEDIA_DEV_PATH;
676            configuration_->configPath_ = ORXONOX_CONFIG_DEV_PATH;
677            configuration_->logPath_    = ORXONOX_LOG_DEV_PATH;
678        }
679        else
680        {
681
682#ifdef INSTALL_COPYABLE // --> relative paths
683
684            // Using paths relative to the install prefix, complete them
685            configuration_->mediaPath_  = configuration_->rootPath_ / ORXONOX_MEDIA_INSTALL_PATH;
686            configuration_->configPath_ = configuration_->rootPath_ / ORXONOX_CONFIG_INSTALL_PATH;
687            configuration_->logPath_    = configuration_->rootPath_ / ORXONOX_LOG_INSTALL_PATH;
688
689#else
690
691            configuration_->mediaPath_  = ORXONOX_MEDIA_INSTALL_PATH;
692
693            // Get user directory
694#  ifdef ORXONOX_PLATFORM_UNIX /* Apple? */
695            char* userDataPathPtr(getenv("HOME"));
696#  else
697            char* userDataPathPtr(getenv("APPDATA"));
698#  endif
699            if (userDataPathPtr == NULL)
700                ThrowException(General, "Could not retrieve user data path.");
701            boost::filesystem::path userDataPath(userDataPathPtr);
702            userDataPath /= ".orxonox";
703
704            configuration_->configPath_ = userDataPath / ORXONOX_CONFIG_INSTALL_PATH;
705            configuration_->logPath_    = userDataPath / ORXONOX_LOG_INSTALL_PATH;
706
707#endif
708
709        }
710
711        // Option to put all the config and log files in a separate folder
712        if (!CommandLine::getArgument("writingPathSuffix")->hasDefaultValue())
713        {
714            std::string directory(CommandLine::getValue("writingPathSuffix").getString());
715            configuration_->configPath_ = configuration_->configPath_ / directory;
716            configuration_->logPath_    = configuration_->logPath_    / directory;
717        }
718
719        // Create directories to avoid problems when opening files in non existent folders.
720        std::vector<std::pair<boost::filesystem::path, std::string> > directories;
721        directories.push_back(std::make_pair(boost::filesystem::path(configuration_->configPath_), "config"));
722        directories.push_back(std::make_pair(boost::filesystem::path(configuration_->logPath_), "log"));
723
724        for (std::vector<std::pair<boost::filesystem::path, std::string> >::iterator it = directories.begin();
725            it != directories.end(); ++it)
726        {
727            if (boost::filesystem::exists(it->first) && !boost::filesystem::is_directory(it->first))
728            {
729                ThrowException(General, std::string("The ") + it->second + " directory has been preoccupied by a file! \
730                                         Please remove " + it->first.string());
731            }
732            if (boost::filesystem::create_directories(it->first)) // function may not return true at all (bug?)
733            {
734                COUT(4) << "Created " << it->second << " directory" << std::endl;
735            }
736        }
737    }
738
739    bool Core::preUpdate(const Clock& time) throw()
740    {
741        std::string exceptionMessage;
742        try
743        {
744            if (this->bGraphicsLoaded_)
745            {
746                // process input events
747                this->inputManager_->update(time);
748                // process gui events
749                this->guiManager_->update(time);
750            }
751            // process thread commands
752            this->tclThreadManager_->update(time);
753        }
754        catch (const std::exception& ex)
755        { exceptionMessage = ex.what(); }
756        catch (...)
757        { exceptionMessage = "Unknown exception"; }
758        if (!exceptionMessage.empty())
759        {
760            COUT(0) << "An exception occurred in the Core preUpdate: " << exceptionMessage << std::endl;
761            COUT(0) << "This should really never happen! Closing the program." << std::endl;
762            return false;
763        }
764        return true;
765    }
766
767    bool Core::postUpdate(const Clock& time) throw()
768    {
769        std::string exceptionMessage;
770        try
771        {
772            if (this->bGraphicsLoaded_)
773            {
774                // Render (doesn't throw)
775                this->graphicsManager_->update(time);
776            }
777        }
778        catch (const std::exception& ex)
779        { exceptionMessage = ex.what(); }
780        catch (...)
781        { exceptionMessage = "Unknown exception"; }
782        if (!exceptionMessage.empty())
783        {
784            COUT(0) << "An exception occurred in the Core postUpdate: " << exceptionMessage << std::endl;
785            COUT(0) << "This should really never happen! Closing the program." << std::endl;
786            return false;
787        }
788        return true;
789    }
790}
Note: See TracBrowser for help on using the repository browser.