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