Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/presentation/src/libraries/core/GraphicsManager.cc @ 8605

Last change on this file since 8605 was 8423, checked in by rgrieder, 14 years ago

Added and incorporated new class DestructionHelper: instead of doing the destruction of certain singletons implicitly via scoped_ptrs and ScopeGuards, use a method named destroy() that essentially achieves the same, but makes the destruction sequence obvious.

  • Property svn:eol-style set to native
File size: 20.7 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 *      Reto Grieder
24 *      Benjamin Knecht <beni_at_orxonox.net>, (C) 2007
25 *   Co-authors:
26 *      Felix Schulthess
27 *
28 */
29
30#include "GraphicsManager.h"
31
32#include <cstdlib>
33#include <fstream>
34#include <sstream>
35#include <boost/filesystem.hpp>
36#include <boost/shared_array.hpp>
37
38#include <OgreFrameListener.h>
39#include <OgreRoot.h>
40#include <OgreLogManager.h>
41#include <OgreRenderWindow.h>
42#include <OgreRenderSystem.h>
43#include <OgreResourceGroupManager.h>
44#include <OgreTextureManager.h>
45#include <OgreViewport.h>
46#include <OgreWindowEventUtilities.h>
47
48#include "SpecialConfig.h"
49#include "util/Clock.h"
50#include "util/Convert.h"
51#include "util/Exception.h"
52#include "util/StringUtils.h"
53#include "util/SubString.h"
54#include "ConfigValueIncludes.h"
55#include "CoreIncludes.h"
56#include "Core.h"
57#include "Game.h"
58#include "GameMode.h"
59#include "GUIManager.h"
60#include "Loader.h"
61#include "PathConfig.h"
62#include "ViewportEventListener.h"
63#include "WindowEventListener.h"
64#include "XMLFile.h"
65#include "command/ConsoleCommand.h"
66#include "input/InputManager.h"
67
68namespace orxonox
69{
70    static const std::string __CC_GraphicsManager_group = "GraphicsManager";
71    static const std::string __CC_setScreenResolution_name = "setScreenResolution";
72    static const std::string __CC_setFSAA_name = "setFSAA";
73    static const std::string __CC_setVSync_name = "setVSync";
74    DeclareConsoleCommand(__CC_GraphicsManager_group, __CC_setScreenResolution_name, &prototype::string__uint_uint_bool);
75    DeclareConsoleCommand(__CC_GraphicsManager_group, __CC_setFSAA_name, &prototype::string__string);
76    DeclareConsoleCommand(__CC_GraphicsManager_group, __CC_setVSync_name, &prototype::string__bool);
77
78    static const std::string __CC_printScreen_name = "printScreen";
79    DeclareConsoleCommand(__CC_printScreen_name, &prototype::void__void);
80
81    class OgreWindowEventListener : public Ogre::WindowEventListener
82    {
83    public:
84        void windowResized     (Ogre::RenderWindow* rw)
85            { orxonox::WindowEventListener::resizeWindow(rw->getWidth(), rw->getHeight()); }
86        void windowFocusChange (Ogre::RenderWindow* rw)
87            { orxonox::WindowEventListener::changeWindowFocus(rw->isActive()); }
88        void windowClosed      (Ogre::RenderWindow* rw)
89            { orxonox::Game::getInstance().stop(); }
90        void windowMoved       (Ogre::RenderWindow* rw)
91            { orxonox::WindowEventListener::moveWindow(); }
92    };
93
94    GraphicsManager* GraphicsManager::singletonPtr_s = 0;
95
96    GraphicsManager::GraphicsManager(bool bLoadRenderer)
97        : ogreWindowEventListener_(new OgreWindowEventListener())
98        , renderWindow_(0)
99        , viewport_(0)
100        , lastFrameStartTime_(0.0f)
101        , lastFrameEndTime_(0.0f)
102        , destructionHelper_(this)
103    {
104        RegisterObject(GraphicsManager);
105
106        this->setConfigValues();
107
108        // Ogre setup procedure (creating Ogre::Root)
109        this->loadOgreRoot();
110
111        // At first, add the root paths of the data directories as resource locations
112        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getDataPathString(), "FileSystem");
113        // Load resources
114        resources_.reset(new XMLFile("DefaultResources.oxr"));
115        resources_->setLuaSupport(false);
116        Loader::open(resources_.get());
117
118        // Only for runs in the build directory (not installed)
119        if (PathConfig::buildDirectoryRun())
120            Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getExternalDataPathString(), "FileSystem");
121
122        extResources_.reset(new XMLFile("resources.oxr"));
123        extResources_->setLuaSupport(false);
124        Loader::open(extResources_.get());
125
126        if (bLoadRenderer)
127        {
128            // Reads the ogre config and creates the render window
129            this->upgradeToGraphics();
130        }
131    }
132
133    void GraphicsManager::destroy()
134    {
135        Loader::unload(debugOverlay_.get());
136
137        Ogre::WindowEventUtilities::removeWindowEventListener(renderWindow_, ogreWindowEventListener_);
138        ModifyConsoleCommand(__CC_printScreen_name).resetFunction();
139        ModifyConsoleCommand(__CC_GraphicsManager_group, __CC_setScreenResolution_name).resetFunction();
140        ModifyConsoleCommand(__CC_GraphicsManager_group, __CC_setFSAA_name).resetFunction();
141        ModifyConsoleCommand(__CC_GraphicsManager_group, __CC_setVSync_name).resetFunction();
142
143        // Undeclare the resources
144        Loader::unload(resources_.get());
145        Loader::unload(extResources_.get());
146
147        safeObjectDelete(&ogreRoot_);
148        safeObjectDelete(&ogreLogger_);
149        safeObjectDelete(&ogreWindowEventListener_);
150    }
151
152    void GraphicsManager::setConfigValues()
153    {
154        SetConfigValue(ogreConfigFile_,  "ogre.cfg")
155            .description("Location of the Ogre config file");
156        SetConfigValue(ogrePlugins_, specialConfig::ogrePlugins)
157            .description("Comma separated list of all plugins to load.");
158        SetConfigValue(ogreLogFile_,     "ogre.log")
159            .description("Logfile for messages from Ogre. Use \"\" to suppress log file creation.");
160        SetConfigValue(ogreLogLevelTrivial_ , 5)
161            .description("Corresponding orxonox debug level for ogre Trivial");
162        SetConfigValue(ogreLogLevelNormal_  , 4)
163            .description("Corresponding orxonox debug level for ogre Normal");
164        SetConfigValue(ogreLogLevelCritical_, 2)
165            .description("Corresponding orxonox debug level for ogre Critical");
166    }
167
168    /**
169    @brief
170        Loads the renderer and creates the render window if not yet done so.
171    @remarks
172        This operation is irreversible without recreating the GraphicsManager!
173        So if it throws you HAVE to recreate the GraphicsManager!!!
174        It therefore offers almost no exception safety.
175    */
176    void GraphicsManager::upgradeToGraphics()
177    {
178        if (renderWindow_ != NULL)
179            return;
180
181        // load all the required plugins for Ogre
182        this->loadOgrePlugins();
183
184        this->loadRenderer();
185
186        // Initialise all resources (do this AFTER the renderer has been loaded!)
187        // Note: You can only do this once! Ogre will check whether a resource group has
188        // already been initialised. If you need to load resources later, you will have to
189        // choose another resource group.
190        Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
191    }
192
193    /**
194    @brief
195        Creates the Ogre Root object and sets up the ogre log.
196    */
197    void GraphicsManager::loadOgreRoot()
198    {
199        COUT(3) << "Setting up Ogre..." << std::endl;
200
201        if (ogreConfigFile_.empty())
202        {
203            COUT(2) << "Warning: Ogre config file set to \"\". Defaulting to config.cfg" << std::endl;
204            ModifyConfigValue(ogreConfigFile_, tset, "config.cfg");
205        }
206        if (ogreLogFile_.empty())
207        {
208            COUT(2) << "Warning: Ogre log file set to \"\". Defaulting to ogre.log" << std::endl;
209            ModifyConfigValue(ogreLogFile_, tset, "ogre.log");
210        }
211
212        boost::filesystem::path ogreConfigFilepath(PathConfig::getConfigPath() / this->ogreConfigFile_);
213        boost::filesystem::path ogreLogFilepath(PathConfig::getLogPath() / this->ogreLogFile_);
214
215        // create a new logManager
216        // Ogre::Root will detect that we've already created a Log
217        ogreLogger_ = new Ogre::LogManager();
218        COUT(4) << "Ogre LogManager created" << std::endl;
219
220        // create our own log that we can listen to
221        Ogre::Log *myLog;
222        myLog = ogreLogger_->createLog(ogreLogFilepath.string(), true, false, false);
223        COUT(4) << "Ogre Log created" << std::endl;
224
225        myLog->setLogDetail(Ogre::LL_BOREME);
226        myLog->addListener(this);
227
228        COUT(4) << "Creating Ogre Root..." << std::endl;
229
230        // check for config file existence because Ogre displays (caught) exceptions if not
231        if (!boost::filesystem::exists(ogreConfigFilepath))
232        {
233            // create a zero sized file
234            std::ofstream creator;
235            creator.open(ogreConfigFilepath.string().c_str());
236            creator.close();
237        }
238
239        // Leave plugins file empty. We're going to do that part manually later
240        ogreRoot_ = new Ogre::Root("", ogreConfigFilepath.string(), ogreLogFilepath.string());
241
242        COUT(3) << "Ogre set up done." << std::endl;
243    }
244
245    void GraphicsManager::loadOgrePlugins()
246    {
247        // Plugin path can have many different locations...
248        std::string pluginPath = specialConfig::ogrePluginsDirectory;
249#ifdef DEPENDENCY_PACKAGE_ENABLE
250        if (!PathConfig::buildDirectoryRun())
251        {
252#  if defined(ORXONOX_PLATFORM_WINDOWS)
253            pluginPath = PathConfig::getExecutablePathString();
254#  elif defined(ORXONOX_PLATFORM_APPLE)
255            // TODO: Where are the plugins being installed to?
256            pluginPath = PathConfig::getExecutablePathString();
257#  endif
258        }
259#endif
260
261#ifdef ORXONOX_PLATFORM_WINDOWS
262        // Add OGRE plugin path to the environment. That way one plugin could
263        // also depend on another without problems on Windows
264        const char* currentPATH = getenv("PATH");
265        std::string newPATH = pluginPath;
266        if (currentPATH != NULL)
267            newPATH = std::string(currentPATH) + ';' + newPATH;
268        putenv(const_cast<char*>(("PATH=" + newPATH).c_str()));
269#endif
270
271        // Do some SubString magic to get the comma separated list of plugins
272        SubString plugins(ogrePlugins_, ",", " ", false, '\\', false, '"', false, '{', '}', false, '\0');
273        for (unsigned int i = 0; i < plugins.size(); ++i)
274            ogreRoot_->loadPlugin(pluginPath + '/' + plugins[i]);
275    }
276
277    void GraphicsManager::loadRenderer()
278    {
279        CCOUT(4) << "Configuring Renderer" << std::endl;
280
281        bool updatedConfig = Core::getInstance().getOgreConfigTimestamp() > Core::getInstance().getLastLevelTimestamp();
282        if (updatedConfig)
283            COUT(2) << "Ogre config file has changed, but no level was started since then. Displaying config dialogue again to verify the changes." << std::endl;
284
285        if (!ogreRoot_->restoreConfig() || updatedConfig)
286        {
287            if (!ogreRoot_->showConfigDialog())
288                ThrowException(InitialisationFailed, "OGRE graphics configuration dialogue canceled.");
289            else
290                Core::getInstance().updateOgreConfigTimestamp();
291        }
292
293        CCOUT(4) << "Creating render window" << std::endl;
294
295        this->renderWindow_ = ogreRoot_->initialise(true, "Orxonox");
296        // Propagate the size of the new winodw
297        this->ogreWindowEventListener_->windowResized(renderWindow_);
298
299        Ogre::WindowEventUtilities::addWindowEventListener(this->renderWindow_, ogreWindowEventListener_);
300
301        // create a full screen default viewport
302        // Note: This may throw when adding a viewport with an existing z-order!
303        //       But in our case we only have one viewport for now anyway, therefore
304        //       no ScopeGuards or anything to handle exceptions.
305        this->viewport_ = this->renderWindow_->addViewport(0, 0);
306
307        Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(Ogre::MIP_UNLIMITED);
308
309        // add console commands
310        ModifyConsoleCommand(__CC_printScreen_name).setFunction(&GraphicsManager::printScreen, this);
311        ModifyConsoleCommand(__CC_GraphicsManager_group, __CC_setScreenResolution_name).setFunction(&GraphicsManager::setScreenResolution, this);
312        ModifyConsoleCommand(__CC_GraphicsManager_group, __CC_setFSAA_name).setFunction(&GraphicsManager::setFSAA, this);
313        ModifyConsoleCommand(__CC_GraphicsManager_group, __CC_setVSync_name).setFunction(&GraphicsManager::setVSync, this);
314    }
315
316    void GraphicsManager::loadDebugOverlay()
317    {
318        // Load debug overlay to show info about fps and tick time
319        COUT(4) << "Loading Debug Overlay..." << std::endl;
320        debugOverlay_.reset(new XMLFile("debug.oxo"));
321        Loader::open(debugOverlay_.get());
322    }
323
324    /**
325    @note
326        A note about the Ogre::FrameListener: Even though we don't use them,
327        they still get called.
328    */
329    void GraphicsManager::postUpdate(const Clock& time)
330    {
331        // Time before rendering
332        uint64_t timeBeforeTick = time.getRealMicroseconds();
333
334        // Ogre's time keeping object
335        Ogre::FrameEvent evt;
336
337        // Translate to Ogre float times before the update
338        float temp = lastFrameStartTime_;
339        lastFrameStartTime_ = (float)timeBeforeTick * 0.000001f;
340        evt.timeSinceLastFrame = lastFrameStartTime_ - temp;
341        evt.timeSinceLastEvent = lastFrameStartTime_ - lastFrameEndTime_;
342
343        // Ogre requires the time too
344        ogreRoot_->_fireFrameStarted(evt);
345
346        // Pump messages in all registered RenderWindows
347        // This calls the WindowEventListener objects.
348        Ogre::WindowEventUtilities::messagePump();
349        // Make sure the window stays active even when not focused
350        // (probably only necessary on windows)
351        this->renderWindow_->setActive(true);
352
353        // Render frame
354        ogreRoot_->_updateAllRenderTargets();
355
356        uint64_t timeAfterTick = time.getRealMicroseconds();
357        // Subtract the time used for rendering from the tick time counter
358        Game::getInstance().subtractTickTime((int32_t)(timeAfterTick - timeBeforeTick));
359
360        // Translate to Ogre float times after the update
361        temp = lastFrameEndTime_;
362        lastFrameEndTime_ = (float)timeBeforeTick * 0.000001f;
363        evt.timeSinceLastFrame = lastFrameEndTime_ - temp;
364        evt.timeSinceLastEvent = lastFrameEndTime_ - lastFrameStartTime_;
365
366        // Ogre also needs the time after the frame finished
367        ogreRoot_->_fireFrameEnded(evt);
368    }
369
370    void GraphicsManager::setCamera(Ogre::Camera* camera)
371    {
372        Ogre::Camera* oldCamera = this->viewport_->getCamera();
373
374        this->viewport_->setCamera(camera);
375        GUIManager::getInstance().setCamera(camera);
376
377        for (ObjectList<ViewportEventListener>::iterator it = ObjectList<ViewportEventListener>::begin(); it != ObjectList<ViewportEventListener>::end(); ++it)
378            it->cameraChanged(this->viewport_, oldCamera);
379    }
380
381    /**
382    @brief
383        Method called by the LogListener interface from Ogre.
384        We use it to capture Ogre log messages and handle it ourselves.
385    @param message
386        The message to be logged
387    @param lml
388        The message level the log is using
389    @param maskDebug
390        If we are printing to the console or not
391    @param logName
392        The name of this log (so you can have several listeners
393        for different logs, and identify them)
394    */
395    void GraphicsManager::messageLogged(const std::string& message,
396        Ogre::LogMessageLevel lml, bool maskDebug, const std::string& logName)
397    {
398        int orxonoxLevel;
399        std::string introduction;
400        // Do not show caught OGRE exceptions in front
401        if (message.find("EXCEPTION") != std::string::npos)
402        {
403            orxonoxLevel = OutputLevel::Debug;
404            introduction = "Ogre, caught exception: ";
405        }
406        else
407        {
408            switch (lml)
409            {
410            case Ogre::LML_TRIVIAL:
411                orxonoxLevel = this->ogreLogLevelTrivial_;
412                break;
413            case Ogre::LML_NORMAL:
414                orxonoxLevel = this->ogreLogLevelNormal_;
415                break;
416            case Ogre::LML_CRITICAL:
417                orxonoxLevel = this->ogreLogLevelCritical_;
418                break;
419            default:
420                orxonoxLevel = 0;
421            }
422            introduction = "Ogre: ";
423        }
424        OutputHandler::getOutStream(orxonoxLevel)
425            << introduction << message << std::endl;
426    }
427
428    size_t GraphicsManager::getRenderWindowHandle()
429    {
430        size_t windowHnd = 0;
431        renderWindow_->getCustomAttribute("WINDOW", &windowHnd);
432        return windowHnd;
433    }
434
435    bool GraphicsManager::isFullScreen() const
436    {
437        return this->renderWindow_->isFullScreen();
438    }
439
440    unsigned int GraphicsManager::getWindowWidth() const
441    {
442        return this->renderWindow_->getWidth();
443    }
444
445    unsigned int GraphicsManager::getWindowHeight() const
446    {
447        return this->renderWindow_->getHeight();
448    }
449
450    bool GraphicsManager::hasVSyncEnabled() const
451    {
452        Ogre::ConfigOptionMap& options = ogreRoot_->getRenderSystem()->getConfigOptions();
453        Ogre::ConfigOptionMap::iterator it = options.find("VSync");
454        if (it != options.end())
455            return (it->second.currentValue == "Yes");
456        else
457            return false;
458    }
459
460    std::string GraphicsManager::getFSAAMode() const
461    {
462        Ogre::ConfigOptionMap& options = ogreRoot_->getRenderSystem()->getConfigOptions();
463        Ogre::ConfigOptionMap::iterator it = options.find("FSAA");
464        if (it != options.end())
465            return it->second.currentValue;
466        else
467            return "";
468    }
469
470    std::string GraphicsManager::setScreenResolution(unsigned int width, unsigned int height, bool fullscreen)
471    {
472        // workaround to detect if the colour depth should be written to the config file
473        bool bWriteColourDepth = false;
474        Ogre::ConfigOptionMap& options = ogreRoot_->getRenderSystem()->getConfigOptions();
475        Ogre::ConfigOptionMap::iterator it = options.find("Video Mode");
476        if (it != options.end())
477            bWriteColourDepth = (it->second.currentValue.find('@') != std::string::npos);
478
479        if (bWriteColourDepth)
480        {
481            this->ogreRoot_->getRenderSystem()->setConfigOption("Video Mode", multi_cast<std::string>(width)
482                                                                    + " x " + multi_cast<std::string>(height)
483                                                                    + " @ " + multi_cast<std::string>(this->getRenderWindow()->getColourDepth()) + "-bit colour");
484        }
485        else
486        {
487            this->ogreRoot_->getRenderSystem()->setConfigOption("Video Mode", multi_cast<std::string>(width)
488                                                                    + " x " + multi_cast<std::string>(height));
489        }
490
491        this->ogreRoot_->getRenderSystem()->setConfigOption("Full Screen", fullscreen ? "Yes" : "No");
492
493        std::string validate = this->ogreRoot_->getRenderSystem()->validateConfigOptions();
494
495        if (validate == "")
496        {
497            GraphicsManager::getInstance().getRenderWindow()->setFullscreen(fullscreen, width, height);
498            this->ogreRoot_->saveConfig();
499            Core::getInstance().updateOgreConfigTimestamp();
500            // Also reload the input devices
501            InputManager::getInstance().reload();
502        }
503
504        return validate;
505    }
506
507    std::string GraphicsManager::setFSAA(const std::string& mode)
508    {
509        this->ogreRoot_->getRenderSystem()->setConfigOption("FSAA", mode);
510
511        std::string validate = this->ogreRoot_->getRenderSystem()->validateConfigOptions();
512
513        if (validate == "")
514        {
515            //this->ogreRoot_->getRenderSystem()->reinitialise(); // can't use this that easily, because it recreates the render window, invalidating renderWindow_
516            this->ogreRoot_->saveConfig();
517            Core::getInstance().updateOgreConfigTimestamp();
518        }
519
520        return validate;
521    }
522
523    std::string GraphicsManager::setVSync(bool vsync)
524    {
525        this->ogreRoot_->getRenderSystem()->setConfigOption("VSync", vsync ? "Yes" : "No");
526
527        std::string validate = this->ogreRoot_->getRenderSystem()->validateConfigOptions();
528
529        if (validate == "")
530        {
531            //this->ogreRoot_->getRenderSystem()->reinitialise(); // can't use this that easily, because it recreates the render window, invalidating renderWindow_
532            this->ogreRoot_->saveConfig();
533            Core::getInstance().updateOgreConfigTimestamp();
534        }
535
536        return validate;
537    }
538
539    void GraphicsManager::printScreen()
540    {
541        assert(this->renderWindow_);
542        this->renderWindow_->writeContentsToTimestampedFile(PathConfig::getLogPathString() + "screenShot_", ".png");
543    }
544}
Note: See TracBrowser for help on using the repository browser.