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/KeyboardEvent.hxx>
24 #include <simgear/canvas/events/MouseEvent.hxx>
25 #include <simgear/scene/util/parse_color.hxx>
26 #include <simgear/scene/util/RenderConstants.hxx>
30 #include <osgText/Text>
31 #include <osgViewer/Viewer>
33 #include <boost/algorithm/string/predicate.hpp>
34 #include <boost/foreach.hpp>
41 //----------------------------------------------------------------------------
42 Canvas::CullCallback::CullCallback(const CanvasWeakPtr& canvas):
48 //----------------------------------------------------------------------------
49 void Canvas::CullCallback::operator()( osg::Node* node,
50 osg::NodeVisitor* nv )
52 if( (nv->getTraversalMask() & simgear::MODEL_BIT) )
54 CanvasPtr canvas = _canvas.lock();
56 canvas->enableRendering();
62 //----------------------------------------------------------------------------
63 Canvas::Canvas(SGPropertyNode* node):
64 PropertyBasedElement(node),
66 _event_manager(new EventManager),
71 _status(node, "status"),
72 _status_msg(node, "status-msg"),
73 _sampling_dirty(false),
79 setStatusFlags(MISSING_SIZE_X | MISSING_SIZE_Y);
81 _root_group.reset( new Group(this, _node) );
83 // Remove automatically created property listener as we forward them on our
85 _root_group->removeListener();
86 _cull_callback = new CullCallback(this);
89 //----------------------------------------------------------------------------
95 //----------------------------------------------------------------------------
96 void Canvas::onDestroy()
100 _root_group->clearEventListener();
101 _root_group->onDestroy();
105 //----------------------------------------------------------------------------
106 void Canvas::setCanvasMgr(CanvasMgr* canvas_mgr)
108 _canvas_mgr = canvas_mgr;
111 //----------------------------------------------------------------------------
112 CanvasMgr* Canvas::getCanvasMgr() const
117 //----------------------------------------------------------------------------
118 bool Canvas::isInit() const
120 return _texture.serviceable();
123 //----------------------------------------------------------------------------
124 void Canvas::addParentCanvas(const CanvasWeakPtr& canvas)
126 if( canvas.expired() )
132 "Canvas::addParentCanvas(" << _node->getPath(true) << "): "
133 "got an expired parent!"
138 _parent_canvases.insert(canvas);
141 //----------------------------------------------------------------------------
142 void Canvas::addChildCanvas(const CanvasWeakPtr& canvas)
144 if( canvas.expired() )
150 "Canvas::addChildCanvas(" << _node->getPath(true) << "): "
151 " got an expired child!"
156 _child_canvases.insert(canvas);
159 //----------------------------------------------------------------------------
160 void Canvas::removeParentCanvas(const CanvasWeakPtr& canvas)
162 _parent_canvases.erase(canvas);
165 //----------------------------------------------------------------------------
166 void Canvas::removeChildCanvas(const CanvasWeakPtr& canvas)
168 _child_canvases.erase(canvas);
171 //----------------------------------------------------------------------------
172 GroupPtr Canvas::createGroup(const std::string& name)
174 return _root_group->createChild<Group>(name);
177 //----------------------------------------------------------------------------
178 GroupPtr Canvas::getGroup(const std::string& name)
180 return _root_group->getChild<Group>(name);
183 //----------------------------------------------------------------------------
184 GroupPtr Canvas::getOrCreateGroup(const std::string& name)
186 return _root_group->getOrCreateChild<Group>(name);
189 //----------------------------------------------------------------------------
190 GroupPtr Canvas::getRootGroup()
195 //----------------------------------------------------------------------------
196 void Canvas::setLayout(const LayoutRef& layout)
199 _layout->setCanvas(this);
202 //----------------------------------------------------------------------------
203 void Canvas::setFocusElement(const ElementPtr& el)
205 if( el && el->getCanvas().lock() != this )
207 SG_LOG(SG_GUI, SG_WARN, "setFocusElement: element not from this canvas");
211 // TODO focus out/in events
215 //----------------------------------------------------------------------------
216 void Canvas::clearFocusElement()
218 _focus_element.reset();
221 //----------------------------------------------------------------------------
222 void Canvas::enableRendering(bool force)
226 _render_dirty = true;
229 //----------------------------------------------------------------------------
230 void Canvas::update(double delta_time_sec)
232 if( _status & (CREATE_FAILED | MISSING_SIZE) )
235 if( _status & STATUS_DIRTY )
237 _texture.setSize(_size_x, _size_y);
239 if( !_texture.serviceable() )
241 _texture.useImageCoords(true);
242 _texture.useStencil(true);
243 _texture.allocRT(/*_camera_callback*/);
247 // Resizing causes a new texture to be created so we need to reapply all
248 // existing placements
252 osg::Camera* camera = _texture.getCamera();
254 // TODO Allow custom render order? For now just keep in order with
256 camera->setRenderOrder(osg::Camera::PRE_RENDER, _node->getIndex());
258 osg::Vec4 clear_color(0.0f, 0.0f, 0.0f , 1.0f);
259 parseColor(_node->getStringValue("background"), clear_color);
260 camera->setClearColor(clear_color);
262 camera->addChild(_root_group->getMatrixTransform());
264 if( _texture.serviceable() )
266 setStatusFlags(STATUS_OK);
267 setStatusFlags(STATUS_DIRTY, false);
268 _render_dirty = true;
272 setStatusFlags(CREATE_FAILED);
278 _layout->setGeometry(SGRecti(0, 0, _view_width, _view_height));
280 if( _visible || _render_always )
282 BOOST_FOREACH(CanvasWeakPtr canvas_weak, _child_canvases)
284 // TODO should we check if the image the child canvas is displayed
285 // within is really visible?
286 CanvasPtr canvas = canvas_weak.lock();
288 canvas->_visible = true;
293 // Also mark all canvases this canvas is displayed within as dirty
294 BOOST_FOREACH(CanvasWeakPtr canvas_weak, _parent_canvases)
296 CanvasPtr canvas = canvas_weak.lock();
298 canvas->_render_dirty = true;
302 _texture.setRender(_render_dirty);
304 _render_dirty = false;
308 _texture.setRender(false);
310 _root_group->update(delta_time_sec);
312 if( _sampling_dirty )
314 _texture.setSampling(
315 _node->getBoolValue("mipmapping"),
316 _node->getIntValue("coverage-samples"),
317 _node->getIntValue("color-samples")
319 _sampling_dirty = false;
320 _render_dirty = true;
323 while( !_dirty_placements.empty() )
325 SGPropertyNode *node = _dirty_placements.back();
326 _dirty_placements.pop_back();
328 if( node->getIndex() >= static_cast<int>(_placements.size()) )
330 _placements.resize(node->getIndex() + 1);
332 // Remove possibly existing placements
333 _placements[ node->getIndex() ].clear();
335 // Get new placements
336 PlacementFactoryMap::const_iterator placement_factory =
337 _placement_factories.find( node->getStringValue("type", "object") );
338 if( placement_factory != _placement_factories.end() )
340 Placements& placements = _placements[ node->getIndex() ] =
341 placement_factory->second(node, this);
345 placements.empty() ? "No match" : "Ok"
349 node->setStringValue("status-msg", "Unknown placement type");
353 //----------------------------------------------------------------------------
354 bool Canvas::addEventListener( const std::string& type,
355 const EventListener& cb )
357 if( !_root_group.get() )
358 throw std::runtime_error("Canvas::addEventListener: no root group!");
360 return _root_group->addEventListener(type, cb);
363 //----------------------------------------------------------------------------
364 bool Canvas::dispatchEvent(const EventPtr& event)
366 if( !_root_group.get() )
367 throw std::runtime_error("Canvas::dispatchEvent: no root group!");
369 return _root_group->dispatchEvent(event);
372 //----------------------------------------------------------------------------
373 void Canvas::setSizeX(int sx)
378 setStatusFlags(STATUS_DIRTY);
381 setStatusFlags(MISSING_SIZE_X);
383 setStatusFlags(MISSING_SIZE_X, false);
385 // reset flag to allow creation with new size
386 setStatusFlags(CREATE_FAILED, false);
389 //----------------------------------------------------------------------------
390 void Canvas::setSizeY(int sy)
395 setStatusFlags(STATUS_DIRTY);
398 setStatusFlags(MISSING_SIZE_Y);
400 setStatusFlags(MISSING_SIZE_Y, false);
402 // reset flag to allow creation with new size
403 setStatusFlags(CREATE_FAILED, false);
406 //----------------------------------------------------------------------------
407 int Canvas::getSizeX() const
412 //----------------------------------------------------------------------------
413 int Canvas::getSizeY() const
418 //----------------------------------------------------------------------------
419 void Canvas::setViewWidth(int w)
421 if( _view_width == w )
425 _texture.setViewSize(_view_width, _view_height);
428 //----------------------------------------------------------------------------
429 void Canvas::setViewHeight(int h)
431 if( _view_height == h )
435 _texture.setViewSize(_view_width, _view_height);
438 //----------------------------------------------------------------------------
439 int Canvas::getViewWidth() const
441 return _texture.getViewSize().x();
444 //----------------------------------------------------------------------------
445 int Canvas::getViewHeight() const
447 return _texture.getViewSize().y();
450 //----------------------------------------------------------------------------
451 SGRect<int> Canvas::getViewport() const
453 return SGRect<int>(0, 0, getViewWidth(), getViewHeight());
456 //----------------------------------------------------------------------------
457 bool Canvas::handleMouseEvent(const MouseEventPtr& event)
462 EventVisitor visitor( EventVisitor::TRAVERSE_DOWN,
463 event->getClientPos(),
465 if( !_root_group->accept(visitor) )
468 return _event_manager->handleEvent(event, visitor.getPropagationPath());
471 //----------------------------------------------------------------------------
472 bool Canvas::handleKeyboardEvent(const KeyboardEventPtr& event)
474 ElementPtr target = _focus_element.lock();
476 target = _root_group;
480 return target->dispatchEvent(event);
483 //----------------------------------------------------------------------------
484 bool Canvas::propagateEvent( EventPtr const& event,
485 EventPropagationPath const& path )
487 return _event_manager->propagateEvent(event, path);
490 //----------------------------------------------------------------------------
491 void Canvas::childAdded( SGPropertyNode * parent,
492 SGPropertyNode * child )
494 if( parent != _node )
497 if( child->getNameString() == "placement" )
498 _dirty_placements.push_back(child);
499 else if( _root_group.get() )
500 static_cast<Element*>(_root_group.get())->childAdded(parent, child);
503 //----------------------------------------------------------------------------
504 void Canvas::childRemoved( SGPropertyNode * parent,
505 SGPropertyNode * child )
507 _render_dirty = true;
509 if( parent != _node )
512 if( child->getNameString() == "placement" )
513 _placements[ child->getIndex() ].clear();
514 else if( _root_group.get() )
515 static_cast<Element*>(_root_group.get())->childRemoved(parent, child);
518 //----------------------------------------------------------------------------
519 void Canvas::valueChanged(SGPropertyNode* node)
521 const std::string& name = node->getNameString();
523 if( boost::starts_with(name, "status")
524 || boost::starts_with(name, "data-") )
526 _render_dirty = true;
529 if( node->getParent()->getParent() == _node
530 && node->getParent()->getNameString() == "placement" )
532 size_t index = node->getIndex();
533 if( index < _placements.size() )
535 Placements& placements = _placements[index];
536 if( !placements.empty() )
538 bool placement_dirty = false;
539 BOOST_FOREACH(PlacementPtr& placement, placements)
541 // check if change can be directly handled by placement
542 if( placement->getProps() == node->getParent()
543 && !placement->childChanged(node) )
544 placement_dirty = true;
547 if( !placement_dirty )
552 // prevent double updates...
553 for( size_t i = 0; i < _dirty_placements.size(); ++i )
555 if( node->getParent() == _dirty_placements[i] )
559 _dirty_placements.push_back(node->getParent());
561 else if( node->getParent() == _node )
563 if( name == "background" )
566 if( _texture.getCamera() && parseColor(node->getStringValue(), color) )
568 _texture.getCamera()->setClearColor(color);
569 _render_dirty = true;
572 else if( name == "mipmapping"
573 || name == "coverage-samples"
574 || name == "color-samples" )
576 _sampling_dirty = true;
578 else if( name == "additive-blend" )
580 _texture.useAdditiveBlend( node->getBoolValue() );
582 else if( name == "render-always" )
584 _render_always = node->getBoolValue();
586 else if( name == "size" )
588 if( node->getIndex() == 0 )
589 setSizeX( node->getIntValue() );
590 else if( node->getIndex() == 1 )
591 setSizeY( node->getIntValue() );
593 else if( name == "update" )
596 _root_group->update(0);
599 else if( name == "view" )
601 if( node->getIndex() == 0 )
602 setViewWidth( node->getIntValue() );
603 else if( node->getIndex() == 1 )
604 setViewHeight( node->getIntValue() );
606 else if( name == "freeze" )
607 _texture.setRender( node->getBoolValue() );
614 if( !handled && _root_group.get() )
615 _root_group->valueChanged(node);
618 //----------------------------------------------------------------------------
619 osg::Texture2D* Canvas::getTexture() const
621 return _texture.getTexture();
624 //----------------------------------------------------------------------------
625 Canvas::CullCallbackPtr Canvas::getCullCallback() const
627 return _cull_callback;
630 //----------------------------------------------------------------------------
631 void Canvas::reloadPlacements(const std::string& type)
633 for(size_t i = 0; i < _placements.size(); ++i)
635 if( _placements[i].empty() )
638 SGPropertyNode* child = _placements[i].front()->getProps();
640 // reload if type matches or no type specified
641 || child->getStringValue("type", type.c_str()) == type )
643 _dirty_placements.push_back(child);
648 //----------------------------------------------------------------------------
649 void Canvas::addPlacementFactory( const std::string& type,
650 PlacementFactory factory )
652 if( _placement_factories.find(type) != _placement_factories.end() )
657 "Canvas::addPlacementFactory: replace existing factory '" << type << "'"
660 _placement_factories[type] = factory;
663 //----------------------------------------------------------------------------
664 void Canvas::removePlacementFactory(const std::string& type)
666 PlacementFactoryMap::iterator it = _placement_factories.find(type);
667 if( it == _placement_factories.end() )
672 "Canvas::removePlacementFactory: no such factory '" << type << "'"
675 _placement_factories.erase(it);
679 //----------------------------------------------------------------------------
680 void Canvas::setSystemAdapter(const SystemAdapterPtr& system_adapter)
682 _system_adapter = system_adapter;
685 //----------------------------------------------------------------------------
686 SystemAdapterPtr Canvas::getSystemAdapter()
688 return _system_adapter;
691 //----------------------------------------------------------------------------
692 void Canvas::setStatusFlags(unsigned int flags, bool set)
699 if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
700 _status_msg = "Missing size";
701 else if( _status & MISSING_SIZE_X )
702 _status_msg = "Missing size-x";
703 else if( _status & MISSING_SIZE_Y )
704 _status_msg = "Missing size-y";
705 else if( _status & CREATE_FAILED )
706 _status_msg = "Creating render target failed";
707 else if( _status & STATUS_DIRTY )
708 _status_msg = "Creation pending...";
713 //----------------------------------------------------------------------------
714 Canvas::PlacementFactoryMap Canvas::_placement_factories;
715 SystemAdapterPtr Canvas::_system_adapter;
717 } // namespace canvas
718 } // namespace simgear