]> git.mxchange.org Git - simgear.git/blob - simgear/canvas/Canvas.cxx
Canvas: basic support for rectangular clipping (like CSS clip property)
[simgear.git] / simgear / canvas / Canvas.cxx
1 // The canvas for rendering with the 2d API
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 "Canvas.hxx"
20 #include "CanvasEventManager.hxx"
21 #include "CanvasEventVisitor.hxx"
22 #include <simgear/canvas/MouseEvent.hxx>
23 #include <simgear/canvas/CanvasPlacement.hxx>
24 #include <simgear/scene/util/parse_color.hxx>
25 #include <simgear/scene/util/RenderConstants.hxx>
26
27 #include <osg/Camera>
28 #include <osg/Geode>
29 #include <osgText/Text>
30 #include <osgViewer/Viewer>
31
32 #include <boost/algorithm/string/predicate.hpp>
33 #include <boost/foreach.hpp>
34 #include <iostream>
35
36 namespace simgear
37 {
38 namespace canvas
39 {
40
41   //----------------------------------------------------------------------------
42   Canvas::CullCallback::CullCallback(const CanvasWeakPtr& canvas):
43     _canvas( canvas )
44   {
45
46   }
47
48   //----------------------------------------------------------------------------
49   void Canvas::CullCallback::operator()( osg::Node* node,
50                                          osg::NodeVisitor* nv )
51   {
52     if( (nv->getTraversalMask() & simgear::MODEL_BIT) && !_canvas.expired() )
53       _canvas.lock()->enableRendering();
54
55     traverse(node, nv);
56   }
57
58   //----------------------------------------------------------------------------
59   Canvas::Canvas(SGPropertyNode* node):
60     PropertyBasedElement(node),
61     _canvas_mgr(0),
62     _event_manager(new EventManager),
63     _size_x(-1),
64     _size_y(-1),
65     _view_width(-1),
66     _view_height(-1),
67     _status(node, "status"),
68     _status_msg(node, "status-msg"),
69     _mouse_x(node, "mouse/x"),
70     _mouse_y(node, "mouse/y"),
71     _mouse_dx(node, "mouse/dx"),
72     _mouse_dy(node, "mouse/dy"),
73     _mouse_button(node, "mouse/button"),
74     _mouse_state(node, "mouse/state"),
75     _mouse_mod(node, "mouse/mod"),
76     _mouse_scroll(node, "mouse/scroll"),
77     _mouse_event(node, "mouse/event"),
78     _sampling_dirty(false),
79     _render_dirty(true),
80     _visible(true),
81     _render_always(false)
82   {
83     _status = 0;
84     setStatusFlags(MISSING_SIZE_X | MISSING_SIZE_Y);
85   }
86
87   //----------------------------------------------------------------------------
88   Canvas::~Canvas()
89   {
90
91   }
92
93   //----------------------------------------------------------------------------
94   void Canvas::setSystemAdapter(const SystemAdapterPtr& system_adapter)
95   {
96     _system_adapter = system_adapter;
97     _texture.setSystemAdapter(system_adapter);
98   }
99
100   //----------------------------------------------------------------------------
101   SystemAdapterPtr Canvas::getSystemAdapter() const
102   {
103     return _system_adapter;
104   }
105
106   //----------------------------------------------------------------------------
107   void Canvas::setCanvasMgr(CanvasMgr* canvas_mgr)
108   {
109     _canvas_mgr = canvas_mgr;
110   }
111
112   //----------------------------------------------------------------------------
113   CanvasMgr* Canvas::getCanvasMgr() const
114   {
115     return _canvas_mgr;
116   }
117
118   //----------------------------------------------------------------------------
119   void Canvas::addDependentCanvas(const CanvasWeakPtr& canvas)
120   {
121     if( canvas.expired() )
122     {
123       SG_LOG
124       (
125         SG_GENERAL,
126         SG_WARN,
127         "Canvas::addDependentCanvas: got an expired Canvas dependent on "
128         << _node->getPath()
129       );
130       return;
131     }
132
133     _dependent_canvases.insert(canvas);
134   }
135
136   //----------------------------------------------------------------------------
137   void Canvas::removeDependentCanvas(const CanvasWeakPtr& canvas)
138   {
139     _dependent_canvases.erase(canvas);
140   }
141
142   //----------------------------------------------------------------------------
143   GroupPtr Canvas::createGroup(const std::string& name)
144   {
145     return boost::dynamic_pointer_cast<Group>
146     (
147       _root_group->createChild("group", name)
148     );
149   }
150
151   //----------------------------------------------------------------------------
152   void Canvas::enableRendering(bool force)
153   {
154     _visible = true;
155     if( force )
156       _render_dirty = true;
157   }
158
159   //----------------------------------------------------------------------------
160   void Canvas::update(double delta_time_sec)
161   {
162     if( !_texture.serviceable() )
163     {
164       if( _status != STATUS_OK )
165         return;
166
167       _texture.setSize(_size_x, _size_y);
168       _texture.useImageCoords(true);
169       _texture.useStencil(true);
170       _texture.allocRT(/*_camera_callback*/);
171
172       osg::Camera* camera = _texture.getCamera();
173
174       osg::Vec4 clear_color(0.0f, 0.0f, 0.0f , 1.0f);
175       parseColor(_node->getStringValue("background"), clear_color);
176       camera->setClearColor(clear_color);
177
178       camera->addChild(_root_group->getMatrixTransform());
179
180       // Ensure objects are drawn in order of traversal
181       camera->getOrCreateStateSet()->setBinName("TraversalOrderBin");
182
183       if( _texture.serviceable() )
184       {
185         setStatusFlags(STATUS_OK);
186       }
187       else
188       {
189         setStatusFlags(CREATE_FAILED);
190         return;
191       }
192     }
193
194     if( _visible || _render_always )
195     {
196       if( _render_dirty )
197       {
198         // Also mark all dependent (eg. recursively used) canvases as dirty
199         BOOST_FOREACH(CanvasWeakPtr canvas, _dependent_canvases)
200         {
201           if( !canvas.expired() )
202             canvas.lock()->_render_dirty = true;
203         }
204       }
205
206       _texture.setRender(_render_dirty);
207
208       _render_dirty = false;
209       _visible = false;
210     }
211     else
212       _texture.setRender(false);
213
214     _root_group->update(delta_time_sec);
215
216     if( _sampling_dirty )
217     {
218       _texture.setSampling(
219         _node->getBoolValue("mipmapping"),
220         _node->getIntValue("coverage-samples"),
221         _node->getIntValue("color-samples")
222       );
223       _sampling_dirty = false;
224       _render_dirty = true;
225     }
226
227     while( !_dirty_placements.empty() )
228     {
229       SGPropertyNode *node = _dirty_placements.back();
230       _dirty_placements.pop_back();
231
232       if( node->getIndex() >= static_cast<int>(_placements.size()) )
233         // New placement
234         _placements.resize(node->getIndex() + 1);
235       else
236         // Remove possibly existing placements
237         _placements[ node->getIndex() ].clear();
238
239       // Get new placements
240       PlacementFactoryMap::const_iterator placement_factory =
241         _placement_factories.find( node->getStringValue("type", "object") );
242       if( placement_factory != _placement_factories.end() )
243       {
244         Placements& placements = _placements[ node->getIndex() ] =
245           placement_factory->second
246           (
247             node,
248             boost::static_pointer_cast<Canvas>(_self.lock())
249           );
250         node->setStringValue
251         (
252           "status-msg",
253           placements.empty() ? "No match" : "Ok"
254         );
255       }
256       else
257         node->setStringValue("status-msg", "Unknown placement type");
258     }
259   }
260
261   //----------------------------------------------------------------------------
262   naRef Canvas::addEventListener(const nasal::CallContext& ctx)
263   {
264     if( !_root_group.get() )
265       naRuntimeError(ctx.c, "Canvas: No root group!");
266
267     return _root_group->addEventListener(ctx);
268   }
269
270   //----------------------------------------------------------------------------
271   void Canvas::setSizeX(int sx)
272   {
273     if( _size_x == sx )
274       return;
275     _size_x = sx;
276
277     // TODO resize if texture already allocated
278
279     if( _size_x <= 0 )
280       setStatusFlags(MISSING_SIZE_X);
281     else
282       setStatusFlags(MISSING_SIZE_X, false);
283
284     // reset flag to allow creation with new size
285     setStatusFlags(CREATE_FAILED, false);
286   }
287
288   //----------------------------------------------------------------------------
289   void Canvas::setSizeY(int sy)
290   {
291     if( _size_y == sy )
292       return;
293     _size_y = sy;
294
295     // TODO resize if texture already allocated
296
297     if( _size_y <= 0 )
298       setStatusFlags(MISSING_SIZE_Y);
299     else
300       setStatusFlags(MISSING_SIZE_Y, false);
301
302     // reset flag to allow creation with new size
303     setStatusFlags(CREATE_FAILED, false);
304   }
305
306   //----------------------------------------------------------------------------
307   int Canvas::getSizeX() const
308   {
309     return _size_x;
310   }
311
312   //----------------------------------------------------------------------------
313   int Canvas::getSizeY() const
314   {
315     return _size_y;
316   }
317
318   //----------------------------------------------------------------------------
319   void Canvas::setViewWidth(int w)
320   {
321     if( _view_width == w )
322       return;
323     _view_width = w;
324
325     _texture.setViewSize(_view_width, _view_height);
326   }
327
328   //----------------------------------------------------------------------------
329   void Canvas::setViewHeight(int h)
330   {
331     if( _view_height == h )
332       return;
333     _view_height = h;
334
335     _texture.setViewSize(_view_width, _view_height);
336   }
337
338   //----------------------------------------------------------------------------
339   int Canvas::getViewWidth() const
340   {
341     return _view_width;
342   }
343
344   //----------------------------------------------------------------------------
345   int Canvas::getViewHeight() const
346   {
347     return _view_height;
348   }
349
350   //----------------------------------------------------------------------------
351   bool Canvas::handleMouseEvent(const MouseEventPtr& event)
352   {
353     _mouse_x = event->pos.x();
354     _mouse_y = event->pos.y();
355     _mouse_dx = event->delta.x();
356     _mouse_dy = event->delta.y();
357     _mouse_button = event->button;
358     _mouse_state = event->state;
359     _mouse_mod = event->mod;
360     //_mouse_scroll = event.scroll;
361     // Always set event type last because all listeners are attached to it
362     _mouse_event = event->type;
363
364     if( !_root_group.get() )
365       return false;
366
367     EventVisitor visitor( EventVisitor::TRAVERSE_DOWN,
368                           event->getPos(),
369                           event->getDelta() );
370     if( !_root_group->accept(visitor) )
371       return false;
372
373     return _event_manager->handleEvent(event, visitor.getPropagationPath());
374   }
375
376   //----------------------------------------------------------------------------
377   void Canvas::childAdded( SGPropertyNode * parent,
378                            SGPropertyNode * child )
379   {
380     if( parent != _node )
381       return;
382
383     if( child->getNameString() == "placement" )
384       _dirty_placements.push_back(child);
385     else if( _root_group.get() )
386       static_cast<Element*>(_root_group.get())->childAdded(parent, child);
387   }
388
389   //----------------------------------------------------------------------------
390   void Canvas::childRemoved( SGPropertyNode * parent,
391                              SGPropertyNode * child )
392   {
393     _render_dirty = true;
394
395     if( parent != _node )
396       return;
397
398     if( child->getNameString() == "placement" )
399       _placements[ child->getIndex() ].clear();
400     else if( _root_group.get() )
401       static_cast<Element*>(_root_group.get())->childRemoved(parent, child);
402   }
403
404   //----------------------------------------------------------------------------
405   void Canvas::valueChanged(SGPropertyNode* node)
406   {
407     if(    boost::starts_with(node->getNameString(), "status")
408         || node->getParent()->getNameString() == "bounding-box" )
409       return;
410     _render_dirty = true;
411
412     bool handled = true;
413     if(    node->getParent()->getParent() == _node
414         && node->getParent()->getNameString() == "placement" )
415     {
416       bool placement_dirty = false;
417       BOOST_FOREACH(Placements& placements, _placements)
418       {
419         BOOST_FOREACH(PlacementPtr& placement, placements)
420         {
421           // check if change can be directly handled by placement
422           if(    placement->getProps() == node->getParent()
423               && !placement->childChanged(node) )
424             placement_dirty = true;
425         }
426       }
427
428       if( !placement_dirty )
429         return;
430
431       // prevent double updates...
432       for( size_t i = 0; i < _dirty_placements.size(); ++i )
433       {
434         if( node->getParent() == _dirty_placements[i] )
435           return;
436       }
437
438       _dirty_placements.push_back(node->getParent());
439     }
440     else if( node->getParent() == _node )
441     {
442       if( node->getNameString() == "background" )
443       {
444         osg::Vec4 color;
445         if( _texture.getCamera() && parseColor(node->getStringValue(), color) )
446         {
447           _texture.getCamera()->setClearColor(color);
448           _render_dirty = true;
449         }
450       }
451       else if(    node->getNameString() == "mipmapping"
452               || node->getNameString() == "coverage-samples"
453               || node->getNameString() == "color-samples" )
454       {
455         _sampling_dirty = true;
456       }
457       else if( node->getNameString() == "render-always" )
458       {
459         _render_always = node->getBoolValue();
460       }
461       else if( node->getNameString() == "size" )
462       {
463         if( node->getIndex() == 0 )
464           setSizeX( node->getIntValue() );
465         else if( node->getIndex() == 1 )
466           setSizeY( node->getIntValue() );
467       }
468       else if( node->getNameString() == "view" )
469       {
470         if( node->getIndex() == 0 )
471           setViewWidth( node->getIntValue() );
472         else if( node->getIndex() == 1 )
473           setViewHeight( node->getIntValue() );
474       }
475       else if( node->getNameString() == "freeze" )
476         _texture.setRender( node->getBoolValue() );
477       else
478         handled = false;
479     }
480     else
481       handled = false;
482
483     if( !handled && _root_group.get() )
484       _root_group->valueChanged(node);
485   }
486
487   //----------------------------------------------------------------------------
488   osg::Texture2D* Canvas::getTexture() const
489   {
490     return _texture.getTexture();
491   }
492
493   //----------------------------------------------------------------------------
494   Canvas::CullCallbackPtr Canvas::getCullCallback() const
495   {
496     return _cull_callback;
497   }
498
499   //----------------------------------------------------------------------------
500   void Canvas::addPlacementFactory( const std::string& type,
501                                     PlacementFactory factory )
502   {
503     if( _placement_factories.find(type) != _placement_factories.end() )
504       SG_LOG
505       (
506         SG_GENERAL,
507         SG_WARN,
508         "Canvas::addPlacementFactory: replace existing factor for type " << type
509       );
510
511     _placement_factories[type] = factory;
512   }
513
514   //----------------------------------------------------------------------------
515   void Canvas::setSelf(const PropertyBasedElementPtr& self)
516   {
517     PropertyBasedElement::setSelf(self);
518
519     CanvasPtr canvas = boost::static_pointer_cast<Canvas>(self);
520
521     _root_group.reset( new Group(canvas, _node) );
522     _root_group->setSelf(_root_group);
523
524     // Remove automatically created property listener as we forward them on our
525     // own
526     _root_group->removeListener();
527
528     _cull_callback = new CullCallback(canvas);
529   }
530
531   //----------------------------------------------------------------------------
532   void Canvas::setStatusFlags(unsigned int flags, bool set)
533   {
534     if( set )
535       _status = _status | flags;
536     else
537       _status = _status & ~flags;
538     // TODO maybe extend simgear::PropertyObject to allow |=, &= etc.
539
540     if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
541       _status_msg = "Missing size";
542     else if( _status & MISSING_SIZE_X )
543       _status_msg = "Missing size-x";
544     else if( _status & MISSING_SIZE_Y )
545       _status_msg = "Missing size-y";
546     else if( _status & CREATE_FAILED )
547       _status_msg = "Creating render target failed";
548     else if( _status == STATUS_OK && !_texture.serviceable() )
549       _status_msg = "Creation pending...";
550     else
551       _status_msg = "Ok";
552   }
553
554   //----------------------------------------------------------------------------
555   Canvas::PlacementFactoryMap Canvas::_placement_factories;
556
557 } // namespace canvas
558 } // namespace simgear