]> git.mxchange.org Git - simgear.git/blob - simgear/canvas/elements/CanvasElement.cxx
Restructure Canvas/PropertyBasedElement
[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/CanvasEventListener.hxx>
22 #include <simgear/canvas/CanvasEventVisitor.hxx>
23 #include <simgear/canvas/MouseEvent.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/lexical_cast.hpp>
33 #include <boost/make_shared.hpp>
34 #include <boost/tokenizer.hpp>
35
36 #include <cassert>
37 #include <cstring>
38
39 namespace simgear
40 {
41 namespace canvas
42 {
43   const std::string NAME_TRANSFORM = "tf";
44
45   //----------------------------------------------------------------------------
46   Element::OSGUserData::OSGUserData(ElementPtr element):
47     element(element)
48   {
49
50   }
51
52   //----------------------------------------------------------------------------
53   Element::~Element()
54   {
55
56   }
57
58   //----------------------------------------------------------------------------
59   void Element::setSelf(const PropertyBasedElementPtr& self)
60   {
61     PropertyBasedElement::setSelf(self);
62
63     _transform->setUserData
64     (
65       new OSGUserData(boost::static_pointer_cast<Element>(self))
66     );
67   }
68
69   //----------------------------------------------------------------------------
70   void Element::onDestroy()
71   {
72     if( !_transform.valid() )
73       return;
74
75     // The transform node keeps a reference on this element, so ensure it is
76     // deleted.
77     BOOST_FOREACH(osg::Group* parent, _transform->getParents())
78     {
79       parent->removeChild(_transform.get());
80     }
81   }
82
83   //----------------------------------------------------------------------------
84   ElementWeakPtr Element::getWeakPtr() const
85   {
86     return boost::static_pointer_cast<Element>(_self.lock());
87   }
88
89   //----------------------------------------------------------------------------
90   void Element::update(double dt)
91   {
92     if( !_transform->getNodeMask() )
93       // Don't do anything if element is hidden
94       return;
95
96     if( _transform_dirty )
97     {
98       osg::Matrix m;
99       for( size_t i = 0; i < _transform_types.size(); ++i )
100       {
101         // Skip unused indizes...
102         if( _transform_types[i] == TT_NONE )
103           continue;
104
105         SGPropertyNode* tf_node = _node->getChild("tf", i, true);
106
107         // Build up the matrix representation of the current transform node
108         osg::Matrix tf;
109         switch( _transform_types[i] )
110         {
111           case TT_MATRIX:
112             tf = osg::Matrix( tf_node->getDoubleValue("m[0]", 1),
113                               tf_node->getDoubleValue("m[1]", 0),
114                               0,
115                               tf_node->getDoubleValue("m[6]", 0),
116
117                               tf_node->getDoubleValue("m[2]", 0),
118                               tf_node->getDoubleValue("m[3]", 1),
119                               0,
120                               tf_node->getDoubleValue("m[7]", 0),
121
122                               0,
123                               0,
124                               1,
125                               0,
126
127                               tf_node->getDoubleValue("m[4]", 0),
128                               tf_node->getDoubleValue("m[5]", 0),
129                               0,
130                               tf_node->getDoubleValue("m[8]", 1) );
131             break;
132           case TT_TRANSLATE:
133             tf.makeTranslate( osg::Vec3f( tf_node->getDoubleValue("t[0]", 0),
134                                           tf_node->getDoubleValue("t[1]", 0),
135                                           0 ) );
136             break;
137           case TT_ROTATE:
138             tf.makeRotate( tf_node->getDoubleValue("rot", 0), 0, 0, 1 );
139             break;
140           case TT_SCALE:
141           {
142             float sx = tf_node->getDoubleValue("s[0]", 1);
143             // sy defaults to sx...
144             tf.makeScale( sx, tf_node->getDoubleValue("s[1]", sx), 1 );
145             break;
146           }
147           default:
148             break;
149         }
150         m.postMult( tf );
151       }
152       _transform->setMatrix(m);
153       _transform_dirty = false;
154     }
155
156     // Update bounding box on manual update (manual updates pass zero dt)
157     if( dt == 0 && _drawable )
158       _drawable->getBound();
159
160     if( _attributes_dirty & BLEND_FUNC )
161     {
162       parseBlendFunc(
163         _transform->getOrCreateStateSet(),
164         _node->getChild("blend-source"),
165         _node->getChild("blend-destination"),
166         _node->getChild("blend-source-rgb"),
167         _node->getChild("blend-destination-rgb"),
168         _node->getChild("blend-source-alpha"),
169         _node->getChild("blend-destination-alpha")
170       );
171       _attributes_dirty &= ~BLEND_FUNC;
172     }
173   }
174
175   //----------------------------------------------------------------------------
176   naRef Element::addEventListener(const nasal::CallContext& ctx)
177   {
178     const std::string type_str = ctx.requireArg<std::string>(0);
179     naRef code = ctx.requireArg<naRef>(1);
180
181     SG_LOG
182     (
183       SG_NASAL,
184       SG_INFO,
185       "addEventListener(" << _node->getPath() << ", " << type_str << ")"
186     );
187
188     Event::Type type = Event::strToType(type_str);
189     if( type == Event::UNKNOWN )
190       naRuntimeError( ctx.c,
191                       "addEventListener: Unknown event type %s",
192                       type_str.c_str() );
193
194     _listener[ type ].push_back
195     (
196       boost::make_shared<EventListener>( code,
197                                          _canvas.lock()->getSystemAdapter() )
198     );
199
200     return naNil();
201   }
202
203   //----------------------------------------------------------------------------
204   void Element::clearEventListener()
205   {
206     _listener.clear();
207   }
208
209   //----------------------------------------------------------------------------
210   bool Element::accept(EventVisitor& visitor)
211   {
212     return visitor.apply(*this);
213   }
214
215   //----------------------------------------------------------------------------
216   bool Element::ascend(EventVisitor& visitor)
217   {
218     if( _parent )
219       return _parent->accept(visitor);
220     return true;
221   }
222
223   //----------------------------------------------------------------------------
224   bool Element::traverse(EventVisitor& visitor)
225   {
226     return true;
227   }
228
229   //----------------------------------------------------------------------------
230   bool Element::handleEvent(canvas::EventPtr event)
231   {
232     ListenerMap::iterator listeners = _listener.find(event->getType());
233     if( listeners == _listener.end() )
234       return false;
235
236     BOOST_FOREACH(EventListenerPtr listener, listeners->second)
237       listener->call(event);
238
239     return true;
240   }
241
242   //----------------------------------------------------------------------------
243   bool Element::hitBound( const osg::Vec2f& pos,
244                           const osg::Vec2f& local_pos ) const
245   {
246     const osg::Vec3f pos3(pos, 0);
247
248     // Drawables have a bounding box...
249     if( _drawable )
250       return _drawable->getBound().contains(osg::Vec3f(local_pos, 0));
251     // ... for other elements, i.e. groups only a bounding sphere is available
252     else
253       return _transform->getBound().contains(osg::Vec3f(pos, 0));
254   }
255
256   //----------------------------------------------------------------------------
257   bool Element::isVisible() const
258   {
259     return _transform->getNodeMask() != 0;
260   }
261
262   //----------------------------------------------------------------------------
263   osg::MatrixTransform* Element::getMatrixTransform()
264   {
265     return _transform.get();
266   }
267
268   //----------------------------------------------------------------------------
269   osg::MatrixTransform const* Element::getMatrixTransform() const
270   {
271     return _transform.get();
272   }
273
274   //----------------------------------------------------------------------------
275   void Element::childAdded(SGPropertyNode* parent, SGPropertyNode* child)
276   {
277     if(    parent == _node
278         && child->getNameString() == NAME_TRANSFORM )
279     {
280       if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
281         _transform_types.resize( child->getIndex() + 1 );
282
283       _transform_types[ child->getIndex() ] = TT_NONE;
284       _transform_dirty = true;
285       return;
286     }
287     else if(    parent->getParent() == _node
288              && parent->getNameString() == NAME_TRANSFORM )
289     {
290       assert(parent->getIndex() < static_cast<int>(_transform_types.size()));
291
292       const std::string& name = child->getNameString();
293
294       TransformType& type = _transform_types[parent->getIndex()];
295
296       if(      name == "m" )
297         type = TT_MATRIX;
298       else if( name == "t" )
299         type = TT_TRANSLATE;
300       else if( name == "rot" )
301         type = TT_ROTATE;
302       else if( name == "s" )
303         type = TT_SCALE;
304
305       _transform_dirty = true;
306       return;
307     }
308
309     childAdded(child);
310   }
311
312   //----------------------------------------------------------------------------
313   void Element::childRemoved(SGPropertyNode* parent, SGPropertyNode* child)
314   {
315     if( parent == _node && child->getNameString() == NAME_TRANSFORM )
316     {
317       if( child->getIndex() >= static_cast<int>(_transform_types.size()) )
318       {
319         SG_LOG
320         (
321           SG_GENERAL,
322           SG_WARN,
323           "Element::childRemoved: unknown transform: " << child->getPath()
324         );
325         return;
326       }
327
328       _transform_types[ child->getIndex() ] = TT_NONE;
329
330       while( !_transform_types.empty() && _transform_types.back() == TT_NONE )
331         _transform_types.pop_back();
332
333       _transform_dirty = true;
334       return;
335     }
336
337     childRemoved(child);
338   }
339
340   //----------------------------------------------------------------------------
341   void Element::valueChanged(SGPropertyNode* child)
342   {
343     SGPropertyNode *parent = child->getParent();
344     if( parent == _node )
345     {
346       const std::string& name = child->getNameString();
347       if( setStyle(child) )
348         return;
349       else if( name == "update" )
350         return update(0);
351       else if( name == "visible" )
352         // TODO check if we need another nodemask
353         return _transform->setNodeMask( child->getBoolValue() ? 0xffffffff : 0 );
354       else if( boost::starts_with(name, "blend-") )
355         return (void)(_attributes_dirty |= BLEND_FUNC);
356     }
357     else if(   parent->getParent() == _node
358             && parent->getNameString() == NAME_TRANSFORM )
359     {
360       _transform_dirty = true;
361       return;
362     }
363
364     childChanged(child);
365   }
366
367   //----------------------------------------------------------------------------
368   bool Element::setStyle(const SGPropertyNode* child)
369   {
370     StyleSetters::const_iterator setter =
371       _style_setters.find(child->getNameString());
372     if( setter == _style_setters.end() )
373       return false;
374
375     const StyleSetter* style_setter = &setter->second.setter;
376     while( style_setter )
377     {
378       if( style_setter->func(*this, child) )
379         return true;
380       style_setter = style_setter->next;
381     }
382     return false;
383   }
384
385   //----------------------------------------------------------------------------
386   void Element::setClip(const std::string& clip)
387   {
388     if( clip.empty() || clip == "auto" )
389     {
390       getOrCreateStateSet()->removeAttribute(osg::StateAttribute::SCISSOR);
391       return;
392     }
393
394     // TODO generalize CSS property parsing
395     const std::string RECT("rect(");
396     if(    !boost::ends_with(clip, ")")
397         || !boost::starts_with(clip, RECT) )
398     {
399       SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
400       return;
401     }
402
403     typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
404     const boost::char_separator<char> del(", \t\npx");
405
406     tokenizer tokens(clip.begin() + RECT.size(), clip.end() - 1, del);
407     int comp = 0;
408     int values[4];
409     for( tokenizer::const_iterator tok = tokens.begin();
410          tok != tokens.end() && comp < 4;
411          ++tok, ++comp )
412     {
413       values[comp] = boost::lexical_cast<int>(*tok);
414     }
415
416     if( comp < 4 )
417     {
418       SG_LOG(SG_GENERAL, SG_WARN, "Canvas: invalid clip: " << clip);
419       return;
420     }
421
422     float scale_x = 1,
423           scale_y = 1;
424
425     CanvasPtr canvas = _canvas.lock();
426     if( canvas )
427     {
428       // The scissor rectangle isn't affected by any transformation, so we need
429       // to convert to image/canvas coordinates on our selves.
430       scale_x = canvas->getSizeX()
431               / static_cast<float>(canvas->getViewWidth());
432       scale_y = canvas->getSizeY()
433               / static_cast<float>(canvas->getViewHeight());
434     }
435
436     osg::Scissor* scissor = new osg::Scissor();
437     // <top>, <right>, <bottom>, <left>
438     scissor->x() = scale_x * values[3];
439     scissor->y() = scale_y * values[0];
440     scissor->width() = scale_x * (values[1] - values[3]);
441     scissor->height() = scale_y * (values[2] - values[0]);
442
443     if( canvas )
444       // Canvas has y axis upside down
445       scissor->y() = canvas->getSizeY() - scissor->y() - scissor->height();
446
447     getOrCreateStateSet()->setAttributeAndModes(scissor);
448   }
449
450   //----------------------------------------------------------------------------
451   void Element::setBoundingBox(const osg::BoundingBox& bb)
452   {
453     if( _bounding_box.empty() )
454     {
455       SGPropertyNode* bb_node = _node->getChild("bounding-box", 0, true);
456       _bounding_box.resize(4);
457       _bounding_box[0] = bb_node->getChild("min-x", 0, true);
458       _bounding_box[1] = bb_node->getChild("min-y", 0, true);
459       _bounding_box[2] = bb_node->getChild("max-x", 0, true);
460       _bounding_box[3] = bb_node->getChild("max-y", 0, true);
461     }
462
463     _bounding_box[0]->setFloatValue(bb._min.x());
464     _bounding_box[1]->setFloatValue(bb._min.y());
465     _bounding_box[2]->setFloatValue(bb._max.x());
466     _bounding_box[3]->setFloatValue(bb._max.y());
467   }
468
469   //----------------------------------------------------------------------------
470   osg::BoundingBox Element::getTransformedBounds(const osg::Matrix& m) const
471   {
472     if( !_drawable )
473       return osg::BoundingBox();
474
475     osg::BoundingBox transformed;
476     const osg::BoundingBox& bb = _drawable->getBound();
477     for(int i = 0; i < 4; ++i)
478       transformed.expandBy( m * bb.corner(i) );
479
480     return transformed;
481   }
482
483   //----------------------------------------------------------------------------
484   Element::StyleSetters Element::_style_setters;
485
486   //----------------------------------------------------------------------------
487   Element::Element( const CanvasWeakPtr& canvas,
488                     const SGPropertyNode_ptr& node,
489                     const Style& parent_style,
490                     Element* parent ):
491     PropertyBasedElement(node),
492     _canvas( canvas ),
493     _parent( parent ),
494     _attributes_dirty( 0 ),
495     _transform_dirty( false ),
496     _transform( new osg::MatrixTransform ),
497     _style( parent_style ),
498     _drawable( 0 )
499   {
500     SG_LOG
501     (
502       SG_GL,
503       SG_DEBUG,
504       "New canvas element " << node->getPath()
505     );
506
507     if( !isInit<Element>() )
508     {
509       addStyle("clip", "", &Element::setClip);
510     }
511   }
512
513   //----------------------------------------------------------------------------
514   void Element::setDrawable( osg::Drawable* drawable )
515   {
516     _drawable = drawable;
517     assert( _drawable );
518
519     osg::ref_ptr<osg::Geode> geode = new osg::Geode;
520     geode->addDrawable(_drawable);
521     _transform->addChild(geode);
522   }
523
524   //----------------------------------------------------------------------------
525   osg::StateSet* Element::getOrCreateStateSet()
526   {
527     return _drawable ? _drawable->getOrCreateStateSet()
528                      : _transform->getOrCreateStateSet();
529   }
530
531   //----------------------------------------------------------------------------
532   void Element::setupStyle()
533   {
534     BOOST_FOREACH( Style::value_type style, _style )
535       setStyle(style.second);
536   }
537
538 } // namespace canvas
539 } // namespace simgear