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 "CanvasEventVisitor.hxx"
21 #include <simgear/canvas/MouseEvent.hxx>
22 #include <simgear/canvas/CanvasPlacement.hxx>
23 #include <simgear/scene/util/parse_color.hxx>
24 #include <simgear/scene/util/RenderConstants.hxx>
28 #include <osgText/Text>
29 #include <osgViewer/Viewer>
31 #include <boost/algorithm/string/predicate.hpp>
32 #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),
65 _status(node, "status"),
66 _status_msg(node, "status-msg"),
67 _mouse_x(node, "mouse/x"),
68 _mouse_y(node, "mouse/y"),
69 _mouse_dx(node, "mouse/dx"),
70 _mouse_dy(node, "mouse/dy"),
71 _mouse_button(node, "mouse/button"),
72 _mouse_state(node, "mouse/state"),
73 _mouse_mod(node, "mouse/mod"),
74 _mouse_scroll(node, "mouse/scroll"),
75 _mouse_event(node, "mouse/event"),
76 _sampling_dirty(false),
82 setStatusFlags(MISSING_SIZE_X | MISSING_SIZE_Y);
85 //----------------------------------------------------------------------------
91 //----------------------------------------------------------------------------
92 void Canvas::setSystemAdapter(const SystemAdapterPtr& system_adapter)
94 _system_adapter = system_adapter;
95 _texture.setSystemAdapter(system_adapter);
98 //----------------------------------------------------------------------------
99 SystemAdapterPtr Canvas::getSystemAdapter() const
101 return _system_adapter;
104 //----------------------------------------------------------------------------
105 void Canvas::setCanvasMgr(CanvasMgr* canvas_mgr)
107 _canvas_mgr = canvas_mgr;
110 //----------------------------------------------------------------------------
111 CanvasMgr* Canvas::getCanvasMgr() const
116 //----------------------------------------------------------------------------
117 void Canvas::addDependentCanvas(const CanvasWeakPtr& canvas)
119 if( canvas.expired() )
125 "Canvas::addDependentCanvas: got an expired Canvas dependent on "
131 _dependent_canvases.insert(canvas);
134 //----------------------------------------------------------------------------
135 void Canvas::removeDependentCanvas(const CanvasWeakPtr& canvas)
137 _dependent_canvases.erase(canvas);
140 //----------------------------------------------------------------------------
141 GroupPtr Canvas::createGroup(const std::string& name)
143 return boost::dynamic_pointer_cast<Group>
145 _root_group->createChild("group", name)
149 //----------------------------------------------------------------------------
150 void Canvas::enableRendering(bool force)
154 _render_dirty = true;
157 //----------------------------------------------------------------------------
158 void Canvas::update(double delta_time_sec)
160 if( !_texture.serviceable() )
162 if( _status != STATUS_OK )
165 _texture.setSize(_size_x, _size_y);
166 _texture.useImageCoords(true);
167 _texture.useStencil(true);
168 _texture.allocRT(/*_camera_callback*/);
170 osg::Camera* camera = _texture.getCamera();
172 osg::Vec4 clear_color(0.0f, 0.0f, 0.0f , 1.0f);
173 parseColor(_node->getStringValue("background"), clear_color);
174 camera->setClearColor(clear_color);
176 camera->addChild(_root_group->getMatrixTransform());
178 // Ensure objects are drawn in order of traversal
179 camera->getOrCreateStateSet()->setBinName("TraversalOrderBin");
181 if( _texture.serviceable() )
183 setStatusFlags(STATUS_OK);
187 setStatusFlags(CREATE_FAILED);
192 if( _visible || _render_always )
196 // Also mark all dependent (eg. recursively used) canvases as dirty
197 BOOST_FOREACH(CanvasWeakPtr canvas, _dependent_canvases)
199 if( !canvas.expired() )
200 canvas.lock()->_render_dirty = true;
204 _texture.setRender(_render_dirty);
206 _render_dirty = false;
210 _texture.setRender(false);
212 _root_group->update(delta_time_sec);
214 if( _sampling_dirty )
216 _texture.setSampling(
217 _node->getBoolValue("mipmapping"),
218 _node->getIntValue("coverage-samples"),
219 _node->getIntValue("color-samples")
221 _sampling_dirty = false;
222 _render_dirty = true;
225 while( !_dirty_placements.empty() )
227 SGPropertyNode *node = _dirty_placements.back();
228 _dirty_placements.pop_back();
230 if( node->getIndex() >= static_cast<int>(_placements.size()) )
232 _placements.resize(node->getIndex() + 1);
234 // Remove possibly existing placements
235 _placements[ node->getIndex() ].clear();
237 // Get new placements
238 PlacementFactoryMap::const_iterator placement_factory =
239 _placement_factories.find( node->getStringValue("type", "object") );
240 if( placement_factory != _placement_factories.end() )
242 Placements& placements = _placements[ node->getIndex() ] =
243 placement_factory->second
246 boost::static_pointer_cast<Canvas>(_self.lock())
251 placements.empty() ? "No match" : "Ok"
255 node->setStringValue("status-msg", "Unknown placement type");
259 //----------------------------------------------------------------------------
260 void Canvas::setSizeX(int sx)
266 // TODO resize if texture already allocated
269 setStatusFlags(MISSING_SIZE_X);
271 setStatusFlags(MISSING_SIZE_X, false);
273 // reset flag to allow creation with new size
274 setStatusFlags(CREATE_FAILED, false);
277 //----------------------------------------------------------------------------
278 void Canvas::setSizeY(int sy)
284 // TODO resize if texture already allocated
287 setStatusFlags(MISSING_SIZE_Y);
289 setStatusFlags(MISSING_SIZE_Y, false);
291 // reset flag to allow creation with new size
292 setStatusFlags(CREATE_FAILED, false);
295 //----------------------------------------------------------------------------
296 int Canvas::getSizeX() const
301 //----------------------------------------------------------------------------
302 int Canvas::getSizeY() const
307 //----------------------------------------------------------------------------
308 void Canvas::setViewWidth(int w)
310 if( _view_width == w )
314 _texture.setViewSize(_view_width, _view_height);
317 //----------------------------------------------------------------------------
318 void Canvas::setViewHeight(int h)
320 if( _view_height == h )
324 _texture.setViewSize(_view_width, _view_height);
327 //----------------------------------------------------------------------------
328 bool Canvas::handleMouseEvent(const MouseEventPtr& event)
330 _mouse_x = event->pos.x();
331 _mouse_y = event->pos.y();
332 _mouse_dx = event->delta.x();
333 _mouse_dy = event->delta.y();
334 _mouse_button = event->button;
335 _mouse_state = event->state;
336 _mouse_mod = event->mod;
337 //_mouse_scroll = event.scroll;
338 // Always set event type last because all listeners are attached to it
339 _mouse_event = event->type;
341 if( !_root_group.get() )
344 EventVisitor visitor( EventVisitor::TRAVERSE_DOWN,
347 if( !_root_group->accept(visitor) )
350 // TODO create special events like click/dblclick etc.
352 return visitor.propagateEvent(event);
355 //----------------------------------------------------------------------------
356 void Canvas::childAdded( SGPropertyNode * parent,
357 SGPropertyNode * child )
359 if( parent != _node )
362 if( child->getNameString() == "placement" )
363 _dirty_placements.push_back(child);
364 else if( _root_group.get() )
365 static_cast<Element*>(_root_group.get())->childAdded(parent, child);
368 //----------------------------------------------------------------------------
369 void Canvas::childRemoved( SGPropertyNode * parent,
370 SGPropertyNode * child )
372 _render_dirty = true;
374 if( parent != _node )
377 if( child->getNameString() == "placement" )
378 _placements[ child->getIndex() ].clear();
379 else if( _root_group.get() )
380 static_cast<Element*>(_root_group.get())->childRemoved(parent, child);
383 //----------------------------------------------------------------------------
384 void Canvas::valueChanged(SGPropertyNode* node)
386 if( boost::starts_with(node->getNameString(), "status")
387 || node->getParent()->getNameString() == "bounding-box" )
389 _render_dirty = true;
392 if( node->getParent()->getParent() == _node
393 && node->getParent()->getNameString() == "placement" )
395 bool placement_dirty = false;
396 BOOST_FOREACH(Placements& placements, _placements)
398 BOOST_FOREACH(PlacementPtr& placement, placements)
400 // check if change can be directly handled by placement
401 if( placement->getProps() == node->getParent()
402 && !placement->childChanged(node) )
403 placement_dirty = true;
407 if( !placement_dirty )
410 // prevent double updates...
411 for( size_t i = 0; i < _dirty_placements.size(); ++i )
413 if( node->getParent() == _dirty_placements[i] )
417 _dirty_placements.push_back(node->getParent());
419 else if( node->getParent() == _node )
421 if( node->getNameString() == "background" )
424 if( _texture.getCamera() && parseColor(node->getStringValue(), color) )
426 _texture.getCamera()->setClearColor(color);
427 _render_dirty = true;
430 else if( node->getNameString() == "mipmapping"
431 || node->getNameString() == "coverage-samples"
432 || node->getNameString() == "color-samples" )
434 _sampling_dirty = true;
436 else if( node->getNameString() == "render-always" )
438 _render_always = node->getBoolValue();
440 else if( node->getNameString() == "size" )
442 if( node->getIndex() == 0 )
443 setSizeX( node->getIntValue() );
444 else if( node->getIndex() == 1 )
445 setSizeY( node->getIntValue() );
447 else if( node->getNameString() == "view" )
449 if( node->getIndex() == 0 )
450 setViewWidth( node->getIntValue() );
451 else if( node->getIndex() == 1 )
452 setViewHeight( node->getIntValue() );
454 else if( node->getNameString() == "freeze" )
455 _texture.setRender( node->getBoolValue() );
462 if( !handled && _root_group.get() )
463 _root_group->valueChanged(node);
466 //----------------------------------------------------------------------------
467 osg::Texture2D* Canvas::getTexture() const
469 return _texture.getTexture();
472 //----------------------------------------------------------------------------
473 Canvas::CullCallbackPtr Canvas::getCullCallback() const
475 return _cull_callback;
478 //----------------------------------------------------------------------------
479 void Canvas::addPlacementFactory( const std::string& type,
480 PlacementFactory factory )
482 if( _placement_factories.find(type) != _placement_factories.end() )
487 "Canvas::addPlacementFactory: replace existing factor for type " << type
490 _placement_factories[type] = factory;
493 //----------------------------------------------------------------------------
494 void Canvas::setSelf(const PropertyBasedElementPtr& self)
496 PropertyBasedElement::setSelf(self);
498 CanvasPtr canvas = boost::static_pointer_cast<Canvas>(self);
500 _root_group.reset( new Group(canvas, _node) );
502 // Remove automatically created property listener as we forward them on our
504 _root_group->removeListener();
506 _cull_callback = new CullCallback(canvas);
509 //----------------------------------------------------------------------------
510 void Canvas::setStatusFlags(unsigned int flags, bool set)
513 _status = _status | flags;
515 _status = _status & ~flags;
516 // TODO maybe extend simgear::PropertyObject to allow |=, &= etc.
518 if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
519 _status_msg = "Missing size";
520 else if( _status & MISSING_SIZE_X )
521 _status_msg = "Missing size-x";
522 else if( _status & MISSING_SIZE_Y )
523 _status_msg = "Missing size-y";
524 else if( _status & CREATE_FAILED )
525 _status_msg = "Creating render target failed";
526 else if( _status == STATUS_OK && !_texture.serviceable() )
527 _status_msg = "Creation pending...";
532 //----------------------------------------------------------------------------
533 Canvas::PlacementFactoryMap Canvas::_placement_factories;
535 } // namespace canvas
536 } // namespace simgear