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 void Canvas::addDependentCanvas(const CanvasWeakPtr& canvas)
112 if( canvas.expired() )
118 "Canvas::addDependentCanvas: got an expired Canvas dependent on "
124 _dependent_canvases.insert(canvas);
127 //----------------------------------------------------------------------------
128 void Canvas::removeDependentCanvas(const CanvasWeakPtr& canvas)
130 _dependent_canvases.erase(canvas);
133 //----------------------------------------------------------------------------
134 GroupPtr Canvas::createGroup(const std::string& name)
136 return boost::dynamic_pointer_cast<Group>
138 _root_group->createChild("group", name)
142 //----------------------------------------------------------------------------
143 void Canvas::enableRendering(bool force)
147 _render_dirty = true;
150 //----------------------------------------------------------------------------
151 void Canvas::update(double delta_time_sec)
153 if( (!_texture.serviceable() && _status != STATUS_DIRTY)
154 || (_status & CREATE_FAILED) )
157 if( _status == STATUS_DIRTY )
159 _texture.setSize(_size_x, _size_y);
161 if( !_texture.serviceable() )
163 _texture.useImageCoords(true);
164 _texture.useStencil(true);
165 _texture.allocRT(/*_camera_callback*/);
169 // Resizing causes a new texture to be created so we need to reapply all
170 // existing placements
171 for(size_t i = 0; i < _placements.size(); ++i)
173 if( !_placements[i].empty() )
174 _dirty_placements.push_back( _placements[i].front()->getProps() );
178 osg::Camera* camera = _texture.getCamera();
180 osg::Vec4 clear_color(0.0f, 0.0f, 0.0f , 1.0f);
181 parseColor(_node->getStringValue("background"), clear_color);
182 camera->setClearColor(clear_color);
184 camera->addChild(_root_group->getMatrixTransform());
186 // Ensure objects are drawn in order of traversal
187 camera->getOrCreateStateSet()->setBinName("TraversalOrderBin");
189 if( _texture.serviceable() )
191 setStatusFlags(STATUS_OK);
192 setStatusFlags(STATUS_DIRTY, false);
193 _render_dirty = true;
197 setStatusFlags(CREATE_FAILED);
202 if( _visible || _render_always )
206 // Also mark all dependent (eg. recursively used) canvases as dirty
207 BOOST_FOREACH(CanvasWeakPtr canvas, _dependent_canvases)
209 if( !canvas.expired() )
210 canvas.lock()->_render_dirty = true;
214 _texture.setRender(_render_dirty);
216 _render_dirty = false;
220 _texture.setRender(false);
222 _root_group->update(delta_time_sec);
224 if( _sampling_dirty )
226 _texture.setSampling(
227 _node->getBoolValue("mipmapping"),
228 _node->getIntValue("coverage-samples"),
229 _node->getIntValue("color-samples")
231 _sampling_dirty = false;
232 _render_dirty = true;
235 while( !_dirty_placements.empty() )
237 SGPropertyNode *node = _dirty_placements.back();
238 _dirty_placements.pop_back();
240 if( node->getIndex() >= static_cast<int>(_placements.size()) )
242 _placements.resize(node->getIndex() + 1);
244 // Remove possibly existing placements
245 _placements[ node->getIndex() ].clear();
247 // Get new placements
248 PlacementFactoryMap::const_iterator placement_factory =
249 _placement_factories.find( node->getStringValue("type", "object") );
250 if( placement_factory != _placement_factories.end() )
252 Placements& placements = _placements[ node->getIndex() ] =
253 placement_factory->second
256 boost::static_pointer_cast<Canvas>(_self.lock())
261 placements.empty() ? "No match" : "Ok"
265 node->setStringValue("status-msg", "Unknown placement type");
269 //----------------------------------------------------------------------------
270 naRef Canvas::addEventListener(const nasal::CallContext& ctx)
272 if( !_root_group.get() )
273 naRuntimeError(ctx.c, "Canvas: No root group!");
275 return _root_group->addEventListener(ctx);
278 //----------------------------------------------------------------------------
279 void Canvas::setSizeX(int sx)
284 setStatusFlags(STATUS_DIRTY);
287 setStatusFlags(MISSING_SIZE_X);
289 setStatusFlags(MISSING_SIZE_X, false);
291 // reset flag to allow creation with new size
292 setStatusFlags(CREATE_FAILED, false);
295 //----------------------------------------------------------------------------
296 void Canvas::setSizeY(int sy)
301 setStatusFlags(STATUS_DIRTY);
304 setStatusFlags(MISSING_SIZE_Y);
306 setStatusFlags(MISSING_SIZE_Y, false);
308 // reset flag to allow creation with new size
309 setStatusFlags(CREATE_FAILED, false);
312 //----------------------------------------------------------------------------
313 int Canvas::getSizeX() const
318 //----------------------------------------------------------------------------
319 int Canvas::getSizeY() const
324 //----------------------------------------------------------------------------
325 void Canvas::setViewWidth(int w)
327 if( _view_width == w )
331 _texture.setViewSize(_view_width, _view_height);
334 //----------------------------------------------------------------------------
335 void Canvas::setViewHeight(int h)
337 if( _view_height == h )
341 _texture.setViewSize(_view_width, _view_height);
344 //----------------------------------------------------------------------------
345 int Canvas::getViewWidth() const
350 //----------------------------------------------------------------------------
351 int Canvas::getViewHeight() const
356 //----------------------------------------------------------------------------
357 bool Canvas::handleMouseEvent(const MouseEventPtr& event)
359 if( !_root_group.get() )
362 EventVisitor visitor( EventVisitor::TRAVERSE_DOWN,
363 event->getClientPos(),
365 if( !_root_group->accept(visitor) )
368 return _event_manager->handleEvent(event, visitor.getPropagationPath());
371 //----------------------------------------------------------------------------
372 void Canvas::childAdded( SGPropertyNode * parent,
373 SGPropertyNode * child )
375 if( parent != _node )
378 if( child->getNameString() == "placement" )
379 _dirty_placements.push_back(child);
380 else if( _root_group.get() )
381 static_cast<Element*>(_root_group.get())->childAdded(parent, child);
384 //----------------------------------------------------------------------------
385 void Canvas::childRemoved( SGPropertyNode * parent,
386 SGPropertyNode * child )
388 _render_dirty = true;
390 if( parent != _node )
393 if( child->getNameString() == "placement" )
394 _placements[ child->getIndex() ].clear();
395 else if( _root_group.get() )
396 static_cast<Element*>(_root_group.get())->childRemoved(parent, child);
399 //----------------------------------------------------------------------------
400 void Canvas::valueChanged(SGPropertyNode* node)
402 if( boost::starts_with(node->getNameString(), "status")
403 || node->getParent()->getNameString() == "bounding-box" )
405 _render_dirty = true;
408 if( node->getParent()->getParent() == _node
409 && node->getParent()->getNameString() == "placement" )
411 bool placement_dirty = false;
412 BOOST_FOREACH(Placements& placements, _placements)
414 BOOST_FOREACH(PlacementPtr& placement, placements)
416 // check if change can be directly handled by placement
417 if( placement->getProps() == node->getParent()
418 && !placement->childChanged(node) )
419 placement_dirty = true;
423 if( !placement_dirty )
426 // prevent double updates...
427 for( size_t i = 0; i < _dirty_placements.size(); ++i )
429 if( node->getParent() == _dirty_placements[i] )
433 _dirty_placements.push_back(node->getParent());
435 else if( node->getParent() == _node )
437 if( node->getNameString() == "background" )
440 if( _texture.getCamera() && parseColor(node->getStringValue(), color) )
442 _texture.getCamera()->setClearColor(color);
443 _render_dirty = true;
446 else if( node->getNameString() == "mipmapping"
447 || node->getNameString() == "coverage-samples"
448 || node->getNameString() == "color-samples" )
450 _sampling_dirty = true;
452 else if( node->getNameString() == "render-always" )
454 _render_always = node->getBoolValue();
456 else if( node->getNameString() == "size" )
458 if( node->getIndex() == 0 )
459 setSizeX( node->getIntValue() );
460 else if( node->getIndex() == 1 )
461 setSizeY( node->getIntValue() );
463 else if( node->getNameString() == "view" )
465 if( node->getIndex() == 0 )
466 setViewWidth( node->getIntValue() );
467 else if( node->getIndex() == 1 )
468 setViewHeight( node->getIntValue() );
470 else if( node->getNameString() == "freeze" )
471 _texture.setRender( node->getBoolValue() );
478 if( !handled && _root_group.get() )
479 _root_group->valueChanged(node);
482 //----------------------------------------------------------------------------
483 osg::Texture2D* Canvas::getTexture() const
485 return _texture.getTexture();
488 //----------------------------------------------------------------------------
489 Canvas::CullCallbackPtr Canvas::getCullCallback() const
491 return _cull_callback;
494 //----------------------------------------------------------------------------
495 void Canvas::addPlacementFactory( const std::string& type,
496 PlacementFactory factory )
498 if( _placement_factories.find(type) != _placement_factories.end() )
503 "Canvas::addPlacementFactory: replace existing factor for type " << type
506 _placement_factories[type] = factory;
509 //----------------------------------------------------------------------------
510 void Canvas::setSelf(const PropertyBasedElementPtr& self)
512 PropertyBasedElement::setSelf(self);
514 CanvasPtr canvas = boost::static_pointer_cast<Canvas>(self);
516 _root_group.reset( new Group(canvas, _node) );
517 _root_group->setSelf(_root_group);
519 // Remove automatically created property listener as we forward them on our
521 _root_group->removeListener();
523 _cull_callback = new CullCallback(canvas);
526 //----------------------------------------------------------------------------
527 void Canvas::setStatusFlags(unsigned int flags, bool set)
534 if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
535 _status_msg = "Missing size";
536 else if( _status & MISSING_SIZE_X )
537 _status_msg = "Missing size-x";
538 else if( _status & MISSING_SIZE_Y )
539 _status_msg = "Missing size-y";
540 else if( _status & CREATE_FAILED )
541 _status_msg = "Creating render target failed";
542 else if( _status == STATUS_DIRTY )
543 _status_msg = "Creation pending...";
548 //----------------------------------------------------------------------------
549 Canvas::PlacementFactoryMap Canvas::_placement_factories;
551 } // namespace canvas
552 } // namespace simgear