]> git.mxchange.org Git - simgear.git/blob - simgear/canvas/Canvas.cxx
Canvas: allow also C++ callable entities as event callbacks.
[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   void Canvas::onDestroy()
79   {
80     if( _root_group )
81     {
82       _root_group->clearEventListener();
83       _root_group->onDestroy();
84     }
85   }
86
87   //----------------------------------------------------------------------------
88   void Canvas::setSystemAdapter(const SystemAdapterPtr& system_adapter)
89   {
90     _system_adapter = system_adapter;
91     _texture.setSystemAdapter(system_adapter);
92   }
93
94   //----------------------------------------------------------------------------
95   SystemAdapterPtr Canvas::getSystemAdapter() const
96   {
97     return _system_adapter;
98   }
99
100   //----------------------------------------------------------------------------
101   void Canvas::setCanvasMgr(CanvasMgr* canvas_mgr)
102   {
103     _canvas_mgr = canvas_mgr;
104   }
105
106   //----------------------------------------------------------------------------
107   CanvasMgr* Canvas::getCanvasMgr() const
108   {
109     return _canvas_mgr;
110   }
111
112   //----------------------------------------------------------------------------
113   bool Canvas::isInit() const
114   {
115     return _texture.serviceable();
116   }
117
118   //----------------------------------------------------------------------------
119   void Canvas::addParentCanvas(const CanvasWeakPtr& canvas)
120   {
121     if( canvas.expired() )
122     {
123       SG_LOG
124       (
125         SG_GENERAL,
126         SG_WARN,
127         "Canvas::addParentCanvas(" << _node->getPath(true) << "): "
128         "got an expired parent!"
129       );
130       return;
131     }
132
133     _parent_canvases.insert(canvas);
134   }
135
136   //----------------------------------------------------------------------------
137   void Canvas::addChildCanvas(const CanvasWeakPtr& canvas)
138   {
139     if( canvas.expired() )
140     {
141       SG_LOG
142       (
143         SG_GENERAL,
144         SG_WARN,
145         "Canvas::addChildCanvas(" << _node->getPath(true) << "): "
146         " got an expired child!"
147       );
148       return;
149     }
150
151     _child_canvases.insert(canvas);
152   }
153
154   //----------------------------------------------------------------------------
155   void Canvas::removeParentCanvas(const CanvasWeakPtr& canvas)
156   {
157     _parent_canvases.erase(canvas);
158   }
159
160   //----------------------------------------------------------------------------
161   void Canvas::removeChildCanvas(const CanvasWeakPtr& canvas)
162   {
163     _child_canvases.erase(canvas);
164   }
165
166   //----------------------------------------------------------------------------
167   GroupPtr Canvas::createGroup(const std::string& name)
168   {
169     return _root_group->createChild<Group>(name);
170   }
171
172   //----------------------------------------------------------------------------
173   GroupPtr Canvas::getGroup(const std::string& name)
174   {
175     return _root_group->getChild<Group>(name);
176   }
177
178   //----------------------------------------------------------------------------
179   GroupPtr Canvas::getOrCreateGroup(const std::string& name)
180   {
181     return _root_group->getOrCreateChild<Group>(name);
182   }
183
184   //----------------------------------------------------------------------------
185   GroupPtr Canvas::getRootGroup()
186   {
187     return _root_group;
188   }
189
190   //----------------------------------------------------------------------------
191   void Canvas::enableRendering(bool force)
192   {
193     _visible = true;
194     if( force )
195       _render_dirty = true;
196   }
197
198   //----------------------------------------------------------------------------
199   void Canvas::update(double delta_time_sec)
200   {
201     if(    (!_texture.serviceable() && _status != STATUS_DIRTY)
202         || (_status & CREATE_FAILED) )
203       return;
204
205     if( _status == STATUS_DIRTY )
206     {
207       _texture.setSize(_size_x, _size_y);
208
209       if( !_texture.serviceable() )
210       {
211         _texture.useImageCoords(true);
212         _texture.useStencil(true);
213         _texture.allocRT(/*_camera_callback*/);
214       }
215       else
216       {
217         // Resizing causes a new texture to be created so we need to reapply all
218         // existing placements
219         reloadPlacements();
220       }
221
222       osg::Camera* camera = _texture.getCamera();
223
224       // TODO Allow custom render order? For now just keep in order with
225       //      property tree.
226       camera->setRenderOrder(osg::Camera::PRE_RENDER, _node->getIndex());
227
228       osg::Vec4 clear_color(0.0f, 0.0f, 0.0f , 1.0f);
229       parseColor(_node->getStringValue("background"), clear_color);
230       camera->setClearColor(clear_color);
231
232       camera->addChild(_root_group->getMatrixTransform());
233
234       if( _texture.serviceable() )
235       {
236         setStatusFlags(STATUS_OK);
237         setStatusFlags(STATUS_DIRTY, false);
238         _render_dirty = true;
239       }
240       else
241       {
242         setStatusFlags(CREATE_FAILED);
243         return;
244       }
245     }
246
247     if( _visible || _render_always )
248     {
249       BOOST_FOREACH(CanvasWeakPtr canvas, _child_canvases)
250       {
251         // TODO should we check if the image the child canvas is displayed
252         //      within is really visible?
253         if( !canvas.expired() )
254           canvas.lock()->_visible = true;
255       }
256
257       if( _render_dirty )
258       {
259         // Also mark all canvases this canvas is displayed within as dirty
260         BOOST_FOREACH(CanvasWeakPtr canvas, _parent_canvases)
261         {
262           if( !canvas.expired() )
263             canvas.lock()->_render_dirty = true;
264         }
265       }
266
267       _texture.setRender(_render_dirty);
268
269       _render_dirty = false;
270       _visible = false;
271     }
272     else
273       _texture.setRender(false);
274
275     _root_group->update(delta_time_sec);
276
277     if( _sampling_dirty )
278     {
279       _texture.setSampling(
280         _node->getBoolValue("mipmapping"),
281         _node->getIntValue("coverage-samples"),
282         _node->getIntValue("color-samples")
283       );
284       _sampling_dirty = false;
285       _render_dirty = true;
286     }
287
288     while( !_dirty_placements.empty() )
289     {
290       SGPropertyNode *node = _dirty_placements.back();
291       _dirty_placements.pop_back();
292
293       if( node->getIndex() >= static_cast<int>(_placements.size()) )
294         // New placement
295         _placements.resize(node->getIndex() + 1);
296       else
297         // Remove possibly existing placements
298         _placements[ node->getIndex() ].clear();
299
300       // Get new placements
301       PlacementFactoryMap::const_iterator placement_factory =
302         _placement_factories.find( node->getStringValue("type", "object") );
303       if( placement_factory != _placement_factories.end() )
304       {
305         Placements& placements = _placements[ node->getIndex() ] =
306           placement_factory->second
307           (
308             node,
309             boost::static_pointer_cast<Canvas>(_self.lock())
310           );
311         node->setStringValue
312         (
313           "status-msg",
314           placements.empty() ? "No match" : "Ok"
315         );
316       }
317       else
318         node->setStringValue("status-msg", "Unknown placement type");
319     }
320   }
321
322   //----------------------------------------------------------------------------
323   bool Canvas::addEventListener( const std::string& type,
324                                  const EventListener& cb )
325   {
326     if( !_root_group.get() )
327       throw std::runtime_error("Canvas::AddEventListener: no root group!");
328
329     return _root_group->addEventListener(type, cb);
330   }
331
332   //----------------------------------------------------------------------------
333   bool Canvas::addNasalEventListener(const std::string& type, naRef code)
334   {
335     if( !_root_group.get() )
336       throw std::runtime_error("Canvas::AddNasalEventListener: no root group!");
337
338     return _root_group->addNasalEventListener(type, code);
339   }
340
341   //----------------------------------------------------------------------------
342   void Canvas::setSizeX(int sx)
343   {
344     if( _size_x == sx )
345       return;
346     _size_x = sx;
347     setStatusFlags(STATUS_DIRTY);
348
349     if( _size_x <= 0 )
350       setStatusFlags(MISSING_SIZE_X);
351     else
352       setStatusFlags(MISSING_SIZE_X, false);
353
354     // reset flag to allow creation with new size
355     setStatusFlags(CREATE_FAILED, false);
356   }
357
358   //----------------------------------------------------------------------------
359   void Canvas::setSizeY(int sy)
360   {
361     if( _size_y == sy )
362       return;
363     _size_y = sy;
364     setStatusFlags(STATUS_DIRTY);
365
366     if( _size_y <= 0 )
367       setStatusFlags(MISSING_SIZE_Y);
368     else
369       setStatusFlags(MISSING_SIZE_Y, false);
370
371     // reset flag to allow creation with new size
372     setStatusFlags(CREATE_FAILED, false);
373   }
374
375   //----------------------------------------------------------------------------
376   int Canvas::getSizeX() const
377   {
378     return _size_x;
379   }
380
381   //----------------------------------------------------------------------------
382   int Canvas::getSizeY() const
383   {
384     return _size_y;
385   }
386
387   //----------------------------------------------------------------------------
388   void Canvas::setViewWidth(int w)
389   {
390     if( _view_width == w )
391       return;
392     _view_width = w;
393
394     _texture.setViewSize(_view_width, _view_height);
395   }
396
397   //----------------------------------------------------------------------------
398   void Canvas::setViewHeight(int h)
399   {
400     if( _view_height == h )
401       return;
402     _view_height = h;
403
404     _texture.setViewSize(_view_width, _view_height);
405   }
406
407   //----------------------------------------------------------------------------
408   int Canvas::getViewWidth() const
409   {
410     return _texture.getViewSize().x();
411   }
412
413   //----------------------------------------------------------------------------
414   int Canvas::getViewHeight() const
415   {
416     return _texture.getViewSize().y();
417   }
418
419   //----------------------------------------------------------------------------
420   SGRect<int> Canvas::getViewport() const
421   {
422     return SGRect<int>(0, 0, getViewWidth(), getViewHeight());
423   }
424
425   //----------------------------------------------------------------------------
426   bool Canvas::handleMouseEvent(const MouseEventPtr& event)
427   {
428     if( !_root_group.get() )
429       return false;
430
431     EventVisitor visitor( EventVisitor::TRAVERSE_DOWN,
432                           event->getClientPos(),
433                           event->getDelta(),
434                           _root_group );
435     if( !_root_group->accept(visitor) )
436       return false;
437
438     return _event_manager->handleEvent(event, visitor.getPropagationPath());
439   }
440
441   //----------------------------------------------------------------------------
442   void Canvas::childAdded( SGPropertyNode * parent,
443                            SGPropertyNode * child )
444   {
445     if( parent != _node )
446       return;
447
448     if( child->getNameString() == "placement" )
449       _dirty_placements.push_back(child);
450     else if( _root_group.get() )
451       static_cast<Element*>(_root_group.get())->childAdded(parent, child);
452   }
453
454   //----------------------------------------------------------------------------
455   void Canvas::childRemoved( SGPropertyNode * parent,
456                              SGPropertyNode * child )
457   {
458     _render_dirty = true;
459
460     if( parent != _node )
461       return;
462
463     if( child->getNameString() == "placement" )
464       _placements[ child->getIndex() ].clear();
465     else if( _root_group.get() )
466       static_cast<Element*>(_root_group.get())->childRemoved(parent, child);
467   }
468
469   //----------------------------------------------------------------------------
470   void Canvas::valueChanged(SGPropertyNode* node)
471   {
472     if(    boost::starts_with(node->getNameString(), "status")
473         || node->getParent()->getNameString() == "bounding-box" )
474       return;
475     _render_dirty = true;
476
477     bool handled = true;
478     if(    node->getParent()->getParent() == _node
479         && node->getParent()->getNameString() == "placement" )
480     {
481       size_t index = node->getIndex();
482       if( index < _placements.size() )
483       {
484         Placements& placements = _placements[index];
485         if( !placements.empty() )
486         {
487           bool placement_dirty = false;
488           BOOST_FOREACH(PlacementPtr& placement, placements)
489           {
490             // check if change can be directly handled by placement
491             if(    placement->getProps() == node->getParent()
492                 && !placement->childChanged(node) )
493               placement_dirty = true;
494           }
495
496           if( !placement_dirty )
497             return;
498         }
499       }
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