Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/Dialog_HS17/src/orxonox/overlays/OrxonoxOverlay.cc @ 11558

Last change on this file since 11558 was 11099, checked in by muemart, 9 years ago

Fix loads of doxygen warnings and other documentation issues

  • Property svn:eol-style set to native
File size: 15.9 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 *   Co-authors:
25 *      ...
26 *
27 */
28
29/**
30@file
31@brief Definition of the OrxonoxOverlay class.
32*/
33
34#include "OrxonoxOverlay.h"
35
36#include <cmath>
37#include <OgreOverlay.h>
38#include <OgreOverlayManager.h>
39#include <OgrePanelOverlayElement.h>
40#include <OgreRenderWindow.h>
41#include <OgreMaterialManager.h>
42#include <OgreTechnique.h>
43#include <OgrePass.h>
44
45#include "util/Convert.h"
46#include "util/Exception.h"
47#include "core/GameMode.h"
48#include "core/CoreIncludes.h"
49#include "core/XMLPort.h"
50#include "core/command/ConsoleCommandIncludes.h"
51
52#include "OverlayGroup.h"
53
54namespace orxonox
55{
56    unsigned int OrxonoxOverlay::hudOverlayCounter_s = 0;
57    std::map<std::string, OrxonoxOverlay*> OrxonoxOverlay::overlays_s;
58
59    SetConsoleCommand("OrxonoxOverlay", "scaleOverlay",     &OrxonoxOverlay::scaleOverlay);
60    SetConsoleCommand("OrxonoxOverlay", "scrollOverlay",    &OrxonoxOverlay::scrollOverlay);
61    SetConsoleCommand("OrxonoxOverlay", "toggleVisibility", &OrxonoxOverlay::toggleVisibility);
62    SetConsoleCommand("OrxonoxOverlay", "show",     &OrxonoxOverlay::showOverlay);
63    SetConsoleCommand("OrxonoxOverlay", "rotateOverlay",    &OrxonoxOverlay::rotateOverlay);
64
65    RegisterClass(OrxonoxOverlay);
66
67    OrxonoxOverlay::OrxonoxOverlay(Context* context)
68        : BaseObject(context)
69    {
70        RegisterObject(OrxonoxOverlay);
71
72        this->owner_ = nullptr;
73        this->group_ = nullptr;
74
75        if (!GameMode::showsGraphics())
76            ThrowException(NoGraphics, "Can't create OrxonoxOverlay, graphics engine not initialized");
77
78        // create the Ogre::Overlay
79        overlay_ = Ogre::OverlayManager::getSingleton().create("OrxonoxOverlay_overlay_"
80            + multi_cast<std::string>(hudOverlayCounter_s++));
81
82        // create background panel (can be used to show any picture)
83        this->background_ = static_cast<Ogre::PanelOverlayElement*>(
84            Ogre::OverlayManager::getSingleton().createOverlayElement("Panel",
85            "OrxonoxOverlay_background_" + multi_cast<std::string>(hudOverlayCounter_s++)));
86        this->overlay_->add2D(this->background_);
87
88        // Get aspect ratio from the render window. Later on, we get informed automatically
89        this->windowAspectRatio_ = static_cast<float>(this->getWindowWidth()) / this->getWindowHeight();
90
91        this->size_ = Vector2(1.0f, 1.0f);
92        this->pickPoint_= Vector2(0.0f, 0.0f);
93        this->position_ = Vector2(0.0f, 0.0f);
94        this->angle_ = Degree(0.0);
95        this->bCorrectAspect_ = false;
96        this->rotState_ = RotationState::Horizontal;
97        this->angleChanged(); // updates all other values as well
98
99        setBackgroundMaterial("");
100    }
101
102    /**
103    @brief
104        Make sure everything gets removed/destroyed.
105    @remark
106        We assume that the Ogre::OverlayManager exists (there is an assert in Ogre for that!)
107    */
108    OrxonoxOverlay::~OrxonoxOverlay()
109    {
110        if (this->isInitialized())
111        {
112            // erase ourself from the map with all overlays
113            std::map<std::string, OrxonoxOverlay*>::iterator it = overlays_s.find(this->getName());
114            if (it != overlays_s.end())
115                overlays_s.erase(it);
116
117            Ogre::OverlayManager::getSingleton().destroyOverlayElement(this->background_);
118            Ogre::OverlayManager::getSingleton().destroy(this->overlay_);
119        }
120    }
121
122    /**
123    @brief
124        Loads the OrxonoxOverlay.
125
126        This has to be called before usage, otherwise strange behaviour is
127        guaranteed! (there should be no segfaults however).
128    @copydoc BaseObject::XMLPort()
129    */
130    void OrxonoxOverlay::XMLPort(Element& xmlelement, XMLPort::Mode mode)
131    {
132        SUPER(OrxonoxOverlay, XMLPort, xmlelement, mode);
133
134        XMLPortParam(OrxonoxOverlay, "size",      setSize,      getSize,      xmlelement, mode);
135        XMLPortParam(OrxonoxOverlay, "pickpoint", setPickPoint, getPickPoint, xmlelement, mode);
136        XMLPortParam(OrxonoxOverlay, "position",  setPosition,  getPosition,  xmlelement, mode);
137        XMLPortParam(OrxonoxOverlay, "rotation",  setRotation,  getRotation,  xmlelement, mode);
138        XMLPortParam(OrxonoxOverlay, "correctaspect", setAspectCorrection,   getAspectCorrection,   xmlelement, mode);
139        XMLPortParam(OrxonoxOverlay, "background",    setBackgroundMaterial, getBackgroundMaterial, xmlelement, mode);
140        XMLPortParam(OrxonoxOverlay, "backgroundtex", setBackgroundTexture,  getBackgroundTexture,  xmlelement, mode);
141    }
142
143    void OrxonoxOverlay::changedName()
144    {
145        SUPER(OrxonoxOverlay, changedName);
146
147        OrxonoxOverlay::overlays_s.erase(this->getOldName());
148
149        if (OrxonoxOverlay::overlays_s.find(this->getName()) != OrxonoxOverlay::overlays_s.end())
150            orxout(internal_warning) << "Overlay names should be unique or you cannnot access them via console. Name: \"" << this->getName() << '"' << endl;
151
152        OrxonoxOverlay::overlays_s[this->getName()] = this;
153    }
154
155    //! Only sets the background material name if not ""
156    void OrxonoxOverlay::setBackgroundMaterial(const std::string& material)
157    {
158        if (this->background_ && !material.empty())
159            this->background_->setMaterialName(material);
160    }
161
162    //! Returns the the material name of the background
163    const std::string& OrxonoxOverlay::getBackgroundMaterial() const
164    {
165        if (this->background_)
166            return this->background_->getMaterialName();
167        else
168            return BLANKSTRING;
169    }
170
171    //! Sets the background texture name and creates a new material if necessary
172    void OrxonoxOverlay::setBackgroundTexture(const std::string& texture)
173    {
174        if (this->background_ && this->background_->getMaterial().isNull() && !texture.empty())
175        {
176            // create new material
177            const std::string& materialname = "generated_material" + getUniqueNumberString();
178            Ogre::MaterialPtr material = static_cast<Ogre::MaterialPtr>(Ogre::MaterialManager::getSingleton().create(materialname, "General"));
179            material->getTechnique(0)->getPass(0)->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);
180            Ogre::TextureUnitState* textureUnitState_ = material->getTechnique(0)->getPass(0)->createTextureUnitState();
181            textureUnitState_->setTextureName(texture);
182            textureUnitState_->setNumMipmaps(0);
183            this->background_->setMaterialName(materialname);
184        }
185    }
186
187    //! Returns the the texture name of the background
188    const std::string& OrxonoxOverlay::getBackgroundTexture() const
189    {
190        if (this->background_)
191        {
192            Ogre::TextureUnitState* tempTx = this->background_->getMaterial()->getTechnique(0)->getPass(0)->getTextureUnitState(0);
193            return tempTx->getTextureName();
194        }
195        else
196            return BLANKSTRING;
197    }
198
199    //! Called by BaseObject when visibility has changed.
200    void OrxonoxOverlay::changedVisibility()
201    {
202        SUPER( OrxonoxOverlay, changedVisibility );
203
204        if (!this->overlay_)
205            return;
206
207        // only set to visible if corresponding OverlayGroup is also visible
208        if (this->isVisible() && (!this->getOverlayGroup() || this->getOverlayGroup()->isVisible()) )
209            this->overlay_->show();
210        else
211            this->overlay_->hide();
212    }
213
214    /**
215    @brief
216        Called by the GraphicsManager whenever the window size changes.
217        Calculates the aspect ratio only.
218    */
219    void OrxonoxOverlay::windowResized(unsigned int newWidth, unsigned int newHeight)
220    {
221        this->windowAspectRatio_ = static_cast<float>(newWidth) / newHeight;
222        this->sizeCorrectionChanged();
223    }
224
225    /**
226    @brief
227        Called whenever the rotation angle has changed.
228    */
229    void OrxonoxOverlay::angleChanged()
230    {
231        if (!this->overlay_)
232            return;
233
234        this->overlay_->setRotate(this->angle_);
235        this->sizeCorrectionChanged();
236    }
237
238    /**
239    @brief
240        Called whenever the aspect ratio or the angle has changed.
241        The method calculates a correction factor for the size to compensate
242        for aspect distortion if desired.
243    @remarks
244        This only works when the angle is about 0 or 90 degrees.
245    */
246    void OrxonoxOverlay::sizeCorrectionChanged()
247    {
248        if (this->bCorrectAspect_)
249        {
250            float angle = this->angle_.valueDegrees();
251            if (angle < 0.0)
252                angle = -angle;
253            angle -= 180.0f * static_cast<int>(angle / 180.0);
254
255            // take the reverse if angle is about 90 degrees
256            float tempAspect;
257            if (angle > 89.0f && angle < 91.0f)
258            {
259                tempAspect = 1.0f / this->windowAspectRatio_;
260                rotState_ = RotationState::Vertical;
261            }
262            else if (angle > 179 || angle < 1)
263            {
264                tempAspect = this->windowAspectRatio_;
265                rotState_ = RotationState::Horizontal;
266            }
267            else
268            {
269                tempAspect = 1.0f;
270                rotState_ = RotationState::Inbetween;
271            }
272
273            // note: this is only an approximation that is mostly valid when the
274            // magnitude of the width is about the magnitude of the height.
275            // Correctly we would have to take the square root of width*height
276            this->sizeCorrection_.x = 2.0f / (tempAspect + 1.0f);
277            this->sizeCorrection_.y = tempAspect * this->sizeCorrection_.x;
278        }
279        else
280        {
281            this->sizeCorrection_ = Vector2::UNIT_SCALE;
282        }
283
284        this->sizeChanged();
285    }
286
287    /**
288    @brief
289        Sets the overlay size using the actual corrected size.
290    */
291    void OrxonoxOverlay::sizeChanged()
292    {
293        if (!this->overlay_)
294            return;
295
296        this->overlay_->setScale(size_.x * sizeCorrection_.x, size_.y * sizeCorrection_.y);
297        positionChanged();
298    }
299
300    /**
301    @brief
302        Determines the position of the overlay.
303        This works also well when a rotation angle is applied. The overlay always
304        gets aligned correctly as well as possible.
305    */
306    void OrxonoxOverlay::positionChanged()
307    {
308        if (!this->overlay_)
309            return;
310
311        // transform the angle to a range of 0 - pi/2 first.
312        float angle = this->angle_.valueRadians();
313        if (angle < 0.0)
314            angle = -angle;
315        angle -= math::pi * static_cast<int>(angle / (math::pi));
316        if (angle > math::pi_2)
317            angle = math::pi - angle;
318
319        // do some mathematical fiddling for a bounding box
320        Vector2 actualSize = size_ * sizeCorrection_;
321        float radius = actualSize.length();
322        float phi = atan(actualSize.y / actualSize.x);
323        Vector2 boundingBox(radius * cos(angle - phi), radius * sin(angle + phi));
324
325        // calculate the scrolling offset
326        Vector2 scroll = (position_ - 0.5 - boundingBox * (pickPoint_ - 0.5)) * 2.0;
327        this->overlay_->setScroll(scroll.x, -scroll.y);
328    }
329
330
331    //########### Console commands ############
332
333    /**
334    @brief
335        Scales an overlay by its name.
336    @param name
337        The name of the overlay defined BaseObject::setName() (usually done with the "name"
338        attribute in the xml file).
339    @param scale
340        The scaling factor
341    */
342    /*static*/ void OrxonoxOverlay::scaleOverlay(const std::string& name, float scale)
343    {
344        std::map<std::string, OrxonoxOverlay*>::const_iterator it = overlays_s.find(name);
345        if (it != overlays_s.end())
346            it->second->scale(Vector2(scale, scale));
347    }
348
349    /**
350    @brief
351        Toggles the visibility of an Overlay by it's name.
352    @param name
353        The name of the overlay defined BaseObject::setName() (usually done with the "name"
354        attribute in the xml file).
355    */
356    /*static*/ void OrxonoxOverlay::toggleVisibility(const std::string& name)
357    {
358        std::map<std::string, OrxonoxOverlay*>::const_iterator it = overlays_s.find(name);
359        if (it != overlays_s.end())
360        {
361            OrxonoxOverlay* overlay= it->second;
362            if(overlay->isVisible())
363            {
364                overlay->hide();
365                orxout(verbose, context::misc::overlays) << "HIDE " << name << endl;
366            }
367            else
368            {
369                overlay->show();
370                orxout(verbose, context::misc::overlays) << "SHOW " << name << endl;
371            }
372        }
373    }
374   
375    /**
376    @brief
377        Shows Overlay by it's name.
378    @param name
379        The name of the overlay defined BaseObject::setName() (usually done with the "name"
380        attribute in the xml file).
381    */
382    /*static*/ void OrxonoxOverlay::showOverlay(const std::string& name)
383    {
384        std::map<std::string, OrxonoxOverlay*>::const_iterator it = overlays_s.find(name);
385        if (it != overlays_s.end())
386        {
387            OrxonoxOverlay* overlay= it->second;
388            if(overlay->isVisible())
389                overlay->changedVisibility();
390            else
391                overlay->show();
392        }
393    }
394
395    /**
396    @brief
397        Scrolls an overlay by its name.
398    @param name
399        The name of the overlay defined BaseObject::setName() (usually done with the "name"
400        attribute in the xml file).
401    @param scroll
402        The relative translation of the overlay
403    */
404    /*static*/ void OrxonoxOverlay::scrollOverlay(const std::string& name, const Vector2& scroll)
405    {
406        std::map<std::string, OrxonoxOverlay*>::const_iterator it = overlays_s.find(name);
407        if (it != overlays_s.end())
408            it->second->scroll(scroll);
409    }
410
411    /**
412    @brief
413        Rotates an overlay by its name.
414    @param name
415        The name of the overlay defined BaseObject::setName() (usually done with the "name"
416        attribute in the xml file).
417    @param angle
418        The rotation angle in degree
419    */
420    /*static*/ void OrxonoxOverlay::rotateOverlay(const std::string& name, const Degree& angle)
421    {
422        std::map<std::string, OrxonoxOverlay*>::const_iterator it = overlays_s.find(name);
423        if (it != overlays_s.end())
424            it->second->rotate(angle);
425    }
426
427    void OrxonoxOverlay::setOverlayGroup(OverlayGroup* group)
428    {
429        if (group != this->group_)
430        {
431            if (this->group_)
432                this->group_->removeElement(this);
433            this->group_ = group;
434            this->changedOverlayGroup();
435        }
436    }
437
438    void OrxonoxOverlay::setBackgroundAlpha(float alpha)
439    {
440        Ogre::MaterialPtr ptr = this->background_->getMaterial();
441        Ogre::TextureUnitState* tempTx = ptr->getTechnique(0)->getPass(0)->getTextureUnitState(0);
442        tempTx->setAlphaOperation(Ogre::LBX_MODULATE, Ogre::LBS_MANUAL, Ogre::LBS_CURRENT, alpha);
443    }
444
445    void OrxonoxOverlay::setBackgroundColour(ColourValue colour)
446    {
447        Ogre::MaterialPtr ptr = this->background_->getMaterial();
448        Ogre::TextureUnitState* tempTx = ptr->getTechnique(0)->getPass(0)->getTextureUnitState(0);
449        tempTx->setColourOperationEx(Ogre::LBX_MODULATE, Ogre::LBS_MANUAL, Ogre::LBS_CURRENT, colour);
450    }
451
452    void OrxonoxOverlay::setZOrder(unsigned short order)
453    {
454        if (this->overlay_)
455        {
456            this->overlay_->setZOrder(order);
457        }
458    }
459}
Note: See TracBrowser for help on using the repository browser.