Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/archive/waypoints/src/orxonox/overlays/OrxonoxOverlay.cc @ 11360

Last change on this file since 11360 was 9159, checked in by scmoritz, 13 years ago

3DScene added. creation of the arrow doesnt work.

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