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