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