]> git.mxchange.org Git - simgear.git/blob - simgear/canvas/elements/CanvasElement.cxx
Canvas: don't crash with invalid clip rect
[simgear.git] / simgear / canvas / elements / CanvasElement.cxx
1 // Interface for 2D Canvas element
2 //
3 // Copyright (C) 2012  Thomas Geymayer <tomgey@gmail.com>
4 //
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.
9 //
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.
14 //
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
18
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>
24 #include <simgear/misc/strutils.hxx>
25 #include <simgear/scene/material/parseBlendFunc.hxx>
26
27 #include <osg/Drawable>
28 #include <osg/Geode>
29 #include <osg/Scissor>
30
31 #include <boost/algorithm/string/predicate.hpp>
32 #include <boost/foreach.hpp>
33 #include <boost/make_shared.hpp>
34
35 #include <cassert>
36 #include <cstring>
37
38 namespace simgear
39 {
40 namespace canvas
41 {
42   const std::string NAME_TRANSFORM = "tf";
43
44   //----------------------------------------------------------------------------
45   Element::OSGUserData::OSGUserData(ElementPtr element):
46     element(element)
47   {
48
49   }
50
51   //----------------------------------------------------------------------------
52   Element::~Element()
53   {
54
55   }
56
57   //----------------------------------------------------------------------------
58   void Element::setSelf(const PropertyBasedElementPtr& self)
59   {
60     PropertyBasedElement::setSelf(self);
61
62     _transform->setUserData
63     (
64       new OSGUserData(boost::static_pointer_cast<Element>(self))
65     );
66   }
67
68   //----------------------------------------------------------------------------
69   void Element::onDestroy()
70   {
71     if( !_transform.valid() )
72       return;
73
74     // The transform node keeps a reference on this element, so ensure it is
75     // deleted.
76     BOOST_FOREACH(osg::Group* parent, _transform->getParents())
77     {
78       parent->removeChild(_transform.get());
79     }
80   }
81
82   //----------------------------------------------------------------------------
83   ElementWeakPtr Element::getWeakPtr() const
84   {
85     return boost::static_pointer_cast<Element>(_self.lock());
86   }
87
88   //----------------------------------------------------------------------------
89   void Element::update(double dt)
90   {
91     if( !_transform->getNodeMask() )
92       // Don't do anything if element is hidden
93       return;
94
95     if( _transform_dirty )
96     {
97       osg::Matrix m;
98       for( size_t i = 0; i < _transform_types.size(); ++i )
99       {
100         // Skip unused indizes...
101         if( _transform_types[i] == TT_NONE )
102           continue;
103
104         SGPropertyNode* tf_node = _node->getChild("tf", i, true);
105
106         // Build up the matrix representation of the current transform node
107         osg::Matrix tf;
108         switch( _transform_types[i] )
109         {
110           case TT_MATRIX:
111             tf = osg::Matrix( tf_node->getDoubleValue("m[0]", 1),
112                               tf_node->getDoubleValue("m[1]", 0),
113                               0,
114                               tf_node->getDoubleValue("m[6]", 0),
115
116                               tf_node->getDoubleValue("m[2]", 0),
117                               tf_node->getDoubleValue("m[3]", 1),
118                               0,
119                               tf_node->getDoubleValue("m[7]", 0),
120
121                               0,
122                               0,
123                               1,
124                               0,
125
126                               tf_node->getDoubleValue("m[4]", 0),
127                               tf_node->getDoubleValue("m[5]", 0),
128                               0,
129                               tf_node->getDoubleValue("m[8]", 1) );
130             break;
131           case TT_TRANSLATE:
132             tf.makeTranslate( osg::Vec3f( tf_node->getDoubleValue("t[0]", 0),
133                                           tf_node->getDoubleValue("t[1]", 0),
134                                           0 ) );
135             break;
136           case TT_ROTATE:
137             tf.makeRotate( tf_node->getDoubleValue("rot", 0), 0, 0, 1 );
138             break;
139           case TT_SCALE:
140           {
141             float sx = tf_node->getDoubleValue("s[0]", 1);
142             // sy defaults to sx...
143             tf.makeScale( sx, tf_node->getDoubleValue("s[1]", sx), 1 );
144             break;
145           }
146           default:
147             break;
148         }
149         m.postMult( tf );
150       }
151       _transform->setMatrix(m);
152       _transform_dirty = false;
153     }
154
155     // Update bounding box on manual update (manual updates pass zero dt)
156     if( dt == 0 && _drawable )
157       _drawable->getBound();
158
159     if( _attributes_dirty & BLEND_FUNC )
160     {
161       parseBlendFunc(
162         _transform->getOrCreateStateSet(),
163         _node->getChild("blend-source"),
164         _node->getChild("blend-destination"),
165         _node->getChild("blend-source-rgb"),
166         _node->getChild("blend-destination-rgb"),
167         _node->getChild("blend-source-alpha"),
168         _node->getChild("blend-destination-alpha")
169       );
170       _attributes_dirty &= ~BLEND_FUNC;
171     }
172   }
173
174   //----------------------------------------------------------------------------
175   naRef Element::addEventListener(const nasal::CallContext& ctx)
176   {
177     const std::string type_str = ctx.requireArg<std::string>(0);
178     naRef code = ctx.requireArg<naRef>(1);
179
180     SG_LOG
181     (
182       SG_NASAL,
183       SG_INFO,
184       "addEventListener(" << _node->getPath() << ", " << type_str << ")"
185     );
186
187     Event::Type type = Event::strToType(type_str);
188     if( type == Event::UNKNOWN )
189       naRuntimeError( ctx.c,
190                       "addEventListener: Unknown event type %s",
191                       type_str.c_str() );
192
193     _listener[ type ].push_back
194     (
195       boost::make_shared<EventListener>( code,
196                                          _canvas.lock()->getSystemAdapter() )
197     );
198
199     return naNil();
200   }
201
202   //----------------------------------------------------------------------------
203   void Element::clearEventListener()
204   {
205     _listener.clear();
206   }
207
208   //----------------------------------------------------------------------------
209   bool Element::accept(EventVisitor& visitor)
210   {
211     if( !isVisible() )
212       return false;
213
214     return visitor.apply(*this);
215   }
216
217   //----------------------------------------------------------------------------
218   bool Element::ascend(EventVisitor& visitor)
219   {
220     if( _parent )
221       return _parent->accept(visitor);
222     return true;
223   }
224
225   //----------------------------------------------------------------------------
226   bool Element::traverse(EventVisitor& visitor)
227   {
228     return true;
229   }
230
231   //----------------------------------------------------------------------------
232   bool Element::handleEvent(canvas::EventPtr event)
233   {
234     ListenerMap::iterator listeners = _listener.find(event->getType());
235     if( listeners == _listener.end() )
236       return false;
237
238     BOOST_FOREACH(EventListenerPtr listener, listeners->second)
239       listener->call(event);
240
241     return true;
242   }
243
244   //----------------------------------------------------------------------------
245   bool Element::hitBound( const osg::Vec2f& pos,
246                           const osg::Vec2f& local_pos ) const
247   {
248     const osg::Vec3f pos3(pos, 0);
249
250     // Drawables have a bounding box...
251     if( _drawable )
252       return _drawable->getBound().contains(osg::Vec3f(local_pos, 0));
253     // ... for other elements, i.e. groups only a bounding sphere is available
254     else
255       return _transform->getBound().contains(osg::Vec3f(pos, 0));
256   }
257
258   //----------------------------------------------------------------------------
259   bool Element::isVisible() const
260   {
261     return _transform.valid() && _transform->getNodeMask() != 0;
262   }
263
264   //----------------------------------------------------------------------------
265   osg::MatrixTransform* Element::getMatrixTransform()
266   {
267     return _transform.get();
268   }
269
270   //----------------------------------------------------------------------------
271   osg::MatrixTransform const* Element::getMatrixTransform() const
272   {
273     return _transform.get();
274   }
275
276   //----------------------------------------------------------------------------
277   void Element::childAdded(SGPropertyNode* parent, SGPropertyNode* child)
278   {
279     if(    parent == _node
280         && child->getNameString() == NAME_TRANSFORM )
281     {
282       if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
283         _transform_types.resize( child->getIndex() + 1 );
284
285       _transform_types[ child->getIndex() ] = TT_NONE;
286       _transform_dirty = true;
287       return;
288     }
289     else if(    parent->getParent() == _node
290              && parent->getNameString() == NAME_TRANSFORM )
291     {
292       assert(parent->getIndex() < static_cast<int>(_transform_types.size()));
293
294       const std::string& name = child->getNameString();
295
296       TransformType& type = _transform_types[parent->getIndex()];
297
298       if(      name == "m" )
299         type = TT_MATRIX;
300       else if( name == "t" )
301         type = TT_TRANSLATE;
302       else if( name == "rot" )
303         type = TT_ROTATE;
304       else if( name == "s" )
305         type = TT_SCALE;
306
307       _transform_dirty = true;
308       return;
309     }
310
311     childAdded(child);
312   }
313
314   //----------------------------------------------------------------------------
315   void Element::childRemoved(SGPropertyNode* parent, SGPropertyNode* child)
316   {
317     if( parent == _node )
318     {
319       if( child->getNameString() == NAME_TRANSFORM )
320       {
321         if( !_transform.valid() )
322           return;
323
324         if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
325         {
326           SG_LOG
327           (
328             SG_GENERAL,
329             SG_WARN,
330             "Element::childRemoved: unknown transform: " << child->getPath()
331           );
332           return;
333         }
334
335         _transform_types[ child->getIndex() ] = TT_NONE;
336
337         while( !_transform_types.empty() && _transform_types.back() == TT_NONE )
338           _transform_types.pop_back();
339
340         _transform_dirty = true;
341         return;
342       }
343       else if( StyleInfo const* style = getStyleInfo(child->getNameString()) )
344       {
345         if( setStyle(getParentStyle(child), style) )
346           return;
347       }
348     }
349
350     childRemoved(child);
351   }
352
353   //----------------------------------------------------------------------------
354   void Element::valueChanged(SGPropertyNode* child)
355   {
356     SGPropertyNode *parent = child->getParent();
357     if( parent == _node )
358     {
359       const std::string& name = child->getNameString();
360       if( StyleInfo const* style_info = getStyleInfo(name) )
361       {
362         SGPropertyNode const* style = child;
363         if( isStyleEmpty(child) )
364         {
365           child->clearValue();
366           style = getParentStyle(child);
367         }
368         setStyle(style, style_info);
369         return;
370       }
371       else if( name == "update" )
372         return update(0);
373       else if( name == "visible" )
374         // TODO check if we need another nodemask
375         return _transform->setNodeMask( child->getBoolValue() ? 0xffffffff : 0 );
376       else if( boost::starts_with(name, "blend-") )
377         return (void)(_attributes_dirty |= BLEND_FUNC);
378     }
379     else if(   parent->getParent() == _node
380             && parent->getNameString() == NAME_TRANSFORM )
381     {
382       _transform_dirty = true;
383       return;
384     }
385
386     childChanged(child);
387   }
388
389   //----------------------------------------------------------------------------
390   bool Element::setStyle( const SGPropertyNode* child,
391                           const StyleInfo* style_info )
392   {
393     return canApplyStyle(child) && setStyleImpl(child, style_info);
394   }
395
396   //----------------------------------------------------------------------------
397   void Element::setClip(const std::string& clip)
398   {
399     if( clip.empty() || clip == "auto" )
400     {
401       getOrCreateStateSet()->removeAttribute(osg::StateAttribute::SCISSOR);
402       return;
403     }
404
405     // TODO generalize CSS property parsing
406     const std::string RECT("rect(");
407     if(    !boost::ends_with(clip, ")")
408         || !boost::starts_with(clip, RECT) )
409     {
410       SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
411       return;
412     }
413
414     const std::string sep(", \t\npx");
415     int comp = 0;
416     int values[4];
417
418     for(size_t pos = RECT.size(); comp < 4; ++comp)
419     {
420       pos = clip.find_first_not_of(sep, pos);
421       if( pos == std::string::npos || pos == clip.size() - 1 )
422         break;
423
424       char *end = 0;
425       values[comp] = strtod(&clip[pos], &end);
426       if( end == &clip[pos] || !end )
427         break;
428
429       pos = end - &clip[0];
430     }
431
432     if( comp < 4 )
433     {
434       SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
435       return;
436     }
437
438     float scale_x = 1,
439           scale_y = 1;
440
441     CanvasPtr canvas = _canvas.lock();
442     if( canvas )
443     {
444       // The scissor rectangle isn't affected by any transformation, so we need
445       // to convert to image/canvas coordinates on our selves.
446       scale_x = canvas->getSizeX()
447               / static_cast<float>(canvas->getViewWidth());
448       scale_y = canvas->getSizeY()
449               / static_cast<float>(canvas->getViewHeight());
450     }
451
452     osg::Scissor* scissor = new osg::Scissor();
453     // <top>, <right>, <bottom>, <left>
454     scissor->x() = scale_x * values[3];
455     scissor->y() = scale_y * values[0];
456     scissor->width() = scale_x * (values[1] - values[3]);
457     scissor->height() = scale_y * (values[2] - values[0]);
458
459     if( canvas )
460       // Canvas has y axis upside down
461       scissor->y() = canvas->getSizeY() - scissor->y() - scissor->height();
462
463     getOrCreateStateSet()->setAttributeAndModes(scissor);
464   }
465
466   //----------------------------------------------------------------------------
467   void Element::setBoundingBox(const osg::BoundingBox& bb)
468   {
469     if( _bounding_box.empty() )
470     {
471       SGPropertyNode* bb_node = _node->getChild("bounding-box", 0, true);
472       _bounding_box.resize(4);
473       _bounding_box[0] = bb_node->getChild("min-x", 0, true);
474       _bounding_box[1] = bb_node->getChild("min-y", 0, true);
475       _bounding_box[2] = bb_node->getChild("max-x", 0, true);
476       _bounding_box[3] = bb_node->getChild("max-y", 0, true);
477     }
478
479     _bounding_box[0]->setFloatValue(bb._min.x());
480     _bounding_box[1]->setFloatValue(bb._min.y());
481     _bounding_box[2]->setFloatValue(bb._max.x());
482     _bounding_box[3]->setFloatValue(bb._max.y());
483   }
484
485   //----------------------------------------------------------------------------
486   osg::BoundingBox Element::getTransformedBounds(const osg::Matrix& m) const
487   {
488     if( !_drawable )
489       return osg::BoundingBox();
490
491     osg::BoundingBox transformed;
492     const osg::BoundingBox& bb = _drawable->getBound();
493     for(int i = 0; i < 4; ++i)
494       transformed.expandBy( bb.corner(i) * m );
495
496     return transformed;
497   }
498
499   //----------------------------------------------------------------------------
500   Element::StyleSetters Element::_style_setters;
501
502   //----------------------------------------------------------------------------
503   Element::Element( const CanvasWeakPtr& canvas,
504                     const SGPropertyNode_ptr& node,
505                     const Style& parent_style,
506                     Element* parent ):
507     PropertyBasedElement(node),
508     _canvas( canvas ),
509     _parent( parent ),
510     _attributes_dirty( 0 ),
511     _transform_dirty( false ),
512     _transform( new osg::MatrixTransform ),
513     _style( parent_style ),
514     _drawable( 0 )
515   {
516     SG_LOG
517     (
518       SG_GL,
519       SG_DEBUG,
520       "New canvas element " << node->getPath()
521     );
522
523     if( !isInit<Element>() )
524     {
525       addStyle("clip", "", &Element::setClip, false);
526     }
527
528     // Ensure elements are drawn in order they appear in the element tree
529     _transform->getOrCreateStateSet()
530               ->setRenderBinDetails
531               (
532                 0,
533                 "PreOrderBin",
534                 osg::StateSet::OVERRIDE_RENDERBIN_DETAILS
535               );
536   }
537
538   //----------------------------------------------------------------------------
539   bool Element::isStyleEmpty(const SGPropertyNode* child) const
540   {
541     return !child
542         || simgear::strutils::strip(child->getStringValue()).empty();
543   }
544
545   //----------------------------------------------------------------------------
546   bool Element::canApplyStyle(const SGPropertyNode* child) const
547   {
548     if( _node == child->getParent() )
549       return true;
550
551     // Parent values do not override if element has own value
552     return isStyleEmpty( _node->getChild(child->getName()) );
553   }
554
555   //----------------------------------------------------------------------------
556   bool Element::setStyleImpl( const SGPropertyNode* child,
557                               const StyleInfo* style_info )
558   {
559     const StyleSetter* style_setter = style_info
560                                     ? &style_info->setter
561                                     : getStyleSetter(child->getNameString());
562     while( style_setter )
563     {
564       if( style_setter->func(*this, child) )
565         return true;
566       style_setter = style_setter->next;
567     }
568     return false;
569   }
570
571   //----------------------------------------------------------------------------
572   const Element::StyleInfo*
573   Element::getStyleInfo(const std::string& name) const
574   {
575     StyleSetters::const_iterator setter = _style_setters.find(name);
576     if( setter == _style_setters.end() )
577       return 0;
578
579     return &setter->second;
580   }
581
582   //----------------------------------------------------------------------------
583   const Element::StyleSetter*
584   Element::getStyleSetter(const std::string& name) const
585   {
586     const StyleInfo* info = getStyleInfo(name);
587     return info ? &info->setter : 0;
588   }
589
590   //----------------------------------------------------------------------------
591   const SGPropertyNode*
592   Element::getParentStyle(const SGPropertyNode* child) const
593   {
594     // Try to get value from parent...
595     if( _parent )
596     {
597       Style::const_iterator style =
598         _parent->_style.find(child->getNameString());
599       if( style != _parent->_style.end() )
600         return style->second;
601     }
602
603     // ...or reset to default if none is available
604     return child; // TODO somehow get default value for each style?
605   }
606
607   //----------------------------------------------------------------------------
608   void Element::setDrawable( osg::Drawable* drawable )
609   {
610     _drawable = drawable;
611     assert( _drawable );
612
613     osg::ref_ptr<osg::Geode> geode = new osg::Geode;
614     geode->addDrawable(_drawable);
615     _transform->addChild(geode);
616   }
617
618   //----------------------------------------------------------------------------
619   osg::StateSet* Element::getOrCreateStateSet()
620   {
621     return _drawable ? _drawable->getOrCreateStateSet()
622                      : _transform->getOrCreateStateSet();
623   }
624
625   //----------------------------------------------------------------------------
626   void Element::setupStyle()
627   {
628     BOOST_FOREACH( Style::value_type style, _style )
629       setStyle(style.second);
630   }
631
632 } // namespace canvas
633 } // namespace simgear