Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/resource3/src/core/GraphicsManager.cc @ 5681

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

@Oli: Try this. I previously removed a call to the texture manager setting the default number of mipmaps to 0 because according to the documentation, 0 already is the default value.
Anyway, I really haven't found anything else that doesn't concern exception handling or shutdown.

  • Property svn:eol-style set to native
File size: 14.1 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 <OgreConfigFile.h>
42#include <OgreFrameListener.h>
43#include <OgreRoot.h>
44#include <OgreLogManager.h>
45#include <OgreException.h>
46#include <OgreRenderWindow.h>
47#include <OgreRenderSystem.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 "WindowEventListener.h"
64
65namespace orxonox
66{
67    class OgreWindowEventListener : public Ogre::WindowEventListener
68    {
69    public:
70        void windowResized     (Ogre::RenderWindow* rw)
71            { orxonox::WindowEventListener::resizeWindow(rw->getWidth(), rw->getHeight()); }
72        void windowFocusChange (Ogre::RenderWindow* rw)
73            { orxonox::WindowEventListener::changeWindowFocus(); }
74        void windowClosed      (Ogre::RenderWindow* rw)
75            { orxonox::Game::getInstance().stop(); }
76        void windowMoved       (Ogre::RenderWindow* rw)
77            { orxonox::WindowEventListener::moveWindow(); }
78    };
79
80    GraphicsManager* GraphicsManager::singletonPtr_s = 0;
81
82    /**
83    @brief
84        Non-initialising constructor.
85    */
86    GraphicsManager::GraphicsManager(bool bLoadRenderer)
87        : ogreWindowEventListener_(new OgreWindowEventListener())
88        , renderWindow_(0)
89        , viewport_(0)
90    {
91        RegisterObject(GraphicsManager);
92
93        this->setConfigValues();
94
95        // Ogre setup procedure (creating Ogre::Root)
96        this->loadOgreRoot();
97        // load all the required plugins for Ogre
98        this->loadOgrePlugins();
99        // read resource declaration file
100        this->declareResources();
101
102        if (bLoadRenderer)
103            this->upgradeToGraphics();
104    }
105
106    /**
107    @brief
108        Destruction is done by the member scoped_ptrs.
109    */
110    GraphicsManager::~GraphicsManager()
111    {
112    }
113
114    void GraphicsManager::setConfigValues()
115    {
116        SetConfigValue(resourceFile_,    "resources.cfg")
117            .description("Location of the resources file in the data path.");
118        SetConfigValue(ogreConfigFile_,  "ogre.cfg")
119            .description("Location of the Ogre config file");
120        SetConfigValue(ogrePluginsDirectory_, specialConfig::ogrePluginsDirectory)
121            .description("Folder where the Ogre plugins are located.");
122        SetConfigValue(ogrePlugins_, specialConfig::ogrePlugins)
123            .description("Comma separated list of all plugins to load.");
124        SetConfigValue(ogreLogFile_,     "ogre.log")
125            .description("Logfile for messages from Ogre. Use \"\" to suppress log file creation.");
126        SetConfigValue(ogreLogLevelTrivial_ , 5)
127            .description("Corresponding orxonox debug level for ogre Trivial");
128        SetConfigValue(ogreLogLevelNormal_  , 4)
129            .description("Corresponding orxonox debug level for ogre Normal");
130        SetConfigValue(ogreLogLevelCritical_, 2)
131            .description("Corresponding orxonox debug level for ogre Critical");
132    }
133
134    /**
135    @brief
136        Loads the renderer and creates the render window if not yet done so.
137    @remarks
138        This operation is irreversible without recreating the GraphicsManager!
139        So if it throws you HAVE to recreate the GraphicsManager!!!
140        It therefore offers almost no exception safety.
141    */
142    void GraphicsManager::upgradeToGraphics()
143    {
144        if (renderWindow_ == NULL)
145        {
146            // Reads the ogre config and creates the render window
147            this->loadRenderer();
148            this->initialiseResources();
149        }
150    }
151
152    /**
153    @brief
154        Creates the Ogre Root object and sets up the ogre log.
155    */
156    void GraphicsManager::loadOgreRoot()
157    {
158        COUT(3) << "Setting up Ogre..." << std::endl;
159
160        if (ogreConfigFile_ == "")
161        {
162            COUT(2) << "Warning: Ogre config file set to \"\". Defaulting to config.cfg" << std::endl;
163            ModifyConfigValue(ogreConfigFile_, tset, "config.cfg");
164        }
165        if (ogreLogFile_ == "")
166        {
167            COUT(2) << "Warning: Ogre log file set to \"\". Defaulting to ogre.log" << std::endl;
168            ModifyConfigValue(ogreLogFile_, tset, "ogre.log");
169        }
170
171        boost::filesystem::path ogreConfigFilepath(Core::getConfigPath() / this->ogreConfigFile_);
172        boost::filesystem::path ogreLogFilepath(Core::getLogPath() / this->ogreLogFile_);
173
174        // create a new logManager
175        // Ogre::Root will detect that we've already created a Log
176        ogreLogger_.reset(new Ogre::LogManager());
177        COUT(4) << "Ogre LogManager created" << std::endl;
178
179        // create our own log that we can listen to
180        Ogre::Log *myLog;
181        myLog = ogreLogger_->createLog(ogreLogFilepath.string(), true, false, false);
182        COUT(4) << "Ogre Log created" << std::endl;
183
184        myLog->setLogDetail(Ogre::LL_BOREME);
185        myLog->addListener(this);
186
187        COUT(4) << "Creating Ogre Root..." << std::endl;
188
189        // check for config file existence because Ogre displays (caught) exceptions if not
190        if (!boost::filesystem::exists(ogreConfigFilepath))
191        {
192            // create a zero sized file
193            std::ofstream creator;
194            creator.open(ogreConfigFilepath.string().c_str());
195            creator.close();
196        }
197
198        // Leave plugins file empty. We're going to do that part manually later
199        ogreRoot_.reset(new Ogre::Root("", ogreConfigFilepath.string(), ogreLogFilepath.string()));
200
201        COUT(3) << "Ogre set up done." << std::endl;
202    }
203
204    void GraphicsManager::loadOgrePlugins()
205    {
206        // just to make sure the next statement doesn't segfault
207        if (ogrePluginsDirectory_ == "")
208            ogrePluginsDirectory_ = ".";
209
210        boost::filesystem::path folder(ogrePluginsDirectory_);
211        // Do some SubString magic to get the comma separated list of plugins
212        SubString plugins(ogrePlugins_, ",", " ", false, '\\', false, '"', false, '(', ')', false, '\0');
213        // Use backslash paths on Windows! file_string() already does that though.
214        for (unsigned int i = 0; i < plugins.size(); ++i)
215            ogreRoot_->loadPlugin((folder / plugins[i]).file_string());
216    }
217
218    void GraphicsManager::declareResources()
219    {
220        CCOUT(4) << "Declaring Resources" << std::endl;
221        //TODO: Specify layout of data file and maybe use xml-loader
222        //TODO: Work with ressource groups (should be generated by a special loader)
223
224        if (resourceFile_ == "")
225        {
226            COUT(2) << "Warning: Ogre resource file set to \"\". Defaulting to resources.cfg" << std::endl;
227            ModifyConfigValue(resourceFile_, tset, "resources.cfg");
228        }
229
230        // Load resource paths from data file using configfile ressource type
231        Ogre::ConfigFile cf;
232        try
233        {
234            cf.load((Core::getExternalMediaPath() / resourceFile_).string());
235        }
236        catch (...)
237        {
238            //COUT(1) << ex.getFullDescription() << std::endl;
239            COUT(0) << "Have you forgotten to set the data path in orxnox.ini?" << std::endl;
240            throw;
241        }
242
243        // Go through all sections & settings in the file
244        Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
245
246        std::string secName, typeName, archName;
247        while (seci.hasMoreElements())
248        {
249            try
250            {
251                secName = seci.peekNextKey();
252                Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
253                Ogre::ConfigFile::SettingsMultiMap::iterator i;
254                for (i = settings->begin(); i != settings->end(); ++i)
255                {
256                    typeName = i->first; // for instance "FileSystem" or "Zip"
257                    archName = i->second; // name (and location) of archive
258
259                    Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
260                        (Core::getExternalMediaPath() / archName).string(), typeName, secName);
261                }
262            }
263            catch (Ogre::Exception& ex)
264            {
265                COUT(1) << ex.getFullDescription() << std::endl;
266            }
267        }
268    }
269
270    void GraphicsManager::loadRenderer()
271    {
272        CCOUT(4) << "Configuring Renderer" << std::endl;
273
274        if (!ogreRoot_->restoreConfig())
275            if (!ogreRoot_->showConfigDialog())
276                ThrowException(InitialisationFailed, "OGRE graphics configuration dialogue failed.");
277
278        CCOUT(4) << "Creating render window" << std::endl;
279
280        this->renderWindow_ = ogreRoot_->initialise(true, "Orxonox");
281        // Propagate the size of the new winodw
282        this->ogreWindowEventListener_->windowResized(renderWindow_);
283
284        Ogre::WindowEventUtilities::addWindowEventListener(this->renderWindow_, ogreWindowEventListener_.get());
285
286        Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(0);
287
288        // create a full screen default viewport
289        // Note: This may throw when adding a viewport with an existing z-order!
290        //       But in our case we only have one viewport for now anyway, therefore
291        //       no ScopeGuards or anything to handle exceptions.
292        this->viewport_ = this->renderWindow_->addViewport(0, 0);
293
294        // add console commands
295        FunctorMember<GraphicsManager>* functor1 = createFunctor(&GraphicsManager::printScreen);
296        ccPrintScreen_ = createConsoleCommand(functor1->setObject(this), "printScreen");
297        CommandExecutor::addConsoleCommandShortcut(ccPrintScreen_);
298    }
299
300    void GraphicsManager::initialiseResources()
301    {
302        CCOUT(4) << "Initialising resources" << std::endl;
303        //TODO: Do NOT load all the groups, why are we doing that? And do we really do that? initialise != load...
304        //try
305        //{
306            Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
307            /*Ogre::StringVector str = Ogre::ResourceGroupManager::getSingleton().getResourceGroups();
308            for (unsigned int i = 0; i < str.size(); i++)
309            {
310            Ogre::ResourceGroupManager::getSingleton().loadResourceGroup(str[i]);
311            }*/
312        //}
313        //catch (...)
314        //{
315        //    CCOUT(2) << "Error: There was a serious error when initialising the resources." << std::endl;
316        //    throw;
317        //}
318    }
319
320    void GraphicsManager::update(const Clock& time)
321    {
322        Ogre::FrameEvent evt;
323        evt.timeSinceLastFrame = time.getDeltaTime();
324        evt.timeSinceLastEvent = time.getDeltaTime(); // note: same time, but shouldn't matter anyway
325
326        // don't forget to call _fireFrameStarted to OGRE to make sure
327        // everything goes smoothly
328        ogreRoot_->_fireFrameStarted(evt);
329
330        // Pump messages in all registered RenderWindows
331        // This calls the WindowEventListener objects.
332        Ogre::WindowEventUtilities::messagePump();
333        // make sure the window stays active even when not focused
334        // (probably only necessary on windows)
335        this->renderWindow_->setActive(true);
336
337        // Time before rendering
338        uint64_t timeBeforeTick = time.getRealMicroseconds();
339
340        // Render frame
341        ogreRoot_->_updateAllRenderTargets();
342
343        uint64_t timeAfterTick = time.getRealMicroseconds();
344        // Subtract the time used for rendering from the tick time counter
345        Game::getInstance().subtractTickTime(timeAfterTick - timeBeforeTick);
346
347        // again, just to be sure OGRE works fine
348        ogreRoot_->_fireFrameEnded(evt); // note: uses the same time as _fireFrameStarted
349    }
350
351    void GraphicsManager::setCamera(Ogre::Camera* camera)
352    {
353        this->viewport_->setCamera(camera);
354    }
355
356    /**
357    @brief
358        Method called by the LogListener interface from Ogre.
359        We use it to capture Ogre log messages and handle it ourselves.
360    @param message
361        The message to be logged
362    @param lml
363        The message level the log is using
364    @param maskDebug
365        If we are printing to the console or not
366    @param logName
367        The name of this log (so you can have several listeners
368        for different logs, and identify them)
369    */
370    void GraphicsManager::messageLogged(const std::string& message,
371        Ogre::LogMessageLevel lml, bool maskDebug, const std::string& logName)
372    {
373        int orxonoxLevel;
374        switch (lml)
375        {
376        case Ogre::LML_TRIVIAL:
377            orxonoxLevel = this->ogreLogLevelTrivial_;
378            break;
379        case Ogre::LML_NORMAL:
380            orxonoxLevel = this->ogreLogLevelNormal_;
381            break;
382        case Ogre::LML_CRITICAL:
383            orxonoxLevel = this->ogreLogLevelCritical_;
384            break;
385        default:
386            orxonoxLevel = 0;
387        }
388        OutputHandler::getOutStream().setOutputLevel(orxonoxLevel)
389            << "Ogre: " << message << std::endl;
390    }
391
392    void GraphicsManager::printScreen()
393    {
394        assert(this->renderWindow_);
395       
396        this->renderWindow_->writeContentsToTimestampedFile(Core::getLogPathString() + "screenShot_", ".jpg");
397    }
398}
Note: See TracBrowser for help on using the repository browser.