1 // The canvas for rendering with the 2d API
3 // Copyright (C) 2012 Thomas Geymayer <tomgey@gmail.com>
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.
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.
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
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>
29 #include <osgText/Text>
30 #include <osgViewer/Viewer>
32 #include <boost/algorithm/string/predicate.hpp>
33 #include <boost/foreach.hpp>
40 //----------------------------------------------------------------------------
41 Canvas::CullCallback::CullCallback(const CanvasWeakPtr& canvas):
47 //----------------------------------------------------------------------------
48 void Canvas::CullCallback::operator()( osg::Node* node,
49 osg::NodeVisitor* nv )
51 if( (nv->getTraversalMask() & simgear::MODEL_BIT) )
53 CanvasPtr canvas = _canvas.lock();
55 canvas->enableRendering();
61 //----------------------------------------------------------------------------
62 Canvas::Canvas(SGPropertyNode* node):
63 PropertyBasedElement(node),
65 _event_manager(new EventManager),
70 _status(node, "status"),
71 _status_msg(node, "status-msg"),
72 _sampling_dirty(false),
78 setStatusFlags(MISSING_SIZE_X | MISSING_SIZE_Y);
80 _root_group.reset( new Group(this, _node) );
82 // Remove automatically created property listener as we forward them on our
84 _root_group->removeListener();
85 _cull_callback = new CullCallback(this);
88 //----------------------------------------------------------------------------
94 //----------------------------------------------------------------------------
95 void Canvas::onDestroy()
99 _root_group->clearEventListener();
100 _root_group->onDestroy();
104 //----------------------------------------------------------------------------
105 void Canvas::setCanvasMgr(CanvasMgr* canvas_mgr)
107 _canvas_mgr = canvas_mgr;
110 //----------------------------------------------------------------------------
111 CanvasMgr* Canvas::getCanvasMgr() const
116 //----------------------------------------------------------------------------
117 bool Canvas::isInit() const
119 return _texture.serviceable();
122 //----------------------------------------------------------------------------
123 void Canvas::addParentCanvas(const CanvasWeakPtr& canvas)
125 if( canvas.expired() )
131 "Canvas::addParentCanvas(" << _node->getPath(true) << "): "
132 "got an expired parent!"
137 _parent_canvases.insert(canvas);
140 //----------------------------------------------------------------------------
141 void Canvas::addChildCanvas(const CanvasWeakPtr& canvas)
143 if( canvas.expired() )
149 "Canvas::addChildCanvas(" << _node->getPath(true) << "): "
150 " got an expired child!"
155 _child_canvases.insert(canvas);
158 //----------------------------------------------------------------------------
159 void Canvas::removeParentCanvas(const CanvasWeakPtr& canvas)
161 _parent_canvases.erase(canvas);
164 //----------------------------------------------------------------------------
165 void Canvas::removeChildCanvas(const CanvasWeakPtr& canvas)
167 _child_canvases.erase(canvas);
170 //----------------------------------------------------------------------------
171 GroupPtr Canvas::createGroup(const std::string& name)
173 return _root_group->createChild<Group>(name);
176 //----------------------------------------------------------------------------
177 GroupPtr Canvas::getGroup(const std::string& name)
179 return _root_group->getChild<Group>(name);
182 //----------------------------------------------------------------------------
183 GroupPtr Canvas::getOrCreateGroup(const std::string& name)
185 return _root_group->getOrCreateChild<Group>(name);
188 //----------------------------------------------------------------------------
189 GroupPtr Canvas::getRootGroup()
194 //----------------------------------------------------------------------------
195 void Canvas::setLayout(const LayoutRef& layout)
198 _layout->setCanvas(this);
201 //----------------------------------------------------------------------------
202 void Canvas::enableRendering(bool force)
206 _render_dirty = true;
209 //----------------------------------------------------------------------------
210 void Canvas::update(double delta_time_sec)
212 if( _status & (CREATE_FAILED | MISSING_SIZE) )
215 if( _status & STATUS_DIRTY )
217 _texture.setSize(_size_x, _size_y);
219 if( !_texture.serviceable() )
221 _texture.useImageCoords(true);
222 _texture.useStencil(true);
223 _texture.allocRT(/*_camera_callback*/);
227 // Resizing causes a new texture to be created so we need to reapply all
228 // existing placements
232 osg::Camera* camera = _texture.getCamera();
234 // TODO Allow custom render order? For now just keep in order with
236 camera->setRenderOrder(osg::Camera::PRE_RENDER, _node->getIndex());
238 osg::Vec4 clear_color(0.0f, 0.0f, 0.0f , 1.0f);
239 parseColor(_node->getStringValue("background"), clear_color);
240 camera->setClearColor(clear_color);
242 camera->addChild(_root_group->getMatrixTransform());
244 if( _texture.serviceable() )
246 setStatusFlags(STATUS_OK);
247 setStatusFlags(STATUS_DIRTY, false);
248 _render_dirty = true;
252 setStatusFlags(CREATE_FAILED);
258 _layout->setGeometry(SGRecti(0, 0, _view_width, _view_height));
260 if( _visible || _render_always )
262 BOOST_FOREACH(CanvasWeakPtr canvas_weak, _child_canvases)
264 // TODO should we check if the image the child canvas is displayed
265 // within is really visible?
266 CanvasPtr canvas = canvas_weak.lock();
268 canvas->_visible = true;
273 // Also mark all canvases this canvas is displayed within as dirty
274 BOOST_FOREACH(CanvasWeakPtr canvas_weak, _parent_canvases)
276 CanvasPtr canvas = canvas_weak.lock();
278 canvas->_render_dirty = true;
282 _texture.setRender(_render_dirty);
284 _render_dirty = false;
288 _texture.setRender(false);
290 _root_group->update(delta_time_sec);
292 if( _sampling_dirty )
294 _texture.setSampling(
295 _node->getBoolValue("mipmapping"),
296 _node->getIntValue("coverage-samples"),
297 _node->getIntValue("color-samples")
299 _sampling_dirty = false;
300 _render_dirty = true;
303 while( !_dirty_placements.empty() )
305 SGPropertyNode *node = _dirty_placements.back();
306 _dirty_placements.pop_back();
308 if( node->getIndex() >= static_cast<int>(_placements.size()) )
310 _placements.resize(node->getIndex() + 1);
312 // Remove possibly existing placements
313 _placements[ node->getIndex() ].clear();
315 // Get new placements
316 PlacementFactoryMap::const_iterator placement_factory =
317 _placement_factories.find( node->getStringValue("type", "object") );
318 if( placement_factory != _placement_factories.end() )
320 Placements& placements = _placements[ node->getIndex() ] =
321 placement_factory->second(node, this);
325 placements.empty() ? "No match" : "Ok"
329 node->setStringValue("status-msg", "Unknown placement type");
333 //----------------------------------------------------------------------------
334 bool Canvas::addEventListener( const std::string& type,
335 const EventListener& cb )
337 if( !_root_group.get() )
338 throw std::runtime_error("Canvas::addEventListener: no root group!");
340 return _root_group->addEventListener(type, cb);
343 //----------------------------------------------------------------------------
344 bool Canvas::dispatchEvent(const EventPtr& event)
346 if( !_root_group.get() )
347 throw std::runtime_error("Canvas::dispatchEvent: no root group!");
349 return _root_group->dispatchEvent(event);
352 //----------------------------------------------------------------------------
353 void Canvas::setSizeX(int sx)
358 setStatusFlags(STATUS_DIRTY);
361 setStatusFlags(MISSING_SIZE_X);
363 setStatusFlags(MISSING_SIZE_X, false);
365 // reset flag to allow creation with new size
366 setStatusFlags(CREATE_FAILED, false);
369 //----------------------------------------------------------------------------
370 void Canvas::setSizeY(int sy)
375 setStatusFlags(STATUS_DIRTY);
378 setStatusFlags(MISSING_SIZE_Y);
380 setStatusFlags(MISSING_SIZE_Y, false);
382 // reset flag to allow creation with new size
383 setStatusFlags(CREATE_FAILED, false);
386 //----------------------------------------------------------------------------
387 int Canvas::getSizeX() const
392 //----------------------------------------------------------------------------
393 int Canvas::getSizeY() const
398 //----------------------------------------------------------------------------
399 void Canvas::setViewWidth(int w)
401 if( _view_width == w )
405 _texture.setViewSize(_view_width, _view_height);
408 //----------------------------------------------------------------------------
409 void Canvas::setViewHeight(int h)
411 if( _view_height == h )
415 _texture.setViewSize(_view_width, _view_height);
418 //----------------------------------------------------------------------------
419 int Canvas::getViewWidth() const
421 return _texture.getViewSize().x();
424 //----------------------------------------------------------------------------
425 int Canvas::getViewHeight() const
427 return _texture.getViewSize().y();
430 //----------------------------------------------------------------------------
431 SGRect<int> Canvas::getViewport() const
433 return SGRect<int>(0, 0, getViewWidth(), getViewHeight());
436 //----------------------------------------------------------------------------
437 bool Canvas::handleMouseEvent(const MouseEventPtr& event)
442 EventVisitor visitor( EventVisitor::TRAVERSE_DOWN,
443 event->getClientPos(),
445 if( !_root_group->accept(visitor) )
448 return _event_manager->handleEvent(event, visitor.getPropagationPath());
451 //----------------------------------------------------------------------------
452 bool Canvas::propagateEvent( EventPtr const& event,
453 EventPropagationPath const& path )
455 return _event_manager->propagateEvent(event, path);
458 //----------------------------------------------------------------------------
459 void Canvas::childAdded( SGPropertyNode * parent,
460 SGPropertyNode * child )
462 if( parent != _node )
465 if( child->getNameString() == "placement" )
466 _dirty_placements.push_back(child);
467 else if( _root_group.get() )
468 static_cast<Element*>(_root_group.get())->childAdded(parent, child);
471 //----------------------------------------------------------------------------
472 void Canvas::childRemoved( SGPropertyNode * parent,
473 SGPropertyNode * child )
475 _render_dirty = true;
477 if( parent != _node )
480 if( child->getNameString() == "placement" )
481 _placements[ child->getIndex() ].clear();
482 else if( _root_group.get() )
483 static_cast<Element*>(_root_group.get())->childRemoved(parent, child);
486 //----------------------------------------------------------------------------
487 void Canvas::valueChanged(SGPropertyNode* node)
489 const std::string& name = node->getNameString();
491 if( boost::starts_with(name, "status")
492 || boost::starts_with(name, "data-") )
494 _render_dirty = true;
497 if( node->getParent()->getParent() == _node
498 && node->getParent()->getNameString() == "placement" )
500 size_t index = node->getIndex();
501 if( index < _placements.size() )
503 Placements& placements = _placements[index];
504 if( !placements.empty() )
506 bool placement_dirty = false;
507 BOOST_FOREACH(PlacementPtr& placement, placements)
509 // check if change can be directly handled by placement
510 if( placement->getProps() == node->getParent()
511 && !placement->childChanged(node) )
512 placement_dirty = true;
515 if( !placement_dirty )
520 // prevent double updates...
521 for( size_t i = 0; i < _dirty_placements.size(); ++i )
523 if( node->getParent() == _dirty_placements[i] )
527 _dirty_placements.push_back(node->getParent());
529 else if( node->getParent() == _node )
531 if( name == "background" )
534 if( _texture.getCamera() && parseColor(node->getStringValue(), color) )
536 _texture.getCamera()->setClearColor(color);
537 _render_dirty = true;
540 else if( name == "mipmapping"
541 || name == "coverage-samples"
542 || name == "color-samples" )
544 _sampling_dirty = true;
546 else if( name == "additive-blend" )
548 _texture.useAdditiveBlend( node->getBoolValue() );
550 else if( name == "render-always" )
552 _render_always = node->getBoolValue();
554 else if( name == "size" )
556 if( node->getIndex() == 0 )
557 setSizeX( node->getIntValue() );
558 else if( node->getIndex() == 1 )
559 setSizeY( node->getIntValue() );
561 else if( name == "update" )
564 _root_group->update(0);
567 else if( name == "view" )
569 if( node->getIndex() == 0 )
570 setViewWidth( node->getIntValue() );
571 else if( node->getIndex() == 1 )
572 setViewHeight( node->getIntValue() );
574 else if( name == "freeze" )
575 _texture.setRender( node->getBoolValue() );
582 if( !handled && _root_group.get() )
583 _root_group->valueChanged(node);
586 //----------------------------------------------------------------------------
587 osg::Texture2D* Canvas::getTexture() const
589 return _texture.getTexture();
592 //----------------------------------------------------------------------------
593 Canvas::CullCallbackPtr Canvas::getCullCallback() const
595 return _cull_callback;
598 //----------------------------------------------------------------------------
599 void Canvas::reloadPlacements(const std::string& type)
601 for(size_t i = 0; i < _placements.size(); ++i)
603 if( _placements[i].empty() )
606 SGPropertyNode* child = _placements[i].front()->getProps();
608 // reload if type matches or no type specified
609 || child->getStringValue("type", type.c_str()) == type )
611 _dirty_placements.push_back(child);
616 //----------------------------------------------------------------------------
617 void Canvas::addPlacementFactory( const std::string& type,
618 PlacementFactory factory )
620 if( _placement_factories.find(type) != _placement_factories.end() )
625 "Canvas::addPlacementFactory: replace existing factory '" << type << "'"
628 _placement_factories[type] = factory;
631 //----------------------------------------------------------------------------
632 void Canvas::removePlacementFactory(const std::string& type)
634 PlacementFactoryMap::iterator it = _placement_factories.find(type);
635 if( it == _placement_factories.end() )
640 "Canvas::removePlacementFactory: no such factory '" << type << "'"
643 _placement_factories.erase(it);
647 //----------------------------------------------------------------------------
648 void Canvas::setSystemAdapter(const SystemAdapterPtr& system_adapter)
650 _system_adapter = system_adapter;
653 //----------------------------------------------------------------------------
654 SystemAdapterPtr Canvas::getSystemAdapter()
656 return _system_adapter;
659 //----------------------------------------------------------------------------
660 void Canvas::setStatusFlags(unsigned int flags, bool set)
667 if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
668 _status_msg = "Missing size";
669 else if( _status & MISSING_SIZE_X )
670 _status_msg = "Missing size-x";
671 else if( _status & MISSING_SIZE_Y )
672 _status_msg = "Missing size-y";
673 else if( _status & CREATE_FAILED )
674 _status_msg = "Creating render target failed";
675 else if( _status & STATUS_DIRTY )
676 _status_msg = "Creation pending...";
681 //----------------------------------------------------------------------------
682 Canvas::PlacementFactoryMap Canvas::_placement_factories;
683 SystemAdapterPtr Canvas::_system_adapter;
685 } // namespace canvas
686 } // namespace simgear