Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

Fixed build and a few issues and removed a warning.

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