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 naRef Canvas::addEventListener(const nasal::CallContext& ctx)
262 if( !_root_group.get() )
263 naRuntimeError(ctx.c, "Canvas: No root group!");
265 return _root_group->addEventListener(ctx);
268 //----------------------------------------------------------------------------
269 void Canvas::setSizeX(int sx)
275 // TODO resize if texture already allocated
278 setStatusFlags(MISSING_SIZE_X);
280 setStatusFlags(MISSING_SIZE_X, false);
282 // reset flag to allow creation with new size
283 setStatusFlags(CREATE_FAILED, false);
286 //----------------------------------------------------------------------------
287 void Canvas::setSizeY(int sy)
293 // TODO resize if texture already allocated
296 setStatusFlags(MISSING_SIZE_Y);
298 setStatusFlags(MISSING_SIZE_Y, false);
300 // reset flag to allow creation with new size
301 setStatusFlags(CREATE_FAILED, false);
304 //----------------------------------------------------------------------------
305 int Canvas::getSizeX() const
310 //----------------------------------------------------------------------------
311 int Canvas::getSizeY() const
316 //----------------------------------------------------------------------------
317 void Canvas::setViewWidth(int w)
319 if( _view_width == w )
323 _texture.setViewSize(_view_width, _view_height);
326 //----------------------------------------------------------------------------
327 void Canvas::setViewHeight(int h)
329 if( _view_height == h )
333 _texture.setViewSize(_view_width, _view_height);
336 //----------------------------------------------------------------------------
337 bool Canvas::handleMouseEvent(const MouseEventPtr& event)
339 _mouse_x = event->pos.x();
340 _mouse_y = event->pos.y();
341 _mouse_dx = event->delta.x();
342 _mouse_dy = event->delta.y();
343 _mouse_button = event->button;
344 _mouse_state = event->state;
345 _mouse_mod = event->mod;
346 //_mouse_scroll = event.scroll;
347 // Always set event type last because all listeners are attached to it
348 _mouse_event = event->type;
350 if( !_root_group.get() )
353 EventVisitor visitor( EventVisitor::TRAVERSE_DOWN,
356 if( !_root_group->accept(visitor) )
359 // TODO create special events like click/dblclick etc.
361 return visitor.propagateEvent(event);
364 //----------------------------------------------------------------------------
365 void Canvas::childAdded( SGPropertyNode * parent,
366 SGPropertyNode * child )
368 if( parent != _node )
371 if( child->getNameString() == "placement" )
372 _dirty_placements.push_back(child);
373 else if( _root_group.get() )
374 static_cast<Element*>(_root_group.get())->childAdded(parent, child);
377 //----------------------------------------------------------------------------
378 void Canvas::childRemoved( SGPropertyNode * parent,
379 SGPropertyNode * child )
381 _render_dirty = true;
383 if( parent != _node )
386 if( child->getNameString() == "placement" )
387 _placements[ child->getIndex() ].clear();
388 else if( _root_group.get() )
389 static_cast<Element*>(_root_group.get())->childRemoved(parent, child);
392 //----------------------------------------------------------------------------
393 void Canvas::valueChanged(SGPropertyNode* node)
395 if( boost::starts_with(node->getNameString(), "status")
396 || node->getParent()->getNameString() == "bounding-box" )
398 _render_dirty = true;
401 if( node->getParent()->getParent() == _node
402 && node->getParent()->getNameString() == "placement" )
404 bool placement_dirty = false;
405 BOOST_FOREACH(Placements& placements, _placements)
407 BOOST_FOREACH(PlacementPtr& placement, placements)
409 // check if change can be directly handled by placement
410 if( placement->getProps() == node->getParent()
411 && !placement->childChanged(node) )
412 placement_dirty = true;
416 if( !placement_dirty )
419 // prevent double updates...
420 for( size_t i = 0; i < _dirty_placements.size(); ++i )
422 if( node->getParent() == _dirty_placements[i] )
426 _dirty_placements.push_back(node->getParent());
428 else if( node->getParent() == _node )
430 if( node->getNameString() == "background" )
433 if( _texture.getCamera() && parseColor(node->getStringValue(), color) )
435 _texture.getCamera()->setClearColor(color);
436 _render_dirty = true;
439 else if( node->getNameString() == "mipmapping"
440 || node->getNameString() == "coverage-samples"
441 || node->getNameString() == "color-samples" )
443 _sampling_dirty = true;
445 else if( node->getNameString() == "render-always" )
447 _render_always = node->getBoolValue();
449 else if( node->getNameString() == "size" )
451 if( node->getIndex() == 0 )
452 setSizeX( node->getIntValue() );
453 else if( node->getIndex() == 1 )
454 setSizeY( node->getIntValue() );
456 else if( node->getNameString() == "view" )
458 if( node->getIndex() == 0 )
459 setViewWidth( node->getIntValue() );
460 else if( node->getIndex() == 1 )
461 setViewHeight( node->getIntValue() );
463 else if( node->getNameString() == "freeze" )
464 _texture.setRender( node->getBoolValue() );
471 if( !handled && _root_group.get() )
472 _root_group->valueChanged(node);
475 //----------------------------------------------------------------------------
476 osg::Texture2D* Canvas::getTexture() const
478 return _texture.getTexture();
481 //----------------------------------------------------------------------------
482 Canvas::CullCallbackPtr Canvas::getCullCallback() const
484 return _cull_callback;
487 //----------------------------------------------------------------------------
488 void Canvas::addPlacementFactory( const std::string& type,
489 PlacementFactory factory )
491 if( _placement_factories.find(type) != _placement_factories.end() )
496 "Canvas::addPlacementFactory: replace existing factor for type " << type
499 _placement_factories[type] = factory;
502 //----------------------------------------------------------------------------
503 void Canvas::setSelf(const PropertyBasedElementPtr& self)
505 PropertyBasedElement::setSelf(self);
507 CanvasPtr canvas = boost::static_pointer_cast<Canvas>(self);
509 _root_group.reset( new Group(canvas, _node) );
511 // Remove automatically created property listener as we forward them on our
513 _root_group->removeListener();
515 _cull_callback = new CullCallback(canvas);
518 //----------------------------------------------------------------------------
519 void Canvas::setStatusFlags(unsigned int flags, bool set)
522 _status = _status | flags;
524 _status = _status & ~flags;
525 // TODO maybe extend simgear::PropertyObject to allow |=, &= etc.
527 if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
528 _status_msg = "Missing size";
529 else if( _status & MISSING_SIZE_X )
530 _status_msg = "Missing size-x";
531 else if( _status & MISSING_SIZE_Y )
532 _status_msg = "Missing size-y";
533 else if( _status & CREATE_FAILED )
534 _status_msg = "Creating render target failed";
535 else if( _status == STATUS_OK && !_texture.serviceable() )
536 _status_msg = "Creation pending...";
541 //----------------------------------------------------------------------------
542 Canvas::PlacementFactoryMap Canvas::_placement_factories;
544 } // namespace canvas
545 } // namespace simgear