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);
199 _status |= LAYOUT_DIRTY;
202 //----------------------------------------------------------------------------
203 void Canvas::enableRendering(bool force)
207 _render_dirty = true;
210 //----------------------------------------------------------------------------
211 void Canvas::update(double delta_time_sec)
213 if( _status & (CREATE_FAILED | MISSING_SIZE) )
216 if( _status & STATUS_DIRTY )
218 _texture.setSize(_size_x, _size_y);
220 if( !_texture.serviceable() )
222 _texture.useImageCoords(true);
223 _texture.useStencil(true);
224 _texture.allocRT(/*_camera_callback*/);
228 // Resizing causes a new texture to be created so we need to reapply all
229 // existing placements
233 osg::Camera* camera = _texture.getCamera();
235 // TODO Allow custom render order? For now just keep in order with
237 camera->setRenderOrder(osg::Camera::PRE_RENDER, _node->getIndex());
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);
243 camera->addChild(_root_group->getMatrixTransform());
245 if( _texture.serviceable() )
247 setStatusFlags(STATUS_OK);
248 setStatusFlags(STATUS_DIRTY, false);
249 _render_dirty = true;
253 setStatusFlags(CREATE_FAILED);
260 if( (_status & LAYOUT_DIRTY) )
262 _layout->setGeometry(SGRecti(0, 0, _view_width, _view_height));
263 _status &= ~LAYOUT_DIRTY;
269 if( _visible || _render_always )
271 BOOST_FOREACH(CanvasWeakPtr canvas_weak, _child_canvases)
273 // TODO should we check if the image the child canvas is displayed
274 // within is really visible?
275 CanvasPtr canvas = canvas_weak.lock();
277 canvas->_visible = true;
282 // Also mark all canvases this canvas is displayed within as dirty
283 BOOST_FOREACH(CanvasWeakPtr canvas_weak, _parent_canvases)
285 CanvasPtr canvas = canvas_weak.lock();
287 canvas->_render_dirty = true;
291 _texture.setRender(_render_dirty);
293 _render_dirty = false;
297 _texture.setRender(false);
299 _root_group->update(delta_time_sec);
301 if( _sampling_dirty )
303 _texture.setSampling(
304 _node->getBoolValue("mipmapping"),
305 _node->getIntValue("coverage-samples"),
306 _node->getIntValue("color-samples")
308 _sampling_dirty = false;
309 _render_dirty = true;
312 while( !_dirty_placements.empty() )
314 SGPropertyNode *node = _dirty_placements.back();
315 _dirty_placements.pop_back();
317 if( node->getIndex() >= static_cast<int>(_placements.size()) )
319 _placements.resize(node->getIndex() + 1);
321 // Remove possibly existing placements
322 _placements[ node->getIndex() ].clear();
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() )
329 Placements& placements = _placements[ node->getIndex() ] =
330 placement_factory->second(node, this);
334 placements.empty() ? "No match" : "Ok"
338 node->setStringValue("status-msg", "Unknown placement type");
342 //----------------------------------------------------------------------------
343 bool Canvas::addEventListener( const std::string& type,
344 const EventListener& cb )
346 if( !_root_group.get() )
347 throw std::runtime_error("Canvas::addEventListener: no root group!");
349 return _root_group->addEventListener(type, cb);
352 //----------------------------------------------------------------------------
353 bool Canvas::dispatchEvent(const EventPtr& event)
355 if( !_root_group.get() )
356 throw std::runtime_error("Canvas::dispatchEvent: no root group!");
358 return _root_group->dispatchEvent(event);
361 //----------------------------------------------------------------------------
362 void Canvas::setSizeX(int sx)
367 setStatusFlags(STATUS_DIRTY);
370 setStatusFlags(MISSING_SIZE_X);
372 setStatusFlags(MISSING_SIZE_X, false);
374 // reset flag to allow creation with new size
375 setStatusFlags(CREATE_FAILED, false);
378 //----------------------------------------------------------------------------
379 void Canvas::setSizeY(int sy)
384 setStatusFlags(STATUS_DIRTY);
387 setStatusFlags(MISSING_SIZE_Y);
389 setStatusFlags(MISSING_SIZE_Y, false);
391 // reset flag to allow creation with new size
392 setStatusFlags(CREATE_FAILED, false);
395 //----------------------------------------------------------------------------
396 int Canvas::getSizeX() const
401 //----------------------------------------------------------------------------
402 int Canvas::getSizeY() const
407 //----------------------------------------------------------------------------
408 void Canvas::setViewWidth(int w)
410 if( _view_width == w )
413 _status |= LAYOUT_DIRTY;
415 _texture.setViewSize(_view_width, _view_height);
418 //----------------------------------------------------------------------------
419 void Canvas::setViewHeight(int h)
421 if( _view_height == h )
424 _status |= LAYOUT_DIRTY;
426 _texture.setViewSize(_view_width, _view_height);
429 //----------------------------------------------------------------------------
430 int Canvas::getViewWidth() const
432 return _texture.getViewSize().x();
435 //----------------------------------------------------------------------------
436 int Canvas::getViewHeight() const
438 return _texture.getViewSize().y();
441 //----------------------------------------------------------------------------
442 SGRect<int> Canvas::getViewport() const
444 return SGRect<int>(0, 0, getViewWidth(), getViewHeight());
447 //----------------------------------------------------------------------------
448 bool Canvas::handleMouseEvent(const MouseEventPtr& event)
453 EventVisitor visitor( EventVisitor::TRAVERSE_DOWN,
454 event->getClientPos(),
456 if( !_root_group->accept(visitor) )
459 return _event_manager->handleEvent(event, visitor.getPropagationPath());
462 //----------------------------------------------------------------------------
463 bool Canvas::propagateEvent( EventPtr const& event,
464 EventPropagationPath const& path )
466 return _event_manager->propagateEvent(event, path);
469 //----------------------------------------------------------------------------
470 void Canvas::childAdded( SGPropertyNode * parent,
471 SGPropertyNode * child )
473 if( parent != _node )
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);
482 //----------------------------------------------------------------------------
483 void Canvas::childRemoved( SGPropertyNode * parent,
484 SGPropertyNode * child )
486 _render_dirty = true;
488 if( parent != _node )
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);
497 //----------------------------------------------------------------------------
498 void Canvas::valueChanged(SGPropertyNode* node)
500 const std::string& name = node->getNameString();
502 if( boost::starts_with(name, "status")
503 || boost::starts_with(name, "data-") )
505 _render_dirty = true;
508 if( node->getParent()->getParent() == _node
509 && node->getParent()->getNameString() == "placement" )
511 size_t index = node->getIndex();
512 if( index < _placements.size() )
514 Placements& placements = _placements[index];
515 if( !placements.empty() )
517 bool placement_dirty = false;
518 BOOST_FOREACH(PlacementPtr& placement, placements)
520 // check if change can be directly handled by placement
521 if( placement->getProps() == node->getParent()
522 && !placement->childChanged(node) )
523 placement_dirty = true;
526 if( !placement_dirty )
531 // prevent double updates...
532 for( size_t i = 0; i < _dirty_placements.size(); ++i )
534 if( node->getParent() == _dirty_placements[i] )
538 _dirty_placements.push_back(node->getParent());
540 else if( node->getParent() == _node )
542 if( name == "background" )
545 if( _texture.getCamera() && parseColor(node->getStringValue(), color) )
547 _texture.getCamera()->setClearColor(color);
548 _render_dirty = true;
551 else if( name == "mipmapping"
552 || name == "coverage-samples"
553 || name == "color-samples" )
555 _sampling_dirty = true;
557 else if( name == "additive-blend" )
559 _texture.useAdditiveBlend( node->getBoolValue() );
561 else if( name == "render-always" )
563 _render_always = node->getBoolValue();
565 else if( name == "size" )
567 if( node->getIndex() == 0 )
568 setSizeX( node->getIntValue() );
569 else if( node->getIndex() == 1 )
570 setSizeY( node->getIntValue() );
572 else if( name == "update" )
575 _root_group->update(0);
578 else if( name == "view" )
580 if( node->getIndex() == 0 )
581 setViewWidth( node->getIntValue() );
582 else if( node->getIndex() == 1 )
583 setViewHeight( node->getIntValue() );
585 else if( name == "freeze" )
586 _texture.setRender( node->getBoolValue() );
593 if( !handled && _root_group.get() )
594 _root_group->valueChanged(node);
597 //----------------------------------------------------------------------------
598 osg::Texture2D* Canvas::getTexture() const
600 return _texture.getTexture();
603 //----------------------------------------------------------------------------
604 Canvas::CullCallbackPtr Canvas::getCullCallback() const
606 return _cull_callback;
609 //----------------------------------------------------------------------------
610 void Canvas::reloadPlacements(const std::string& type)
612 for(size_t i = 0; i < _placements.size(); ++i)
614 if( _placements[i].empty() )
617 SGPropertyNode* child = _placements[i].front()->getProps();
619 // reload if type matches or no type specified
620 || child->getStringValue("type", type.c_str()) == type )
622 _dirty_placements.push_back(child);
627 //----------------------------------------------------------------------------
628 void Canvas::addPlacementFactory( const std::string& type,
629 PlacementFactory factory )
631 if( _placement_factories.find(type) != _placement_factories.end() )
636 "Canvas::addPlacementFactory: replace existing factory '" << type << "'"
639 _placement_factories[type] = factory;
642 //----------------------------------------------------------------------------
643 void Canvas::removePlacementFactory(const std::string& type)
645 PlacementFactoryMap::iterator it = _placement_factories.find(type);
646 if( it == _placement_factories.end() )
651 "Canvas::removePlacementFactory: no such factory '" << type << "'"
654 _placement_factories.erase(it);
658 //----------------------------------------------------------------------------
659 void Canvas::setSystemAdapter(const SystemAdapterPtr& system_adapter)
661 _system_adapter = system_adapter;
664 //----------------------------------------------------------------------------
665 SystemAdapterPtr Canvas::getSystemAdapter()
667 return _system_adapter;
670 //----------------------------------------------------------------------------
671 void Canvas::setStatusFlags(unsigned int flags, bool set)
678 if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
679 _status_msg = "Missing size";
680 else if( _status & MISSING_SIZE_X )
681 _status_msg = "Missing size-x";
682 else if( _status & MISSING_SIZE_Y )
683 _status_msg = "Missing size-y";
684 else if( _status & CREATE_FAILED )
685 _status_msg = "Creating render target failed";
686 else if( _status & STATUS_DIRTY )
687 _status_msg = "Creation pending...";
692 //----------------------------------------------------------------------------
693 Canvas::PlacementFactoryMap Canvas::_placement_factories;
694 SystemAdapterPtr Canvas::_system_adapter;
696 } // namespace canvas
697 } // namespace simgear