]> git.mxchange.org Git - simgear.git/blob - simgear/canvas/Canvas.cxx
9873ba6d09c8b40fc88eef0a5a74efaef31286c8
[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                           _root_group );
418     if( !_root_group->accept(visitor) )
419       return false;
420
421     return _event_manager->handleEvent(event, visitor.getPropagationPath());
422   }
423
424   //----------------------------------------------------------------------------
425   void Canvas::childAdded( SGPropertyNode * parent,
426                            SGPropertyNode * child )
427   {
428     if( parent != _node )
429       return;
430
431     if( child->getNameString() == "placement" )
432       _dirty_placements.push_back(child);
433     else if( _root_group.get() )
434       static_cast<Element*>(_root_group.get())->childAdded(parent, child);
435   }
436
437   //----------------------------------------------------------------------------
438   void Canvas::childRemoved( SGPropertyNode * parent,
439                              SGPropertyNode * child )
440   {
441     _render_dirty = true;
442
443     if( parent != _node )
444       return;
445
446     if( child->getNameString() == "placement" )
447       _placements[ child->getIndex() ].clear();
448     else if( _root_group.get() )
449       static_cast<Element*>(_root_group.get())->childRemoved(parent, child);
450   }
451
452   //----------------------------------------------------------------------------
453   void Canvas::valueChanged(SGPropertyNode* node)
454   {
455     if( boost::starts_with(node->getNameString(), "status") )
456       return;
457     _render_dirty = true;
458
459     bool handled = true;
460     if(    node->getParent()->getParent() == _node
461         && node->getParent()->getNameString() == "placement" )
462     {
463       size_t index = node->getIndex();
464       if( index < _placements.size() )
465       {
466         Placements& placements = _placements[index];
467         if( !placements.empty() )
468         {
469           bool placement_dirty = false;
470           BOOST_FOREACH(PlacementPtr& placement, placements)
471           {
472             // check if change can be directly handled by placement
473             if(    placement->getProps() == node->getParent()
474                 && !placement->childChanged(node) )
475               placement_dirty = true;
476           }
477
478           if( !placement_dirty )
479             return;
480         }
481       }
482
483       // prevent double updates...
484       for( size_t i = 0; i < _dirty_placements.size(); ++i )
485       {
486         if( node->getParent() == _dirty_placements[i] )
487           return;
488       }
489
490       _dirty_placements.push_back(node->getParent());
491     }
492     else if( node->getParent() == _node )
493     {
494       if( node->getNameString() == "background" )
495       {
496         osg::Vec4 color;
497         if( _texture.getCamera() && parseColor(node->getStringValue(), color) )
498         {
499           _texture.getCamera()->setClearColor(color);
500           _render_dirty = true;
501         }
502       }
503       else if(    node->getNameString() == "mipmapping"
504               || node->getNameString() == "coverage-samples"
505               || node->getNameString() == "color-samples" )
506       {
507         _sampling_dirty = true;
508       }
509       else if( node->getNameString() == "additive-blend" )
510       {
511         _texture.useAdditiveBlend( node->getBoolValue() );
512       }
513       else if( node->getNameString() == "render-always" )
514       {
515         _render_always = node->getBoolValue();
516       }
517       else if( node->getNameString() == "size" )
518       {
519         if( node->getIndex() == 0 )
520           setSizeX( node->getIntValue() );
521         else if( node->getIndex() == 1 )
522           setSizeY( node->getIntValue() );
523       }
524       else if( node->getNameString() == "view" )
525       {
526         if( node->getIndex() == 0 )
527           setViewWidth( node->getIntValue() );
528         else if( node->getIndex() == 1 )
529           setViewHeight( node->getIntValue() );
530       }
531       else if( node->getNameString() == "freeze" )
532         _texture.setRender( node->getBoolValue() );
533       else
534         handled = false;
535     }
536     else
537       handled = false;
538
539     if( !handled && _root_group.get() )
540       _root_group->valueChanged(node);
541   }
542
543   //----------------------------------------------------------------------------
544   osg::Texture2D* Canvas::getTexture() const
545   {
546     return _texture.getTexture();
547   }
548
549   //----------------------------------------------------------------------------
550   Canvas::CullCallbackPtr Canvas::getCullCallback() const
551   {
552     return _cull_callback;
553   }
554
555   //----------------------------------------------------------------------------
556   void Canvas::reloadPlacements(const std::string& type)
557   {
558     for(size_t i = 0; i < _placements.size(); ++i)
559     {
560       if( _placements[i].empty() )
561         continue;
562
563       SGPropertyNode* child = _placements[i].front()->getProps();
564       if(    type.empty()
565              // reload if type matches or no type specified
566           || child->getStringValue("type", type.c_str()) == type )
567       {
568         _dirty_placements.push_back(child);
569       }
570     }
571   }
572
573   //----------------------------------------------------------------------------
574   void Canvas::addPlacementFactory( const std::string& type,
575                                     PlacementFactory factory )
576   {
577     if( _placement_factories.find(type) != _placement_factories.end() )
578       SG_LOG
579       (
580         SG_GENERAL,
581         SG_WARN,
582         "Canvas::addPlacementFactory: replace existing factory '" << type << "'"
583       );
584
585     _placement_factories[type] = factory;
586   }
587
588   //----------------------------------------------------------------------------
589   void Canvas::removePlacementFactory(const std::string& type)
590   {
591     PlacementFactoryMap::iterator it = _placement_factories.find(type);
592     if( it == _placement_factories.end() )
593       SG_LOG
594       (
595         SG_GENERAL,
596         SG_WARN,
597         "Canvas::removePlacementFactory: no such factory '" << type << "'"
598       );
599     else
600       _placement_factories.erase(it);
601   }
602
603
604   //----------------------------------------------------------------------------
605   void Canvas::setSystemAdapter(const SystemAdapterPtr& system_adapter)
606   {
607     _system_adapter = system_adapter;
608   }
609
610   //----------------------------------------------------------------------------
611   SystemAdapterPtr Canvas::getSystemAdapter()
612   {
613     return _system_adapter;
614   }
615
616   //----------------------------------------------------------------------------
617   void Canvas::setSelf(const PropertyBasedElementPtr& self)
618   {
619     PropertyBasedElement::setSelf(self);
620
621     CanvasPtr canvas = boost::static_pointer_cast<Canvas>(self);
622
623     _root_group.reset( new Group(canvas, _node) );
624     _root_group->setSelf(_root_group);
625
626     // Remove automatically created property listener as we forward them on our
627     // own
628     _root_group->removeListener();
629
630     _cull_callback = new CullCallback(canvas);
631   }
632
633   //----------------------------------------------------------------------------
634   void Canvas::setStatusFlags(unsigned int flags, bool set)
635   {
636     if( set )
637       _status |= flags;
638     else
639       _status &= ~flags;
640
641     if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
642       _status_msg = "Missing size";
643     else if( _status & MISSING_SIZE_X )
644       _status_msg = "Missing size-x";
645     else if( _status & MISSING_SIZE_Y )
646       _status_msg = "Missing size-y";
647     else if( _status & CREATE_FAILED )
648       _status_msg = "Creating render target failed";
649     else if( _status == STATUS_DIRTY )
650       _status_msg = "Creation pending...";
651     else
652       _status_msg = "Ok";
653   }
654
655   //----------------------------------------------------------------------------
656   Canvas::PlacementFactoryMap Canvas::_placement_factories;
657   SystemAdapterPtr Canvas::_system_adapter;
658
659 } // namespace canvas
660 } // namespace simgear