1 // Interface for 2D Canvas element
3 // Copyright (C) 2012 Thomas Geymayer <tomgey@gmail.com>
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Library General Public
7 // License as published by the Free Software Foundation; either
8 // version 2 of the License, or (at your option) any later version.
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 // Library General Public License for more details.
15 // You should have received a copy of the GNU Library General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 #include "CanvasElement.hxx"
20 #include <simgear/canvas/CanvasEventVisitor.hxx>
21 #include <simgear/canvas/MouseEvent.hxx>
22 #include <simgear/math/SGMisc.hxx>
23 #include <simgear/misc/strutils.hxx>
24 #include <simgear/scene/material/parseBlendFunc.hxx>
26 #include <osg/Drawable>
28 #include <osg/Scissor>
30 #include <boost/algorithm/string/predicate.hpp>
31 #include <boost/foreach.hpp>
32 #include <boost/make_shared.hpp>
42 const std::string NAME_TRANSFORM = "tf";
45 * glScissor with coordinates relative to different reference frames.
47 class Element::RelativeScissor:
52 ReferenceFrame _coord_reference;
53 osg::Matrix _parent_inverse;
56 _coord_reference(GLOBAL)
59 bool contains(const osg::Vec2f& pos) const
61 return _x <= pos.x() && pos.x() <= _x + _width
62 && _y <= pos.y() && pos.y() <= _y + _height;
65 bool contains( const osg::Vec2f& global_pos,
66 const osg::Vec2f& parent_pos,
67 const osg::Vec2f& local_pos ) const
69 switch( _coord_reference )
71 case GLOBAL: return contains(global_pos);
72 case PARENT: return contains(parent_pos);
73 case LOCAL: return contains(local_pos);
79 virtual void apply(osg::State& state) const
81 const osg::Viewport* vp = state.getCurrentViewport();
82 float w2 = 0.5 * vp->width(),
83 h2 = 0.5 * vp->height();
85 osg::Matrix model_view
92 model_view.preMult(state.getProjectionMatrix());
94 if( _coord_reference != GLOBAL )
96 model_view.preMult(state.getModelViewMatrix());
98 if( _coord_reference == PARENT )
99 model_view.preMult(_parent_inverse);
102 const osg::Vec2 scale( model_view(0,0), model_view(1,1)),
103 offset(model_view(3,0), model_view(3,1));
105 // TODO check/warn for rotation?
107 GLint x = SGMiscf::roundToInt(scale.x() * _x + offset.x()),
108 y = SGMiscf::roundToInt(scale.y() * _y + offset.y()),
109 w = SGMiscf::roundToInt(std::fabs(scale.x()) * _width),
110 h = SGMiscf::roundToInt(std::fabs(scale.y()) * _height);
117 glScissor(x, y, w, h);
121 //----------------------------------------------------------------------------
122 Element::OSGUserData::OSGUserData(ElementPtr element):
128 //----------------------------------------------------------------------------
131 if( !_transform.valid() )
134 for(unsigned int i = 0; i < _transform->getNumChildren(); ++i)
137 static_cast<OSGUserData*>(_transform->getChild(i)->getUserData());
140 // Ensure parent is cleared to prevent accessing released memory if an
141 // element somehow survives longer than his parent.
142 ud->element->_parent = 0;
146 //----------------------------------------------------------------------------
147 void Element::setSelf(const PropertyBasedElementPtr& self)
149 PropertyBasedElement::setSelf(self);
151 _transform->setUserData
153 new OSGUserData(boost::static_pointer_cast<Element>(self))
157 //----------------------------------------------------------------------------
158 void Element::onDestroy()
160 if( !_transform.valid() )
163 // The transform node keeps a reference on this element, so ensure it is
165 BOOST_FOREACH(osg::Group* parent, _transform->getParents())
167 parent->removeChild(_transform.get());
171 //----------------------------------------------------------------------------
172 ElementWeakPtr Element::getWeakPtr() const
174 return boost::static_pointer_cast<Element>(_self.lock());
177 //----------------------------------------------------------------------------
178 ElementPtr Element::getParent()
180 return _parent ? _parent->getWeakPtr().lock() : ElementPtr();
183 //----------------------------------------------------------------------------
184 void Element::update(double dt)
189 // Trigger matrix update
192 // TODO limit bounding box to scissor
193 if( _attributes_dirty & SCISSOR_COORDS )
195 if( _scissor && _scissor->_coord_reference != GLOBAL )
196 _scissor->_parent_inverse = _transform->getInverseMatrix();
198 _attributes_dirty &= ~SCISSOR_COORDS;
201 // Update bounding box on manual update (manual updates pass zero dt)
202 if( dt == 0 && _drawable )
203 _drawable->getBound();
205 if( _attributes_dirty & BLEND_FUNC )
208 _transform->getOrCreateStateSet(),
209 _node->getChild("blend-source"),
210 _node->getChild("blend-destination"),
211 _node->getChild("blend-source-rgb"),
212 _node->getChild("blend-destination-rgb"),
213 _node->getChild("blend-source-alpha"),
214 _node->getChild("blend-destination-alpha")
216 _attributes_dirty &= ~BLEND_FUNC;
220 //----------------------------------------------------------------------------
221 bool Element::addEventListener( const std::string& type_str,
222 const EventListener& cb )
228 "addEventListener(" << _node->getPath() << ", " << type_str << ")"
231 Event::Type type = Event::strToType(type_str);
232 if( type == Event::UNKNOWN )
236 "addEventListener: Unknown event type " << type_str );
240 _listener[ type ].push_back(cb);
245 //----------------------------------------------------------------------------
246 void Element::clearEventListener()
251 //----------------------------------------------------------------------------
252 bool Element::accept(EventVisitor& visitor)
257 return visitor.apply(*this);
260 //----------------------------------------------------------------------------
261 bool Element::ascend(EventVisitor& visitor)
264 return _parent->accept(visitor);
268 //----------------------------------------------------------------------------
269 bool Element::traverse(EventVisitor& visitor)
274 //----------------------------------------------------------------------------
275 bool Element::handleEvent(canvas::EventPtr event)
277 ListenerMap::iterator listeners = _listener.find(event->getType());
278 if( listeners == _listener.end() )
281 BOOST_FOREACH(EventListener const& listener, listeners->second)
287 //----------------------------------------------------------------------------
288 bool Element::hitBound( const osg::Vec2f& global_pos,
289 const osg::Vec2f& parent_pos,
290 const osg::Vec2f& local_pos ) const
292 if( _scissor && !_scissor->contains(global_pos, parent_pos, local_pos) )
295 const osg::Vec3f pos3(parent_pos, 0);
297 // Drawables have a bounding box...
299 return _drawable->getBound().contains(osg::Vec3f(local_pos, 0));
300 else if( _transform.valid() )
301 // ... for other elements, i.e. groups only a bounding sphere is available
302 return _transform->getBound().contains(osg::Vec3f(parent_pos, 0));
308 //----------------------------------------------------------------------------
309 void Element::setVisible(bool visible)
311 if( _transform.valid() )
312 // TODO check if we need another nodemask
313 _transform->setNodeMask(visible ? 0xffffffff : 0);
316 //----------------------------------------------------------------------------
317 bool Element::isVisible() const
319 return _transform.valid() && _transform->getNodeMask() != 0;
322 //----------------------------------------------------------------------------
323 osg::MatrixTransform* Element::getMatrixTransform()
325 return _transform.get();
328 //----------------------------------------------------------------------------
329 osg::MatrixTransform const* Element::getMatrixTransform() const
331 return _transform.get();
334 //----------------------------------------------------------------------------
335 osg::Vec2f Element::posToLocal(const osg::Vec2f& pos) const
338 const osg::Matrix& m = _transform->getInverseMatrix();
341 m(0, 0) * pos[0] + m(1, 0) * pos[1] + m(3, 0),
342 m(0, 1) * pos[0] + m(1, 1) * pos[1] + m(3, 1)
346 //----------------------------------------------------------------------------
347 void Element::childAdded(SGPropertyNode* parent, SGPropertyNode* child)
350 && child->getNameString() == NAME_TRANSFORM )
352 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
353 _transform_types.resize( child->getIndex() + 1 );
355 _transform_types[ child->getIndex() ] = TT_NONE;
356 _attributes_dirty |= TRANSFORM;
359 else if( parent->getParent() == _node
360 && parent->getNameString() == NAME_TRANSFORM )
362 assert(parent->getIndex() < static_cast<int>(_transform_types.size()));
364 const std::string& name = child->getNameString();
366 TransformType& type = _transform_types[parent->getIndex()];
370 else if( name == "t" )
372 else if( name == "rot" )
374 else if( name == "s" )
377 _attributes_dirty |= TRANSFORM;
384 //----------------------------------------------------------------------------
385 void Element::childRemoved(SGPropertyNode* parent, SGPropertyNode* child)
387 if( parent == _node )
389 if( child->getNameString() == NAME_TRANSFORM )
391 if( !_transform.valid() )
394 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
400 "Element::childRemoved: unknown transform: " << child->getPath()
405 _transform_types[ child->getIndex() ] = TT_NONE;
407 while( !_transform_types.empty() && _transform_types.back() == TT_NONE )
408 _transform_types.pop_back();
410 _attributes_dirty |= TRANSFORM;
413 else if( StyleInfo const* style = getStyleInfo(child->getNameString()) )
415 if( setStyle(getParentStyle(child), style) )
423 //----------------------------------------------------------------------------
424 void Element::valueChanged(SGPropertyNode* child)
426 SGPropertyNode *parent = child->getParent();
427 if( parent == _node )
429 const std::string& name = child->getNameString();
430 if( StyleInfo const* style_info = getStyleInfo(name) )
432 SGPropertyNode const* style = child;
433 if( isStyleEmpty(child) )
436 style = getParentStyle(child);
438 setStyle(style, style_info);
441 else if( name == "update" )
443 else if( boost::starts_with(name, "blend-") )
444 return (void)(_attributes_dirty |= BLEND_FUNC);
446 else if( parent->getParent() == _node
447 && parent->getNameString() == NAME_TRANSFORM )
449 _attributes_dirty |= TRANSFORM;
456 //----------------------------------------------------------------------------
457 bool Element::setStyle( const SGPropertyNode* child,
458 const StyleInfo* style_info )
460 return canApplyStyle(child) && setStyleImpl(child, style_info);
463 //----------------------------------------------------------------------------
464 void Element::setClip(const std::string& clip)
466 if( clip.empty() || clip == "auto" )
468 getOrCreateStateSet()->removeAttribute(osg::StateAttribute::SCISSOR);
473 // TODO generalize CSS property parsing
474 const std::string RECT("rect(");
475 if( !boost::ends_with(clip, ")")
476 || !boost::starts_with(clip, RECT) )
478 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
482 const std::string sep(", \t\npx");
486 for(size_t pos = RECT.size(); comp < 4; ++comp)
488 pos = clip.find_first_not_of(sep, pos);
489 if( pos == std::string::npos || pos == clip.size() - 1 )
493 values[comp] = strtod(&clip[pos], &end);
494 if( end == &clip[pos] || !end )
497 pos = end - &clip[0];
502 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
506 float width = values[1] - values[3],
507 height = values[2] - values[0];
509 if( width < 0 || height < 0 )
511 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: negative clip size: " << clip);
515 _scissor = new RelativeScissor();
516 // <top>, <right>, <bottom>, <left>
517 _scissor->x() = SGMiscf::roundToInt(values[3]);
518 _scissor->y() = SGMiscf::roundToInt(values[0]);
519 _scissor->width() = SGMiscf::roundToInt(width);
520 _scissor->height() = SGMiscf::roundToInt(height);
522 getOrCreateStateSet()->setAttributeAndModes(_scissor);
524 SGPropertyNode* clip_frame = _node->getChild("clip-frame", 0);
526 valueChanged(clip_frame);
529 //----------------------------------------------------------------------------
530 void Element::setClipFrame(ReferenceFrame rf)
534 _scissor->_coord_reference = rf;
535 _attributes_dirty |= SCISSOR_COORDS;
539 //----------------------------------------------------------------------------
540 osg::BoundingBox Element::getBoundingBox() const
543 return _drawable->getBound();
547 if( _transform.valid() )
548 bb.expandBy(_transform->getBound());
553 //----------------------------------------------------------------------------
554 osg::BoundingBox Element::getTightBoundingBox() const
556 return getTransformedBounds(getMatrix());
559 //----------------------------------------------------------------------------
560 osg::BoundingBox Element::getTransformedBounds(const osg::Matrix& m) const
563 return osg::BoundingBox();
565 osg::BoundingBox transformed;
566 const osg::BoundingBox& bb = _drawable->getBound();
567 for(int i = 0; i < 4; ++i)
568 transformed.expandBy( bb.corner(i) * m );
573 //----------------------------------------------------------------------------
574 osg::Matrix Element::getMatrix() const
577 return osg::Matrix::identity();
579 if( !(_attributes_dirty & TRANSFORM) )
580 return _transform->getMatrix();
583 for( size_t i = 0; i < _transform_types.size(); ++i )
585 // Skip unused indizes...
586 if( _transform_types[i] == TT_NONE )
589 SGPropertyNode* tf_node = _node->getChild("tf", i, true);
591 // Build up the matrix representation of the current transform node
593 switch( _transform_types[i] )
596 tf = osg::Matrix( tf_node->getDoubleValue("m[0]", 1),
597 tf_node->getDoubleValue("m[1]", 0),
599 tf_node->getDoubleValue("m[6]", 0),
601 tf_node->getDoubleValue("m[2]", 0),
602 tf_node->getDoubleValue("m[3]", 1),
604 tf_node->getDoubleValue("m[7]", 0),
611 tf_node->getDoubleValue("m[4]", 0),
612 tf_node->getDoubleValue("m[5]", 0),
614 tf_node->getDoubleValue("m[8]", 1) );
617 tf.makeTranslate( osg::Vec3f( tf_node->getDoubleValue("t[0]", 0),
618 tf_node->getDoubleValue("t[1]", 0),
622 tf.makeRotate( tf_node->getDoubleValue("rot", 0), 0, 0, 1 );
626 float sx = tf_node->getDoubleValue("s[0]", 1);
627 // sy defaults to sx...
628 tf.makeScale( sx, tf_node->getDoubleValue("s[1]", sx), 1 );
636 _transform->setMatrix(m);
637 _attributes_dirty &= ~TRANSFORM;
638 _attributes_dirty |= SCISSOR_COORDS;
643 //----------------------------------------------------------------------------
644 Element::StyleSetters Element::_style_setters;
646 //----------------------------------------------------------------------------
647 Element::Element( const CanvasWeakPtr& canvas,
648 const SGPropertyNode_ptr& node,
649 const Style& parent_style,
651 PropertyBasedElement(node),
654 _attributes_dirty( 0 ),
655 _transform( new osg::MatrixTransform ),
656 _style( parent_style ),
666 "New canvas element " << node->getPath()
669 // Ensure elements are drawn in order they appear in the element tree
670 _transform->getOrCreateStateSet()
671 ->setRenderBinDetails
675 osg::StateSet::OVERRIDE_RENDERBIN_DETAILS
679 //----------------------------------------------------------------------------
680 void Element::staticInit()
682 if( isInit<Element>() )
685 addStyle("clip", "", &Element::setClip, false);
686 addStyle("clip-frame", "", &Element::setClipFrame, false);
687 addStyle("visible", "", &Element::setVisible, false);
690 //----------------------------------------------------------------------------
691 bool Element::isStyleEmpty(const SGPropertyNode* child) const
694 || simgear::strutils::strip(child->getStringValue()).empty();
697 //----------------------------------------------------------------------------
698 bool Element::canApplyStyle(const SGPropertyNode* child) const
700 if( _node == child->getParent() )
703 // Parent values do not override if element has own value
704 return isStyleEmpty( _node->getChild(child->getName()) );
707 //----------------------------------------------------------------------------
708 bool Element::setStyleImpl( const SGPropertyNode* child,
709 const StyleInfo* style_info )
711 const StyleSetter* style_setter = style_info
712 ? &style_info->setter
713 : getStyleSetter(child->getNameString());
714 while( style_setter )
716 if( style_setter->func(*this, child) )
718 style_setter = style_setter->next;
723 //----------------------------------------------------------------------------
724 const Element::StyleInfo*
725 Element::getStyleInfo(const std::string& name) const
727 StyleSetters::const_iterator setter = _style_setters.find(name);
728 if( setter == _style_setters.end() )
731 return &setter->second;
734 //----------------------------------------------------------------------------
735 const Element::StyleSetter*
736 Element::getStyleSetter(const std::string& name) const
738 const StyleInfo* info = getStyleInfo(name);
739 return info ? &info->setter : 0;
742 //----------------------------------------------------------------------------
743 const SGPropertyNode*
744 Element::getParentStyle(const SGPropertyNode* child) const
746 // Try to get value from parent...
749 Style::const_iterator style =
750 _parent->_style.find(child->getNameString());
751 if( style != _parent->_style.end() )
752 return style->second;
755 // ...or reset to default if none is available
756 return child; // TODO somehow get default value for each style?
759 //----------------------------------------------------------------------------
760 void Element::setDrawable( osg::Drawable* drawable )
762 _drawable = drawable;
765 osg::ref_ptr<osg::Geode> geode = new osg::Geode;
766 geode->addDrawable(_drawable);
767 _transform->addChild(geode);
770 //----------------------------------------------------------------------------
771 osg::StateSet* Element::getOrCreateStateSet()
773 return _drawable ? _drawable->getOrCreateStateSet()
774 : _transform->getOrCreateStateSet();
777 //----------------------------------------------------------------------------
778 void Element::setupStyle()
780 BOOST_FOREACH( Style::value_type style, _style )
781 setStyle(style.second);
784 } // namespace canvas
785 } // namespace simgear