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/Canvas.hxx>
21 #include <simgear/canvas/CanvasEventVisitor.hxx>
22 #include <simgear/canvas/events/MouseEvent.hxx>
23 #include <simgear/math/SGMisc.hxx>
24 #include <simgear/misc/strutils.hxx>
25 #include <simgear/scene/material/parseBlendFunc.hxx>
27 #include <osg/Drawable>
29 #include <osg/StateAttribute>
31 #include <boost/algorithm/string/predicate.hpp>
32 #include <boost/foreach.hpp>
33 #include <boost/make_shared.hpp>
43 const std::string NAME_TRANSFORM = "tf";
46 * glScissor with coordinates relative to different reference frames.
48 class Element::RelativeScissor:
49 public osg::StateAttribute
53 ReferenceFrame _coord_reference;
54 osg::observer_ptr<osg::Node> _node;
56 explicit RelativeScissor(osg::Node* node = NULL):
57 _coord_reference(GLOBAL),
67 /** Copy constructor using CopyOp to manage deep vs shallow copy. */
68 RelativeScissor( const RelativeScissor& vp,
69 const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY ):
70 StateAttribute(vp, copyop),
71 _coord_reference(vp._coord_reference),
79 META_StateAttribute(simgear, RelativeScissor, SCISSOR);
81 /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */
82 virtual int compare(const StateAttribute& sa) const
84 // check the types are equal and then create the rhs variable
85 // used by the COMPARE_StateAttribute_Parameter macros below.
86 COMPARE_StateAttribute_Types(RelativeScissor,sa)
88 // compare each parameter in turn against the rhs.
89 COMPARE_StateAttribute_Parameter(_x)
90 COMPARE_StateAttribute_Parameter(_y)
91 COMPARE_StateAttribute_Parameter(_width)
92 COMPARE_StateAttribute_Parameter(_height)
93 COMPARE_StateAttribute_Parameter(_coord_reference)
94 COMPARE_StateAttribute_Parameter(_node)
96 return 0; // passed all the above comparison macros, must be equal.
99 virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const
101 usage.usesMode(GL_SCISSOR_TEST);
105 inline float& x() { return _x; }
106 inline float x() const { return _x; }
108 inline float& y() { return _y; }
109 inline float y() const { return _y; }
111 inline float& width() { return _width; }
112 inline float width() const { return _width; }
114 inline float& height() { return _height; }
115 inline float height() const { return _height; }
117 virtual void apply(osg::State& state) const
119 if( _width <= 0 || _height <= 0 )
122 const osg::Viewport* vp = state.getCurrentViewport();
123 float w2 = 0.5 * vp->width(),
124 h2 = 0.5 * vp->height();
126 osg::Matrix model_view
133 model_view.preMult(state.getProjectionMatrix());
135 if( _coord_reference != GLOBAL )
137 osg::Node* ref_obj = _node.get();
139 if( _coord_reference == PARENT )
141 if( _node->getNumParents() < 1 )
143 SG_LOG(SG_GL, SG_WARN, "RelativeScissor: missing parent.");
147 ref_obj = _node->getParent(0);
150 osg::MatrixList const& parent_matrices = ref_obj->getWorldMatrices();
151 assert( !parent_matrices.empty() );
152 model_view.preMult(parent_matrices.front());
155 const osg::Vec2 scale( model_view(0,0), model_view(1,1)),
156 offset(model_view(3,0), model_view(3,1));
158 // TODO check/warn for rotation?
159 GLint x = SGMiscf::roundToInt(scale.x() * _x + offset.x()),
160 y = SGMiscf::roundToInt(scale.y() * _y + offset.y()),
161 w = SGMiscf::roundToInt(std::fabs(scale.x()) * _width),
162 h = SGMiscf::roundToInt(std::fabs(scale.y()) * _height);
169 glScissor(x, y, w, h);
172 bool contains(const osg::Vec2f& pos) const
174 return _x <= pos.x() && pos.x() <= _x + _width
175 && _y <= pos.y() && pos.y() <= _y + _height;
178 bool contains( const osg::Vec2f& global_pos,
179 const osg::Vec2f& parent_pos,
180 const osg::Vec2f& local_pos ) const
182 switch( _coord_reference )
184 case GLOBAL: return contains(global_pos);
185 case PARENT: return contains(parent_pos);
186 case LOCAL: return contains(local_pos);
199 //----------------------------------------------------------------------------
200 Element::OSGUserData::OSGUserData(ElementPtr element):
206 //----------------------------------------------------------------------------
209 if( !_transform.valid() )
212 for(unsigned int i = 0; i < _transform->getNumChildren(); ++i)
215 static_cast<OSGUserData*>(_transform->getChild(i)->getUserData());
218 // Ensure parent is cleared to prevent accessing released memory if an
219 // element somehow survives longer than his parent.
220 ud->element->_parent = 0;
224 //----------------------------------------------------------------------------
225 void Element::onDestroy()
227 if( !_transform.valid() )
230 // The transform node keeps a reference on this element, so ensure it is
232 BOOST_FOREACH(osg::Group* parent, _transform->getParents())
234 parent->removeChild(_transform.get());
237 // Hide in case someone still holds a reference
245 //----------------------------------------------------------------------------
246 ElementPtr Element::getParent() const
251 //----------------------------------------------------------------------------
252 CanvasWeakPtr Element::getCanvas() const
257 //----------------------------------------------------------------------------
258 void Element::update(double dt)
263 // Trigger matrix update
266 // Update bounding box on manual update (manual updates pass zero dt)
267 if( dt == 0 && _drawable )
268 _drawable->getBound();
270 if( (_attributes_dirty & BLEND_FUNC) && _transform.valid() )
273 _transform->getOrCreateStateSet(),
274 _node->getChild("blend-source"),
275 _node->getChild("blend-destination"),
276 _node->getChild("blend-source-rgb"),
277 _node->getChild("blend-destination-rgb"),
278 _node->getChild("blend-source-alpha"),
279 _node->getChild("blend-destination-alpha")
281 _attributes_dirty &= ~BLEND_FUNC;
285 //----------------------------------------------------------------------------
286 bool Element::addEventListener( const std::string& type_str,
287 const EventListener& cb )
293 "addEventListener(" << _node->getPath() << ", " << type_str << ")"
296 _listener[ Event::getOrRegisterType(type_str) ].push_back(cb);
300 //----------------------------------------------------------------------------
301 void Element::clearEventListener()
306 //----------------------------------------------------------------------------
307 bool Element::accept(EventVisitor& visitor)
312 return visitor.apply(*this);
315 //----------------------------------------------------------------------------
316 bool Element::ascend(EventVisitor& visitor)
319 return _parent->accept(visitor);
323 //----------------------------------------------------------------------------
324 bool Element::traverse(EventVisitor& visitor)
329 //----------------------------------------------------------------------------
330 bool Element::handleEvent(const EventPtr& event)
332 ListenerMap::iterator listeners = _listener.find(event->getType());
333 if( listeners == _listener.end() )
336 BOOST_FOREACH(EventListener const& listener, listeners->second)
341 catch( std::exception const& ex )
346 "canvas::Element: event handler error: '" << ex.what() << "'"
353 //----------------------------------------------------------------------------
354 bool Element::dispatchEvent(const EventPtr& event)
356 EventPropagationPath path;
357 path.push_back( EventTarget(this) );
359 for( Element* parent = _parent;
361 parent = parent->_parent )
362 path.push_front( EventTarget(parent) );
364 CanvasPtr canvas = _canvas.lock();
368 return canvas->propagateEvent(event, path);
371 //----------------------------------------------------------------------------
372 bool Element::hitBound( const osg::Vec2f& global_pos,
373 const osg::Vec2f& parent_pos,
374 const osg::Vec2f& local_pos ) const
376 if( _scissor && !_scissor->contains(global_pos, parent_pos, local_pos) )
379 const osg::Vec3f pos3(parent_pos, 0);
381 // Drawables have a bounding box...
383 return _drawable->getBound().contains(osg::Vec3f(local_pos, 0));
384 else if( _transform.valid() )
385 // ... for other elements, i.e. groups only a bounding sphere is available
386 return _transform->getBound().contains(osg::Vec3f(parent_pos, 0));
392 //----------------------------------------------------------------------------
393 void Element::setVisible(bool visible)
395 if( _transform.valid() )
396 // TODO check if we need another nodemask
397 _transform->setNodeMask(visible ? 0xffffffff : 0);
400 //----------------------------------------------------------------------------
401 bool Element::isVisible() const
403 return _transform.valid() && _transform->getNodeMask() != 0;
406 //----------------------------------------------------------------------------
407 osg::MatrixTransform* Element::getMatrixTransform()
409 return _transform.get();
412 //----------------------------------------------------------------------------
413 osg::MatrixTransform const* Element::getMatrixTransform() const
415 return _transform.get();
418 //----------------------------------------------------------------------------
419 osg::Vec2f Element::posToLocal(const osg::Vec2f& pos) const
422 const osg::Matrix& m = _transform->getInverseMatrix();
425 m(0, 0) * pos[0] + m(1, 0) * pos[1] + m(3, 0),
426 m(0, 1) * pos[0] + m(1, 1) * pos[1] + m(3, 1)
430 //----------------------------------------------------------------------------
431 void Element::childAdded(SGPropertyNode* parent, SGPropertyNode* child)
434 && child->getNameString() == NAME_TRANSFORM )
436 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
437 _transform_types.resize( child->getIndex() + 1 );
439 _transform_types[ child->getIndex() ] = TT_NONE;
440 _attributes_dirty |= TRANSFORM;
443 else if( parent->getParent() == _node
444 && parent->getNameString() == NAME_TRANSFORM )
446 assert(parent->getIndex() < static_cast<int>(_transform_types.size()));
448 const std::string& name = child->getNameString();
450 TransformType& type = _transform_types[parent->getIndex()];
454 else if( name == "t" )
456 else if( name == "rot" )
458 else if( name == "s" )
461 _attributes_dirty |= TRANSFORM;
468 //----------------------------------------------------------------------------
469 void Element::childRemoved(SGPropertyNode* parent, SGPropertyNode* child)
471 if( parent == _node )
473 if( child->getNameString() == NAME_TRANSFORM )
475 if( !_transform.valid() )
478 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
484 "Element::childRemoved: unknown transform: " << child->getPath()
489 _transform_types[ child->getIndex() ] = TT_NONE;
491 while( !_transform_types.empty() && _transform_types.back() == TT_NONE )
492 _transform_types.pop_back();
494 _attributes_dirty |= TRANSFORM;
497 else if( StyleInfo const* style = getStyleInfo(child->getNameString()) )
499 if( setStyle(getParentStyle(child), style) )
507 //----------------------------------------------------------------------------
508 void Element::valueChanged(SGPropertyNode* child)
510 SGPropertyNode *parent = child->getParent();
511 if( parent == _node )
513 const std::string& name = child->getNameString();
514 if( boost::starts_with(name, "data-") )
516 else if( StyleInfo const* style_info = getStyleInfo(name) )
518 SGPropertyNode const* style = child;
519 if( isStyleEmpty(child) )
522 style = getParentStyle(child);
524 setStyle(style, style_info);
527 else if( name == "update" )
529 else if( boost::starts_with(name, "blend-") )
530 return (void)(_attributes_dirty |= BLEND_FUNC);
533 && parent->getParent() == _node
534 && parent->getNameString() == NAME_TRANSFORM )
536 _attributes_dirty |= TRANSFORM;
543 //----------------------------------------------------------------------------
544 bool Element::setStyle( const SGPropertyNode* child,
545 const StyleInfo* style_info )
547 return canApplyStyle(child) && setStyleImpl(child, style_info);
550 //----------------------------------------------------------------------------
551 void Element::setClip(const std::string& clip)
553 osg::StateSet* ss = getOrCreateStateSet();
557 if( clip.empty() || clip == "auto" )
559 ss->removeAttribute(osg::StateAttribute::SCISSOR);
564 // TODO generalize CSS property parsing
565 const std::string RECT("rect(");
566 if( !boost::ends_with(clip, ")")
567 || !boost::starts_with(clip, RECT) )
569 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
573 const std::string sep(", \t\npx");
577 for(size_t pos = RECT.size(); comp < 4; ++comp)
579 pos = clip.find_first_not_of(sep, pos);
580 if( pos == std::string::npos || pos == clip.size() - 1 )
584 values[comp] = strtod(&clip[pos], &end);
585 if( end == &clip[pos] || !end )
588 pos = end - &clip[0];
593 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
597 float width = values[1] - values[3],
598 height = values[2] - values[0];
600 if( width < 0 || height < 0 )
602 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: negative clip size: " << clip);
607 _scissor = new RelativeScissor(_transform.get());
609 // <top>, <right>, <bottom>, <left>
610 _scissor->x() = values[3];
611 _scissor->y() = values[0];
612 _scissor->width() = width;
613 _scissor->height() = height;
615 SGPropertyNode* clip_frame = _node->getChild("clip-frame", 0);
617 valueChanged(clip_frame);
619 _scissor->_coord_reference = GLOBAL;
621 ss->setAttributeAndModes(_scissor);
624 //----------------------------------------------------------------------------
625 void Element::setClipFrame(ReferenceFrame rf)
628 _scissor->_coord_reference = rf;
631 //----------------------------------------------------------------------------
632 osg::BoundingBox Element::getBoundingBox() const
635 return _drawable->getBound();
639 if( _transform.valid() )
640 bb.expandBy(_transform->getBound());
645 //----------------------------------------------------------------------------
646 osg::BoundingBox Element::getTightBoundingBox() const
648 return getTransformedBounds(getMatrix());
651 //----------------------------------------------------------------------------
652 osg::BoundingBox Element::getTransformedBounds(const osg::Matrix& m) const
655 return osg::BoundingBox();
657 osg::BoundingBox transformed;
658 const osg::BoundingBox& bb = _drawable->getBound();
659 for(int i = 0; i < 4; ++i)
660 transformed.expandBy( bb.corner(i) * m );
665 //----------------------------------------------------------------------------
666 osg::Matrix Element::getMatrix() const
669 return osg::Matrix::identity();
671 if( !(_attributes_dirty & TRANSFORM) )
672 return _transform->getMatrix();
675 for( size_t i = 0; i < _transform_types.size(); ++i )
677 // Skip unused indizes...
678 if( _transform_types[i] == TT_NONE )
681 SGPropertyNode* tf_node = _node->getChild("tf", i, true);
683 // Build up the matrix representation of the current transform node
685 switch( _transform_types[i] )
688 tf = osg::Matrix( tf_node->getDoubleValue("m[0]", 1),
689 tf_node->getDoubleValue("m[1]", 0),
691 tf_node->getDoubleValue("m[6]", 0),
693 tf_node->getDoubleValue("m[2]", 0),
694 tf_node->getDoubleValue("m[3]", 1),
696 tf_node->getDoubleValue("m[7]", 0),
703 tf_node->getDoubleValue("m[4]", 0),
704 tf_node->getDoubleValue("m[5]", 0),
706 tf_node->getDoubleValue("m[8]", 1) );
709 tf.makeTranslate( osg::Vec3f( tf_node->getDoubleValue("t[0]", 0),
710 tf_node->getDoubleValue("t[1]", 0),
714 tf.makeRotate( tf_node->getDoubleValue("rot", 0), 0, 0, 1 );
718 float sx = tf_node->getDoubleValue("s[0]", 1);
719 // sy defaults to sx...
720 tf.makeScale( sx, tf_node->getDoubleValue("s[1]", sx), 1 );
728 _transform->setMatrix(m);
729 _attributes_dirty &= ~TRANSFORM;
734 //----------------------------------------------------------------------------
735 Element::StyleSetters Element::_style_setters;
737 //----------------------------------------------------------------------------
738 Element::Element( const CanvasWeakPtr& canvas,
739 const SGPropertyNode_ptr& node,
740 const Style& parent_style,
742 PropertyBasedElement(node),
745 _attributes_dirty( 0 ),
746 _transform( new osg::MatrixTransform ),
747 _style( parent_style ),
757 "New canvas element " << node->getPath()
760 // Ensure elements are drawn in order they appear in the element tree
761 _transform->getOrCreateStateSet()
762 ->setRenderBinDetails
766 osg::StateSet::OVERRIDE_RENDERBIN_DETAILS
769 _transform->setUserData( new OSGUserData(this) );
772 //----------------------------------------------------------------------------
773 void Element::staticInit()
775 if( isInit<Element>() )
778 addStyle("clip", "", &Element::setClip, false);
779 addStyle("clip-frame", "", &Element::setClipFrame, false);
780 addStyle("visible", "", &Element::setVisible, false);
783 //----------------------------------------------------------------------------
784 bool Element::isStyleEmpty(const SGPropertyNode* child) const
787 || simgear::strutils::strip(child->getStringValue()).empty();
790 //----------------------------------------------------------------------------
791 bool Element::canApplyStyle(const SGPropertyNode* child) const
793 if( _node == child->getParent() )
796 // Parent values do not override if element has own value
797 return isStyleEmpty( _node->getChild(child->getName()) );
800 //----------------------------------------------------------------------------
801 bool Element::setStyleImpl( const SGPropertyNode* child,
802 const StyleInfo* style_info )
804 const StyleSetter* style_setter = style_info
805 ? &style_info->setter
806 : getStyleSetter(child->getNameString());
807 while( style_setter )
809 if( style_setter->func(*this, child) )
811 style_setter = style_setter->next;
816 //----------------------------------------------------------------------------
817 const Element::StyleInfo*
818 Element::getStyleInfo(const std::string& name) const
820 StyleSetters::const_iterator setter = _style_setters.find(name);
821 if( setter == _style_setters.end() )
824 return &setter->second;
827 //----------------------------------------------------------------------------
828 const Element::StyleSetter*
829 Element::getStyleSetter(const std::string& name) const
831 const StyleInfo* info = getStyleInfo(name);
832 return info ? &info->setter : 0;
835 //----------------------------------------------------------------------------
836 const SGPropertyNode*
837 Element::getParentStyle(const SGPropertyNode* child) const
839 // Try to get value from parent...
842 Style::const_iterator style =
843 _parent->_style.find(child->getNameString());
844 if( style != _parent->_style.end() )
845 return style->second;
848 // ...or reset to default if none is available
849 return child; // TODO somehow get default value for each style?
852 //----------------------------------------------------------------------------
853 void Element::setDrawable( osg::Drawable* drawable )
855 _drawable = drawable;
858 osg::ref_ptr<osg::Geode> geode = new osg::Geode;
859 geode->addDrawable(_drawable);
860 _transform->addChild(geode);
863 //----------------------------------------------------------------------------
864 osg::StateSet* Element::getOrCreateStateSet()
866 if( _drawable.valid() )
867 return _drawable->getOrCreateStateSet();
868 if( _transform.valid() )
869 return _transform->getOrCreateStateSet();
874 //----------------------------------------------------------------------------
875 void Element::setupStyle()
877 BOOST_FOREACH( Style::value_type style, _style )
878 setStyle(style.second);
881 } // namespace canvas
882 } // namespace simgear