Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/orxonox/GraphicsManager.cc @ 2915

Last change on this file since 2915 was 2896, checked in by landauf, 16 years ago

Merged gui branch back to trunk.

I did 2 small changes in IngameManager.cc on line 777 and 888 (yes, really), because const_reverse_iterator strangely doesn't work on MinGW.

  • Property svn:eol-style set to native
File size: 15.5 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 "OrxonoxStableHeaders.h"
37#include "GraphicsManager.h"
38
39#include <fstream>
40#include <boost/filesystem.hpp>
41
42#include <OgreCompositorManager.h>
43#include <OgreConfigFile.h>
44#include <OgreFrameListener.h>
45#include <OgreRoot.h>
46#include <OgreLogManager.h>
47#include <OgreException.h>
48#include <OgreRenderWindow.h>
49#include <OgreRenderSystem.h>
50#include <OgreTextureManager.h>
51#include <OgreViewport.h>
52#include <OgreWindowEventUtilities.h>
53
54#include "SpecialConfig.h"
55#include "util/Debug.h"
56#include "util/Exception.h"
57#include "util/String.h"
58#include "util/SubString.h"
59#include "core/Clock.h"
60#include "core/ConsoleCommand.h"
61#include "core/ConfigValueIncludes.h"
62#include "core/CoreIncludes.h"
63#include "core/Core.h"
64#include "core/GameMode.h"
65#include "tools/WindowEventListener.h"
66#include "tools/ParticleInterface.h"
67
68namespace orxonox
69{
70    class _OrxonoxExport OgreWindowEventListener : public Ogre::WindowEventListener
71    {
72        void windowResized     (Ogre::RenderWindow* rw);
73        void windowFocusChange (Ogre::RenderWindow* rw);
74        void windowClosed      (Ogre::RenderWindow* rw);
75        //void windowMoved       (Ogre::RenderWindow* rw);
76    };
77
78    GraphicsManager* GraphicsManager::singletonRef_s = 0;
79
80    /**
81    @brief
82        Non-initialising constructor.
83    */
84    GraphicsManager::GraphicsManager()
85        : ogreRoot_(0)
86        , ogreLogger_(0)
87        , renderWindow_(0)
88        , viewport_(0)
89        , ogreWindowEventListener_(0)
90        , avgTickTime_(0.0f)
91        , avgFramesPerSecond_(0.0f)
92    {
93        RegisterObject(GraphicsManager);
94
95        assert(singletonRef_s == 0);
96        singletonRef_s = this;
97
98        this->loaded_ = false;
99
100        this->setConfigValues();
101    }
102
103    void GraphicsManager::initialise()
104    {
105        // Ogre setup procedure
106        setupOgre();
107        // load all the required plugins for Ogre
108        loadOgrePlugins();
109        // read resource declaration file
110        this->declareResources();
111        // Reads ogre config and creates the render window
112        this->loadRenderer();
113
114        // TODO: Spread this
115        this->initialiseResources();
116
117        // add console commands
118        FunctorMember<GraphicsManager>* functor1 = createFunctor(&GraphicsManager::printScreen);
119        functor1->setObject(this);
120        ccPrintScreen_ = createConsoleCommand(functor1, "printScreen");
121        CommandExecutor::addConsoleCommandShortcut(ccPrintScreen_);
122
123        this->loaded_ = true;
124    }
125
126    /**
127    @brief
128        Destroys all the Ogre related objects
129    */
130    GraphicsManager::~GraphicsManager()
131    {
132        if (this->loaded_)
133        {
134            delete this->ccPrintScreen_;
135
136            if (this->ogreWindowEventListener_)
137            {
138                // remove our WindowEventListener first to avoid bad calls after the window has been destroyed
139                Ogre::WindowEventUtilities::removeWindowEventListener(this->renderWindow_, this->ogreWindowEventListener_);
140                delete this->ogreWindowEventListener_;
141            }
142
143            // unload all compositors
144            Ogre::CompositorManager::getSingleton().removeAll();
145
146            // destroy render window
147            Ogre::RenderSystem* renderer = this->ogreRoot_->getRenderSystem();
148            renderer->destroyRenderWindow("Orxonox");
149
150            // Delete OGRE main control organ
151            delete this->ogreRoot_;
152
153            // delete the ogre log and the logManager (since we have created it in the first place).
154            this->ogreLogger_->getDefaultLog()->removeListener(this);
155            this->ogreLogger_->destroyLog(Ogre::LogManager::getSingleton().getDefaultLog());
156            delete this->ogreLogger_;
157        }
158
159        assert(singletonRef_s);
160        singletonRef_s = 0;
161    }
162
163    void GraphicsManager::setConfigValues()
164    {
165        SetConfigValue(resourceFile_,    "resources.cfg")
166            .description("Location of the resources file in the data path.");
167        SetConfigValue(ogreConfigFile_,  "ogre.cfg")
168            .description("Location of the Ogre config file");
169        SetConfigValue(ogrePluginsFolder_, ORXONOX_OGRE_PLUGINS_FOLDER)
170            .description("Folder where the Ogre plugins are located.");
171        SetConfigValue(ogrePlugins_, ORXONOX_OGRE_PLUGINS)
172            .description("Comma separated list of all plugins to load.");
173        SetConfigValue(ogreLogFile_,     "ogre.log")
174            .description("Logfile for messages from Ogre. Use \"\" to suppress log file creation.");
175        SetConfigValue(ogreLogLevelTrivial_ , 5)
176            .description("Corresponding orxonox debug level for ogre Trivial");
177        SetConfigValue(ogreLogLevelNormal_  , 4)
178            .description("Corresponding orxonox debug level for ogre Normal");
179        SetConfigValue(ogreLogLevelCritical_, 2)
180            .description("Corresponding orxonox debug level for ogre Critical");
181        SetConfigValue(detailLevelParticle_, 2)
182            .description("O: off, 1: low, 2: normal, 3: high").callback(this, &GraphicsManager::detailLevelParticleChanged);
183    }
184
185    void GraphicsManager::detailLevelParticleChanged()
186    {
187        for (ObjectList<ParticleInterface>::iterator it = ObjectList<ParticleInterface>::begin(); it; ++it)
188            it->detailLevelChanged(this->detailLevelParticle_);
189    }
190
191    void GraphicsManager::update(const Clock& time)
192    {
193        if (this->loaded_)
194        {
195            Ogre::FrameEvent evt;
196            evt.timeSinceLastFrame = time.getDeltaTime();
197            evt.timeSinceLastEvent = time.getDeltaTime(); // note: same time, but shouldn't matter anyway
198
199            // don't forget to call _fireFrameStarted to OGRE to make sure
200            // everything goes smoothly
201            ogreRoot_->_fireFrameStarted(evt);
202
203            // Pump messages in all registered RenderWindows
204            // This calls the WindowEventListener objects.
205            Ogre::WindowEventUtilities::messagePump();
206            // make sure the window stays active even when not focused
207            // (probably only necessary on windows)
208            this->renderWindow_->setActive(true);
209
210            // render
211            ogreRoot_->_updateAllRenderTargets();
212
213            // again, just to be sure OGRE works fine
214            ogreRoot_->_fireFrameEnded(evt); // note: uses the same time as _fireFrameStarted
215        }
216    }
217
218    void GraphicsManager::setCamera(Ogre::Camera* camera)
219    {
220        this->viewport_->setCamera(camera);
221    }
222
223    /**
224    @brief
225        Creates the Ogre Root object and sets up the ogre log.
226    */
227    void GraphicsManager::setupOgre()
228    {
229        COUT(3) << "Setting up Ogre..." << std::endl;
230
231        if (ogreConfigFile_ == "")
232        {
233            COUT(2) << "Warning: Ogre config file set to \"\". Defaulting to config.cfg" << std::endl;
234            ModifyConfigValue(ogreConfigFile_, tset, "config.cfg");
235        }
236        if (ogreLogFile_ == "")
237        {
238            COUT(2) << "Warning: Ogre log file set to \"\". Defaulting to ogre.log" << std::endl;
239            ModifyConfigValue(ogreLogFile_, tset, "ogre.log");
240        }
241
242        boost::filesystem::path ogreConfigFilepath(Core::getConfigPath() / this->ogreConfigFile_);
243        boost::filesystem::path ogreLogFilepath(Core::getLogPath() / this->ogreLogFile_);
244
245        // create a new logManager
246        // Ogre::Root will detect that we've already created a Log
247        ogreLogger_ = new Ogre::LogManager();
248        COUT(4) << "Ogre LogManager created" << std::endl;
249
250        // create our own log that we can listen to
251        Ogre::Log *myLog;
252        myLog = ogreLogger_->createLog(ogreLogFilepath.string(), true, false, false);
253        COUT(4) << "Ogre Log created" << std::endl;
254
255        myLog->setLogDetail(Ogre::LL_BOREME);
256        myLog->addListener(this);
257
258        COUT(4) << "Creating Ogre Root..." << std::endl;
259
260        // check for config file existence because Ogre displays (caught) exceptions if not
261        if (!boost::filesystem::exists(ogreConfigFilepath))
262        {
263            // create a zero sized file
264            std::ofstream creator;
265            creator.open(ogreConfigFilepath.string().c_str());
266            creator.close();
267        }
268
269        // Leave plugins file empty. We're going to do that part manually later
270        ogreRoot_ = new Ogre::Root("", ogreConfigFilepath.string(), ogreLogFilepath.string());
271
272        COUT(3) << "Ogre set up done." << std::endl;
273    }
274
275    void GraphicsManager::loadOgrePlugins()
276    {
277        // just to make sure the next statement doesn't segfault
278        if (ogrePluginsFolder_ == "")
279            ogrePluginsFolder_ = ".";
280
281        boost::filesystem::path folder(ogrePluginsFolder_);
282        // Do some SubString magic to get the comma separated list of plugins
283        SubString plugins(ogrePlugins_, ",", " ", false, 92, false, 34, false, 40, 41, false, '\0');
284        // Use backslash paths on Windows! file_string() already does that though.
285        for (unsigned int i = 0; i < plugins.size(); ++i)
286            ogreRoot_->loadPlugin((folder / plugins[i]).file_string());
287    }
288
289    void GraphicsManager::declareResources()
290    {
291        CCOUT(4) << "Declaring Resources" << std::endl;
292        //TODO: Specify layout of data file and maybe use xml-loader
293        //TODO: Work with ressource groups (should be generated by a special loader)
294
295        if (resourceFile_ == "")
296        {
297            COUT(2) << "Warning: Ogre resource file set to \"\". Defaulting to resources.cfg" << std::endl;
298            ModifyConfigValue(resourceFile_, tset, "resources.cfg");
299        }
300
301        // Load resource paths from data file using configfile ressource type
302        Ogre::ConfigFile cf;
303        try
304        {
305            cf.load((Core::getMediaPath() / resourceFile_).string());
306        }
307        catch (...)
308        {
309            //COUT(1) << ex.getFullDescription() << std::endl;
310            COUT(0) << "Have you forgotten to set the data path in orxnox.ini?" << std::endl;
311            throw;
312        }
313
314        // Go through all sections & settings in the file
315        Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
316
317        std::string secName, typeName, archName;
318        while (seci.hasMoreElements())
319        {
320            try
321            {
322                secName = seci.peekNextKey();
323                Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
324                Ogre::ConfigFile::SettingsMultiMap::iterator i;
325                for (i = settings->begin(); i != settings->end(); ++i)
326                {
327                    typeName = i->first; // for instance "FileSystem" or "Zip"
328                    archName = i->second; // name (and location) of archive
329
330                    Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
331                        (Core::getMediaPath() / archName).string(), typeName, secName);
332                }
333            }
334            catch (Ogre::Exception& ex)
335            {
336                COUT(1) << ex.getFullDescription() << std::endl;
337            }
338        }
339    }
340
341    void GraphicsManager::loadRenderer()
342    {
343        CCOUT(4) << "Configuring Renderer" << std::endl;
344
345        if (!ogreRoot_->restoreConfig())
346            if (!ogreRoot_->showConfigDialog())
347                ThrowException(InitialisationFailed, "Could not show Ogre configuration dialogue.");
348
349        CCOUT(4) << "Creating render window" << std::endl;
350
351        this->renderWindow_ = ogreRoot_->initialise(true, "Orxonox");
352
353        this->ogreWindowEventListener_ = new OgreWindowEventListener();
354        Ogre::WindowEventUtilities::addWindowEventListener(this->renderWindow_, ogreWindowEventListener_);
355
356        Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(0);
357
358        // create a full screen default viewport
359        this->viewport_ = this->renderWindow_->addViewport(0, 0);
360    }
361
362    void GraphicsManager::initialiseResources()
363    {
364        CCOUT(4) << "Initialising resources" << std::endl;
365        //TODO: Do NOT load all the groups, why are we doing that? And do we really do that? initialise != load...
366        //try
367        //{
368            Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
369            /*Ogre::StringVector str = Ogre::ResourceGroupManager::getSingleton().getResourceGroups();
370            for (unsigned int i = 0; i < str.size(); i++)
371            {
372            Ogre::ResourceGroupManager::getSingleton().loadResourceGroup(str[i]);
373            }*/
374        //}
375        //catch (...)
376        //{
377        //    CCOUT(2) << "Error: There was a serious error when initialising the resources." << std::endl;
378        //    throw;
379        //}
380    }
381
382    /**
383    @brief
384        Method called by the LogListener interface from Ogre.
385        We use it to capture Ogre log messages and handle it ourselves.
386    @param message
387        The message to be logged
388    @param lml
389        The message level the log is using
390    @param maskDebug
391        If we are printing to the console or not
392    @param logName
393        The name of this log (so you can have several listeners
394        for different logs, and identify them)
395    */
396    void GraphicsManager::messageLogged(const std::string& message,
397        Ogre::LogMessageLevel lml, bool maskDebug, const std::string& logName)
398    {
399        int orxonoxLevel;
400        switch (lml)
401        {
402        case Ogre::LML_TRIVIAL:
403            orxonoxLevel = this->ogreLogLevelTrivial_;
404            break;
405        case Ogre::LML_NORMAL:
406            orxonoxLevel = this->ogreLogLevelNormal_;
407            break;
408        case Ogre::LML_CRITICAL:
409            orxonoxLevel = this->ogreLogLevelCritical_;
410            break;
411        default:
412            orxonoxLevel = 0;
413        }
414        OutputHandler::getOutStream().setOutputLevel(orxonoxLevel)
415            << "Ogre: " << message << std::endl;
416    }
417
418    void GraphicsManager::printScreen()
419    {
420        assert(this->renderWindow_);
421       
422        this->renderWindow_->writeContentsToTimestampedFile(Core::getLogPathString() + "screenShot_", ".jpg");
423    }
424
425
426    /****** OgreWindowEventListener ******/
427
428    void OgreWindowEventListener::windowResized(Ogre::RenderWindow* rw)
429    {
430        for (ObjectList<orxonox::WindowEventListener>::iterator it
431            = ObjectList<orxonox::WindowEventListener>::begin(); it; ++it)
432            it->windowResized(rw->getWidth(), rw->getHeight());
433    }
434    void OgreWindowEventListener::windowFocusChange(Ogre::RenderWindow* rw)
435    {
436        for (ObjectList<orxonox::WindowEventListener>::iterator it
437            = ObjectList<orxonox::WindowEventListener>::begin(); it; ++it)
438            it->windowFocusChanged();
439    }
440    void OgreWindowEventListener::windowClosed(Ogre::RenderWindow* rw)
441    {
442        // TODO: Notify the right class to shut down the Game
443    }
444}
Note: See TracBrowser for help on using the repository browser.