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