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