]> git.mxchange.org Git - simgear.git/blob - simgear/canvas/Canvas.cxx
Canvas: proper forwarding of dirty and visible flags within nested canvases.
[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     _sampling_dirty(false),
70     _render_dirty(true),
71     _visible(true),
72     _render_always(false)
73   {
74     _status = 0;
75     setStatusFlags(MISSING_SIZE_X | MISSING_SIZE_Y);
76   }
77
78   //----------------------------------------------------------------------------
79   Canvas::~Canvas()
80   {
81
82   }
83
84   //----------------------------------------------------------------------------
85   void Canvas::setSystemAdapter(const SystemAdapterPtr& system_adapter)
86   {
87     _system_adapter = system_adapter;
88     _texture.setSystemAdapter(system_adapter);
89   }
90
91   //----------------------------------------------------------------------------
92   SystemAdapterPtr Canvas::getSystemAdapter() const
93   {
94     return _system_adapter;
95   }
96
97   //----------------------------------------------------------------------------
98   void Canvas::setCanvasMgr(CanvasMgr* canvas_mgr)
99   {
100     _canvas_mgr = canvas_mgr;
101   }
102
103   //----------------------------------------------------------------------------
104   CanvasMgr* Canvas::getCanvasMgr() const
105   {
106     return _canvas_mgr;
107   }
108
109   //----------------------------------------------------------------------------
110   void Canvas::addParentCanvas(const CanvasWeakPtr& canvas)
111   {
112     if( canvas.expired() )
113     {
114       SG_LOG
115       (
116         SG_GENERAL,
117         SG_WARN,
118         "Canvas::addParentCanvas: got an expired parent: " << _node->getPath()
119       );
120       return;
121     }
122
123     _parent_canvases.insert(canvas);
124   }
125
126   //----------------------------------------------------------------------------
127   void Canvas::addChildCanvas(const CanvasWeakPtr& canvas)
128   {
129     if( canvas.expired() )
130     {
131       SG_LOG
132       (
133         SG_GENERAL,
134         SG_WARN,
135         "Canvas::addChildCanvas: got an expired child: " << _node->getPath()
136       );
137       return;
138     }
139
140     _child_canvases.insert(canvas);
141   }
142
143   //----------------------------------------------------------------------------
144   void Canvas::removeParentCanvas(const CanvasWeakPtr& canvas)
145   {
146     _parent_canvases.erase(canvas);
147   }
148
149   //----------------------------------------------------------------------------
150   void Canvas::removeChildCanvas(const CanvasWeakPtr& canvas)
151   {
152     _child_canvases.erase(canvas);
153   }
154
155   //----------------------------------------------------------------------------
156   GroupPtr Canvas::createGroup(const std::string& name)
157   {
158     return boost::dynamic_pointer_cast<Group>
159     (
160       _root_group->createChild("group", name)
161     );
162   }
163
164   //----------------------------------------------------------------------------
165   void Canvas::enableRendering(bool force)
166   {
167     _visible = true;
168     if( force )
169       _render_dirty = true;
170   }
171
172   //----------------------------------------------------------------------------
173   void Canvas::update(double delta_time_sec)
174   {
175     if(    (!_texture.serviceable() && _status != STATUS_DIRTY)
176         || (_status & CREATE_FAILED) )
177       return;
178
179     if( _status == STATUS_DIRTY )
180     {
181       _texture.setSize(_size_x, _size_y);
182
183       if( !_texture.serviceable() )
184       {
185         _texture.useImageCoords(true);
186         _texture.useStencil(true);
187         _texture.allocRT(/*_camera_callback*/);
188       }
189       else
190       {
191         // Resizing causes a new texture to be created so we need to reapply all
192         // existing placements
193         reloadPlacements();
194       }
195
196       osg::Camera* camera = _texture.getCamera();
197
198       osg::Vec4 clear_color(0.0f, 0.0f, 0.0f , 1.0f);
199       parseColor(_node->getStringValue("background"), clear_color);
200       camera->setClearColor(clear_color);
201
202       camera->addChild(_root_group->getMatrixTransform());
203
204       // Ensure objects are drawn in order of traversal
205       camera->getOrCreateStateSet()->setBinName("TraversalOrderBin");
206
207       if( _texture.serviceable() )
208       {
209         setStatusFlags(STATUS_OK);
210         setStatusFlags(STATUS_DIRTY, false);
211         _render_dirty = true;
212       }
213       else
214       {
215         setStatusFlags(CREATE_FAILED);
216         return;
217       }
218     }
219
220     if( _visible || _render_always )
221     {
222       BOOST_FOREACH(CanvasWeakPtr canvas, _child_canvases)
223       {
224         // TODO should we check if the image the child canvas is displayed
225         //      within is really visible?
226         if( !canvas.expired() )
227           canvas.lock()->_visible = true;
228       }
229
230       if( _render_dirty )
231       {
232         // Also mark all canvases this canvas is displayed within as dirty
233         BOOST_FOREACH(CanvasWeakPtr canvas, _parent_canvases)
234         {
235           if( !canvas.expired() )
236             canvas.lock()->_render_dirty = true;
237         }
238       }
239
240       _texture.setRender(_render_dirty);
241
242       _render_dirty = false;
243       _visible = false;
244     }
245     else
246       _texture.setRender(false);
247
248     _root_group->update(delta_time_sec);
249
250     if( _sampling_dirty )
251     {
252       _texture.setSampling(
253         _node->getBoolValue("mipmapping"),
254         _node->getIntValue("coverage-samples"),
255         _node->getIntValue("color-samples")
256       );
257       _sampling_dirty = false;
258       _render_dirty = true;
259     }
260
261     while( !_dirty_placements.empty() )
262     {
263       SGPropertyNode *node = _dirty_placements.back();
264       _dirty_placements.pop_back();
265
266       if( node->getIndex() >= static_cast<int>(_placements.size()) )
267         // New placement
268         _placements.resize(node->getIndex() + 1);
269       else
270         // Remove possibly existing placements
271         _placements[ node->getIndex() ].clear();
272
273       // Get new placements
274       PlacementFactoryMap::const_iterator placement_factory =
275         _placement_factories.find( node->getStringValue("type", "object") );
276       if( placement_factory != _placement_factories.end() )
277       {
278         Placements& placements = _placements[ node->getIndex() ] =
279           placement_factory->second
280           (
281             node,
282             boost::static_pointer_cast<Canvas>(_self.lock())
283           );
284         node->setStringValue
285         (
286           "status-msg",
287           placements.empty() ? "No match" : "Ok"
288         );
289       }
290       else
291         node->setStringValue("status-msg", "Unknown placement type");
292     }
293   }
294
295   //----------------------------------------------------------------------------
296   naRef Canvas::addEventListener(const nasal::CallContext& ctx)
297   {
298     if( !_root_group.get() )
299       naRuntimeError(ctx.c, "Canvas: No root group!");
300
301     return _root_group->addEventListener(ctx);
302   }
303
304   //----------------------------------------------------------------------------
305   void Canvas::setSizeX(int sx)
306   {
307     if( _size_x == sx )
308       return;
309     _size_x = sx;
310     setStatusFlags(STATUS_DIRTY);
311
312     if( _size_x <= 0 )
313       setStatusFlags(MISSING_SIZE_X);
314     else
315       setStatusFlags(MISSING_SIZE_X, false);
316
317     // reset flag to allow creation with new size
318     setStatusFlags(CREATE_FAILED, false);
319   }
320
321   //----------------------------------------------------------------------------
322   void Canvas::setSizeY(int sy)
323   {
324     if( _size_y == sy )
325       return;
326     _size_y = sy;
327     setStatusFlags(STATUS_DIRTY);
328
329     if( _size_y <= 0 )
330       setStatusFlags(MISSING_SIZE_Y);
331     else
332       setStatusFlags(MISSING_SIZE_Y, false);
333
334     // reset flag to allow creation with new size
335     setStatusFlags(CREATE_FAILED, false);
336   }
337
338   //----------------------------------------------------------------------------
339   int Canvas::getSizeX() const
340   {
341     return _size_x;
342   }
343
344   //----------------------------------------------------------------------------
345   int Canvas::getSizeY() const
346   {
347     return _size_y;
348   }
349
350   //----------------------------------------------------------------------------
351   void Canvas::setViewWidth(int w)
352   {
353     if( _view_width == w )
354       return;
355     _view_width = w;
356
357     _texture.setViewSize(_view_width, _view_height);
358   }
359
360   //----------------------------------------------------------------------------
361   void Canvas::setViewHeight(int h)
362   {
363     if( _view_height == h )
364       return;
365     _view_height = h;
366
367     _texture.setViewSize(_view_width, _view_height);
368   }
369
370   //----------------------------------------------------------------------------
371   int Canvas::getViewWidth() const
372   {
373     return _texture.getViewSize().x();
374   }
375
376   //----------------------------------------------------------------------------
377   int Canvas::getViewHeight() const
378   {
379     return _texture.getViewSize().y();
380   }
381
382   //----------------------------------------------------------------------------
383   bool Canvas::handleMouseEvent(const MouseEventPtr& event)
384   {
385     if( !_root_group.get() )
386       return false;
387
388     EventVisitor visitor( EventVisitor::TRAVERSE_DOWN,
389                           event->getClientPos(),
390                           event->getDelta() );
391     if( !_root_group->accept(visitor) )
392       return false;
393
394     return _event_manager->handleEvent(event, visitor.getPropagationPath());
395   }
396
397   //----------------------------------------------------------------------------
398   void Canvas::childAdded( SGPropertyNode * parent,
399                            SGPropertyNode * child )
400   {
401     if( parent != _node )
402       return;
403
404     if( child->getNameString() == "placement" )
405       _dirty_placements.push_back(child);
406     else if( _root_group.get() )
407       static_cast<Element*>(_root_group.get())->childAdded(parent, child);
408   }
409
410   //----------------------------------------------------------------------------
411   void Canvas::childRemoved( SGPropertyNode * parent,
412                              SGPropertyNode * child )
413   {
414     _render_dirty = true;
415
416     if( parent != _node )
417       return;
418
419     if( child->getNameString() == "placement" )
420       _placements[ child->getIndex() ].clear();
421     else if( _root_group.get() )
422       static_cast<Element*>(_root_group.get())->childRemoved(parent, child);
423   }
424
425   //----------------------------------------------------------------------------
426   void Canvas::valueChanged(SGPropertyNode* node)
427   {
428     if(    boost::starts_with(node->getNameString(), "status")
429         || node->getParent()->getNameString() == "bounding-box" )
430       return;
431     _render_dirty = true;
432
433     bool handled = true;
434     if(    node->getParent()->getParent() == _node
435         && node->getParent()->getNameString() == "placement" )
436     {
437       bool placement_dirty = false;
438       BOOST_FOREACH(Placements& placements, _placements)
439       {
440         BOOST_FOREACH(PlacementPtr& placement, placements)
441         {
442           // check if change can be directly handled by placement
443           if(    placement->getProps() == node->getParent()
444               && !placement->childChanged(node) )
445             placement_dirty = true;
446         }
447       }
448
449       if( !placement_dirty )
450         return;
451
452       // prevent double updates...
453       for( size_t i = 0; i < _dirty_placements.size(); ++i )
454       {
455         if( node->getParent() == _dirty_placements[i] )
456           return;
457       }
458
459       _dirty_placements.push_back(node->getParent());
460     }
461     else if( node->getParent() == _node )
462     {
463       if( node->getNameString() == "background" )
464       {
465         osg::Vec4 color;
466         if( _texture.getCamera() && parseColor(node->getStringValue(), color) )
467         {
468           _texture.getCamera()->setClearColor(color);
469           _render_dirty = true;
470         }
471       }
472       else if(    node->getNameString() == "mipmapping"
473               || node->getNameString() == "coverage-samples"
474               || node->getNameString() == "color-samples" )
475       {
476         _sampling_dirty = true;
477       }
478       else if( node->getNameString() == "additive-blend" )
479       {
480         _texture.useAdditiveBlend( node->getBoolValue() );
481       }
482       else if( node->getNameString() == "render-always" )
483       {
484         _render_always = node->getBoolValue();
485       }
486       else if( node->getNameString() == "size" )
487       {
488         if( node->getIndex() == 0 )
489           setSizeX( node->getIntValue() );
490         else if( node->getIndex() == 1 )
491           setSizeY( node->getIntValue() );
492       }
493       else if( node->getNameString() == "view" )
494       {
495         if( node->getIndex() == 0 )
496           setViewWidth( node->getIntValue() );
497         else if( node->getIndex() == 1 )
498           setViewHeight( node->getIntValue() );
499       }
500       else if( node->getNameString() == "freeze" )
501         _texture.setRender( node->getBoolValue() );
502       else
503         handled = false;
504     }
505     else
506       handled = false;
507
508     if( !handled && _root_group.get() )
509       _root_group->valueChanged(node);
510   }
511
512   //----------------------------------------------------------------------------
513   osg::Texture2D* Canvas::getTexture() const
514   {
515     return _texture.getTexture();
516   }
517
518   //----------------------------------------------------------------------------
519   Canvas::CullCallbackPtr Canvas::getCullCallback() const
520   {
521     return _cull_callback;
522   }
523
524   //----------------------------------------------------------------------------
525   void Canvas::reloadPlacements(const std::string& type)
526   {
527     for(size_t i = 0; i < _placements.size(); ++i)
528     {
529       if( _placements[i].empty() )
530         continue;
531
532       SGPropertyNode* child = _placements[i].front()->getProps();
533       if(    type.empty()
534              // reload if type matches or no type specified
535           || child->getStringValue("type", type.c_str()) == type )
536       {
537         _dirty_placements.push_back(child);
538       }
539     }
540   }
541
542   //----------------------------------------------------------------------------
543   void Canvas::addPlacementFactory( const std::string& type,
544                                     PlacementFactory factory )
545   {
546     if( _placement_factories.find(type) != _placement_factories.end() )
547       SG_LOG
548       (
549         SG_GENERAL,
550         SG_WARN,
551         "Canvas::addPlacementFactory: replace existing factor for type " << type
552       );
553
554     _placement_factories[type] = factory;
555   }
556
557   //----------------------------------------------------------------------------
558   void Canvas::setSelf(const PropertyBasedElementPtr& self)
559   {
560     PropertyBasedElement::setSelf(self);
561
562     CanvasPtr canvas = boost::static_pointer_cast<Canvas>(self);
563
564     _root_group.reset( new Group(canvas, _node) );
565     _root_group->setSelf(_root_group);
566
567     // Remove automatically created property listener as we forward them on our
568     // own
569     _root_group->removeListener();
570
571     _cull_callback = new CullCallback(canvas);
572   }
573
574   //----------------------------------------------------------------------------
575   void Canvas::setStatusFlags(unsigned int flags, bool set)
576   {
577     if( set )
578       _status |= flags;
579     else
580       _status &= ~flags;
581
582     if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
583       _status_msg = "Missing size";
584     else if( _status & MISSING_SIZE_X )
585       _status_msg = "Missing size-x";
586     else if( _status & MISSING_SIZE_Y )
587       _status_msg = "Missing size-y";
588     else if( _status & CREATE_FAILED )
589       _status_msg = "Creating render target failed";
590     else if( _status == STATUS_DIRTY )
591       _status_msg = "Creation pending...";
592     else
593       _status_msg = "Ok";
594   }
595
596   //----------------------------------------------------------------------------
597   Canvas::PlacementFactoryMap Canvas::_placement_factories;
598
599 } // namespace canvas
600 } // namespace simgear