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::getRootGroup()
186 //----------------------------------------------------------------------------
187 void Canvas::enableRendering(bool force)
191 _render_dirty = true;
194 //----------------------------------------------------------------------------
195 void Canvas::update(double delta_time_sec)
197 if( (!_texture.serviceable() && _status != STATUS_DIRTY)
198 || (_status & CREATE_FAILED) )
201 if( _status == STATUS_DIRTY )
203 _texture.setSize(_size_x, _size_y);
205 if( !_texture.serviceable() )
207 _texture.useImageCoords(true);
208 _texture.useStencil(true);
209 _texture.allocRT(/*_camera_callback*/);
213 // Resizing causes a new texture to be created so we need to reapply all
214 // existing placements
218 osg::Camera* camera = _texture.getCamera();
220 osg::Vec4 clear_color(0.0f, 0.0f, 0.0f , 1.0f);
221 parseColor(_node->getStringValue("background"), clear_color);
222 camera->setClearColor(clear_color);
224 camera->addChild(_root_group->getMatrixTransform());
226 // Ensure objects are drawn in order of traversal
227 camera->getOrCreateStateSet()->setBinName("TraversalOrderBin");
229 if( _texture.serviceable() )
231 setStatusFlags(STATUS_OK);
232 setStatusFlags(STATUS_DIRTY, false);
233 _render_dirty = true;
237 setStatusFlags(CREATE_FAILED);
242 if( _visible || _render_always )
244 BOOST_FOREACH(CanvasWeakPtr canvas, _child_canvases)
246 // TODO should we check if the image the child canvas is displayed
247 // within is really visible?
248 if( !canvas.expired() )
249 canvas.lock()->_visible = true;
254 // Also mark all canvases this canvas is displayed within as dirty
255 BOOST_FOREACH(CanvasWeakPtr canvas, _parent_canvases)
257 if( !canvas.expired() )
258 canvas.lock()->_render_dirty = true;
262 _texture.setRender(_render_dirty);
264 _render_dirty = false;
268 _texture.setRender(false);
270 _root_group->update(delta_time_sec);
272 if( _sampling_dirty )
274 _texture.setSampling(
275 _node->getBoolValue("mipmapping"),
276 _node->getIntValue("coverage-samples"),
277 _node->getIntValue("color-samples")
279 _sampling_dirty = false;
280 _render_dirty = true;
283 while( !_dirty_placements.empty() )
285 SGPropertyNode *node = _dirty_placements.back();
286 _dirty_placements.pop_back();
288 if( node->getIndex() >= static_cast<int>(_placements.size()) )
290 _placements.resize(node->getIndex() + 1);
292 // Remove possibly existing placements
293 _placements[ node->getIndex() ].clear();
295 // Get new placements
296 PlacementFactoryMap::const_iterator placement_factory =
297 _placement_factories.find( node->getStringValue("type", "object") );
298 if( placement_factory != _placement_factories.end() )
300 Placements& placements = _placements[ node->getIndex() ] =
301 placement_factory->second
304 boost::static_pointer_cast<Canvas>(_self.lock())
309 placements.empty() ? "No match" : "Ok"
313 node->setStringValue("status-msg", "Unknown placement type");
317 //----------------------------------------------------------------------------
318 naRef Canvas::addEventListener(const nasal::CallContext& ctx)
320 if( !_root_group.get() )
321 naRuntimeError(ctx.c, "Canvas: No root group!");
323 return _root_group->addEventListener(ctx);
326 //----------------------------------------------------------------------------
327 void Canvas::setSizeX(int sx)
332 setStatusFlags(STATUS_DIRTY);
335 setStatusFlags(MISSING_SIZE_X);
337 setStatusFlags(MISSING_SIZE_X, false);
339 // reset flag to allow creation with new size
340 setStatusFlags(CREATE_FAILED, false);
343 //----------------------------------------------------------------------------
344 void Canvas::setSizeY(int sy)
349 setStatusFlags(STATUS_DIRTY);
352 setStatusFlags(MISSING_SIZE_Y);
354 setStatusFlags(MISSING_SIZE_Y, false);
356 // reset flag to allow creation with new size
357 setStatusFlags(CREATE_FAILED, false);
360 //----------------------------------------------------------------------------
361 int Canvas::getSizeX() const
366 //----------------------------------------------------------------------------
367 int Canvas::getSizeY() const
372 //----------------------------------------------------------------------------
373 void Canvas::setViewWidth(int w)
375 if( _view_width == w )
379 _texture.setViewSize(_view_width, _view_height);
382 //----------------------------------------------------------------------------
383 void Canvas::setViewHeight(int h)
385 if( _view_height == h )
389 _texture.setViewSize(_view_width, _view_height);
392 //----------------------------------------------------------------------------
393 int Canvas::getViewWidth() const
395 return _texture.getViewSize().x();
398 //----------------------------------------------------------------------------
399 int Canvas::getViewHeight() const
401 return _texture.getViewSize().y();
404 //----------------------------------------------------------------------------
405 SGRect<int> Canvas::getViewport() const
407 return SGRect<int>(0, 0, getViewWidth(), getViewHeight());
410 //----------------------------------------------------------------------------
411 bool Canvas::handleMouseEvent(const MouseEventPtr& event)
413 if( !_root_group.get() )
416 EventVisitor visitor( EventVisitor::TRAVERSE_DOWN,
417 event->getClientPos(),
419 if( !_root_group->accept(visitor) )
422 return _event_manager->handleEvent(event, visitor.getPropagationPath());
425 //----------------------------------------------------------------------------
426 void Canvas::childAdded( SGPropertyNode * parent,
427 SGPropertyNode * child )
429 if( parent != _node )
432 if( child->getNameString() == "placement" )
433 _dirty_placements.push_back(child);
434 else if( _root_group.get() )
435 static_cast<Element*>(_root_group.get())->childAdded(parent, child);
438 //----------------------------------------------------------------------------
439 void Canvas::childRemoved( SGPropertyNode * parent,
440 SGPropertyNode * child )
442 _render_dirty = true;
444 if( parent != _node )
447 if( child->getNameString() == "placement" )
448 _placements[ child->getIndex() ].clear();
449 else if( _root_group.get() )
450 static_cast<Element*>(_root_group.get())->childRemoved(parent, child);
453 //----------------------------------------------------------------------------
454 void Canvas::valueChanged(SGPropertyNode* node)
456 if( boost::starts_with(node->getNameString(), "status")
457 || node->getParent()->getNameString() == "bounding-box" )
459 _render_dirty = true;
462 if( node->getParent()->getParent() == _node
463 && node->getParent()->getNameString() == "placement" )
465 bool placement_dirty = false;
466 BOOST_FOREACH(Placements& placements, _placements)
468 BOOST_FOREACH(PlacementPtr& placement, placements)
470 // check if change can be directly handled by placement
471 if( placement->getProps() == node->getParent()
472 && !placement->childChanged(node) )
473 placement_dirty = true;
477 if( !placement_dirty )
480 // prevent double updates...
481 for( size_t i = 0; i < _dirty_placements.size(); ++i )
483 if( node->getParent() == _dirty_placements[i] )
487 _dirty_placements.push_back(node->getParent());
489 else if( node->getParent() == _node )
491 if( node->getNameString() == "background" )
494 if( _texture.getCamera() && parseColor(node->getStringValue(), color) )
496 _texture.getCamera()->setClearColor(color);
497 _render_dirty = true;
500 else if( node->getNameString() == "mipmapping"
501 || node->getNameString() == "coverage-samples"
502 || node->getNameString() == "color-samples" )
504 _sampling_dirty = true;
506 else if( node->getNameString() == "additive-blend" )
508 _texture.useAdditiveBlend( node->getBoolValue() );
510 else if( node->getNameString() == "render-always" )
512 _render_always = node->getBoolValue();
514 else if( node->getNameString() == "size" )
516 if( node->getIndex() == 0 )
517 setSizeX( node->getIntValue() );
518 else if( node->getIndex() == 1 )
519 setSizeY( node->getIntValue() );
521 else if( node->getNameString() == "view" )
523 if( node->getIndex() == 0 )
524 setViewWidth( node->getIntValue() );
525 else if( node->getIndex() == 1 )
526 setViewHeight( node->getIntValue() );
528 else if( node->getNameString() == "freeze" )
529 _texture.setRender( node->getBoolValue() );
536 if( !handled && _root_group.get() )
537 _root_group->valueChanged(node);
540 //----------------------------------------------------------------------------
541 osg::Texture2D* Canvas::getTexture() const
543 return _texture.getTexture();
546 //----------------------------------------------------------------------------
547 Canvas::CullCallbackPtr Canvas::getCullCallback() const
549 return _cull_callback;
552 //----------------------------------------------------------------------------
553 void Canvas::reloadPlacements(const std::string& type)
555 for(size_t i = 0; i < _placements.size(); ++i)
557 if( _placements[i].empty() )
560 SGPropertyNode* child = _placements[i].front()->getProps();
562 // reload if type matches or no type specified
563 || child->getStringValue("type", type.c_str()) == type )
565 _dirty_placements.push_back(child);
570 //----------------------------------------------------------------------------
571 void Canvas::addPlacementFactory( const std::string& type,
572 PlacementFactory factory )
574 if( _placement_factories.find(type) != _placement_factories.end() )
579 "Canvas::addPlacementFactory: replace existing factor for type " << type
582 _placement_factories[type] = factory;
585 //----------------------------------------------------------------------------
586 void Canvas::setSelf(const PropertyBasedElementPtr& self)
588 PropertyBasedElement::setSelf(self);
590 CanvasPtr canvas = boost::static_pointer_cast<Canvas>(self);
592 _root_group.reset( new Group(canvas, _node) );
593 _root_group->setSelf(_root_group);
595 // Remove automatically created property listener as we forward them on our
597 _root_group->removeListener();
599 _cull_callback = new CullCallback(canvas);
602 //----------------------------------------------------------------------------
603 void Canvas::setStatusFlags(unsigned int flags, bool set)
610 if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
611 _status_msg = "Missing size";
612 else if( _status & MISSING_SIZE_X )
613 _status_msg = "Missing size-x";
614 else if( _status & MISSING_SIZE_Y )
615 _status_msg = "Missing size-y";
616 else if( _status & CREATE_FAILED )
617 _status_msg = "Creating render target failed";
618 else if( _status == STATUS_DIRTY )
619 _status_msg = "Creation pending...";
624 //----------------------------------------------------------------------------
625 Canvas::PlacementFactoryMap Canvas::_placement_factories;
627 } // namespace canvas
628 } // namespace simgear