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