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/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>
42 const std::string NAME_TRANSFORM = "tf";
44 //----------------------------------------------------------------------------
45 Element::OSGUserData::OSGUserData(ElementPtr element):
51 //----------------------------------------------------------------------------
57 //----------------------------------------------------------------------------
58 void Element::setSelf(const PropertyBasedElementPtr& self)
60 PropertyBasedElement::setSelf(self);
62 _transform->setUserData
64 new OSGUserData(boost::static_pointer_cast<Element>(self))
68 //----------------------------------------------------------------------------
69 void Element::onDestroy()
71 if( !_transform.valid() )
74 // The transform node keeps a reference on this element, so ensure it is
76 BOOST_FOREACH(osg::Group* parent, _transform->getParents())
78 parent->removeChild(_transform.get());
82 //----------------------------------------------------------------------------
83 ElementWeakPtr Element::getWeakPtr() const
85 return boost::static_pointer_cast<Element>(_self.lock());
88 //----------------------------------------------------------------------------
89 ElementPtr Element::getParent()
91 return _parent ? _parent->getWeakPtr().lock() : ElementPtr();
94 //----------------------------------------------------------------------------
95 void Element::update(double dt)
97 if( !_transform->getNodeMask() )
98 // Don't do anything if element is hidden
101 if( _transform_dirty )
104 for( size_t i = 0; i < _transform_types.size(); ++i )
106 // Skip unused indizes...
107 if( _transform_types[i] == TT_NONE )
110 SGPropertyNode* tf_node = _node->getChild("tf", i, true);
112 // Build up the matrix representation of the current transform node
114 switch( _transform_types[i] )
117 tf = osg::Matrix( tf_node->getDoubleValue("m[0]", 1),
118 tf_node->getDoubleValue("m[1]", 0),
120 tf_node->getDoubleValue("m[6]", 0),
122 tf_node->getDoubleValue("m[2]", 0),
123 tf_node->getDoubleValue("m[3]", 1),
125 tf_node->getDoubleValue("m[7]", 0),
132 tf_node->getDoubleValue("m[4]", 0),
133 tf_node->getDoubleValue("m[5]", 0),
135 tf_node->getDoubleValue("m[8]", 1) );
138 tf.makeTranslate( osg::Vec3f( tf_node->getDoubleValue("t[0]", 0),
139 tf_node->getDoubleValue("t[1]", 0),
143 tf.makeRotate( tf_node->getDoubleValue("rot", 0), 0, 0, 1 );
147 float sx = tf_node->getDoubleValue("s[0]", 1);
148 // sy defaults to sx...
149 tf.makeScale( sx, tf_node->getDoubleValue("s[1]", sx), 1 );
157 _transform->setMatrix(m);
158 _transform_dirty = false;
161 // Update bounding box on manual update (manual updates pass zero dt)
162 if( dt == 0 && _drawable )
163 _drawable->getBound();
165 if( _attributes_dirty & BLEND_FUNC )
168 _transform->getOrCreateStateSet(),
169 _node->getChild("blend-source"),
170 _node->getChild("blend-destination"),
171 _node->getChild("blend-source-rgb"),
172 _node->getChild("blend-destination-rgb"),
173 _node->getChild("blend-source-alpha"),
174 _node->getChild("blend-destination-alpha")
176 _attributes_dirty &= ~BLEND_FUNC;
180 //----------------------------------------------------------------------------
181 bool Element::addEventListener( const std::string& type_str,
182 const EventListener& cb )
188 "addEventListener(" << _node->getPath() << ", " << type_str << ")"
191 Event::Type type = Event::strToType(type_str);
192 if( type == Event::UNKNOWN )
196 "addEventListener: Unknown event type " << type_str );
200 _listener[ type ].push_back(cb);
205 //----------------------------------------------------------------------------
206 void Element::clearEventListener()
211 //----------------------------------------------------------------------------
212 bool Element::accept(EventVisitor& visitor)
217 return visitor.apply(*this);
220 //----------------------------------------------------------------------------
221 bool Element::ascend(EventVisitor& visitor)
224 return _parent->accept(visitor);
228 //----------------------------------------------------------------------------
229 bool Element::traverse(EventVisitor& visitor)
234 //----------------------------------------------------------------------------
235 bool Element::handleEvent(canvas::EventPtr event)
237 ListenerMap::iterator listeners = _listener.find(event->getType());
238 if( listeners == _listener.end() )
241 BOOST_FOREACH(EventListener const& listener, listeners->second)
247 //----------------------------------------------------------------------------
248 bool Element::hitBound( const osg::Vec2f& pos,
249 const osg::Vec2f& local_pos ) const
251 const osg::Vec3f pos3(pos, 0);
253 // Drawables have a bounding box...
255 return _drawable->getBound().contains(osg::Vec3f(local_pos, 0));
256 // ... for other elements, i.e. groups only a bounding sphere is available
258 return _transform->getBound().contains(osg::Vec3f(pos, 0));
261 //----------------------------------------------------------------------------
262 bool Element::isVisible() const
264 return _transform.valid() && _transform->getNodeMask() != 0;
267 //----------------------------------------------------------------------------
268 osg::MatrixTransform* Element::getMatrixTransform()
270 return _transform.get();
273 //----------------------------------------------------------------------------
274 osg::MatrixTransform const* Element::getMatrixTransform() const
276 return _transform.get();
279 //----------------------------------------------------------------------------
280 void Element::childAdded(SGPropertyNode* parent, SGPropertyNode* child)
283 && child->getNameString() == NAME_TRANSFORM )
285 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
286 _transform_types.resize( child->getIndex() + 1 );
288 _transform_types[ child->getIndex() ] = TT_NONE;
289 _transform_dirty = true;
292 else if( parent->getParent() == _node
293 && parent->getNameString() == NAME_TRANSFORM )
295 assert(parent->getIndex() < static_cast<int>(_transform_types.size()));
297 const std::string& name = child->getNameString();
299 TransformType& type = _transform_types[parent->getIndex()];
303 else if( name == "t" )
305 else if( name == "rot" )
307 else if( name == "s" )
310 _transform_dirty = true;
317 //----------------------------------------------------------------------------
318 void Element::childRemoved(SGPropertyNode* parent, SGPropertyNode* child)
320 if( parent == _node )
322 if( child->getNameString() == NAME_TRANSFORM )
324 if( !_transform.valid() )
327 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
333 "Element::childRemoved: unknown transform: " << child->getPath()
338 _transform_types[ child->getIndex() ] = TT_NONE;
340 while( !_transform_types.empty() && _transform_types.back() == TT_NONE )
341 _transform_types.pop_back();
343 _transform_dirty = true;
346 else if( StyleInfo const* style = getStyleInfo(child->getNameString()) )
348 if( setStyle(getParentStyle(child), style) )
356 //----------------------------------------------------------------------------
357 void Element::valueChanged(SGPropertyNode* child)
359 SGPropertyNode *parent = child->getParent();
360 if( parent == _node )
362 const std::string& name = child->getNameString();
363 if( StyleInfo const* style_info = getStyleInfo(name) )
365 SGPropertyNode const* style = child;
366 if( isStyleEmpty(child) )
369 style = getParentStyle(child);
371 setStyle(style, style_info);
374 else if( name == "update" )
376 else if( name == "visible" )
377 // TODO check if we need another nodemask
378 return _transform->setNodeMask( child->getBoolValue() ? 0xffffffff : 0 );
379 else if( boost::starts_with(name, "blend-") )
380 return (void)(_attributes_dirty |= BLEND_FUNC);
382 else if( parent->getParent() == _node
383 && parent->getNameString() == NAME_TRANSFORM )
385 _transform_dirty = true;
392 //----------------------------------------------------------------------------
393 bool Element::setStyle( const SGPropertyNode* child,
394 const StyleInfo* style_info )
396 return canApplyStyle(child) && setStyleImpl(child, style_info);
399 //----------------------------------------------------------------------------
400 void Element::setClip(const std::string& clip)
402 if( clip.empty() || clip == "auto" )
404 getOrCreateStateSet()->removeAttribute(osg::StateAttribute::SCISSOR);
408 // TODO generalize CSS property parsing
409 const std::string RECT("rect(");
410 if( !boost::ends_with(clip, ")")
411 || !boost::starts_with(clip, RECT) )
413 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
417 const std::string sep(", \t\npx");
421 for(size_t pos = RECT.size(); comp < 4; ++comp)
423 pos = clip.find_first_not_of(sep, pos);
424 if( pos == std::string::npos || pos == clip.size() - 1 )
428 values[comp] = strtod(&clip[pos], &end);
429 if( end == &clip[pos] || !end )
432 pos = end - &clip[0];
437 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
441 float width = values[1] - values[3],
442 height = values[2] - values[0];
444 if( width < 0 || height < 0 )
446 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: negative clip size: " << clip);
453 CanvasPtr canvas = _canvas.lock();
456 // The scissor rectangle isn't affected by any transformation, so we need
457 // to convert to image/canvas coordinates on our selves.
458 scale_x = canvas->getSizeX()
459 / static_cast<float>(canvas->getViewWidth());
460 scale_y = canvas->getSizeY()
461 / static_cast<float>(canvas->getViewHeight());
464 osg::Scissor* scissor = new osg::Scissor();
465 // <top>, <right>, <bottom>, <left>
466 scissor->x() = SGMiscf::roundToInt(scale_x * values[3]);
467 scissor->y() = SGMiscf::roundToInt(scale_y * values[0]);
468 scissor->width() = SGMiscf::roundToInt(scale_x * width);
469 scissor->height() = SGMiscf::roundToInt(scale_y * height);
472 // Canvas has y axis upside down
473 scissor->y() = canvas->getSizeY() - scissor->y() - scissor->height();
475 getOrCreateStateSet()->setAttributeAndModes(scissor);
478 //----------------------------------------------------------------------------
479 void Element::setBoundingBox(const osg::BoundingBox& bb)
481 if( _bounding_box.empty() )
483 SGPropertyNode* bb_node = _node->getChild("bounding-box", 0, true);
484 _bounding_box.resize(4);
485 _bounding_box[0] = bb_node->getChild("min-x", 0, true);
486 _bounding_box[1] = bb_node->getChild("min-y", 0, true);
487 _bounding_box[2] = bb_node->getChild("max-x", 0, true);
488 _bounding_box[3] = bb_node->getChild("max-y", 0, true);
491 _bounding_box[0]->setFloatValue(bb._min.x());
492 _bounding_box[1]->setFloatValue(bb._min.y());
493 _bounding_box[2]->setFloatValue(bb._max.x());
494 _bounding_box[3]->setFloatValue(bb._max.y());
497 //----------------------------------------------------------------------------
498 osg::BoundingBox Element::getTransformedBounds(const osg::Matrix& m) const
501 return osg::BoundingBox();
503 osg::BoundingBox transformed;
504 const osg::BoundingBox& bb = _drawable->getBound();
505 for(int i = 0; i < 4; ++i)
506 transformed.expandBy( bb.corner(i) * m );
511 //----------------------------------------------------------------------------
512 Element::StyleSetters Element::_style_setters;
514 //----------------------------------------------------------------------------
515 Element::Element( const CanvasWeakPtr& canvas,
516 const SGPropertyNode_ptr& node,
517 const Style& parent_style,
519 PropertyBasedElement(node),
522 _attributes_dirty( 0 ),
523 _transform_dirty( false ),
524 _transform( new osg::MatrixTransform ),
525 _style( parent_style ),
534 "New canvas element " << node->getPath()
537 // Ensure elements are drawn in order they appear in the element tree
538 _transform->getOrCreateStateSet()
539 ->setRenderBinDetails
543 osg::StateSet::OVERRIDE_RENDERBIN_DETAILS
547 //----------------------------------------------------------------------------
548 void Element::staticInit()
550 if( isInit<Element>() )
553 addStyle("clip", "", &Element::setClip, false);
556 //----------------------------------------------------------------------------
557 bool Element::isStyleEmpty(const SGPropertyNode* child) const
560 || simgear::strutils::strip(child->getStringValue()).empty();
563 //----------------------------------------------------------------------------
564 bool Element::canApplyStyle(const SGPropertyNode* child) const
566 if( _node == child->getParent() )
569 // Parent values do not override if element has own value
570 return isStyleEmpty( _node->getChild(child->getName()) );
573 //----------------------------------------------------------------------------
574 bool Element::setStyleImpl( const SGPropertyNode* child,
575 const StyleInfo* style_info )
577 const StyleSetter* style_setter = style_info
578 ? &style_info->setter
579 : getStyleSetter(child->getNameString());
580 while( style_setter )
582 if( style_setter->func(*this, child) )
584 style_setter = style_setter->next;
589 //----------------------------------------------------------------------------
590 const Element::StyleInfo*
591 Element::getStyleInfo(const std::string& name) const
593 StyleSetters::const_iterator setter = _style_setters.find(name);
594 if( setter == _style_setters.end() )
597 return &setter->second;
600 //----------------------------------------------------------------------------
601 const Element::StyleSetter*
602 Element::getStyleSetter(const std::string& name) const
604 const StyleInfo* info = getStyleInfo(name);
605 return info ? &info->setter : 0;
608 //----------------------------------------------------------------------------
609 const SGPropertyNode*
610 Element::getParentStyle(const SGPropertyNode* child) const
612 // Try to get value from parent...
615 Style::const_iterator style =
616 _parent->_style.find(child->getNameString());
617 if( style != _parent->_style.end() )
618 return style->second;
621 // ...or reset to default if none is available
622 return child; // TODO somehow get default value for each style?
625 //----------------------------------------------------------------------------
626 void Element::setDrawable( osg::Drawable* drawable )
628 _drawable = drawable;
631 osg::ref_ptr<osg::Geode> geode = new osg::Geode;
632 geode->addDrawable(_drawable);
633 _transform->addChild(geode);
636 //----------------------------------------------------------------------------
637 osg::StateSet* Element::getOrCreateStateSet()
639 return _drawable ? _drawable->getOrCreateStateSet()
640 : _transform->getOrCreateStateSet();
643 //----------------------------------------------------------------------------
644 void Element::setupStyle()
646 BOOST_FOREACH( Style::value_type style, _style )
647 setStyle(style.second);
650 } // namespace canvas
651 } // namespace simgear