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/CanvasEventListener.hxx>
22 #include <simgear/canvas/CanvasEventVisitor.hxx>
23 #include <simgear/canvas/MouseEvent.hxx>
25 #include <osg/Drawable>
27 #include <osg/Scissor>
29 #include <boost/algorithm/string/predicate.hpp>
30 #include <boost/foreach.hpp>
31 #include <boost/lexical_cast.hpp>
32 #include <boost/make_shared.hpp>
33 #include <boost/tokenizer.hpp>
42 const std::string NAME_TRANSFORM = "tf";
44 //----------------------------------------------------------------------------
45 void Element::removeListener()
47 _node->removeChangeListener(this);
50 //----------------------------------------------------------------------------
55 BOOST_FOREACH(osg::Group* parent, _transform->getParents())
57 parent->removeChild(_transform);
61 //----------------------------------------------------------------------------
62 ElementWeakPtr Element::getWeakPtr() const
64 return boost::static_pointer_cast<Element>(_self.lock());
67 //----------------------------------------------------------------------------
68 void Element::update(double dt)
70 if( !_transform->getNodeMask() )
71 // Don't do anything if element is hidden
74 if( _transform_dirty )
77 for( size_t i = 0; i < _transform_types.size(); ++i )
79 // Skip unused indizes...
80 if( _transform_types[i] == TT_NONE )
83 SGPropertyNode* tf_node = _node->getChild("tf", i, true);
85 // Build up the matrix representation of the current transform node
87 switch( _transform_types[i] )
90 tf = osg::Matrix( tf_node->getDoubleValue("m[0]", 1),
91 tf_node->getDoubleValue("m[1]", 0), 0, 0,
93 tf_node->getDoubleValue("m[2]", 0),
94 tf_node->getDoubleValue("m[3]", 1), 0, 0,
97 tf_node->getDoubleValue("m[4]", 0),
98 tf_node->getDoubleValue("m[5]", 0), 0, 1 );
101 tf.makeTranslate( osg::Vec3f( tf_node->getDoubleValue("t[0]", 0),
102 tf_node->getDoubleValue("t[1]", 0),
106 tf.makeRotate( tf_node->getDoubleValue("rot", 0), 0, 0, 1 );
110 float sx = tf_node->getDoubleValue("s[0]", 1);
111 // sy defaults to sx...
112 tf.makeScale( sx, tf_node->getDoubleValue("s[1]", sx), 1 );
120 _transform->setMatrix(m);
121 _transform_dirty = false;
125 //----------------------------------------------------------------------------
126 naRef Element::addEventListener(const nasal::CallContext& ctx)
128 const std::string type_str = ctx.requireArg<std::string>(0);
129 naRef code = ctx.requireArg<naRef>(1);
135 "addEventListener(" << _node->getPath() << ", " << type_str << ")"
138 Event::Type type = Event::strToType(type_str);
139 if( type == Event::UNKNOWN )
140 naRuntimeError( ctx.c,
141 "addEventListener: Unknown event type %s",
144 _listener[ type ].push_back
146 boost::make_shared<EventListener>( code,
147 _canvas.lock()->getSystemAdapter() )
153 //----------------------------------------------------------------------------
154 bool Element::accept(EventVisitor& visitor)
156 return visitor.apply(*this);
159 //----------------------------------------------------------------------------
160 bool Element::ascend(EventVisitor& visitor)
163 return _parent->accept(visitor);
167 //----------------------------------------------------------------------------
168 bool Element::traverse(EventVisitor& visitor)
173 //----------------------------------------------------------------------------
174 void Element::callListeners(const canvas::EventPtr& event)
176 ListenerMap::iterator listeners = _listener.find(event->getType());
177 if( listeners == _listener.end() )
180 BOOST_FOREACH(EventListenerPtr listener, listeners->second)
181 listener->call(event);
184 //----------------------------------------------------------------------------
185 bool Element::hitBound(const osg::Vec2f& pos) const
187 const osg::Vec3f pos3(pos, 0);
189 // Drawables have a bounding box...
192 if( !_drawable->getBound().contains(pos3) )
195 // ... for other elements, i.e. groups only a bounding sphere is available
196 else if( !_transform->getBound().contains(pos3) )
202 //----------------------------------------------------------------------------
203 osg::ref_ptr<osg::MatrixTransform> Element::getMatrixTransform()
208 //----------------------------------------------------------------------------
209 void Element::childAdded(SGPropertyNode* parent, SGPropertyNode* child)
212 && child->getNameString() == NAME_TRANSFORM )
214 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
215 _transform_types.resize( child->getIndex() + 1 );
217 _transform_types[ child->getIndex() ] = TT_NONE;
218 _transform_dirty = true;
221 else if( parent->getParent() == _node
222 && parent->getNameString() == NAME_TRANSFORM )
224 assert(parent->getIndex() < static_cast<int>(_transform_types.size()));
226 const std::string& name = child->getNameString();
228 TransformType& type = _transform_types[parent->getIndex()];
232 else if( name == "t" )
234 else if( name == "rot" )
236 else if( name == "s" )
239 _transform_dirty = true;
246 //----------------------------------------------------------------------------
247 void Element::childRemoved(SGPropertyNode* parent, SGPropertyNode* child)
249 if( parent == _node && child->getNameString() == NAME_TRANSFORM )
251 if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
257 "Element::childRemoved: unknown transform: " << child->getPath()
262 _transform_types[ child->getIndex() ] = TT_NONE;
264 while( !_transform_types.empty() && _transform_types.back() == TT_NONE )
265 _transform_types.pop_back();
267 _transform_dirty = true;
274 //----------------------------------------------------------------------------
275 void Element::valueChanged(SGPropertyNode* child)
277 SGPropertyNode *parent = child->getParent();
278 if( parent == _node )
280 if( setStyle(child) )
282 else if( child->getNameString() == "update" )
284 else if( child->getNameString() == "visible" )
285 // TODO check if we need another nodemask
286 return _transform->setNodeMask( child->getBoolValue() ? 0xffffffff : 0 );
288 else if( parent->getParent() == _node
289 && parent->getNameString() == NAME_TRANSFORM )
291 _transform_dirty = true;
298 //----------------------------------------------------------------------------
299 bool Element::setStyle(const SGPropertyNode* child)
301 StyleSetters::const_iterator setter =
302 _style_setters.find(child->getNameString());
303 if( setter == _style_setters.end() )
306 setter->second(child);
310 //----------------------------------------------------------------------------
311 void Element::setClip(const std::string& clip)
313 if( clip.empty() || clip == "auto" )
315 getOrCreateStateSet()->removeAttribute(osg::StateAttribute::SCISSOR);
319 // TODO generalize CSS property parsing
320 const std::string RECT("rect(");
321 if( !boost::ends_with(clip, ")")
322 || !boost::starts_with(clip, RECT) )
324 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
328 typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
329 const boost::char_separator<char> del(", \t\npx");
331 tokenizer tokens(clip.begin() + RECT.size(), clip.end() - 1, del);
334 for( tokenizer::const_iterator tok = tokens.begin();
335 tok != tokens.end() && comp < 4;
338 values[comp] = boost::lexical_cast<int>(*tok);
343 SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
350 CanvasPtr canvas = _canvas.lock();
353 // The scissor rectangle isn't affected by any transformation, so we need
354 // to convert to image/canvas coordinates on our selves.
355 scale_x = canvas->getSizeX()
356 / static_cast<float>(canvas->getViewWidth());
357 scale_y = canvas->getSizeY()
358 / static_cast<float>(canvas->getViewHeight());
361 osg::Scissor* scissor = new osg::Scissor();
362 // <top>, <right>, <bottom>, <left>
363 scissor->x() = scale_x * values[3];
364 scissor->y() = scale_y * values[0];
365 scissor->width() = scale_x * (values[1] - values[3]);
366 scissor->height() = scale_y * (values[2] - values[0]);
369 // Canvas has y axis upside down
370 scissor->y() = canvas->getSizeY() - scissor->y() - scissor->height();
372 getOrCreateStateSet()->setAttributeAndModes(scissor);
375 //----------------------------------------------------------------------------
376 void Element::setBoundingBox(const osg::BoundingBox& bb)
378 if( _bounding_box.empty() )
380 SGPropertyNode* bb_node = _node->getChild("bounding-box", 0, true);
381 _bounding_box.resize(4);
382 _bounding_box[0] = bb_node->getChild("min-x", 0, true);
383 _bounding_box[1] = bb_node->getChild("min-y", 0, true);
384 _bounding_box[2] = bb_node->getChild("max-x", 0, true);
385 _bounding_box[3] = bb_node->getChild("max-y", 0, true);
388 _bounding_box[0]->setFloatValue(bb._min.x());
389 _bounding_box[1]->setFloatValue(bb._min.y());
390 _bounding_box[2]->setFloatValue(bb._max.x());
391 _bounding_box[3]->setFloatValue(bb._max.y());
394 //----------------------------------------------------------------------------
395 osg::BoundingBox Element::getTransformedBounds(const osg::Matrix& m) const
397 return osg::BoundingBox();
400 //----------------------------------------------------------------------------
401 Element::Element( const CanvasWeakPtr& canvas,
402 const SGPropertyNode_ptr& node,
403 const Style& parent_style,
405 PropertyBasedElement(node),
408 _transform_dirty( false ),
409 _transform( new osg::MatrixTransform ),
410 _style( parent_style ),
417 "New canvas element " << node->getPath()
420 addStyle("clip", &Element::setClip, this);
423 //----------------------------------------------------------------------------
424 void Element::setDrawable( osg::Drawable* drawable )
426 _drawable = drawable;
429 osg::ref_ptr<osg::Geode> geode = new osg::Geode;
430 geode->addDrawable(_drawable);
431 _transform->addChild(geode);
434 //----------------------------------------------------------------------------
435 osg::StateSet* Element::getOrCreateStateSet()
437 return _drawable ? _drawable->getOrCreateStateSet()
438 : _transform->getOrCreateStateSet();
441 //----------------------------------------------------------------------------
442 void Element::setupStyle()
444 BOOST_FOREACH( Style::value_type style, _style )
445 setStyle(style.second);
448 } // namespace canvas
449 } // namespace simgear