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