Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/resource2/src/core/GraphicsManager.cc @ 5682

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

Bugfix (probably for the OpenGL renderer only).

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