Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/kicklib/src/libraries/core/GraphicsManager.cc @ 8225

Last change on this file since 8225 was 8225, checked in by rgrieder, 13 years ago

Resolved problems with different Boost filesystem versions.

  • Property svn:eol-style set to native
File size: 14.9 KB
RevLine 
[612]1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
[1293]3 *                    > www.orxonox.net <
[612]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
[1349]11 *   of the License, or (at your option) any later version.
12 *
[612]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:
[1535]23 *      Reto Grieder
[1755]24 *      Benjamin Knecht <beni_at_orxonox.net>, (C) 2007
[612]25 *   Co-authors:
[1755]26 *      Felix Schulthess
[612]27 *
28 */
[1035]29
[2801]30#include "GraphicsManager.h"
[612]31
[2801]32#include <fstream>
[5695]33#include <sstream>
[2801]34#include <boost/filesystem.hpp>
[5695]35#include <boost/shared_array.hpp>
[2801]36
37#include <OgreFrameListener.h>
38#include <OgreRoot.h>
39#include <OgreLogManager.h>
[1755]40#include <OgreRenderWindow.h>
[2801]41#include <OgreRenderSystem.h>
[5695]42#include <OgreResourceGroupManager.h>
[2801]43#include <OgreTextureManager.h>
44#include <OgreViewport.h>
45#include <OgreWindowEventUtilities.h>
[1538]46
[2801]47#include "SpecialConfig.h"
[5929]48#include "util/Clock.h"
[2801]49#include "util/Exception.h"
[3280]50#include "util/StringUtils.h"
[2801]51#include "util/SubString.h"
[3346]52#include "ConfigValueIncludes.h"
53#include "CoreIncludes.h"
[7870]54#include "Core.h"
[3346]55#include "Game.h"
56#include "GameMode.h"
[5695]57#include "Loader.h"
[5929]58#include "PathConfig.h"
[3346]59#include "WindowEventListener.h"
[5695]60#include "XMLFile.h"
[7284]61#include "command/ConsoleCommand.h"
[1032]62
[8225]63// Differentiate Boost Filesystem v2 and v3
64#if (BOOST_FILESYSTEM_VERSION < 3)
65#  define BF_NATIVE_STRING file_string
66#else
67#  define BF_NATIVE_STRING string
68#endif
69
[1625]70namespace orxonox
71{
[7284]72    static const std::string __CC_printScreen_name = "printScreen";
73    DeclareConsoleCommand(__CC_printScreen_name, &prototype::void__void);
74
[3327]75    class OgreWindowEventListener : public Ogre::WindowEventListener
[2801]76    {
[3327]77    public:
78        void windowResized     (Ogre::RenderWindow* rw)
79            { orxonox::WindowEventListener::resizeWindow(rw->getWidth(), rw->getHeight()); }
80        void windowFocusChange (Ogre::RenderWindow* rw)
[7874]81            { orxonox::WindowEventListener::changeWindowFocus(rw->isActive()); }
[3327]82        void windowClosed      (Ogre::RenderWindow* rw)
83            { orxonox::Game::getInstance().stop(); }
84        void windowMoved       (Ogre::RenderWindow* rw)
85            { orxonox::WindowEventListener::moveWindow(); }
[2801]86    };
[1032]87
[3366]88    GraphicsManager* GraphicsManager::singletonPtr_s = 0;
[1293]89
[1755]90    /**
91    @brief
[2801]92        Non-initialising constructor.
[1755]93    */
[5695]94    GraphicsManager::GraphicsManager(bool bLoadRenderer)
95        : ogreWindowEventListener_(new OgreWindowEventListener())
[2801]96        , renderWindow_(0)
97        , viewport_(0)
[1024]98    {
[2801]99        RegisterObject(GraphicsManager);
100
101        this->setConfigValues();
[612]102
[5695]103        // Ogre setup procedure (creating Ogre::Root)
104        this->loadOgreRoot();
[2801]105
[5695]106        // At first, add the root paths of the data directories as resource locations
[6417]107        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getDataPathString(), "FileSystem");
[5695]108        // Load resources
[6417]109        resources_.reset(new XMLFile("DefaultResources.oxr"));
[5695]110        resources_->setLuaSupport(false);
111        Loader::open(resources_.get());
112
113        // Only for development runs
[5929]114        if (PathConfig::isDevelopmentRun())
[3280]115        {
[6417]116            Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getExternalDataPathString(), "FileSystem");
117            extResources_.reset(new XMLFile("resources.oxr"));
[5695]118            extResources_->setLuaSupport(false);
119            Loader::open(extResources_.get());
120        }
[2801]121
[5695]122        if (bLoadRenderer)
[3280]123        {
[5695]124            // Reads the ogre config and creates the render window
125            this->upgradeToGraphics();
[3280]126        }
[2801]127    }
128
[1755]129    /**
130    @brief
[5695]131        Destruction is done by the member scoped_ptrs.
[1755]132    */
[2801]133    GraphicsManager::~GraphicsManager()
[1535]134    {
[5929]135        Loader::unload(debugOverlay_.get());
136
[5695]137        Ogre::WindowEventUtilities::removeWindowEventListener(renderWindow_, ogreWindowEventListener_.get());
[7284]138        ModifyConsoleCommand(__CC_printScreen_name).resetFunction();
[5929]139
140        // Undeclare the resources
141        Loader::unload(resources_.get());
142        if (PathConfig::isDevelopmentRun())
143            Loader::unload(extResources_.get());
[1535]144    }
145
[2801]146    void GraphicsManager::setConfigValues()
[1535]147    {
[2801]148        SetConfigValue(ogreConfigFile_,  "ogre.cfg")
149            .description("Location of the Ogre config file");
[5695]150        SetConfigValue(ogrePluginsDirectory_, specialConfig::ogrePluginsDirectory)
[2801]151            .description("Folder where the Ogre plugins are located.");
[5695]152        SetConfigValue(ogrePlugins_, specialConfig::ogrePlugins)
[2801]153            .description("Comma separated list of all plugins to load.");
154        SetConfigValue(ogreLogFile_,     "ogre.log")
155            .description("Logfile for messages from Ogre. Use \"\" to suppress log file creation.");
156        SetConfigValue(ogreLogLevelTrivial_ , 5)
157            .description("Corresponding orxonox debug level for ogre Trivial");
158        SetConfigValue(ogreLogLevelNormal_  , 4)
159            .description("Corresponding orxonox debug level for ogre Normal");
160        SetConfigValue(ogreLogLevelCritical_, 2)
161            .description("Corresponding orxonox debug level for ogre Critical");
[1535]162    }
[612]163
[5695]164    /**
165    @brief
166        Loads the renderer and creates the render window if not yet done so.
167    @remarks
168        This operation is irreversible without recreating the GraphicsManager!
169        So if it throws you HAVE to recreate the GraphicsManager!!!
170        It therefore offers almost no exception safety.
171    */
172    void GraphicsManager::upgradeToGraphics()
[2801]173    {
[5695]174        if (renderWindow_ != NULL)
175            return;
[2801]176
[6075]177        // load all the required plugins for Ogre
178        this->loadOgrePlugins();
179
[5695]180        this->loadRenderer();
[2801]181
[5695]182        // Initialise all resources (do this AFTER the renderer has been loaded!)
183        // Note: You can only do this once! Ogre will check whether a resource group has
184        // already been initialised. If you need to load resources later, you will have to
185        // choose another resource group.
186        Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
[2801]187    }
188
[1755]189    /**
190    @brief
[2801]191        Creates the Ogre Root object and sets up the ogre log.
[1755]192    */
[5695]193    void GraphicsManager::loadOgreRoot()
[1538]194    {
[2801]195        COUT(3) << "Setting up Ogre..." << std::endl;
196
[6417]197        if (ogreConfigFile_.empty())
[2801]198        {
199            COUT(2) << "Warning: Ogre config file set to \"\". Defaulting to config.cfg" << std::endl;
200            ModifyConfigValue(ogreConfigFile_, tset, "config.cfg");
201        }
[6417]202        if (ogreLogFile_.empty())
[2801]203        {
204            COUT(2) << "Warning: Ogre log file set to \"\". Defaulting to ogre.log" << std::endl;
205            ModifyConfigValue(ogreLogFile_, tset, "ogre.log");
206        }
207
[5929]208        boost::filesystem::path ogreConfigFilepath(PathConfig::getConfigPath() / this->ogreConfigFile_);
209        boost::filesystem::path ogreLogFilepath(PathConfig::getLogPath() / this->ogreLogFile_);
[2801]210
211        // create a new logManager
212        // Ogre::Root will detect that we've already created a Log
[5695]213        ogreLogger_.reset(new Ogre::LogManager());
[2801]214        COUT(4) << "Ogre LogManager created" << std::endl;
215
216        // create our own log that we can listen to
217        Ogre::Log *myLog;
[5695]218        myLog = ogreLogger_->createLog(ogreLogFilepath.string(), true, false, false);
[2801]219        COUT(4) << "Ogre Log created" << std::endl;
220
221        myLog->setLogDetail(Ogre::LL_BOREME);
222        myLog->addListener(this);
223
224        COUT(4) << "Creating Ogre Root..." << std::endl;
225
226        // check for config file existence because Ogre displays (caught) exceptions if not
227        if (!boost::filesystem::exists(ogreConfigFilepath))
228        {
229            // create a zero sized file
230            std::ofstream creator;
231            creator.open(ogreConfigFilepath.string().c_str());
232            creator.close();
233        }
234
235        // Leave plugins file empty. We're going to do that part manually later
[5695]236        ogreRoot_.reset(new Ogre::Root("", ogreConfigFilepath.string(), ogreLogFilepath.string()));
[2801]237
238        COUT(3) << "Ogre set up done." << std::endl;
[1538]239    }
[2801]240
241    void GraphicsManager::loadOgrePlugins()
242    {
243        // just to make sure the next statement doesn't segfault
[6417]244        if (ogrePluginsDirectory_.empty())
245            ogrePluginsDirectory_ = '.';
[2801]246
[5695]247        boost::filesystem::path folder(ogrePluginsDirectory_);
[2801]248        // Do some SubString magic to get the comma separated list of plugins
[7284]249        SubString plugins(ogrePlugins_, ",", " ", false, '\\', false, '"', false, '{', '}', false, '\0');
[2801]250        // Use backslash paths on Windows! file_string() already does that though.
251        for (unsigned int i = 0; i < plugins.size(); ++i)
[8225]252            ogreRoot_->loadPlugin((folder / plugins[i]).BF_NATIVE_STRING());
[2801]253    }
254
255    void GraphicsManager::loadRenderer()
256    {
257        CCOUT(4) << "Configuring Renderer" << std::endl;
258
[7870]259        if (!ogreRoot_->restoreConfig() || Core::getInstance().getOgreConfigTimestamp() > Core::getInstance().getLastLevelTimestamp())
260        {
[2801]261            if (!ogreRoot_->showConfigDialog())
[7868]262                ThrowException(InitialisationFailed, "OGRE graphics configuration dialogue canceled.");
[7870]263            else
264                Core::getInstance().updateOgreConfigTimestamp();
265        }
[2801]266
267        CCOUT(4) << "Creating render window" << std::endl;
268
269        this->renderWindow_ = ogreRoot_->initialise(true, "Orxonox");
[5695]270        // Propagate the size of the new winodw
[3327]271        this->ogreWindowEventListener_->windowResized(renderWindow_);
[2801]272
[5695]273        Ogre::WindowEventUtilities::addWindowEventListener(this->renderWindow_, ogreWindowEventListener_.get());
[8073]274
[5695]275        // create a full screen default viewport
276        // Note: This may throw when adding a viewport with an existing z-order!
277        //       But in our case we only have one viewport for now anyway, therefore
278        //       no ScopeGuards or anything to handle exceptions.
279        this->viewport_ = this->renderWindow_->addViewport(0, 0);
280
[6524]281        Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(Ogre::MIP_UNLIMITED);
[2801]282
[5695]283        // add console commands
[7284]284        ModifyConsoleCommand(__CC_printScreen_name).setFunction(&GraphicsManager::printScreen, this);
[2801]285    }
286
[5929]287    void GraphicsManager::loadDebugOverlay()
288    {
289        // Load debug overlay to show info about fps and tick time
290        COUT(4) << "Loading Debug Overlay..." << std::endl;
291        debugOverlay_.reset(new XMLFile("debug.oxo"));
292        Loader::open(debugOverlay_.get());
293    }
294
295    /**
296    @note
297        A note about the Ogre::FrameListener: Even though we don't use them,
298        they still get called. However, the delta times are not correct (except
299        for timeSinceLastFrame, which is the most important). A little research
300        as shown that there is probably only one FrameListener that doesn't even
301        need the time. So we shouldn't run into problems.
302    */
[6417]303    void GraphicsManager::postUpdate(const Clock& time)
[2801]304    {
[5695]305        Ogre::FrameEvent evt;
306        evt.timeSinceLastFrame = time.getDeltaTime();
307        evt.timeSinceLastEvent = time.getDeltaTime(); // note: same time, but shouldn't matter anyway
308
309        // don't forget to call _fireFrameStarted to OGRE to make sure
310        // everything goes smoothly
311        ogreRoot_->_fireFrameStarted(evt);
312
313        // Pump messages in all registered RenderWindows
314        // This calls the WindowEventListener objects.
315        Ogre::WindowEventUtilities::messagePump();
316        // make sure the window stays active even when not focused
317        // (probably only necessary on windows)
318        this->renderWindow_->setActive(true);
319
320        // Time before rendering
321        uint64_t timeBeforeTick = time.getRealMicroseconds();
322
323        // Render frame
324        ogreRoot_->_updateAllRenderTargets();
325
326        uint64_t timeAfterTick = time.getRealMicroseconds();
327        // Subtract the time used for rendering from the tick time counter
[6502]328        Game::getInstance().subtractTickTime((int32_t)(timeAfterTick - timeBeforeTick));
[5695]329
330        // again, just to be sure OGRE works fine
331        ogreRoot_->_fireFrameEnded(evt); // note: uses the same time as _fireFrameStarted
[2801]332    }
333
[5695]334    void GraphicsManager::setCamera(Ogre::Camera* camera)
335    {
336        this->viewport_->setCamera(camera);
337    }
338
[2801]339    /**
340    @brief
341        Method called by the LogListener interface from Ogre.
342        We use it to capture Ogre log messages and handle it ourselves.
343    @param message
344        The message to be logged
345    @param lml
346        The message level the log is using
347    @param maskDebug
348        If we are printing to the console or not
349    @param logName
350        The name of this log (so you can have several listeners
351        for different logs, and identify them)
352    */
353    void GraphicsManager::messageLogged(const std::string& message,
354        Ogre::LogMessageLevel lml, bool maskDebug, const std::string& logName)
355    {
356        int orxonoxLevel;
[6417]357        std::string introduction;
358        // Do not show caught OGRE exceptions in front
359        if (message.find("EXCEPTION") != std::string::npos)
[2801]360        {
[6417]361            orxonoxLevel = OutputLevel::Debug;
362            introduction = "Ogre, caught exception: ";
[2801]363        }
[6417]364        else
365        {
366            switch (lml)
367            {
368            case Ogre::LML_TRIVIAL:
369                orxonoxLevel = this->ogreLogLevelTrivial_;
370                break;
371            case Ogre::LML_NORMAL:
372                orxonoxLevel = this->ogreLogLevelNormal_;
373                break;
374            case Ogre::LML_CRITICAL:
375                orxonoxLevel = this->ogreLogLevelCritical_;
376                break;
377            default:
378                orxonoxLevel = 0;
379            }
380            introduction = "Ogre: ";
381        }
[6105]382        OutputHandler::getOutStream(orxonoxLevel)
[6417]383            << introduction << message << std::endl;
[2801]384    }
385
[5695]386    size_t GraphicsManager::getRenderWindowHandle()
387    {
388        size_t windowHnd = 0;
389        renderWindow_->getCustomAttribute("WINDOW", &windowHnd);
390        return windowHnd;
391    }
392
393    bool GraphicsManager::isFullScreen() const
394    {
395        Ogre::ConfigOptionMap& options = ogreRoot_->getRenderSystem()->getConfigOptions();
396        if (options.find("Full Screen") != options.end())
397        {
398            if (options["Full Screen"].currentValue == "Yes")
399                return true;
400            else
401                return false;
402        }
403        else
404        {
405            COUT(0) << "Could not find 'Full Screen' render system option. Fix This!!!" << std::endl;
406            return false;
407        }
408    }
409
[2801]410    void GraphicsManager::printScreen()
411    {
412        assert(this->renderWindow_);
[6417]413        this->renderWindow_->writeContentsToTimestampedFile(PathConfig::getLogPathString() + "screenShot_", ".png");
[2801]414    }
[612]415}
Note: See TracBrowser for help on using the repository browser.