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