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 <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>
29 #include <osgText/Text>
30 #include <osgViewer/Viewer>
32 #include <boost/algorithm/string/predicate.hpp>
33 #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) && !_canvas.expired() )
53 _canvas.lock()->enableRendering();
58 //----------------------------------------------------------------------------
59 Canvas::Canvas(SGPropertyNode* node):
60 PropertyBasedElement(node),
62 _event_manager(new EventManager),
67 _status(node, "status"),
68 _status_msg(node, "status-msg"),
69 _sampling_dirty(false),
75 setStatusFlags(MISSING_SIZE_X | MISSING_SIZE_Y);
78 //----------------------------------------------------------------------------
84 //----------------------------------------------------------------------------
85 void Canvas::setSystemAdapter(const SystemAdapterPtr& system_adapter)
87 _system_adapter = system_adapter;
88 _texture.setSystemAdapter(system_adapter);
91 //----------------------------------------------------------------------------
92 SystemAdapterPtr Canvas::getSystemAdapter() const
94 return _system_adapter;
97 //----------------------------------------------------------------------------
98 void Canvas::setCanvasMgr(CanvasMgr* canvas_mgr)
100 _canvas_mgr = canvas_mgr;
103 //----------------------------------------------------------------------------
104 CanvasMgr* Canvas::getCanvasMgr() const
109 //----------------------------------------------------------------------------
110 bool Canvas::isInit() const
112 return _texture.serviceable();
115 //----------------------------------------------------------------------------
116 void Canvas::destroy()
118 // TODO check if really not in use anymore
119 getProps()->getParent()
120 ->removeChild( getProps()->getName(),
121 getProps()->getIndex(),
125 //----------------------------------------------------------------------------
126 void Canvas::addParentCanvas(const CanvasWeakPtr& canvas)
128 if( canvas.expired() )
134 "Canvas::addParentCanvas: got an expired parent: " << _node->getPath()
139 _parent_canvases.insert(canvas);
142 //----------------------------------------------------------------------------
143 void Canvas::addChildCanvas(const CanvasWeakPtr& canvas)
145 if( canvas.expired() )
151 "Canvas::addChildCanvas: got an expired child: " << _node->getPath()
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 boost::dynamic_pointer_cast<Group>
176 _root_group->createChild("group", name)
180 //----------------------------------------------------------------------------
181 GroupPtr Canvas::getGroup(const std::string& name)
183 return boost::dynamic_pointer_cast<Group>
185 _root_group->getChild(name)
189 //----------------------------------------------------------------------------
190 GroupPtr Canvas::getRootGroup()
195 //----------------------------------------------------------------------------
196 void Canvas::enableRendering(bool force)
200 _render_dirty = true;
203 //----------------------------------------------------------------------------
204 void Canvas::update(double delta_time_sec)
206 if( (!_texture.serviceable() && _status != STATUS_DIRTY)
207 || (_status & CREATE_FAILED) )
210 if( _status == STATUS_DIRTY )
212 _texture.setSize(_size_x, _size_y);
214 if( !_texture.serviceable() )
216 _texture.useImageCoords(true);
217 _texture.useStencil(true);
218 _texture.allocRT(/*_camera_callback*/);
222 // Resizing causes a new texture to be created so we need to reapply all
223 // existing placements
227 osg::Camera* camera = _texture.getCamera();
229 osg::Vec4 clear_color(0.0f, 0.0f, 0.0f , 1.0f);
230 parseColor(_node->getStringValue("background"), clear_color);
231 camera->setClearColor(clear_color);
233 camera->addChild(_root_group->getMatrixTransform());
235 // Ensure objects are drawn in order of traversal
236 camera->getOrCreateStateSet()->setBinName("TraversalOrderBin");
238 if( _texture.serviceable() )
240 setStatusFlags(STATUS_OK);
241 setStatusFlags(STATUS_DIRTY, false);
242 _render_dirty = true;
246 setStatusFlags(CREATE_FAILED);
251 if( _visible || _render_always )
253 BOOST_FOREACH(CanvasWeakPtr canvas, _child_canvases)
255 // TODO should we check if the image the child canvas is displayed
256 // within is really visible?
257 if( !canvas.expired() )
258 canvas.lock()->_visible = true;
263 // Also mark all canvases this canvas is displayed within as dirty
264 BOOST_FOREACH(CanvasWeakPtr canvas, _parent_canvases)
266 if( !canvas.expired() )
267 canvas.lock()->_render_dirty = true;
271 _texture.setRender(_render_dirty);
273 _render_dirty = false;
277 _texture.setRender(false);
279 _root_group->update(delta_time_sec);
281 if( _sampling_dirty )
283 _texture.setSampling(
284 _node->getBoolValue("mipmapping"),
285 _node->getIntValue("coverage-samples"),
286 _node->getIntValue("color-samples")
288 _sampling_dirty = false;
289 _render_dirty = true;
292 while( !_dirty_placements.empty() )
294 SGPropertyNode *node = _dirty_placements.back();
295 _dirty_placements.pop_back();
297 if( node->getIndex() >= static_cast<int>(_placements.size()) )
299 _placements.resize(node->getIndex() + 1);
301 // Remove possibly existing placements
302 _placements[ node->getIndex() ].clear();
304 // Get new placements
305 PlacementFactoryMap::const_iterator placement_factory =
306 _placement_factories.find( node->getStringValue("type", "object") );
307 if( placement_factory != _placement_factories.end() )
309 Placements& placements = _placements[ node->getIndex() ] =
310 placement_factory->second
313 boost::static_pointer_cast<Canvas>(_self.lock())
318 placements.empty() ? "No match" : "Ok"
322 node->setStringValue("status-msg", "Unknown placement type");
326 //----------------------------------------------------------------------------
327 naRef Canvas::addEventListener(const nasal::CallContext& ctx)
329 if( !_root_group.get() )
330 naRuntimeError(ctx.c, "Canvas: No root group!");
332 return _root_group->addEventListener(ctx);
335 //----------------------------------------------------------------------------
336 void Canvas::setSizeX(int sx)
341 setStatusFlags(STATUS_DIRTY);
344 setStatusFlags(MISSING_SIZE_X);
346 setStatusFlags(MISSING_SIZE_X, false);
348 // reset flag to allow creation with new size
349 setStatusFlags(CREATE_FAILED, false);
352 //----------------------------------------------------------------------------
353 void Canvas::setSizeY(int sy)
358 setStatusFlags(STATUS_DIRTY);
361 setStatusFlags(MISSING_SIZE_Y);
363 setStatusFlags(MISSING_SIZE_Y, false);
365 // reset flag to allow creation with new size
366 setStatusFlags(CREATE_FAILED, false);
369 //----------------------------------------------------------------------------
370 int Canvas::getSizeX() const
375 //----------------------------------------------------------------------------
376 int Canvas::getSizeY() const
381 //----------------------------------------------------------------------------
382 void Canvas::setViewWidth(int w)
384 if( _view_width == w )
388 _texture.setViewSize(_view_width, _view_height);
391 //----------------------------------------------------------------------------
392 void Canvas::setViewHeight(int h)
394 if( _view_height == h )
398 _texture.setViewSize(_view_width, _view_height);
401 //----------------------------------------------------------------------------
402 int Canvas::getViewWidth() const
404 return _texture.getViewSize().x();
407 //----------------------------------------------------------------------------
408 int Canvas::getViewHeight() const
410 return _texture.getViewSize().y();
413 //----------------------------------------------------------------------------
414 SGRect<int> Canvas::getViewport() const
416 return SGRect<int>(0, 0, getViewWidth(), getViewHeight());
419 //----------------------------------------------------------------------------
420 bool Canvas::handleMouseEvent(const MouseEventPtr& event)
422 if( !_root_group.get() )
425 EventVisitor visitor( EventVisitor::TRAVERSE_DOWN,
426 event->getClientPos(),
428 if( !_root_group->accept(visitor) )
431 return _event_manager->handleEvent(event, visitor.getPropagationPath());
434 //----------------------------------------------------------------------------
435 void Canvas::childAdded( SGPropertyNode * parent,
436 SGPropertyNode * child )
438 if( parent != _node )
441 if( child->getNameString() == "placement" )
442 _dirty_placements.push_back(child);
443 else if( _root_group.get() )
444 static_cast<Element*>(_root_group.get())->childAdded(parent, child);
447 //----------------------------------------------------------------------------
448 void Canvas::childRemoved( SGPropertyNode * parent,
449 SGPropertyNode * child )
451 _render_dirty = true;
453 if( parent != _node )
456 if( child->getNameString() == "placement" )
457 _placements[ child->getIndex() ].clear();
458 else if( _root_group.get() )
459 static_cast<Element*>(_root_group.get())->childRemoved(parent, child);
462 //----------------------------------------------------------------------------
463 void Canvas::valueChanged(SGPropertyNode* node)
465 if( boost::starts_with(node->getNameString(), "status")
466 || node->getParent()->getNameString() == "bounding-box" )
468 _render_dirty = true;
471 if( node->getParent()->getParent() == _node
472 && node->getParent()->getNameString() == "placement" )
474 bool placement_dirty = false;
475 BOOST_FOREACH(Placements& placements, _placements)
477 BOOST_FOREACH(PlacementPtr& placement, placements)
479 // check if change can be directly handled by placement
480 if( placement->getProps() == node->getParent()
481 && !placement->childChanged(node) )
482 placement_dirty = true;
486 if( !placement_dirty )
489 // prevent double updates...
490 for( size_t i = 0; i < _dirty_placements.size(); ++i )
492 if( node->getParent() == _dirty_placements[i] )
496 _dirty_placements.push_back(node->getParent());
498 else if( node->getParent() == _node )
500 if( node->getNameString() == "background" )
503 if( _texture.getCamera() && parseColor(node->getStringValue(), color) )
505 _texture.getCamera()->setClearColor(color);
506 _render_dirty = true;
509 else if( node->getNameString() == "mipmapping"
510 || node->getNameString() == "coverage-samples"
511 || node->getNameString() == "color-samples" )
513 _sampling_dirty = true;
515 else if( node->getNameString() == "additive-blend" )
517 _texture.useAdditiveBlend( node->getBoolValue() );
519 else if( node->getNameString() == "render-always" )
521 _render_always = node->getBoolValue();
523 else if( node->getNameString() == "size" )
525 if( node->getIndex() == 0 )
526 setSizeX( node->getIntValue() );
527 else if( node->getIndex() == 1 )
528 setSizeY( node->getIntValue() );
530 else if( node->getNameString() == "view" )
532 if( node->getIndex() == 0 )
533 setViewWidth( node->getIntValue() );
534 else if( node->getIndex() == 1 )
535 setViewHeight( node->getIntValue() );
537 else if( node->getNameString() == "freeze" )
538 _texture.setRender( node->getBoolValue() );
545 if( !handled && _root_group.get() )
546 _root_group->valueChanged(node);
549 //----------------------------------------------------------------------------
550 osg::Texture2D* Canvas::getTexture() const
552 return _texture.getTexture();
555 //----------------------------------------------------------------------------
556 Canvas::CullCallbackPtr Canvas::getCullCallback() const
558 return _cull_callback;
561 //----------------------------------------------------------------------------
562 void Canvas::reloadPlacements(const std::string& type)
564 for(size_t i = 0; i < _placements.size(); ++i)
566 if( _placements[i].empty() )
569 SGPropertyNode* child = _placements[i].front()->getProps();
571 // reload if type matches or no type specified
572 || child->getStringValue("type", type.c_str()) == type )
574 _dirty_placements.push_back(child);
579 //----------------------------------------------------------------------------
580 void Canvas::addPlacementFactory( const std::string& type,
581 PlacementFactory factory )
583 if( _placement_factories.find(type) != _placement_factories.end() )
588 "Canvas::addPlacementFactory: replace existing factor for type " << type
591 _placement_factories[type] = factory;
594 //----------------------------------------------------------------------------
595 void Canvas::setSelf(const PropertyBasedElementPtr& self)
597 PropertyBasedElement::setSelf(self);
599 CanvasPtr canvas = boost::static_pointer_cast<Canvas>(self);
601 _root_group.reset( new Group(canvas, _node) );
602 _root_group->setSelf(_root_group);
604 // Remove automatically created property listener as we forward them on our
606 _root_group->removeListener();
608 _cull_callback = new CullCallback(canvas);
611 //----------------------------------------------------------------------------
612 void Canvas::setStatusFlags(unsigned int flags, bool set)
619 if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
620 _status_msg = "Missing size";
621 else if( _status & MISSING_SIZE_X )
622 _status_msg = "Missing size-x";
623 else if( _status & MISSING_SIZE_Y )
624 _status_msg = "Missing size-y";
625 else if( _status & CREATE_FAILED )
626 _status_msg = "Creating render target failed";
627 else if( _status == STATUS_DIRTY )
628 _status_msg = "Creation pending...";
633 //----------------------------------------------------------------------------
634 Canvas::PlacementFactoryMap Canvas::_placement_factories;
636 } // namespace canvas
637 } // namespace simgear