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