]> git.mxchange.org Git - simgear.git/blob - simgear/canvas/elements/CanvasElement.cxx
canvas: exclude data-* properties from triggering an update.
[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/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>
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 <cmath>
37 #include <cstring>
38
39 namespace simgear
40 {
41 namespace canvas
42 {
43   const std::string NAME_TRANSFORM = "tf";
44
45   /**
46    * glScissor with coordinates relative to different reference frames.
47    */
48   class Element::RelativeScissor:
49     public osg::Scissor
50   {
51     public:
52
53       ReferenceFrame    _coord_reference;
54       osg::Matrix       _parent_inverse;
55
56       RelativeScissor():
57         _coord_reference(GLOBAL)
58       {}
59
60       bool contains(const osg::Vec2f& pos) const
61       {
62         return _x <= pos.x() && pos.x() <= _x + _width
63             && _y <= pos.y() && pos.y() <= _y + _height;
64       }
65
66       bool contains( const osg::Vec2f& global_pos,
67                      const osg::Vec2f& parent_pos,
68                      const osg::Vec2f& local_pos ) const
69       {
70         switch( _coord_reference )
71         {
72           case GLOBAL: return contains(global_pos);
73           case PARENT: return contains(parent_pos);
74           case LOCAL:  return contains(local_pos);
75         }
76
77         return false;
78       }
79
80       virtual void apply(osg::State& state) const
81       {
82         const osg::Viewport* vp = state.getCurrentViewport();
83         float w2 = 0.5 * vp->width(),
84               h2 = 0.5 * vp->height();
85
86         osg::Matrix model_view
87         (
88           w2, 0,  0, 0,
89           0,  h2, 0, 0,
90           0,  0,  1, 0,
91           w2, h2, 0, 1
92         );
93         model_view.preMult(state.getProjectionMatrix());
94
95         if( _coord_reference != GLOBAL )
96         {
97           model_view.preMult(state.getModelViewMatrix());
98
99           if( _coord_reference == PARENT )
100             model_view.preMult(_parent_inverse);
101         }
102
103         const osg::Vec2 scale( model_view(0,0), model_view(1,1)),
104                         offset(model_view(3,0), model_view(3,1));
105
106         // TODO check/warn for rotation?
107
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);
112
113         if( scale.x() < 0 )
114           x -= w;
115         if( scale.y() < 0 )
116           y -= h;
117
118         glScissor(x, y, w, h);
119       }
120   };
121
122   //----------------------------------------------------------------------------
123   Element::OSGUserData::OSGUserData(ElementPtr element):
124     element(element)
125   {
126
127   }
128
129   //----------------------------------------------------------------------------
130   Element::~Element()
131   {
132     if( !_transform.valid() )
133       return;
134
135     for(unsigned int i = 0; i < _transform->getNumChildren(); ++i)
136     {
137       OSGUserData* ud =
138         static_cast<OSGUserData*>(_transform->getChild(i)->getUserData());
139
140       if( ud )
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;
144     }
145   }
146
147   //----------------------------------------------------------------------------
148   void Element::onDestroy()
149   {
150     if( !_transform.valid() )
151       return;
152
153     // The transform node keeps a reference on this element, so ensure it is
154     // deleted.
155     BOOST_FOREACH(osg::Group* parent, _transform->getParents())
156     {
157       parent->removeChild(_transform.get());
158     }
159   }
160
161   //----------------------------------------------------------------------------
162   ElementPtr Element::getParent()
163   {
164     return _parent;
165   }
166
167   //----------------------------------------------------------------------------
168   void Element::update(double dt)
169   {
170     if( !isVisible() )
171       return;
172
173     // Trigger matrix update
174     getMatrix();
175
176     // TODO limit bounding box to scissor
177     if( _attributes_dirty & SCISSOR_COORDS )
178     {
179       if( _scissor && _scissor->_coord_reference != GLOBAL )
180         _scissor->_parent_inverse = _transform->getInverseMatrix();
181
182       _attributes_dirty &= ~SCISSOR_COORDS;
183     }
184
185     // Update bounding box on manual update (manual updates pass zero dt)
186     if( dt == 0 && _drawable )
187       _drawable->getBound();
188
189     if( _attributes_dirty & BLEND_FUNC )
190     {
191       parseBlendFunc(
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")
199       );
200       _attributes_dirty &= ~BLEND_FUNC;
201     }
202   }
203
204   //----------------------------------------------------------------------------
205   bool Element::addEventListener( const std::string& type_str,
206                                   const EventListener& cb )
207   {
208     SG_LOG
209     (
210       SG_GENERAL,
211       SG_INFO,
212       "addEventListener(" << _node->getPath() << ", " << type_str << ")"
213     );
214
215     _listener[ Event::getOrRegisterType(type_str) ].push_back(cb);
216     return true;
217   }
218
219   //----------------------------------------------------------------------------
220   void Element::clearEventListener()
221   {
222     _listener.clear();
223   }
224
225   //----------------------------------------------------------------------------
226   bool Element::accept(EventVisitor& visitor)
227   {
228     if( !isVisible() )
229       return false;
230
231     return visitor.apply(*this);
232   }
233
234   //----------------------------------------------------------------------------
235   bool Element::ascend(EventVisitor& visitor)
236   {
237     if( _parent )
238       return _parent->accept(visitor);
239     return true;
240   }
241
242   //----------------------------------------------------------------------------
243   bool Element::traverse(EventVisitor& visitor)
244   {
245     return true;
246   }
247
248   //----------------------------------------------------------------------------
249   bool Element::handleEvent(EventPtr event)
250   {
251     ListenerMap::iterator listeners = _listener.find(event->getType());
252     if( listeners == _listener.end() )
253       return false;
254
255     BOOST_FOREACH(EventListener const& listener, listeners->second)
256       listener(event);
257
258     return true;
259   }
260
261   //----------------------------------------------------------------------------
262   bool Element::dispatchEvent(EventPtr event)
263   {
264     EventPropagationPath path;
265     path.push_back( EventTarget(this) );
266
267     for( Element* parent = _parent;
268                   parent != NULL;
269                   parent = parent->_parent )
270       path.push_front( EventTarget(parent) );
271
272     CanvasPtr canvas = _canvas.lock();
273     if( !canvas )
274       return false;
275
276     return canvas->propagateEvent(event, path);
277   }
278
279   //----------------------------------------------------------------------------
280   bool Element::hitBound( const osg::Vec2f& global_pos,
281                           const osg::Vec2f& parent_pos,
282                           const osg::Vec2f& local_pos ) const
283   {
284     if( _scissor && !_scissor->contains(global_pos, parent_pos, local_pos) )
285       return false;
286
287     const osg::Vec3f pos3(parent_pos, 0);
288
289     // Drawables have a bounding box...
290     if( _drawable )
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));
295     else
296       return false;
297   }
298
299
300   //----------------------------------------------------------------------------
301   void Element::setVisible(bool visible)
302   {
303     if( _transform.valid() )
304       // TODO check if we need another nodemask
305       _transform->setNodeMask(visible ? 0xffffffff : 0);
306   }
307
308   //----------------------------------------------------------------------------
309   bool Element::isVisible() const
310   {
311     return _transform.valid() && _transform->getNodeMask() != 0;
312   }
313
314   //----------------------------------------------------------------------------
315   osg::MatrixTransform* Element::getMatrixTransform()
316   {
317     return _transform.get();
318   }
319
320   //----------------------------------------------------------------------------
321   osg::MatrixTransform const* Element::getMatrixTransform() const
322   {
323     return _transform.get();
324   }
325
326   //----------------------------------------------------------------------------
327   osg::Vec2f Element::posToLocal(const osg::Vec2f& pos) const
328   {
329     getMatrix();
330     const osg::Matrix& m = _transform->getInverseMatrix();
331     return osg::Vec2f
332     (
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)
335     );
336   }
337
338   //----------------------------------------------------------------------------
339   void Element::childAdded(SGPropertyNode* parent, SGPropertyNode* child)
340   {
341     if(    parent == _node
342         && child->getNameString() == NAME_TRANSFORM )
343     {
344       if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
345         _transform_types.resize( child->getIndex() + 1 );
346
347       _transform_types[ child->getIndex() ] = TT_NONE;
348       _attributes_dirty |= TRANSFORM;
349       return;
350     }
351     else if(    parent->getParent() == _node
352              && parent->getNameString() == NAME_TRANSFORM )
353     {
354       assert(parent->getIndex() < static_cast<int>(_transform_types.size()));
355
356       const std::string& name = child->getNameString();
357
358       TransformType& type = _transform_types[parent->getIndex()];
359
360       if(      name == "m" )
361         type = TT_MATRIX;
362       else if( name == "t" )
363         type = TT_TRANSLATE;
364       else if( name == "rot" )
365         type = TT_ROTATE;
366       else if( name == "s" )
367         type = TT_SCALE;
368
369       _attributes_dirty |= TRANSFORM;
370       return;
371     }
372
373     childAdded(child);
374   }
375
376   //----------------------------------------------------------------------------
377   void Element::childRemoved(SGPropertyNode* parent, SGPropertyNode* child)
378   {
379     if( parent == _node )
380     {
381       if( child->getNameString() == NAME_TRANSFORM )
382       {
383         if( !_transform.valid() )
384           return;
385
386         if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
387         {
388           SG_LOG
389           (
390             SG_GENERAL,
391             SG_WARN,
392             "Element::childRemoved: unknown transform: " << child->getPath()
393           );
394           return;
395         }
396
397         _transform_types[ child->getIndex() ] = TT_NONE;
398
399         while( !_transform_types.empty() && _transform_types.back() == TT_NONE )
400           _transform_types.pop_back();
401
402         _attributes_dirty |= TRANSFORM;
403         return;
404       }
405       else if( StyleInfo const* style = getStyleInfo(child->getNameString()) )
406       {
407         if( setStyle(getParentStyle(child), style) )
408           return;
409       }
410     }
411
412     childRemoved(child);
413   }
414
415   //----------------------------------------------------------------------------
416   void Element::valueChanged(SGPropertyNode* child)
417   {
418     SGPropertyNode *parent = child->getParent();
419     if( parent == _node )
420     {
421       const std::string& name = child->getNameString();
422       if( boost::starts_with(name, "data-") )
423         return;
424       else if( StyleInfo const* style_info = getStyleInfo(name) )
425       {
426         SGPropertyNode const* style = child;
427         if( isStyleEmpty(child) )
428         {
429           child->clearValue();
430           style = getParentStyle(child);
431         }
432         setStyle(style, style_info);
433         return;
434       }
435       else if( name == "update" )
436         return update(0);
437       else if( boost::starts_with(name, "blend-") )
438         return (void)(_attributes_dirty |= BLEND_FUNC);
439     }
440     else if(   parent->getParent() == _node
441             && parent->getNameString() == NAME_TRANSFORM )
442     {
443       _attributes_dirty |= TRANSFORM;
444       return;
445     }
446
447     childChanged(child);
448   }
449
450   //----------------------------------------------------------------------------
451   bool Element::setStyle( const SGPropertyNode* child,
452                           const StyleInfo* style_info )
453   {
454     return canApplyStyle(child) && setStyleImpl(child, style_info);
455   }
456
457   //----------------------------------------------------------------------------
458   void Element::setClip(const std::string& clip)
459   {
460     if( clip.empty() || clip == "auto" )
461     {
462       getOrCreateStateSet()->removeAttribute(osg::StateAttribute::SCISSOR);
463       _scissor = 0;
464       return;
465     }
466
467     // TODO generalize CSS property parsing
468     const std::string RECT("rect(");
469     if(    !boost::ends_with(clip, ")")
470         || !boost::starts_with(clip, RECT) )
471     {
472       SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
473       return;
474     }
475
476     const std::string sep(", \t\npx");
477     int comp = 0;
478     float values[4];
479
480     for(size_t pos = RECT.size(); comp < 4; ++comp)
481     {
482       pos = clip.find_first_not_of(sep, pos);
483       if( pos == std::string::npos || pos == clip.size() - 1 )
484         break;
485
486       char *end = 0;
487       values[comp] = strtod(&clip[pos], &end);
488       if( end == &clip[pos] || !end )
489         break;
490
491       pos = end - &clip[0];
492     }
493
494     if( comp < 4 )
495     {
496       SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
497       return;
498     }
499
500     float width = values[1] - values[3],
501           height = values[2] - values[0];
502
503     if( width < 0 || height < 0 )
504     {
505       SG_LOG(SG_GENERAL, SG_WARN, "Canvas: negative clip size: " << clip);
506       return;
507     }
508
509     _scissor = new RelativeScissor();
510     // <top>, <right>, <bottom>, <left>
511     _scissor->x() = SGMiscf::roundToInt(values[3]);
512     _scissor->y() = SGMiscf::roundToInt(values[0]);
513     _scissor->width() = SGMiscf::roundToInt(width);
514     _scissor->height() = SGMiscf::roundToInt(height);
515
516     getOrCreateStateSet()->setAttributeAndModes(_scissor);
517
518     SGPropertyNode* clip_frame = _node->getChild("clip-frame", 0);
519     if( clip_frame )
520       valueChanged(clip_frame);
521   }
522
523   //----------------------------------------------------------------------------
524   void Element::setClipFrame(ReferenceFrame rf)
525   {
526     if( _scissor )
527     {
528       _scissor->_coord_reference = rf;
529       _attributes_dirty |= SCISSOR_COORDS;
530     }
531   }
532
533   //----------------------------------------------------------------------------
534   osg::BoundingBox Element::getBoundingBox() const
535   {
536     if( _drawable )
537       return _drawable->getBound();
538
539     osg::BoundingBox bb;
540
541     if( _transform.valid() )
542       bb.expandBy(_transform->getBound());
543
544     return bb;
545   }
546
547   //----------------------------------------------------------------------------
548   osg::BoundingBox Element::getTightBoundingBox() const
549   {
550     return getTransformedBounds(getMatrix());
551   }
552
553   //----------------------------------------------------------------------------
554   osg::BoundingBox Element::getTransformedBounds(const osg::Matrix& m) const
555   {
556     if( !_drawable )
557       return osg::BoundingBox();
558
559     osg::BoundingBox transformed;
560     const osg::BoundingBox& bb = _drawable->getBound();
561     for(int i = 0; i < 4; ++i)
562       transformed.expandBy( bb.corner(i) * m );
563
564     return transformed;
565   }
566
567   //----------------------------------------------------------------------------
568   osg::Matrix Element::getMatrix() const
569   {
570     if( !_transform )
571       return osg::Matrix::identity();
572
573     if( !(_attributes_dirty & TRANSFORM) )
574       return _transform->getMatrix();
575
576     osg::Matrix m;
577     for( size_t i = 0; i < _transform_types.size(); ++i )
578     {
579       // Skip unused indizes...
580       if( _transform_types[i] == TT_NONE )
581         continue;
582
583       SGPropertyNode* tf_node = _node->getChild("tf", i, true);
584
585       // Build up the matrix representation of the current transform node
586       osg::Matrix tf;
587       switch( _transform_types[i] )
588       {
589         case TT_MATRIX:
590           tf = osg::Matrix( tf_node->getDoubleValue("m[0]", 1),
591                             tf_node->getDoubleValue("m[1]", 0),
592                             0,
593                             tf_node->getDoubleValue("m[6]", 0),
594
595                             tf_node->getDoubleValue("m[2]", 0),
596                             tf_node->getDoubleValue("m[3]", 1),
597                             0,
598                             tf_node->getDoubleValue("m[7]", 0),
599
600                             0,
601                             0,
602                             1,
603                             0,
604
605                             tf_node->getDoubleValue("m[4]", 0),
606                             tf_node->getDoubleValue("m[5]", 0),
607                             0,
608                             tf_node->getDoubleValue("m[8]", 1) );
609           break;
610         case TT_TRANSLATE:
611           tf.makeTranslate( osg::Vec3f( tf_node->getDoubleValue("t[0]", 0),
612                                         tf_node->getDoubleValue("t[1]", 0),
613                                         0 ) );
614           break;
615         case TT_ROTATE:
616           tf.makeRotate( tf_node->getDoubleValue("rot", 0), 0, 0, 1 );
617           break;
618         case TT_SCALE:
619         {
620           float sx = tf_node->getDoubleValue("s[0]", 1);
621           // sy defaults to sx...
622           tf.makeScale( sx, tf_node->getDoubleValue("s[1]", sx), 1 );
623           break;
624         }
625         default:
626           break;
627       }
628       m.postMult( tf );
629     }
630     _transform->setMatrix(m);
631     _attributes_dirty &= ~TRANSFORM;
632     _attributes_dirty |= SCISSOR_COORDS;
633
634     return m;
635   }
636
637   //----------------------------------------------------------------------------
638   Element::StyleSetters Element::_style_setters;
639
640   //----------------------------------------------------------------------------
641   Element::Element( const CanvasWeakPtr& canvas,
642                     const SGPropertyNode_ptr& node,
643                     const Style& parent_style,
644                     Element* parent ):
645     PropertyBasedElement(node),
646     _canvas( canvas ),
647     _parent( parent ),
648     _attributes_dirty( 0 ),
649     _transform( new osg::MatrixTransform ),
650     _style( parent_style ),
651     _scissor( 0 ),
652     _drawable( 0 )
653   {
654     staticInit();
655
656     SG_LOG
657     (
658       SG_GL,
659       SG_DEBUG,
660       "New canvas element " << node->getPath()
661     );
662
663     // Ensure elements are drawn in order they appear in the element tree
664     _transform->getOrCreateStateSet()
665               ->setRenderBinDetails
666               (
667                 0,
668                 "PreOrderBin",
669                 osg::StateSet::OVERRIDE_RENDERBIN_DETAILS
670               );
671
672     _transform->setUserData( new OSGUserData(this) );
673   }
674
675   //----------------------------------------------------------------------------
676   void Element::staticInit()
677   {
678     if( isInit<Element>() )
679       return;
680
681     addStyle("clip", "", &Element::setClip, false);
682     addStyle("clip-frame", "", &Element::setClipFrame, false);
683     addStyle("visible", "", &Element::setVisible, false);
684   }
685
686   //----------------------------------------------------------------------------
687   bool Element::isStyleEmpty(const SGPropertyNode* child) const
688   {
689     return !child
690         || simgear::strutils::strip(child->getStringValue()).empty();
691   }
692
693   //----------------------------------------------------------------------------
694   bool Element::canApplyStyle(const SGPropertyNode* child) const
695   {
696     if( _node == child->getParent() )
697       return true;
698
699     // Parent values do not override if element has own value
700     return isStyleEmpty( _node->getChild(child->getName()) );
701   }
702
703   //----------------------------------------------------------------------------
704   bool Element::setStyleImpl( const SGPropertyNode* child,
705                               const StyleInfo* style_info )
706   {
707     const StyleSetter* style_setter = style_info
708                                     ? &style_info->setter
709                                     : getStyleSetter(child->getNameString());
710     while( style_setter )
711     {
712       if( style_setter->func(*this, child) )
713         return true;
714       style_setter = style_setter->next;
715     }
716     return false;
717   }
718
719   //----------------------------------------------------------------------------
720   const Element::StyleInfo*
721   Element::getStyleInfo(const std::string& name) const
722   {
723     StyleSetters::const_iterator setter = _style_setters.find(name);
724     if( setter == _style_setters.end() )
725       return 0;
726
727     return &setter->second;
728   }
729
730   //----------------------------------------------------------------------------
731   const Element::StyleSetter*
732   Element::getStyleSetter(const std::string& name) const
733   {
734     const StyleInfo* info = getStyleInfo(name);
735     return info ? &info->setter : 0;
736   }
737
738   //----------------------------------------------------------------------------
739   const SGPropertyNode*
740   Element::getParentStyle(const SGPropertyNode* child) const
741   {
742     // Try to get value from parent...
743     if( _parent )
744     {
745       Style::const_iterator style =
746         _parent->_style.find(child->getNameString());
747       if( style != _parent->_style.end() )
748         return style->second;
749     }
750
751     // ...or reset to default if none is available
752     return child; // TODO somehow get default value for each style?
753   }
754
755   //----------------------------------------------------------------------------
756   void Element::setDrawable( osg::Drawable* drawable )
757   {
758     _drawable = drawable;
759     assert( _drawable );
760
761     osg::ref_ptr<osg::Geode> geode = new osg::Geode;
762     geode->addDrawable(_drawable);
763     _transform->addChild(geode);
764   }
765
766   //----------------------------------------------------------------------------
767   osg::StateSet* Element::getOrCreateStateSet()
768   {
769     return _drawable ? _drawable->getOrCreateStateSet()
770                      : _transform->getOrCreateStateSet();
771   }
772
773   //----------------------------------------------------------------------------
774   void Element::setupStyle()
775   {
776     BOOST_FOREACH( Style::value_type style, _style )
777       setStyle(style.second);
778   }
779
780 } // namespace canvas
781 } // namespace simgear