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