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