Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/core7/src/libraries/core/GraphicsManager.cc @ 11009

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

unload debug overly while unloading graphics

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