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 virtual void apply(osg::State& state) const
61 const osg::Viewport* vp = state.getCurrentViewport();
62 float w2 = 0.5 * vp->width(),
63 h2 = 0.5 * vp->height();
65 osg::Matrix model_view
72 model_view.preMult(state.getProjectionMatrix());
74 if( _coord_reference != GLOBAL )
76 model_view.preMult(state.getModelViewMatrix());
78 if( _coord_reference == PARENT )
79 model_view.preMult(_parent_inverse);
82 const osg::Vec2 scale( model_view(0,0), model_view(1,1)),
83 offset(model_view(3,0), model_view(3,1));
85 // TODO check/warn for rotation?
87 GLint x = SGMiscf::roundToInt(scale.x() * _x + offset.x()),
88 y = SGMiscf::roundToInt(scale.y() * _y + offset.y()),
89 w = SGMiscf::roundToInt(std::fabs(scale.x()) * _width),
90 h = SGMiscf::roundToInt(std::fabs(scale.y()) * _height);
97 glScissor(x, y, w, h);
101 //----------------------------------------------------------------------------
102 Element::OSGUserData::OSGUserData(ElementPtr element):
108 //----------------------------------------------------------------------------
111 if( !_transform.valid() )
114 for(unsigned int i = 0; i < _transform->getNumChildren(); ++i)
117 static_cast<OSGUserData*>(_transform->getChild(i)->getUserData());
120 // Ensure parent is cleared to prevent accessing released memory if an
121 // element somehow survives longer than his parent.
122 ud->element->_parent = 0;
126 //----------------------------------------------------------------------------
127 void Element::setSelf(const PropertyBasedElementPtr& self)
129 PropertyBasedElement::setSelf(self);
131 _transform->setUserData
133 new OSGUserData(boost::static_pointer_cast<Element>(self))
137 //----------------------------------------------------------------------------
138 void Element::onDestroy()
140 if( !_transform.valid() )
143 // The transform node keeps a reference on this element, so ensure it is
145 BOOST_FOREACH(osg::Group* parent, _transform->getParents())
147 parent->removeChild(_transform.get());
151 //----------------------------------------------------------------------------
152 ElementWeakPtr Element::getWeakPtr() const
154 return boost::static_pointer_cast<Element>(_self.lock());
157 //----------------------------------------------------------------------------
158 ElementPtr Element::getParent()
160 return _parent ? _parent->getWeakPtr().lock() : ElementPtr();
163 //----------------------------------------------------------------------------
164 void Element::update(double dt)
169 // Trigger matrix update
172 if( _attributes_dirty & SCISSOR_COORDS )
174 if( _scissor && _scissor->_coord_reference != GLOBAL )
175 _scissor->_parent_inverse = _transform->getInverseMatrix();
177 _attributes_dirty &= ~SCISSOR_COORDS;
180 // Update bounding box on manual update (manual updates pass zero dt)
181 if( dt == 0 && _drawable )
182 _drawable->getBound();
184 if( _attributes_dirty & BLEND_FUNC )
187 _transform->getOrCreateStateSet(),
188 _node->getChild("blend-source"),
189 _node->getChild("blend-destination"),
190 _node->getChild("blend-source-rgb"),
191 _node->getChild("blend-destination-rgb"),
192 _node->getChild("blend-source-alpha"),
193 _node->getChild("blend-destination-alpha")
195 _attributes_dirty &= ~BLEND_FUNC;
199 //----------------------------------------------------------------------------
200 bool Element::addEventListener( const std::string& type_str,
201 const EventListener& cb )
207 "addEventListener(" << _node->getPath() << ", " << type_str << ")"
210 Event::Type type = Event::strToType(type_str);
211 if( type == Event::UNKNOWN )
215 "addEventListener: Unknown event type " << type_str );
219 _listener[ type ].push_back(cb);
224 //----------------------------------------------------------------------------
225 void Element::clearEventListener()
230 //----------------------------------------------------------------------------
231 bool Element::accept(EventVisitor& visitor)
236 return visitor.apply(*this);
239 //----------------------------------------------------------------------------
240 bool Element::ascend(EventVisitor& visitor)
243 return _parent->accept(visitor);
247 //----------------------------------------------------------------------------
248 bool Element::traverse(EventVisitor& visitor)
253 //----------------------------------------------------------------------------
254 bool Element::handleEvent(canvas::EventPtr event)
256 ListenerMap::iterator listeners = _listener.find(event->getType());
257 if( listeners == _listener.end() )
260 BOOST_FOREACH(EventListener const& listener, listeners->second)
266 //----------------------------------------------------------------------------
267 bool Element::hitBound( const osg::Vec2f& pos,
268 const osg::Vec2f& local_pos ) const
270 const osg::Vec3f pos3(pos, 0);
272 // Drawables have a bounding box...
274 return _drawable->getBound().contains(osg::Vec3f(local_pos, 0));
275 // ... for other elements, i.e. groups only a bounding sphere is available
277 return _transform->getBound().contains(osg::Vec3f(pos, 0));
280 //----------------------------------------------------------------------------
281 void Element::setVisible(bool visible)
283 if( _transform.valid() )
284 // TODO check if we need another nodemask
285 _transform->setNodeMask(visible ? 0xffffffff : 0);
288 //----------------------------------------------------------------------------
289 bool Element::isVisible() const
291 return _transform.valid() && _transform->getNodeMask() != 0;
294 //----------------------------------------------------------------------------
295 osg::MatrixTransform* Element::getMatrixTransform()
297 return _transform.get();
300 //----------------------------------------------------------------------------
301 osg::MatrixTransform const* Element::getMatrixTransform() const
303 return _transform.get();
306 //----------------------------------------------------------------------------
307 void Element::childAdded(SGPropertyNode* parent, SGPropertyNode* child)
310 && child->getNameString() == NAME_TRANSFORM )
312 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
313 _transform_types.resize( child->getIndex() + 1 );
315 _transform_types[ child->getIndex() ] = TT_NONE;
316 _attributes_dirty |= TRANSFORM;
319 else if( parent->getParent() == _node
320 && parent->getNameString() == NAME_TRANSFORM )
322 assert(parent->getIndex() < static_cast<int>(_transform_types.size()));
324 const std::string& name = child->getNameString();
326 TransformType& type = _transform_types[parent->getIndex()];
330 else if( name == "t" )
332 else if( name == "rot" )
334 else if( name == "s" )
337 _attributes_dirty |= TRANSFORM;
344 //----------------------------------------------------------------------------
345 void Element::childRemoved(SGPropertyNode* parent, SGPropertyNode* child)
347 if( parent == _node )
349 if( child->getNameString() == NAME_TRANSFORM )
351 if( !_transform.valid() )
354 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
360 "Element::childRemoved: unknown transform: " << child->getPath()
365 _transform_types[ child->getIndex() ] = TT_NONE;
367 while( !_transform_types.empty() && _transform_types.back() == TT_NONE )
368 _transform_types.pop_back();
370 _attributes_dirty |= TRANSFORM;
373 else if( StyleInfo const* style = getStyleInfo(child->getNameString()) )
375 if( setStyle(getParentStyle(child), style) )
383 //----------------------------------------------------------------------------
384 void Element::valueChanged(SGPropertyNode* child)
386 SGPropertyNode *parent = child->getParent();
387 if( parent == _node )
389 const std::string& name = child->getNameString();
390 if( StyleInfo const* style_info = getStyleInfo(name) )
392 SGPropertyNode const* style = child;
393 if( isStyleEmpty(child) )
396 style = getParentStyle(child);
398 setStyle(style, style_info);
401 else if( name == "update" )
403 else if( boost::starts_with(name, "blend-") )
404 return (void)(_attributes_dirty |= BLEND_FUNC);
406 else if( parent->getParent() == _node
407 && parent->getNameString() == NAME_TRANSFORM )
409 _attributes_dirty |= TRANSFORM;
416 //----------------------------------------------------------------------------
417 bool Element::setStyle( const SGPropertyNode* child,
418 const StyleInfo* style_info )
420 return canApplyStyle(child) && setStyleImpl(child, style_info);
423 //----------------------------------------------------------------------------
424 void Element::setClip(const std::string& clip)
426 if( clip.empty() || clip == "auto" )
428 getOrCreateStateSet()->removeAttribute(osg::StateAttribute::SCISSOR);
433 // TODO generalize CSS property parsing
434 const std::string RECT("rect(");
435 if( !boost::ends_with(clip, ")")
436 || !boost::starts_with(clip, RECT) )
438 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
442 const std::string sep(", \t\npx");
446 for(size_t pos = RECT.size(); comp < 4; ++comp)
448 pos = clip.find_first_not_of(sep, pos);
449 if( pos == std::string::npos || pos == clip.size() - 1 )
453 values[comp] = strtod(&clip[pos], &end);
454 if( end == &clip[pos] || !end )
457 pos = end - &clip[0];
462 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
466 float width = values[1] - values[3],
467 height = values[2] - values[0];
469 if( width < 0 || height < 0 )
471 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: negative clip size: " << clip);
475 _scissor = new RelativeScissor();
476 // <top>, <right>, <bottom>, <left>
477 _scissor->x() = SGMiscf::roundToInt(values[3]);
478 _scissor->y() = SGMiscf::roundToInt(values[0]);
479 _scissor->width() = SGMiscf::roundToInt(width);
480 _scissor->height() = SGMiscf::roundToInt(height);
482 getOrCreateStateSet()->setAttributeAndModes(_scissor);
484 SGPropertyNode* clip_frame = _node->getChild("clip-frame", 0);
486 valueChanged(clip_frame);
489 //----------------------------------------------------------------------------
490 void Element::setClipFrame(ReferenceFrame rf)
494 _scissor->_coord_reference = rf;
495 _attributes_dirty |= SCISSOR_COORDS;
499 //----------------------------------------------------------------------------
500 void Element::setBoundingBox(const osg::BoundingBox& bb)
502 if( _bounding_box.empty() )
504 SGPropertyNode* bb_node = _node->getChild("bounding-box", 0, true);
505 _bounding_box.resize(4);
506 _bounding_box[0] = bb_node->getChild("min-x", 0, true);
507 _bounding_box[1] = bb_node->getChild("min-y", 0, true);
508 _bounding_box[2] = bb_node->getChild("max-x", 0, true);
509 _bounding_box[3] = bb_node->getChild("max-y", 0, true);
512 _bounding_box[0]->setFloatValue(bb._min.x());
513 _bounding_box[1]->setFloatValue(bb._min.y());
514 _bounding_box[2]->setFloatValue(bb._max.x());
515 _bounding_box[3]->setFloatValue(bb._max.y());
518 //----------------------------------------------------------------------------
519 osg::BoundingBox Element::getTransformedBounds(const osg::Matrix& m) const
522 return osg::BoundingBox();
524 osg::BoundingBox transformed;
525 const osg::BoundingBox& bb = _drawable->getBound();
526 for(int i = 0; i < 4; ++i)
527 transformed.expandBy( bb.corner(i) * m );
532 //----------------------------------------------------------------------------
533 osg::Matrix Element::getMatrix() const
535 if( !(_attributes_dirty & TRANSFORM) )
536 return _transform->getMatrix();
539 for( size_t i = 0; i < _transform_types.size(); ++i )
541 // Skip unused indizes...
542 if( _transform_types[i] == TT_NONE )
545 SGPropertyNode* tf_node = _node->getChild("tf", i, true);
547 // Build up the matrix representation of the current transform node
549 switch( _transform_types[i] )
552 tf = osg::Matrix( tf_node->getDoubleValue("m[0]", 1),
553 tf_node->getDoubleValue("m[1]", 0),
555 tf_node->getDoubleValue("m[6]", 0),
557 tf_node->getDoubleValue("m[2]", 0),
558 tf_node->getDoubleValue("m[3]", 1),
560 tf_node->getDoubleValue("m[7]", 0),
567 tf_node->getDoubleValue("m[4]", 0),
568 tf_node->getDoubleValue("m[5]", 0),
570 tf_node->getDoubleValue("m[8]", 1) );
573 tf.makeTranslate( osg::Vec3f( tf_node->getDoubleValue("t[0]", 0),
574 tf_node->getDoubleValue("t[1]", 0),
578 tf.makeRotate( tf_node->getDoubleValue("rot", 0), 0, 0, 1 );
582 float sx = tf_node->getDoubleValue("s[0]", 1);
583 // sy defaults to sx...
584 tf.makeScale( sx, tf_node->getDoubleValue("s[1]", sx), 1 );
592 _transform->setMatrix(m);
593 _attributes_dirty &= ~TRANSFORM;
594 _attributes_dirty |= SCISSOR_COORDS;
599 //----------------------------------------------------------------------------
600 Element::StyleSetters Element::_style_setters;
602 //----------------------------------------------------------------------------
603 Element::Element( const CanvasWeakPtr& canvas,
604 const SGPropertyNode_ptr& node,
605 const Style& parent_style,
607 PropertyBasedElement(node),
610 _attributes_dirty( 0 ),
611 _transform( new osg::MatrixTransform ),
612 _style( parent_style ),
622 "New canvas element " << node->getPath()
625 // Ensure elements are drawn in order they appear in the element tree
626 _transform->getOrCreateStateSet()
627 ->setRenderBinDetails
631 osg::StateSet::OVERRIDE_RENDERBIN_DETAILS
635 //----------------------------------------------------------------------------
636 void Element::staticInit()
638 if( isInit<Element>() )
641 addStyle("clip", "", &Element::setClip, false);
642 addStyle("clip-frame", "", &Element::setClipFrame, false);
643 addStyle("visible", "", &Element::setVisible, false);
646 //----------------------------------------------------------------------------
647 bool Element::isStyleEmpty(const SGPropertyNode* child) const
650 || simgear::strutils::strip(child->getStringValue()).empty();
653 //----------------------------------------------------------------------------
654 bool Element::canApplyStyle(const SGPropertyNode* child) const
656 if( _node == child->getParent() )
659 // Parent values do not override if element has own value
660 return isStyleEmpty( _node->getChild(child->getName()) );
663 //----------------------------------------------------------------------------
664 bool Element::setStyleImpl( const SGPropertyNode* child,
665 const StyleInfo* style_info )
667 const StyleSetter* style_setter = style_info
668 ? &style_info->setter
669 : getStyleSetter(child->getNameString());
670 while( style_setter )
672 if( style_setter->func(*this, child) )
674 style_setter = style_setter->next;
679 //----------------------------------------------------------------------------
680 const Element::StyleInfo*
681 Element::getStyleInfo(const std::string& name) const
683 StyleSetters::const_iterator setter = _style_setters.find(name);
684 if( setter == _style_setters.end() )
687 return &setter->second;
690 //----------------------------------------------------------------------------
691 const Element::StyleSetter*
692 Element::getStyleSetter(const std::string& name) const
694 const StyleInfo* info = getStyleInfo(name);
695 return info ? &info->setter : 0;
698 //----------------------------------------------------------------------------
699 const SGPropertyNode*
700 Element::getParentStyle(const SGPropertyNode* child) const
702 // Try to get value from parent...
705 Style::const_iterator style =
706 _parent->_style.find(child->getNameString());
707 if( style != _parent->_style.end() )
708 return style->second;
711 // ...or reset to default if none is available
712 return child; // TODO somehow get default value for each style?
715 //----------------------------------------------------------------------------
716 void Element::setDrawable( osg::Drawable* drawable )
718 _drawable = drawable;
721 osg::ref_ptr<osg::Geode> geode = new osg::Geode;
722 geode->addDrawable(_drawable);
723 _transform->addChild(geode);
726 //----------------------------------------------------------------------------
727 osg::StateSet* Element::getOrCreateStateSet()
729 return _drawable ? _drawable->getOrCreateStateSet()
730 : _transform->getOrCreateStateSet();
733 //----------------------------------------------------------------------------
734 void Element::setupStyle()
736 BOOST_FOREACH( Style::value_type style, _style )
737 setStyle(style.second);
740 } // namespace canvas
741 } // namespace simgear