Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/kicklib/src/libraries/core/GraphicsManager.cc @ 8526

Last change on this file since 8526 was 8274, checked in by rgrieder, 14 years ago

Do not merge resources.oxr files to avoid problems at intall time.

  • Property svn:eol-style set to native
File size: 15.2 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/Exception.h"
51#include "util/StringUtils.h"
52#include "util/SubString.h"
53#include "ConfigValueIncludes.h"
54#include "CoreIncludes.h"
55#include "Core.h"
56#include "Game.h"
57#include "GameMode.h"
58#include "Loader.h"
59#include "PathConfig.h"
60#include "WindowEventListener.h"
61#include "XMLFile.h"
62#include "command/ConsoleCommand.h"
63
64namespace orxonox
65{
66    static const std::string __CC_printScreen_name = "printScreen";
67    DeclareConsoleCommand(__CC_printScreen_name, &prototype::void__void);
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(rw->isActive()); }
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
100        // At first, add the root paths of the data directories as resource locations
101        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getDataPathString(), "FileSystem");
102        // Load resources
103        resources_.reset(new XMLFile("DefaultResources.oxr"));
104        resources_->setLuaSupport(false);
105        Loader::open(resources_.get());
106
107        // Only for development runs
108        if (PathConfig::isDevelopmentRun())
109            Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getExternalDataPathString(), "FileSystem");
110
111        extResources_.reset(new XMLFile("resources.oxr"));
112        extResources_->setLuaSupport(false);
113        Loader::open(extResources_.get());
114
115        if (bLoadRenderer)
116        {
117            // Reads the ogre config and creates the render window
118            this->upgradeToGraphics();
119        }
120    }
121
122    /**
123    @brief
124        Destruction is done by the member scoped_ptrs.
125    */
126    GraphicsManager::~GraphicsManager()
127    {
128        Loader::unload(debugOverlay_.get());
129
130        Ogre::WindowEventUtilities::removeWindowEventListener(renderWindow_, ogreWindowEventListener_.get());
131        ModifyConsoleCommand(__CC_printScreen_name).resetFunction();
132
133        // Undeclare the resources
134        Loader::unload(resources_.get());
135        Loader::unload(extResources_.get());
136    }
137
138    void GraphicsManager::setConfigValues()
139    {
140        SetConfigValue(ogreConfigFile_,  "ogre.cfg")
141            .description("Location of the Ogre config file");
142        SetConfigValue(ogrePlugins_, specialConfig::ogrePlugins)
143            .description("Comma separated list of all plugins to load.");
144        SetConfigValue(ogreLogFile_,     "ogre.log")
145            .description("Logfile for messages from Ogre. Use \"\" to suppress log file creation.");
146        SetConfigValue(ogreLogLevelTrivial_ , 5)
147            .description("Corresponding orxonox debug level for ogre Trivial");
148        SetConfigValue(ogreLogLevelNormal_  , 4)
149            .description("Corresponding orxonox debug level for ogre Normal");
150        SetConfigValue(ogreLogLevelCritical_, 2)
151            .description("Corresponding orxonox debug level for ogre Critical");
152    }
153
154    /**
155    @brief
156        Loads the renderer and creates the render window if not yet done so.
157    @remarks
158        This operation is irreversible without recreating the GraphicsManager!
159        So if it throws you HAVE to recreate the GraphicsManager!!!
160        It therefore offers almost no exception safety.
161    */
162    void GraphicsManager::upgradeToGraphics()
163    {
164        if (renderWindow_ != NULL)
165            return;
166
167        // load all the required plugins for Ogre
168        this->loadOgrePlugins();
169
170        this->loadRenderer();
171
172        // Initialise all resources (do this AFTER the renderer has been loaded!)
173        // Note: You can only do this once! Ogre will check whether a resource group has
174        // already been initialised. If you need to load resources later, you will have to
175        // choose another resource group.
176        Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
177    }
178
179    /**
180    @brief
181        Creates the Ogre Root object and sets up the ogre log.
182    */
183    void GraphicsManager::loadOgreRoot()
184    {
185        COUT(3) << "Setting up Ogre..." << std::endl;
186
187        if (ogreConfigFile_.empty())
188        {
189            COUT(2) << "Warning: Ogre config file set to \"\". Defaulting to config.cfg" << std::endl;
190            ModifyConfigValue(ogreConfigFile_, tset, "config.cfg");
191        }
192        if (ogreLogFile_.empty())
193        {
194            COUT(2) << "Warning: Ogre log file set to \"\". Defaulting to ogre.log" << std::endl;
195            ModifyConfigValue(ogreLogFile_, tset, "ogre.log");
196        }
197
198        boost::filesystem::path ogreConfigFilepath(PathConfig::getConfigPath() / this->ogreConfigFile_);
199        boost::filesystem::path ogreLogFilepath(PathConfig::getLogPath() / this->ogreLogFile_);
200
201        // create a new logManager
202        // Ogre::Root will detect that we've already created a Log
203        ogreLogger_.reset(new Ogre::LogManager());
204        COUT(4) << "Ogre LogManager created" << std::endl;
205
206        // create our own log that we can listen to
207        Ogre::Log *myLog;
208        myLog = ogreLogger_->createLog(ogreLogFilepath.string(), true, false, false);
209        COUT(4) << "Ogre Log created" << std::endl;
210
211        myLog->setLogDetail(Ogre::LL_BOREME);
212        myLog->addListener(this);
213
214        COUT(4) << "Creating Ogre Root..." << std::endl;
215
216        // check for config file existence because Ogre displays (caught) exceptions if not
217        if (!boost::filesystem::exists(ogreConfigFilepath))
218        {
219            // create a zero sized file
220            std::ofstream creator;
221            creator.open(ogreConfigFilepath.string().c_str());
222            creator.close();
223        }
224
225        // Leave plugins file empty. We're going to do that part manually later
226        ogreRoot_.reset(new Ogre::Root("", ogreConfigFilepath.string(), ogreLogFilepath.string()));
227
228        COUT(3) << "Ogre set up done." << std::endl;
229    }
230
231    void GraphicsManager::loadOgrePlugins()
232    {
233        // Plugin path can have many different locations...
234        std::string pluginPath = specialConfig::ogrePluginsDirectory;
235#ifdef DEPENDENCY_PACKAGE_ENABLE
236        if (!PathConfig::isDevelopmentRun())
237        {
238#  if defined(ORXONOX_PLATFORM_WINDOWS)
239            pluginPath = PathConfig::getExecutablePathString();
240#  elif defined(ORXONOX_PLATFORM_APPLE)
241            // TODO: Where are the plugins being installed to?
242            pluginPath = PathConfig::getExecutablePathString();
243#  endif
244        }
245#endif
246
247#ifdef ORXONOX_PLATFORM_WINDOWS
248        // Add OGRE plugin path to the environment. That way one plugin could
249        // also depend on another without problems on Windows
250        const char* currentPATH = getenv("PATH");
251        std::string newPATH = pluginPath;
252        if (currentPATH != NULL)
253            newPATH = std::string(currentPATH) + ';' + newPATH;
254        putenv(const_cast<char*>(("PATH=" + newPATH).c_str()));
255#endif
256
257        // Do some SubString magic to get the comma separated list of plugins
258        SubString plugins(ogrePlugins_, ",", " ", false, '\\', false, '"', false, '{', '}', false, '\0');
259        for (unsigned int i = 0; i < plugins.size(); ++i)
260            ogreRoot_->loadPlugin(pluginPath + '/' + plugins[i]);
261    }
262
263    void GraphicsManager::loadRenderer()
264    {
265        CCOUT(4) << "Configuring Renderer" << std::endl;
266
267        if (!ogreRoot_->restoreConfig() || Core::getInstance().getOgreConfigTimestamp() > Core::getInstance().getLastLevelTimestamp())
268        {
269            if (!ogreRoot_->showConfigDialog())
270                ThrowException(InitialisationFailed, "OGRE graphics configuration dialogue canceled.");
271            else
272                Core::getInstance().updateOgreConfigTimestamp();
273        }
274
275        CCOUT(4) << "Creating render window" << std::endl;
276
277        this->renderWindow_ = ogreRoot_->initialise(true, "Orxonox");
278        // Propagate the size of the new winodw
279        this->ogreWindowEventListener_->windowResized(renderWindow_);
280
281        Ogre::WindowEventUtilities::addWindowEventListener(this->renderWindow_, ogreWindowEventListener_.get());
282
283        // create a full screen default viewport
284        // Note: This may throw when adding a viewport with an existing z-order!
285        //       But in our case we only have one viewport for now anyway, therefore
286        //       no ScopeGuards or anything to handle exceptions.
287        this->viewport_ = this->renderWindow_->addViewport(0, 0);
288
289        Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(Ogre::MIP_UNLIMITED);
290
291        // add console commands
292        ModifyConsoleCommand(__CC_printScreen_name).setFunction(&GraphicsManager::printScreen, this);
293    }
294
295    void GraphicsManager::loadDebugOverlay()
296    {
297        // Load debug overlay to show info about fps and tick time
298        COUT(4) << "Loading Debug Overlay..." << std::endl;
299        debugOverlay_.reset(new XMLFile("debug.oxo"));
300        Loader::open(debugOverlay_.get());
301    }
302
303    /**
304    @note
305        A note about the Ogre::FrameListener: Even though we don't use them,
306        they still get called. However, the delta times are not correct (except
307        for timeSinceLastFrame, which is the most important). A little research
308        as shown that there is probably only one FrameListener that doesn't even
309        need the time. So we shouldn't run into problems.
310    */
311    void GraphicsManager::postUpdate(const Clock& time)
312    {
313        Ogre::FrameEvent evt;
314        evt.timeSinceLastFrame = time.getDeltaTime();
315        evt.timeSinceLastEvent = time.getDeltaTime(); // note: same time, but shouldn't matter anyway
316
317        // don't forget to call _fireFrameStarted to OGRE to make sure
318        // everything goes smoothly
319        ogreRoot_->_fireFrameStarted(evt);
320
321        // Pump messages in all registered RenderWindows
322        // This calls the WindowEventListener objects.
323        Ogre::WindowEventUtilities::messagePump();
324        // make sure the window stays active even when not focused
325        // (probably only necessary on windows)
326        this->renderWindow_->setActive(true);
327
328        // Time before rendering
329        uint64_t timeBeforeTick = time.getRealMicroseconds();
330
331        // Render frame
332        ogreRoot_->_updateAllRenderTargets();
333
334        uint64_t timeAfterTick = time.getRealMicroseconds();
335        // Subtract the time used for rendering from the tick time counter
336        Game::getInstance().subtractTickTime((int32_t)(timeAfterTick - timeBeforeTick));
337
338        // again, just to be sure OGRE works fine
339        ogreRoot_->_fireFrameEnded(evt); // note: uses the same time as _fireFrameStarted
340    }
341
342    void GraphicsManager::setCamera(Ogre::Camera* camera)
343    {
344        this->viewport_->setCamera(camera);
345    }
346
347    /**
348    @brief
349        Method called by the LogListener interface from Ogre.
350        We use it to capture Ogre log messages and handle it ourselves.
351    @param message
352        The message to be logged
353    @param lml
354        The message level the log is using
355    @param maskDebug
356        If we are printing to the console or not
357    @param logName
358        The name of this log (so you can have several listeners
359        for different logs, and identify them)
360    */
361    void GraphicsManager::messageLogged(const std::string& message,
362        Ogre::LogMessageLevel lml, bool maskDebug, const std::string& logName)
363    {
364        int orxonoxLevel;
365        std::string introduction;
366        // Do not show caught OGRE exceptions in front
367        if (message.find("EXCEPTION") != std::string::npos)
368        {
369            orxonoxLevel = OutputLevel::Debug;
370            introduction = "Ogre, caught exception: ";
371        }
372        else
373        {
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            introduction = "Ogre: ";
389        }
390        OutputHandler::getOutStream(orxonoxLevel)
391            << introduction << message << std::endl;
392    }
393
394    size_t GraphicsManager::getRenderWindowHandle()
395    {
396        size_t windowHnd = 0;
397        renderWindow_->getCustomAttribute("WINDOW", &windowHnd);
398        return windowHnd;
399    }
400
401    bool GraphicsManager::isFullScreen() const
402    {
403        Ogre::ConfigOptionMap& options = ogreRoot_->getRenderSystem()->getConfigOptions();
404        if (options.find("Full Screen") != options.end())
405        {
406            if (options["Full Screen"].currentValue == "Yes")
407                return true;
408            else
409                return false;
410        }
411        else
412        {
413            COUT(0) << "Could not find 'Full Screen' render system option. Fix This!!!" << std::endl;
414            return false;
415        }
416    }
417
418    void GraphicsManager::printScreen()
419    {
420        assert(this->renderWindow_);
421        this->renderWindow_->writeContentsToTimestampedFile(PathConfig::getLogPathString() + "screenShot_", ".png");
422    }
423}
Note: See TracBrowser for help on using the repository browser.