Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/usability/src/libraries/core/GraphicsManager.cc @ 7966

Last change on this file since 7966 was 7966, checked in by landauf, 13 years ago

some changes related to camera switching:

  • added ViewportEventListener (currently only listens to camera changes in a viewport)
  • Shader now correctly updates its visibility if the camera changes the scene
  • (the same lines of code also fix the weird Ogre behavior which was originally fixed in CameraManager)
  • GraphicsManager also updates the GUIManager's camera
  • if all cameras are destroyed, CameraManager now officially switches to NULL camera
  • Property svn:eol-style set to native
File size: 17.8 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 <fstream>
33#include <sstream>
34#include <boost/filesystem.hpp>
35#include <boost/shared_array.hpp>
36
37#include <OgreArchiveFactory.h>
38#include <OgreArchiveManager.h>
39#include <OgreFrameListener.h>
40#include <OgreRoot.h>
41#include <OgreLogManager.h>
42#include <OgreRenderWindow.h>
43#include <OgreRenderSystem.h>
44#include <OgreResourceGroupManager.h>
45#include <OgreTextureManager.h>
46#include <OgreViewport.h>
47#include <OgreWindowEventUtilities.h>
48
49#include "SpecialConfig.h"
50#include "util/Clock.h"
51#include "util/Exception.h"
52#include "util/StringUtils.h"
53#include "util/SubString.h"
54#include "ConfigValueIncludes.h"
55#include "CoreIncludes.h"
56#include "Core.h"
57#include "Game.h"
58#include "GameMode.h"
59#include "GUIManager.h"
60#include "Loader.h"
61#include "MemoryArchive.h"
62#include "PathConfig.h"
63#include "ViewportEventListener.h"
64#include "WindowEventListener.h"
65#include "XMLFile.h"
66#include "command/ConsoleCommand.h"
67
68namespace orxonox
69{
70    static const std::string __CC_printScreen_name = "printScreen";
71    DeclareConsoleCommand(__CC_printScreen_name, &prototype::void__void);
72
73    class OgreWindowEventListener : public Ogre::WindowEventListener
74    {
75    public:
76        void windowResized     (Ogre::RenderWindow* rw)
77            { orxonox::WindowEventListener::resizeWindow(rw->getWidth(), rw->getHeight()); }
78        void windowFocusChange (Ogre::RenderWindow* rw)
79            { orxonox::WindowEventListener::changeWindowFocus(rw->isActive()); }
80        void windowClosed      (Ogre::RenderWindow* rw)
81            { orxonox::Game::getInstance().stop(); }
82        void windowMoved       (Ogre::RenderWindow* rw)
83            { orxonox::WindowEventListener::moveWindow(); }
84    };
85
86    GraphicsManager* GraphicsManager::singletonPtr_s = 0;
87
88    /**
89    @brief
90        Non-initialising constructor.
91    */
92    GraphicsManager::GraphicsManager(bool bLoadRenderer)
93        : ogreWindowEventListener_(new OgreWindowEventListener())
94#if OGRE_VERSION < 0x010600
95        , memoryArchiveFactory_(new MemoryArchiveFactory())
96#endif
97        , renderWindow_(0)
98        , viewport_(0)
99    {
100        RegisterObject(GraphicsManager);
101
102        this->setConfigValues();
103
104        // Ogre setup procedure (creating Ogre::Root)
105        this->loadOgreRoot();
106
107        // At first, add the root paths of the data directories as resource locations
108        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getDataPathString(), "FileSystem");
109        // Load resources
110        resources_.reset(new XMLFile("DefaultResources.oxr"));
111        resources_->setLuaSupport(false);
112        Loader::open(resources_.get());
113
114        // Only for development runs
115        if (PathConfig::isDevelopmentRun())
116        {
117            Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getExternalDataPathString(), "FileSystem");
118            extResources_.reset(new XMLFile("resources.oxr"));
119            extResources_->setLuaSupport(false);
120            Loader::open(extResources_.get());
121        }
122
123        if (bLoadRenderer)
124        {
125            // Reads the ogre config and creates the render window
126            this->upgradeToGraphics();
127        }
128    }
129
130    /**
131    @brief
132        Destruction is done by the member scoped_ptrs.
133    */
134    GraphicsManager::~GraphicsManager()
135    {
136        Loader::unload(debugOverlay_.get());
137
138        Ogre::WindowEventUtilities::removeWindowEventListener(renderWindow_, ogreWindowEventListener_.get());
139        ModifyConsoleCommand(__CC_printScreen_name).resetFunction();
140
141        // Undeclare the resources
142        Loader::unload(resources_.get());
143        if (PathConfig::isDevelopmentRun())
144            Loader::unload(extResources_.get());
145    }
146
147    void GraphicsManager::setConfigValues()
148    {
149        SetConfigValue(ogreConfigFile_,  "ogre.cfg")
150            .description("Location of the Ogre config file");
151        SetConfigValue(ogrePluginsDirectory_, specialConfig::ogrePluginsDirectory)
152            .description("Folder where the Ogre plugins are located.");
153        SetConfigValue(ogrePlugins_, specialConfig::ogrePlugins)
154            .description("Comma separated list of all plugins to load.");
155        SetConfigValue(ogreLogFile_,     "ogre.log")
156            .description("Logfile for messages from Ogre. Use \"\" to suppress log file creation.");
157        SetConfigValue(ogreLogLevelTrivial_ , 5)
158            .description("Corresponding orxonox debug level for ogre Trivial");
159        SetConfigValue(ogreLogLevelNormal_  , 4)
160            .description("Corresponding orxonox debug level for ogre Normal");
161        SetConfigValue(ogreLogLevelCritical_, 2)
162            .description("Corresponding orxonox debug level for ogre Critical");
163    }
164
165    /**
166    @brief
167        Loads the renderer and creates the render window if not yet done so.
168    @remarks
169        This operation is irreversible without recreating the GraphicsManager!
170        So if it throws you HAVE to recreate the GraphicsManager!!!
171        It therefore offers almost no exception safety.
172    */
173    void GraphicsManager::upgradeToGraphics()
174    {
175        if (renderWindow_ != NULL)
176            return;
177
178        // load all the required plugins for Ogre
179        this->loadOgrePlugins();
180
181        this->loadRenderer();
182
183#if OGRE_VERSION < 0x010600
184        // WORKAROUND: There is an incompatibility for particle scripts when trying
185        // to support both Ogre 1.4 and 1.6. The hacky solution is to create
186        // scripts for the 1.6 version and then remove the inserted "particle_system"
187        // keyword. But we need to supply these new scripts as well, which is why
188        // there is an extra Ogre::Archive dealing with it in the memory.
189        using namespace Ogre;
190        ArchiveManager::getSingleton().addArchiveFactory(memoryArchiveFactory_.get());
191        const StringVector& groups = ResourceGroupManager::getSingleton().getResourceGroups();
192        // Travers all groups
193        for (StringVector::const_iterator itGroup = groups.begin(); itGroup != groups.end(); ++itGroup)
194        {
195            FileInfoListPtr files = ResourceGroupManager::getSingleton().findResourceFileInfo(*itGroup, "*.particle");
196            for (FileInfoList::const_iterator itFile = files->begin(); itFile != files->end(); ++itFile)
197            {
198                // open file
199                Ogre::DataStreamPtr input = ResourceGroupManager::getSingleton().openResource(itFile->filename, *itGroup, false);
200                std::stringstream output;
201                // Parse file and replace "particle_system" with nothing
202                while (!input->eof())
203                {
204                    std::string line = input->getLine();
205                    size_t pos = line.find("particle_system");
206                    if (pos != std::string::npos)
207                    {
208                        // 15 is the length of "particle_system"
209                        line.replace(pos, 15, "");
210                    }
211                    output << line << std::endl;
212                }
213                // Add file to the memory archive
214                shared_array<char> data(new char[output.str().size()]);
215                // Debug optimisations
216                const std::string& outputStr = output.str();
217                char* rawData = data.get();
218                for (unsigned i = 0; i < outputStr.size(); ++i)
219                    rawData[i] = outputStr[i];
220                MemoryArchive::addFile("particle_scripts_ogre_1.4_" + *itGroup, itFile->filename, data, output.str().size());
221            }
222            if (!files->empty())
223            {
224                // Declare the files, but using a new group
225                ResourceGroupManager::getSingleton().addResourceLocation("particle_scripts_ogre_1.4_" + *itGroup,
226                    "Memory", "particle_scripts_ogre_1.4_" + *itGroup);
227            }
228        }
229#endif
230
231        // Initialise all resources (do this AFTER the renderer has been loaded!)
232        // Note: You can only do this once! Ogre will check whether a resource group has
233        // already been initialised. If you need to load resources later, you will have to
234        // choose another resource group.
235        Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
236    }
237
238    /**
239    @brief
240        Creates the Ogre Root object and sets up the ogre log.
241    */
242    void GraphicsManager::loadOgreRoot()
243    {
244        COUT(3) << "Setting up Ogre..." << std::endl;
245
246        if (ogreConfigFile_.empty())
247        {
248            COUT(2) << "Warning: Ogre config file set to \"\". Defaulting to config.cfg" << std::endl;
249            ModifyConfigValue(ogreConfigFile_, tset, "config.cfg");
250        }
251        if (ogreLogFile_.empty())
252        {
253            COUT(2) << "Warning: Ogre log file set to \"\". Defaulting to ogre.log" << std::endl;
254            ModifyConfigValue(ogreLogFile_, tset, "ogre.log");
255        }
256
257        boost::filesystem::path ogreConfigFilepath(PathConfig::getConfigPath() / this->ogreConfigFile_);
258        boost::filesystem::path ogreLogFilepath(PathConfig::getLogPath() / this->ogreLogFile_);
259
260        // create a new logManager
261        // Ogre::Root will detect that we've already created a Log
262        ogreLogger_.reset(new Ogre::LogManager());
263        COUT(4) << "Ogre LogManager created" << std::endl;
264
265        // create our own log that we can listen to
266        Ogre::Log *myLog;
267        myLog = ogreLogger_->createLog(ogreLogFilepath.string(), true, false, false);
268        COUT(4) << "Ogre Log created" << std::endl;
269
270        myLog->setLogDetail(Ogre::LL_BOREME);
271        myLog->addListener(this);
272
273        COUT(4) << "Creating Ogre Root..." << std::endl;
274
275        // check for config file existence because Ogre displays (caught) exceptions if not
276        if (!boost::filesystem::exists(ogreConfigFilepath))
277        {
278            // create a zero sized file
279            std::ofstream creator;
280            creator.open(ogreConfigFilepath.string().c_str());
281            creator.close();
282        }
283
284        // Leave plugins file empty. We're going to do that part manually later
285        ogreRoot_.reset(new Ogre::Root("", ogreConfigFilepath.string(), ogreLogFilepath.string()));
286
287        COUT(3) << "Ogre set up done." << std::endl;
288    }
289
290    void GraphicsManager::loadOgrePlugins()
291    {
292        // just to make sure the next statement doesn't segfault
293        if (ogrePluginsDirectory_.empty())
294            ogrePluginsDirectory_ = '.';
295
296        boost::filesystem::path folder(ogrePluginsDirectory_);
297        // Do some SubString magic to get the comma separated list of plugins
298        SubString plugins(ogrePlugins_, ",", " ", false, '\\', false, '"', false, '{', '}', false, '\0');
299        // Use backslash paths on Windows! file_string() already does that though.
300        for (unsigned int i = 0; i < plugins.size(); ++i)
301            ogreRoot_->loadPlugin((folder / plugins[i]).file_string());
302    }
303
304    void GraphicsManager::loadRenderer()
305    {
306        CCOUT(4) << "Configuring Renderer" << std::endl;
307
308        if (!ogreRoot_->restoreConfig() || Core::getInstance().getOgreConfigTimestamp() > Core::getInstance().getLastLevelTimestamp())
309        {
310            if (!ogreRoot_->showConfigDialog())
311                ThrowException(InitialisationFailed, "OGRE graphics configuration dialogue canceled.");
312            else
313                Core::getInstance().updateOgreConfigTimestamp();
314        }
315
316        CCOUT(4) << "Creating render window" << std::endl;
317
318        this->renderWindow_ = ogreRoot_->initialise(true, "Orxonox");
319        // Propagate the size of the new winodw
320        this->ogreWindowEventListener_->windowResized(renderWindow_);
321
322        Ogre::WindowEventUtilities::addWindowEventListener(this->renderWindow_, ogreWindowEventListener_.get());
323
324        // create a full screen default viewport
325        // Note: This may throw when adding a viewport with an existing z-order!
326        //       But in our case we only have one viewport for now anyway, therefore
327        //       no ScopeGuards or anything to handle exceptions.
328        this->viewport_ = this->renderWindow_->addViewport(0, 0);
329
330        Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(Ogre::MIP_UNLIMITED);
331
332        // add console commands
333        ModifyConsoleCommand(__CC_printScreen_name).setFunction(&GraphicsManager::printScreen, this);
334    }
335
336    void GraphicsManager::loadDebugOverlay()
337    {
338        // Load debug overlay to show info about fps and tick time
339        COUT(4) << "Loading Debug Overlay..." << std::endl;
340        debugOverlay_.reset(new XMLFile("debug.oxo"));
341        Loader::open(debugOverlay_.get());
342    }
343
344    /**
345    @note
346        A note about the Ogre::FrameListener: Even though we don't use them,
347        they still get called. However, the delta times are not correct (except
348        for timeSinceLastFrame, which is the most important). A little research
349        as shown that there is probably only one FrameListener that doesn't even
350        need the time. So we shouldn't run into problems.
351    */
352    void GraphicsManager::postUpdate(const Clock& time)
353    {
354        Ogre::FrameEvent evt;
355        evt.timeSinceLastFrame = time.getDeltaTime();
356        evt.timeSinceLastEvent = time.getDeltaTime(); // note: same time, but shouldn't matter anyway
357
358        // don't forget to call _fireFrameStarted to OGRE to make sure
359        // everything goes smoothly
360        ogreRoot_->_fireFrameStarted(evt);
361
362        // Pump messages in all registered RenderWindows
363        // This calls the WindowEventListener objects.
364        Ogre::WindowEventUtilities::messagePump();
365        // make sure the window stays active even when not focused
366        // (probably only necessary on windows)
367        this->renderWindow_->setActive(true);
368
369        // Time before rendering
370        uint64_t timeBeforeTick = time.getRealMicroseconds();
371
372        // Render frame
373        ogreRoot_->_updateAllRenderTargets();
374
375        uint64_t timeAfterTick = time.getRealMicroseconds();
376        // Subtract the time used for rendering from the tick time counter
377        Game::getInstance().subtractTickTime((int32_t)(timeAfterTick - timeBeforeTick));
378
379        // again, just to be sure OGRE works fine
380        ogreRoot_->_fireFrameEnded(evt); // note: uses the same time as _fireFrameStarted
381    }
382
383    void GraphicsManager::setCamera(Ogre::Camera* camera)
384    {
385        Ogre::Camera* oldCamera = this->viewport_->getCamera();
386
387        this->viewport_->setCamera(camera);
388        GUIManager::getInstance().setCamera(camera);
389
390        for (ObjectList<ViewportEventListener>::iterator it = ObjectList<ViewportEventListener>::begin(); it != ObjectList<ViewportEventListener>::end(); ++it)
391            it->cameraChanged(this->viewport_, oldCamera);
392    }
393
394    /**
395    @brief
396        Method called by the LogListener interface from Ogre.
397        We use it to capture Ogre log messages and handle it ourselves.
398    @param message
399        The message to be logged
400    @param lml
401        The message level the log is using
402    @param maskDebug
403        If we are printing to the console or not
404    @param logName
405        The name of this log (so you can have several listeners
406        for different logs, and identify them)
407    */
408    void GraphicsManager::messageLogged(const std::string& message,
409        Ogre::LogMessageLevel lml, bool maskDebug, const std::string& logName)
410    {
411        int orxonoxLevel;
412        std::string introduction;
413        // Do not show caught OGRE exceptions in front
414        if (message.find("EXCEPTION") != std::string::npos)
415        {
416            orxonoxLevel = OutputLevel::Debug;
417            introduction = "Ogre, caught exception: ";
418        }
419        else
420        {
421            switch (lml)
422            {
423            case Ogre::LML_TRIVIAL:
424                orxonoxLevel = this->ogreLogLevelTrivial_;
425                break;
426            case Ogre::LML_NORMAL:
427                orxonoxLevel = this->ogreLogLevelNormal_;
428                break;
429            case Ogre::LML_CRITICAL:
430                orxonoxLevel = this->ogreLogLevelCritical_;
431                break;
432            default:
433                orxonoxLevel = 0;
434            }
435            introduction = "Ogre: ";
436        }
437        OutputHandler::getOutStream(orxonoxLevel)
438            << introduction << message << std::endl;
439    }
440
441    size_t GraphicsManager::getRenderWindowHandle()
442    {
443        size_t windowHnd = 0;
444        renderWindow_->getCustomAttribute("WINDOW", &windowHnd);
445        return windowHnd;
446    }
447
448    bool GraphicsManager::isFullScreen() const
449    {
450        Ogre::ConfigOptionMap& options = ogreRoot_->getRenderSystem()->getConfigOptions();
451        if (options.find("Full Screen") != options.end())
452        {
453            if (options["Full Screen"].currentValue == "Yes")
454                return true;
455            else
456                return false;
457        }
458        else
459        {
460            COUT(0) << "Could not find 'Full Screen' render system option. Fix This!!!" << std::endl;
461            return false;
462        }
463    }
464
465    void GraphicsManager::printScreen()
466    {
467        assert(this->renderWindow_);
468        this->renderWindow_->writeContentsToTimestampedFile(PathConfig::getLogPathString() + "screenShot_", ".png");
469    }
470}
Note: See TracBrowser for help on using the repository browser.