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
174 osg::Camera* camera = _texture.getCamera();
176 osg::Vec4 clear_color(0.0f, 0.0f, 0.0f , 1.0f);
177 parseColor(_node->getStringValue("background"), clear_color);
178 camera->setClearColor(clear_color);
180 camera->addChild(_root_group->getMatrixTransform());
182 // Ensure objects are drawn in order of traversal
183 camera->getOrCreateStateSet()->setBinName("TraversalOrderBin");
185 if( _texture.serviceable() )
187 setStatusFlags(STATUS_OK);
188 setStatusFlags(STATUS_DIRTY, false);
189 _render_dirty = true;
193 setStatusFlags(CREATE_FAILED);
198 if( _visible || _render_always )
202 // Also mark all dependent (eg. recursively used) canvases as dirty
203 BOOST_FOREACH(CanvasWeakPtr canvas, _dependent_canvases)
205 if( !canvas.expired() )
206 canvas.lock()->_render_dirty = true;
210 _texture.setRender(_render_dirty);
212 _render_dirty = false;
216 _texture.setRender(false);
218 _root_group->update(delta_time_sec);
220 if( _sampling_dirty )
222 _texture.setSampling(
223 _node->getBoolValue("mipmapping"),
224 _node->getIntValue("coverage-samples"),
225 _node->getIntValue("color-samples")
227 _sampling_dirty = false;
228 _render_dirty = true;
231 while( !_dirty_placements.empty() )
233 SGPropertyNode *node = _dirty_placements.back();
234 _dirty_placements.pop_back();
236 if( node->getIndex() >= static_cast<int>(_placements.size()) )
238 _placements.resize(node->getIndex() + 1);
240 // Remove possibly existing placements
241 _placements[ node->getIndex() ].clear();
243 // Get new placements
244 PlacementFactoryMap::const_iterator placement_factory =
245 _placement_factories.find( node->getStringValue("type", "object") );
246 if( placement_factory != _placement_factories.end() )
248 Placements& placements = _placements[ node->getIndex() ] =
249 placement_factory->second
252 boost::static_pointer_cast<Canvas>(_self.lock())
257 placements.empty() ? "No match" : "Ok"
261 node->setStringValue("status-msg", "Unknown placement type");
265 //----------------------------------------------------------------------------
266 naRef Canvas::addEventListener(const nasal::CallContext& ctx)
268 if( !_root_group.get() )
269 naRuntimeError(ctx.c, "Canvas: No root group!");
271 return _root_group->addEventListener(ctx);
274 //----------------------------------------------------------------------------
275 void Canvas::setSizeX(int sx)
280 setStatusFlags(STATUS_DIRTY);
283 setStatusFlags(MISSING_SIZE_X);
285 setStatusFlags(MISSING_SIZE_X, false);
287 // reset flag to allow creation with new size
288 setStatusFlags(CREATE_FAILED, false);
291 //----------------------------------------------------------------------------
292 void Canvas::setSizeY(int sy)
297 setStatusFlags(STATUS_DIRTY);
300 setStatusFlags(MISSING_SIZE_Y);
302 setStatusFlags(MISSING_SIZE_Y, false);
304 // reset flag to allow creation with new size
305 setStatusFlags(CREATE_FAILED, false);
308 //----------------------------------------------------------------------------
309 int Canvas::getSizeX() const
314 //----------------------------------------------------------------------------
315 int Canvas::getSizeY() const
320 //----------------------------------------------------------------------------
321 void Canvas::setViewWidth(int w)
323 if( _view_width == w )
327 _texture.setViewSize(_view_width, _view_height);
330 //----------------------------------------------------------------------------
331 void Canvas::setViewHeight(int h)
333 if( _view_height == h )
337 _texture.setViewSize(_view_width, _view_height);
340 //----------------------------------------------------------------------------
341 int Canvas::getViewWidth() const
346 //----------------------------------------------------------------------------
347 int Canvas::getViewHeight() const
352 //----------------------------------------------------------------------------
353 bool Canvas::handleMouseEvent(const MouseEventPtr& event)
355 if( !_root_group.get() )
358 EventVisitor visitor( EventVisitor::TRAVERSE_DOWN,
359 event->getClientPos(),
361 if( !_root_group->accept(visitor) )
364 return _event_manager->handleEvent(event, visitor.getPropagationPath());
367 //----------------------------------------------------------------------------
368 void Canvas::childAdded( SGPropertyNode * parent,
369 SGPropertyNode * child )
371 if( parent != _node )
374 if( child->getNameString() == "placement" )
375 _dirty_placements.push_back(child);
376 else if( _root_group.get() )
377 static_cast<Element*>(_root_group.get())->childAdded(parent, child);
380 //----------------------------------------------------------------------------
381 void Canvas::childRemoved( SGPropertyNode * parent,
382 SGPropertyNode * child )
384 _render_dirty = true;
386 if( parent != _node )
389 if( child->getNameString() == "placement" )
390 _placements[ child->getIndex() ].clear();
391 else if( _root_group.get() )
392 static_cast<Element*>(_root_group.get())->childRemoved(parent, child);
395 //----------------------------------------------------------------------------
396 void Canvas::valueChanged(SGPropertyNode* node)
398 if( boost::starts_with(node->getNameString(), "status")
399 || node->getParent()->getNameString() == "bounding-box" )
401 _render_dirty = true;
404 if( node->getParent()->getParent() == _node
405 && node->getParent()->getNameString() == "placement" )
407 bool placement_dirty = false;
408 BOOST_FOREACH(Placements& placements, _placements)
410 BOOST_FOREACH(PlacementPtr& placement, placements)
412 // check if change can be directly handled by placement
413 if( placement->getProps() == node->getParent()
414 && !placement->childChanged(node) )
415 placement_dirty = true;
419 if( !placement_dirty )
422 // prevent double updates...
423 for( size_t i = 0; i < _dirty_placements.size(); ++i )
425 if( node->getParent() == _dirty_placements[i] )
429 _dirty_placements.push_back(node->getParent());
431 else if( node->getParent() == _node )
433 if( node->getNameString() == "background" )
436 if( _texture.getCamera() && parseColor(node->getStringValue(), color) )
438 _texture.getCamera()->setClearColor(color);
439 _render_dirty = true;
442 else if( node->getNameString() == "mipmapping"
443 || node->getNameString() == "coverage-samples"
444 || node->getNameString() == "color-samples" )
446 _sampling_dirty = true;
448 else if( node->getNameString() == "render-always" )
450 _render_always = node->getBoolValue();
452 else if( node->getNameString() == "size" )
454 if( node->getIndex() == 0 )
455 setSizeX( node->getIntValue() );
456 else if( node->getIndex() == 1 )
457 setSizeY( node->getIntValue() );
459 else if( node->getNameString() == "view" )
461 if( node->getIndex() == 0 )
462 setViewWidth( node->getIntValue() );
463 else if( node->getIndex() == 1 )
464 setViewHeight( node->getIntValue() );
466 else if( node->getNameString() == "freeze" )
467 _texture.setRender( node->getBoolValue() );
474 if( !handled && _root_group.get() )
475 _root_group->valueChanged(node);
478 //----------------------------------------------------------------------------
479 osg::Texture2D* Canvas::getTexture() const
481 return _texture.getTexture();
484 //----------------------------------------------------------------------------
485 Canvas::CullCallbackPtr Canvas::getCullCallback() const
487 return _cull_callback;
490 //----------------------------------------------------------------------------
491 void Canvas::reloadPlacements(const std::string& type)
493 for(size_t i = 0; i < _placements.size(); ++i)
495 if( _placements[i].empty() )
498 SGPropertyNode* child = _placements[i].front()->getProps();
500 // reload if type matches or no type specified
501 || child->getStringValue("type", type.c_str()) == type )
503 _dirty_placements.push_back(child);
508 //----------------------------------------------------------------------------
509 void Canvas::addPlacementFactory( const std::string& type,
510 PlacementFactory factory )
512 if( _placement_factories.find(type) != _placement_factories.end() )
517 "Canvas::addPlacementFactory: replace existing factor for type " << type
520 _placement_factories[type] = factory;
523 //----------------------------------------------------------------------------
524 void Canvas::setSelf(const PropertyBasedElementPtr& self)
526 PropertyBasedElement::setSelf(self);
528 CanvasPtr canvas = boost::static_pointer_cast<Canvas>(self);
530 _root_group.reset( new Group(canvas, _node) );
531 _root_group->setSelf(_root_group);
533 // Remove automatically created property listener as we forward them on our
535 _root_group->removeListener();
537 _cull_callback = new CullCallback(canvas);
540 //----------------------------------------------------------------------------
541 void Canvas::setStatusFlags(unsigned int flags, bool set)
548 if( (_status & MISSING_SIZE_X) && (_status & MISSING_SIZE_Y) )
549 _status_msg = "Missing size";
550 else if( _status & MISSING_SIZE_X )
551 _status_msg = "Missing size-x";
552 else if( _status & MISSING_SIZE_Y )
553 _status_msg = "Missing size-y";
554 else if( _status & CREATE_FAILED )
555 _status_msg = "Creating render target failed";
556 else if( _status == STATUS_DIRTY )
557 _status_msg = "Creation pending...";
562 //----------------------------------------------------------------------------
563 Canvas::PlacementFactoryMap Canvas::_placement_factories;
565 } // namespace canvas
566 } // namespace simgear