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