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/Scissor>
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:
53 ReferenceFrame _coord_reference;
54 osg::Matrix _parent_inverse;
57 _coord_reference(GLOBAL)
60 bool contains(const osg::Vec2f& pos) const
62 return _x <= pos.x() && pos.x() <= _x + _width
63 && _y <= pos.y() && pos.y() <= _y + _height;
66 bool contains( const osg::Vec2f& global_pos,
67 const osg::Vec2f& parent_pos,
68 const osg::Vec2f& local_pos ) const
70 switch( _coord_reference )
72 case GLOBAL: return contains(global_pos);
73 case PARENT: return contains(parent_pos);
74 case LOCAL: return contains(local_pos);
80 virtual void apply(osg::State& state) const
82 const osg::Viewport* vp = state.getCurrentViewport();
83 float w2 = 0.5 * vp->width(),
84 h2 = 0.5 * vp->height();
86 osg::Matrix model_view
93 model_view.preMult(state.getProjectionMatrix());
95 if( _coord_reference != GLOBAL )
97 model_view.preMult(state.getModelViewMatrix());
99 if( _coord_reference == PARENT )
100 model_view.preMult(_parent_inverse);
103 const osg::Vec2 scale( model_view(0,0), model_view(1,1)),
104 offset(model_view(3,0), model_view(3,1));
106 // TODO check/warn for rotation?
108 GLint x = SGMiscf::roundToInt(scale.x() * _x + offset.x()),
109 y = SGMiscf::roundToInt(scale.y() * _y + offset.y()),
110 w = SGMiscf::roundToInt(std::fabs(scale.x()) * _width),
111 h = SGMiscf::roundToInt(std::fabs(scale.y()) * _height);
118 glScissor(x, y, w, h);
122 //----------------------------------------------------------------------------
123 Element::OSGUserData::OSGUserData(ElementPtr element):
129 //----------------------------------------------------------------------------
132 if( !_transform.valid() )
135 for(unsigned int i = 0; i < _transform->getNumChildren(); ++i)
138 static_cast<OSGUserData*>(_transform->getChild(i)->getUserData());
141 // Ensure parent is cleared to prevent accessing released memory if an
142 // element somehow survives longer than his parent.
143 ud->element->_parent = 0;
147 //----------------------------------------------------------------------------
148 void Element::onDestroy()
150 if( !_transform.valid() )
153 // The transform node keeps a reference on this element, so ensure it is
155 BOOST_FOREACH(osg::Group* parent, _transform->getParents())
157 parent->removeChild(_transform.get());
161 //----------------------------------------------------------------------------
162 ElementPtr Element::getParent()
167 //----------------------------------------------------------------------------
168 void Element::update(double dt)
173 // Trigger matrix update
176 // TODO limit bounding box to scissor
177 if( _attributes_dirty & SCISSOR_COORDS )
179 if( _scissor && _scissor->_coord_reference != GLOBAL )
180 _scissor->_parent_inverse = _transform->getInverseMatrix();
182 _attributes_dirty &= ~SCISSOR_COORDS;
185 // Update bounding box on manual update (manual updates pass zero dt)
186 if( dt == 0 && _drawable )
187 _drawable->getBound();
189 if( _attributes_dirty & BLEND_FUNC )
192 _transform->getOrCreateStateSet(),
193 _node->getChild("blend-source"),
194 _node->getChild("blend-destination"),
195 _node->getChild("blend-source-rgb"),
196 _node->getChild("blend-destination-rgb"),
197 _node->getChild("blend-source-alpha"),
198 _node->getChild("blend-destination-alpha")
200 _attributes_dirty &= ~BLEND_FUNC;
204 //----------------------------------------------------------------------------
205 bool Element::addEventListener( const std::string& type_str,
206 const EventListener& cb )
212 "addEventListener(" << _node->getPath() << ", " << type_str << ")"
215 _listener[ Event::getOrRegisterType(type_str) ].push_back(cb);
219 //----------------------------------------------------------------------------
220 void Element::clearEventListener()
225 //----------------------------------------------------------------------------
226 bool Element::accept(EventVisitor& visitor)
231 return visitor.apply(*this);
234 //----------------------------------------------------------------------------
235 bool Element::ascend(EventVisitor& visitor)
238 return _parent->accept(visitor);
242 //----------------------------------------------------------------------------
243 bool Element::traverse(EventVisitor& visitor)
248 //----------------------------------------------------------------------------
249 bool Element::handleEvent(EventPtr event)
251 ListenerMap::iterator listeners = _listener.find(event->getType());
252 if( listeners == _listener.end() )
255 BOOST_FOREACH(EventListener const& listener, listeners->second)
261 //----------------------------------------------------------------------------
262 bool Element::dispatchEvent(EventPtr event)
264 EventPropagationPath path;
265 path.push_back( EventTarget(this) );
267 for( Element* parent = _parent;
269 parent = parent->_parent )
270 path.push_front( EventTarget(parent) );
272 CanvasPtr canvas = _canvas.lock();
276 return canvas->propagateEvent(event, path);
279 //----------------------------------------------------------------------------
280 bool Element::hitBound( const osg::Vec2f& global_pos,
281 const osg::Vec2f& parent_pos,
282 const osg::Vec2f& local_pos ) const
284 if( _scissor && !_scissor->contains(global_pos, parent_pos, local_pos) )
287 const osg::Vec3f pos3(parent_pos, 0);
289 // Drawables have a bounding box...
291 return _drawable->getBound().contains(osg::Vec3f(local_pos, 0));
292 else if( _transform.valid() )
293 // ... for other elements, i.e. groups only a bounding sphere is available
294 return _transform->getBound().contains(osg::Vec3f(parent_pos, 0));
300 //----------------------------------------------------------------------------
301 void Element::setVisible(bool visible)
303 if( _transform.valid() )
304 // TODO check if we need another nodemask
305 _transform->setNodeMask(visible ? 0xffffffff : 0);
308 //----------------------------------------------------------------------------
309 bool Element::isVisible() const
311 return _transform.valid() && _transform->getNodeMask() != 0;
314 //----------------------------------------------------------------------------
315 osg::MatrixTransform* Element::getMatrixTransform()
317 return _transform.get();
320 //----------------------------------------------------------------------------
321 osg::MatrixTransform const* Element::getMatrixTransform() const
323 return _transform.get();
326 //----------------------------------------------------------------------------
327 osg::Vec2f Element::posToLocal(const osg::Vec2f& pos) const
330 const osg::Matrix& m = _transform->getInverseMatrix();
333 m(0, 0) * pos[0] + m(1, 0) * pos[1] + m(3, 0),
334 m(0, 1) * pos[0] + m(1, 1) * pos[1] + m(3, 1)
338 //----------------------------------------------------------------------------
339 void Element::childAdded(SGPropertyNode* parent, SGPropertyNode* child)
342 && child->getNameString() == NAME_TRANSFORM )
344 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
345 _transform_types.resize( child->getIndex() + 1 );
347 _transform_types[ child->getIndex() ] = TT_NONE;
348 _attributes_dirty |= TRANSFORM;
351 else if( parent->getParent() == _node
352 && parent->getNameString() == NAME_TRANSFORM )
354 assert(parent->getIndex() < static_cast<int>(_transform_types.size()));
356 const std::string& name = child->getNameString();
358 TransformType& type = _transform_types[parent->getIndex()];
362 else if( name == "t" )
364 else if( name == "rot" )
366 else if( name == "s" )
369 _attributes_dirty |= TRANSFORM;
376 //----------------------------------------------------------------------------
377 void Element::childRemoved(SGPropertyNode* parent, SGPropertyNode* child)
379 if( parent == _node )
381 if( child->getNameString() == NAME_TRANSFORM )
383 if( !_transform.valid() )
386 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
392 "Element::childRemoved: unknown transform: " << child->getPath()
397 _transform_types[ child->getIndex() ] = TT_NONE;
399 while( !_transform_types.empty() && _transform_types.back() == TT_NONE )
400 _transform_types.pop_back();
402 _attributes_dirty |= TRANSFORM;
405 else if( StyleInfo const* style = getStyleInfo(child->getNameString()) )
407 if( setStyle(getParentStyle(child), style) )
415 //----------------------------------------------------------------------------
416 void Element::valueChanged(SGPropertyNode* child)
418 SGPropertyNode *parent = child->getParent();
419 if( parent == _node )
421 const std::string& name = child->getNameString();
422 if( boost::starts_with(name, "data-") )
424 else if( StyleInfo const* style_info = getStyleInfo(name) )
426 SGPropertyNode const* style = child;
427 if( isStyleEmpty(child) )
430 style = getParentStyle(child);
432 setStyle(style, style_info);
435 else if( name == "update" )
437 else if( boost::starts_with(name, "blend-") )
438 return (void)(_attributes_dirty |= BLEND_FUNC);
441 && parent->getParent() == _node
442 && parent->getNameString() == NAME_TRANSFORM )
444 _attributes_dirty |= TRANSFORM;
451 //----------------------------------------------------------------------------
452 bool Element::setStyle( const SGPropertyNode* child,
453 const StyleInfo* style_info )
455 return canApplyStyle(child) && setStyleImpl(child, style_info);
458 //----------------------------------------------------------------------------
459 void Element::setClip(const std::string& clip)
461 if( clip.empty() || clip == "auto" )
463 getOrCreateStateSet()->removeAttribute(osg::StateAttribute::SCISSOR);
468 // TODO generalize CSS property parsing
469 const std::string RECT("rect(");
470 if( !boost::ends_with(clip, ")")
471 || !boost::starts_with(clip, RECT) )
473 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
477 const std::string sep(", \t\npx");
481 for(size_t pos = RECT.size(); comp < 4; ++comp)
483 pos = clip.find_first_not_of(sep, pos);
484 if( pos == std::string::npos || pos == clip.size() - 1 )
488 values[comp] = strtod(&clip[pos], &end);
489 if( end == &clip[pos] || !end )
492 pos = end - &clip[0];
497 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
501 float width = values[1] - values[3],
502 height = values[2] - values[0];
504 if( width < 0 || height < 0 )
506 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: negative clip size: " << clip);
510 _scissor = new RelativeScissor();
511 // <top>, <right>, <bottom>, <left>
512 _scissor->x() = SGMiscf::roundToInt(values[3]);
513 _scissor->y() = SGMiscf::roundToInt(values[0]);
514 _scissor->width() = SGMiscf::roundToInt(width);
515 _scissor->height() = SGMiscf::roundToInt(height);
517 getOrCreateStateSet()->setAttributeAndModes(_scissor);
519 SGPropertyNode* clip_frame = _node->getChild("clip-frame", 0);
521 valueChanged(clip_frame);
524 //----------------------------------------------------------------------------
525 void Element::setClipFrame(ReferenceFrame rf)
529 _scissor->_coord_reference = rf;
530 _attributes_dirty |= SCISSOR_COORDS;
534 //----------------------------------------------------------------------------
535 osg::BoundingBox Element::getBoundingBox() const
538 return _drawable->getBound();
542 if( _transform.valid() )
543 bb.expandBy(_transform->getBound());
548 //----------------------------------------------------------------------------
549 osg::BoundingBox Element::getTightBoundingBox() const
551 return getTransformedBounds(getMatrix());
554 //----------------------------------------------------------------------------
555 osg::BoundingBox Element::getTransformedBounds(const osg::Matrix& m) const
558 return osg::BoundingBox();
560 osg::BoundingBox transformed;
561 const osg::BoundingBox& bb = _drawable->getBound();
562 for(int i = 0; i < 4; ++i)
563 transformed.expandBy( bb.corner(i) * m );
568 //----------------------------------------------------------------------------
569 osg::Matrix Element::getMatrix() const
572 return osg::Matrix::identity();
574 if( !(_attributes_dirty & TRANSFORM) )
575 return _transform->getMatrix();
578 for( size_t i = 0; i < _transform_types.size(); ++i )
580 // Skip unused indizes...
581 if( _transform_types[i] == TT_NONE )
584 SGPropertyNode* tf_node = _node->getChild("tf", i, true);
586 // Build up the matrix representation of the current transform node
588 switch( _transform_types[i] )
591 tf = osg::Matrix( tf_node->getDoubleValue("m[0]", 1),
592 tf_node->getDoubleValue("m[1]", 0),
594 tf_node->getDoubleValue("m[6]", 0),
596 tf_node->getDoubleValue("m[2]", 0),
597 tf_node->getDoubleValue("m[3]", 1),
599 tf_node->getDoubleValue("m[7]", 0),
606 tf_node->getDoubleValue("m[4]", 0),
607 tf_node->getDoubleValue("m[5]", 0),
609 tf_node->getDoubleValue("m[8]", 1) );
612 tf.makeTranslate( osg::Vec3f( tf_node->getDoubleValue("t[0]", 0),
613 tf_node->getDoubleValue("t[1]", 0),
617 tf.makeRotate( tf_node->getDoubleValue("rot", 0), 0, 0, 1 );
621 float sx = tf_node->getDoubleValue("s[0]", 1);
622 // sy defaults to sx...
623 tf.makeScale( sx, tf_node->getDoubleValue("s[1]", sx), 1 );
631 _transform->setMatrix(m);
632 _attributes_dirty &= ~TRANSFORM;
633 _attributes_dirty |= SCISSOR_COORDS;
638 //----------------------------------------------------------------------------
639 static const std::string DATA_PREFIX("data-");
641 //----------------------------------------------------------------------------
642 std::string Element::dataPropToAttrName(const std::string& name)
644 // http://www.w3.org/TR/html5/dom.html#attr-data-*
646 // 3. Insert the string data- at the front of name.
648 std::string attr_name;
649 for( std::string::const_iterator cur = name.begin();
653 // If name contains a "-" (U+002D) character followed by a lowercase ASCII
654 // letter, throw a SyntaxError exception and abort these steps.
657 std::string::const_iterator next = cur + 1;
658 if( next != name.end() && islower(*next) )
659 return std::string();
662 // For each uppercase ASCII letter in name, insert a "-" (U+002D)
663 // character before the character and replace the character with the same
664 // character converted to ASCII lowercase.
667 attr_name.push_back('-');
668 attr_name.push_back( tolower(*cur) );
671 attr_name.push_back( *cur );
673 return DATA_PREFIX + attr_name;
676 //----------------------------------------------------------------------------
677 std::string Element::attrToDataPropName(const std::string& name)
679 // http://www.w3.org/TR/html5/dom.html#attr-data-*
681 // For each "-" (U+002D) character in the name that is followed by a
682 // lowercase ASCII letter, remove the "-" (U+002D) character and replace the
683 // character that followed it by the same character converted to ASCII
686 if( !boost::starts_with(name, DATA_PREFIX) )
687 return std::string();
689 std::string data_name;
690 for( std::string::const_iterator cur = name.begin() + DATA_PREFIX.length();
694 std::string::const_iterator next = cur + 1;
695 if( *cur == '-' && next != name.end() && islower(*next) )
697 data_name.push_back( toupper(*next) );
701 data_name.push_back(*cur);
706 //----------------------------------------------------------------------------
707 Element::StyleSetters Element::_style_setters;
709 //----------------------------------------------------------------------------
710 Element::Element( const CanvasWeakPtr& canvas,
711 const SGPropertyNode_ptr& node,
712 const Style& parent_style,
714 PropertyBasedElement(node),
717 _attributes_dirty( 0 ),
718 _transform( new osg::MatrixTransform ),
719 _style( parent_style ),
729 "New canvas element " << node->getPath()
732 // Ensure elements are drawn in order they appear in the element tree
733 _transform->getOrCreateStateSet()
734 ->setRenderBinDetails
738 osg::StateSet::OVERRIDE_RENDERBIN_DETAILS
741 _transform->setUserData( new OSGUserData(this) );
744 //----------------------------------------------------------------------------
745 void Element::staticInit()
747 if( isInit<Element>() )
750 addStyle("clip", "", &Element::setClip, false);
751 addStyle("clip-frame", "", &Element::setClipFrame, false);
752 addStyle("visible", "", &Element::setVisible, false);
755 //----------------------------------------------------------------------------
756 bool Element::isStyleEmpty(const SGPropertyNode* child) const
759 || simgear::strutils::strip(child->getStringValue()).empty();
762 //----------------------------------------------------------------------------
763 bool Element::canApplyStyle(const SGPropertyNode* child) const
765 if( _node == child->getParent() )
768 // Parent values do not override if element has own value
769 return isStyleEmpty( _node->getChild(child->getName()) );
772 //----------------------------------------------------------------------------
773 bool Element::setStyleImpl( const SGPropertyNode* child,
774 const StyleInfo* style_info )
776 const StyleSetter* style_setter = style_info
777 ? &style_info->setter
778 : getStyleSetter(child->getNameString());
779 while( style_setter )
781 if( style_setter->func(*this, child) )
783 style_setter = style_setter->next;
788 //----------------------------------------------------------------------------
789 const Element::StyleInfo*
790 Element::getStyleInfo(const std::string& name) const
792 StyleSetters::const_iterator setter = _style_setters.find(name);
793 if( setter == _style_setters.end() )
796 return &setter->second;
799 //----------------------------------------------------------------------------
800 const Element::StyleSetter*
801 Element::getStyleSetter(const std::string& name) const
803 const StyleInfo* info = getStyleInfo(name);
804 return info ? &info->setter : 0;
807 //----------------------------------------------------------------------------
808 const SGPropertyNode*
809 Element::getParentStyle(const SGPropertyNode* child) const
811 // Try to get value from parent...
814 Style::const_iterator style =
815 _parent->_style.find(child->getNameString());
816 if( style != _parent->_style.end() )
817 return style->second;
820 // ...or reset to default if none is available
821 return child; // TODO somehow get default value for each style?
824 //----------------------------------------------------------------------------
825 void Element::setDrawable( osg::Drawable* drawable )
827 _drawable = drawable;
830 osg::ref_ptr<osg::Geode> geode = new osg::Geode;
831 geode->addDrawable(_drawable);
832 _transform->addChild(geode);
835 //----------------------------------------------------------------------------
836 osg::StateSet* Element::getOrCreateStateSet()
838 return _drawable ? _drawable->getOrCreateStateSet()
839 : _transform->getOrCreateStateSet();
842 //----------------------------------------------------------------------------
843 void Element::setupStyle()
845 BOOST_FOREACH( Style::value_type style, _style )
846 setStyle(style.second);
849 } // namespace canvas
850 } // namespace simgear