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>
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) && !_canvas.expired() )
52 _canvas.lock()->enableRendering();
57 //----------------------------------------------------------------------------
58 Canvas::Canvas(SGPropertyNode* node):
59 PropertyBasedElement(node),
61 _event_manager(new EventManager),
66 _status(node, "status"),
67 _status_msg(node, "status-msg"),
68 _sampling_dirty(false),
74 setStatusFlags(MISSING_SIZE_X | MISSING_SIZE_Y);
77 //----------------------------------------------------------------------------
83 //----------------------------------------------------------------------------
84 void Canvas::setSystemAdapter(const SystemAdapterPtr& system_adapter)
86 _system_adapter = system_adapter;
87 _texture.setSystemAdapter(system_adapter);
90 //----------------------------------------------------------------------------
91 SystemAdapterPtr Canvas::getSystemAdapter() const
93 return _system_adapter;
96 //----------------------------------------------------------------------------
97 void Canvas::setCanvasMgr(CanvasMgr* canvas_mgr)
99 _canvas_mgr = canvas_mgr;
102 //----------------------------------------------------------------------------
103 CanvasMgr* Canvas::getCanvasMgr() const
108 //----------------------------------------------------------------------------
109 bool Canvas::isInit() const
111 return _texture.serviceable();
114 //----------------------------------------------------------------------------
115 void Canvas::destroy()
118 _root_group->clearEventListener();
120 // TODO check if really not in use anymore
121 getProps()->getParent()
122 ->removeChild( getProps()->getName(),
123 getProps()->getIndex(),
127 //----------------------------------------------------------------------------
128 void Canvas::addParentCanvas(const CanvasWeakPtr& canvas)
130 if( canvas.expired() )
136 "Canvas::addParentCanvas: got an expired parent: " << _node->getPath()
141 _parent_canvases.insert(canvas);
144 //----------------------------------------------------------------------------
145 void Canvas::addChildCanvas(const CanvasWeakPtr& canvas)
147 if( canvas.expired() )
153 "Canvas::addChildCanvas: got an expired child: " << _node->getPath()
158 _child_canvases.insert(canvas);
161 //----------------------------------------------------------------------------
162 void Canvas::removeParentCanvas(const CanvasWeakPtr& canvas)
164 _parent_canvases.erase(canvas);
167 //----------------------------------------------------------------------------
168 void Canvas::removeChildCanvas(const CanvasWeakPtr& canvas)
170 _child_canvases.erase(canvas);
173 //----------------------------------------------------------------------------
174 GroupPtr Canvas::createGroup(const std::string& name)
176 return _root_group->createChild<Group>(name);
179 //----------------------------------------------------------------------------
180 GroupPtr Canvas::getGroup(const std::string& name)
182 return _root_group->getChild<Group>(name);
185 //----------------------------------------------------------------------------
186 GroupPtr Canvas::getOrCreateGroup(const std::string& name)
188 return _root_group->getOrCreateChild<Group>(name);
191 //----------------------------------------------------------------------------
192 GroupPtr Canvas::getRootGroup()
197 //----------------------------------------------------------------------------
198 void Canvas::enableRendering(bool force)
202 _render_dirty = true;
205 //----------------------------------------------------------------------------
206 void Canvas::update(double delta_time_sec)
208 if( (!_texture.serviceable() && _status != STATUS_DIRTY)
209 || (_status & CREATE_FAILED) )
212 if( _status == STATUS_DIRTY )
214 _texture.setSize(_size_x, _size_y);
216 if( !_texture.serviceable() )
218 _texture.useImageCoords(true);
219 _texture.useStencil(true);
220 _texture.allocRT(/*_camera_callback*/);
224 // Resizing causes a new texture to be created so we need to reapply all
225 // existing placements
229 osg::Camera* camera = _texture.getCamera();
231 osg::Vec4 clear_color(0.0f, 0.0f, 0.0f , 1.0f);
232 parseColor(_node->getStringValue("background"), clear_color);
233 camera->setClearColor(clear_color);
235 camera->addChild(_root_group->getMatrixTransform());
237 // Ensure objects are drawn in order of traversal
238 camera->getOrCreateStateSet()->setBinName("TraversalOrderBin");
240 if( _texture.serviceable() )
242 setStatusFlags(STATUS_OK);
243 setStatusFlags(STATUS_DIRTY, false);
244 _render_dirty = true;
248 setStatusFlags(CREATE_FAILED);
253 if( _visible || _render_always )
255 BOOST_FOREACH(CanvasWeakPtr canvas, _child_canvases)
257 // TODO should we check if the image the child canvas is displayed
258 // within is really visible?
259 if( !canvas.expired() )
260 canvas.lock()->_visible = true;
265 // Also mark all canvases this canvas is displayed within as dirty
266 BOOST_FOREACH(CanvasWeakPtr canvas, _parent_canvases)
268 if( !canvas.expired() )
269 canvas.lock()->_render_dirty = true;
273 _texture.setRender(_render_dirty);
275 _render_dirty = false;
279 _texture.setRender(false);
281 _root_group->update(delta_time_sec);
283 if( _sampling_dirty )
285 _texture.setSampling(
286 _node->getBoolValue("mipmapping"),
287 _node->getIntValue("coverage-samples"),
288 _node->getIntValue("color-samples")
290 _sampling_dirty = false;
291 _render_dirty = true;
294 while( !_dirty_placements.empty() )
296 SGPropertyNode *node = _dirty_placements.back();
297 _dirty_placements.pop_back();
299 if( node->getIndex() >= static_cast<int>(_placements.size()) )
301 _placements.resize(node->getIndex() + 1);
303 // Remove possibly existing placements
304 _placements[ node->getIndex() ].clear();
306 // Get new placements
307 PlacementFactoryMap::const_iterator placement_factory =
308 _placement_factories.find( node->getStringValue("type", "object") );
309 if( placement_factory != _placement_factories.end() )
311 Placements& placements = _placements[ node->getIndex() ] =
312 placement_factory->second
315 boost::static_pointer_cast<Canvas>(_self.lock())
320 placements.empty() ? "No match" : "Ok"
324 node->setStringValue("status-msg", "Unknown placement type");
328 //----------------------------------------------------------------------------
329 naRef Canvas::addEventListener(const nasal::CallContext& ctx)
331 if( !_root_group.get() )
332 naRuntimeError(ctx.c, "Canvas: No root group!");
334 return _root_group->addEventListener(ctx);
337 //----------------------------------------------------------------------------
338 void Canvas::setSizeX(int sx)
343 setStatusFlags(STATUS_DIRTY);
346 setStatusFlags(MISSING_SIZE_X);
348 setStatusFlags(MISSING_SIZE_X, false);
350 // reset flag to allow creation with new size
351 setStatusFlags(CREATE_FAILED, false);
354 //----------------------------------------------------------------------------
355 void Canvas::setSizeY(int sy)
360 setStatusFlags(STATUS_DIRTY);
363 setStatusFlags(MISSING_SIZE_Y);
365 setStatusFlags(MISSING_SIZE_Y, false);
367 // reset flag to allow creation with new size
368 setStatusFlags(CREATE_FAILED, false);
371 //----------------------------------------------------------------------------
372 int Canvas::getSizeX() const
377 //----------------------------------------------------------------------------
378 int Canvas::getSizeY() const
383 //----------------------------------------------------------------------------
384 void Canvas::setViewWidth(int w)
386 if( _view_width == w )
390 _texture.setViewSize(_view_width, _view_height);
393 //----------------------------------------------------------------------------
394 void Canvas::setViewHeight(int h)
396 if( _view_height == h )
400 _texture.setViewSize(_view_width, _view_height);
403 //----------------------------------------------------------------------------
404 int Canvas::getViewWidth() const
406 return _texture.getViewSize().x();
409 //----------------------------------------------------------------------------
410 int Canvas::getViewHeight() const
412 return _texture.getViewSize().y();
415 //----------------------------------------------------------------------------
416 SGRect<int> Canvas::getViewport() const
418 return SGRect<int>(0, 0, getViewWidth(), getViewHeight());
421 //----------------------------------------------------------------------------
422 bool Canvas::handleMouseEvent(const MouseEventPtr& event)
424 if( !_root_group.get() )
427 EventVisitor visitor( EventVisitor::TRAVERSE_DOWN,
428 event->getClientPos(),
430 if( !_root_group->accept(visitor) )
433 return _event_manager->handleEvent(event, visitor.getPropagationPath());
436 //----------------------------------------------------------------------------
437 void Canvas::childAdded( SGPropertyNode * parent,
438 SGPropertyNode * child )
440 if( parent != _node )
443 if( child->getNameString() == "placement" )
444 _dirty_placements.push_back(child);
445 else if( _root_group.get() )
446 static_cast<Element*>(_root_group.get())->childAdded(parent, child);
449 //----------------------------------------------------------------------------
450 void Canvas::childRemoved( SGPropertyNode * parent,
451 SGPropertyNode * child )
453 _render_dirty = true;
455 if( parent != _node )
458 if( child->getNameString() == "placement" )
459 _placements[ child->getIndex() ].clear();
460 else if( _root_group.get() )
461 static_cast<Element*>(_root_group.get())->childRemoved(parent, child);
464 //----------------------------------------------------------------------------
465 void Canvas::valueChanged(SGPropertyNode* node)
467 if( boost::starts_with(node->getNameString(), "status")
468 || node->getParent()->getNameString() == "bounding-box" )
470 _render_dirty = true;
473 if( node->getParent()->getParent() == _node
474 && node->getParent()->getNameString() == "placement" )
476 bool placement_dirty = false;
477 BOOST_FOREACH(Placements& placements, _placements)
479 BOOST_FOREACH(PlacementPtr& placement, placements)
481 // check if change can be directly handled by placement
482 if( placement->getProps() == node->getParent()
483 && !placement->childChanged(node) )
484 placement_dirty = true;
488 if( !placement_dirty )
491 // prevent double updates...
492 for( size_t i = 0; i < _dirty_placements.size(); ++i )
494 if( node->getParent() == _dirty_placements[i] )
498 _dirty_placements.push_back(node->getParent());
500 else if( node->getParent() == _node )
502 if( node->getNameString() == "background" )
505 if( _texture.getCamera() && parseColor(node->getStringValue(), color) )
507 _texture.getCamera()->setClearColor(color);
508 _render_dirty = true;
511 else if( node->getNameString() == "mipmapping"
512 || node->getNameString() == "coverage-samples"
513 || node->getNameString() == "color-samples" )
515 _sampling_dirty = true;
517 else if( node->getNameString() == "additive-blend" )
519 _texture.useAdditiveBlend( node->getBoolValue() );
521 else if( node->getNameString() == "render-always" )
523 _render_always = node->getBoolValue();
525 else if( node->getNameString() == "size" )
527 if( node->getIndex() == 0 )
528 setSizeX( node->getIntValue() );
529 else if( node->getIndex() == 1 )
530 setSizeY( node->getIntValue() );
532 else if( node->getNameString() == "view" )
534 if( node->getIndex() == 0 )
535 setViewWidth( node->getIntValue() );
536 else if( node->getIndex() == 1 )
537 setViewHeight( node->getIntValue() );
539 else if( node->getNameString() == "freeze" )
540 _texture.setRender( node->getBoolValue() );
547 if( !handled && _root_group.get() )
548 _root_group->valueChanged(node);
551 //----------------------------------------------------------------------------
552 osg::Texture2D* Canvas::getTexture() const
554 return _texture.getTexture();
557 //----------------------------------------------------------------------------
558 Canvas::CullCallbackPtr Canvas::getCullCallback() const
560 return _cull_callback;
563 //----------------------------------------------------------------------------
564 void Canvas::reloadPlacements(const std::string& type)
566 for(size_t i = 0; i < _placements.size(); ++i)
568 if( _placements[i].empty() )
571 SGPropertyNode* child = _placements[i].front()->getProps();
573 // reload if type matches or no type specified
574 || child->getStringValue("type", type.c_str()) == type )
576 _dirty_placements.push_back(child);
581 //----------------------------------------------------------------------------
582 void Canvas::addPlacementFactory( const std::string& type,
583 PlacementFactory factory )
585 if( _placement_factories.find(type) != _placement_factories.end() )
590 "Canvas::addPlacementFactory: replace existing factor for type " << type
593 _placement_factories[type] = factory;
596 //----------------------------------------------------------------------------
597 void Canvas::setSelf(const PropertyBasedElementPtr& self)
599 PropertyBasedElement::setSelf(self);
601 CanvasPtr canvas = boost::static_pointer_cast<Canvas>(self);
603 _root_group.reset( new Group(canvas, _node) );
604 _root_group->setSelf(_root_group);
606 // Remove automatically created property listener as we forward them on our
608 _root_group->removeListener();
610 _cull_callback = new CullCallback(canvas);
613 //----------------------------------------------------------------------------
614 void Canvas::setStatusFlags(unsigned int flags, bool set)
621 if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
622 _status_msg = "Missing size";
623 else if( _status & MISSING_SIZE_X )
624 _status_msg = "Missing size-x";
625 else if( _status & MISSING_SIZE_Y )
626 _status_msg = "Missing size-y";
627 else if( _status & CREATE_FAILED )
628 _status_msg = "Creating render target failed";
629 else if( _status == STATUS_DIRTY )
630 _status_msg = "Creation pending...";
635 //----------------------------------------------------------------------------
636 Canvas::PlacementFactoryMap Canvas::_placement_factories;
638 } // namespace canvas
639 } // namespace simgear