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