]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/od_gauge.cxx
Merge branch 'next' of gitorious.org:fg/flightgear into next
[flightgear.git] / src / Instrumentation / od_gauge.cxx
1 // Owner Drawn Gauge helper class
2 //
3 // Written by Harald JOHNSEN, started May 2005.
4 //
5 // Copyright (C) 2005  Harald JOHNSEN
6 //
7 // Ported to OSG by Tim Moore - Jun 2007
8 //
9 // Heavily modified to be usable for the 2d Canvas by Thomas Geymayer - April 2012
10 // Supports now multisampling/mipmapping, usage of the stencil buffer and placing
11 // the texture in the scene by certain filter criteria
12 //
13 // This program is free software; you can redistribute it and/or
14 // modify it under the terms of the GNU General Public License as
15 // published by the Free Software Foundation; either version 2 of the
16 // License, or (at your option) any later version.
17 //
18 // This program is distributed in the hope that it will be useful, but
19 // WITHOUT ANY WARRANTY; without even the implied warranty of
20 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21 // General Public License for more details.
22 //
23 // You should have received a copy of the GNU General Public License
24 // along with this program; if not, write to the Free Software
25 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
26 //
27 //
28
29 #ifdef HAVE_CONFIG_H
30 #  include "config.h"
31 #endif
32
33 #include <osg/Texture2D>
34 #include <osg/AlphaFunc>
35 #include <osg/BlendFunc>
36 #include <osg/Camera>
37 #include <osg/Geode>
38 #include <osg/NodeVisitor>
39 #include <osg/Matrix>
40 #include <osg/PolygonMode>
41 #include <osg/ShadeModel>
42 #include <osg/StateSet>
43 #include <osg/FrameBufferObject> // for GL_DEPTH_STENCIL_EXT on Windows
44
45 #include <osgDB/FileNameUtils>
46
47 #include <simgear/scene/material/EffectGeode.hxx>
48 #include <simgear/scene/util/RenderConstants.hxx>
49
50 #include <Main/globals.hxx>
51 #include <Viewer/renderer.hxx>
52 #include <Scenery/scenery.hxx>
53 #include "od_gauge.hxx"
54
55 #include <cassert>
56
57 //------------------------------------------------------------------------------
58 FGODGauge::FGODGauge():
59   _size_x( -1 ),
60   _size_y( -1 ),
61   _view_width( -1 ),
62   _view_height( -1 ),
63   _use_image_coords( false ),
64   _use_stencil( false ),
65   _use_mipmapping( false ),
66   _coverage_samples( 0 ),
67   _color_samples( 0 ),
68   rtAvailable( false )
69 {
70 }
71
72 //------------------------------------------------------------------------------
73 FGODGauge::~FGODGauge()
74 {
75   if( camera.valid() )
76     globals->get_renderer()->removeCamera(camera.get());
77 }
78
79 //------------------------------------------------------------------------------
80 void FGODGauge::setSize(int size_x, int size_y)
81 {
82   _size_x = size_x;
83   _size_y = size_y < 0 ? size_x : size_y;
84
85   if( texture.valid() )
86     texture->setTextureSize(_size_x, _size_x);
87 }
88
89 //----------------------------------------------------------------------------
90 void FGODGauge::setViewSize(int width, int height)
91 {
92   _view_width = width;
93   _view_height = height < 0 ? width : height;
94
95   if( camera )
96     updateCoordinateFrame();
97 }
98
99 //------------------------------------------------------------------------------
100 void FGODGauge::useImageCoords(bool use)
101 {
102   if( use == _use_image_coords )
103     return;
104
105   _use_image_coords = use;
106
107   if( texture )
108     updateCoordinateFrame();
109 }
110
111 //------------------------------------------------------------------------------
112 void FGODGauge::useStencil(bool use)
113 {
114   if( use == _use_stencil )
115     return;
116
117   _use_stencil = use;
118
119   if( texture )
120     updateStencil();
121 }
122
123 //------------------------------------------------------------------------------
124 void FGODGauge::setSampling( bool mipmapping,
125                              int coverage_samples,
126                              int color_samples )
127 {
128   if(    _use_mipmapping == mipmapping
129       && _coverage_samples == coverage_samples
130       && _color_samples == color_samples )
131     return;
132
133   _use_mipmapping = mipmapping;
134
135   if( color_samples > coverage_samples )
136   {
137     SG_LOG
138     (
139       SG_GL,
140       SG_WARN,
141       "FGODGauge::setSampling: color_samples > coverage_samples not allowed!"
142     );
143     color_samples = coverage_samples;
144   }
145
146   _coverage_samples = coverage_samples;
147   _color_samples = color_samples;
148
149   updateSampling();
150 }
151
152 //------------------------------------------------------------------------------
153 bool FGODGauge::serviceable(void) 
154 {
155   return rtAvailable;
156 }
157
158 //------------------------------------------------------------------------------
159 void FGODGauge::allocRT(osg::NodeCallback* camera_cull_callback)
160 {
161   camera = new osg::Camera;
162   camera->setDataVariance(osg::Object::DYNAMIC);
163   // Only the far camera should trigger this texture to be rendered.
164   camera->setNodeMask(simgear::BACKGROUND_BIT);
165   camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
166   camera->setRenderOrder(osg::Camera::PRE_RENDER);
167   camera->setClearColor(osg::Vec4(0.0f, 0.0f, 0.0f , 0.0f));
168   camera->setClearStencil(0);
169   camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT,
170                                              osg::Camera::FRAME_BUFFER );
171
172   if( camera_cull_callback )
173     camera->setCullCallback(camera_cull_callback);
174
175   updateCoordinateFrame();
176   updateStencil();
177
178   osg::StateSet* stateSet = camera->getOrCreateStateSet();
179   stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
180   stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
181   stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
182   stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
183   stateSet->setAttributeAndModes(new osg::PolygonMode(osg::PolygonMode::FRONT_AND_BACK,
184           osg::PolygonMode::FILL),
185           osg::StateAttribute::ON);
186   stateSet->setAttributeAndModes(new osg::AlphaFunc(osg::AlphaFunc::GREATER,
187           0.0f),
188           osg::StateAttribute::ON);
189   stateSet->setAttribute(new osg::ShadeModel(osg::ShadeModel::FLAT));
190   stateSet->setAttributeAndModes(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA,
191           osg::BlendFunc::ONE_MINUS_SRC_ALPHA),
192           osg::StateAttribute::ON);
193   if( !texture )
194   {
195     texture = new osg::Texture2D;
196     texture->setTextureSize(_size_x, _size_y);
197     texture->setInternalFormat(GL_RGBA);
198   }
199
200   updateSampling();
201
202   globals->get_renderer()->addCamera(camera.get(), false);
203   rtAvailable = true;
204 }
205
206 //------------------------------------------------------------------------------
207 void FGODGauge::updateCoordinateFrame()
208 {
209   assert( camera );
210
211   if( _view_width < 0 )
212     _view_width = _size_x;
213   if( _view_height < 0 )
214     _view_height = _size_y;
215
216   camera->setViewport(0, 0, _size_x, _size_y);
217
218   if( _use_image_coords )
219     camera->setProjectionMatrix(
220       osg::Matrix::ortho2D(0, _view_width, _view_height, 0)
221     );
222   else
223     camera->setProjectionMatrix(
224       osg::Matrix::ortho2D( -_view_width/2.,  _view_width/2.,
225                             -_view_height/2., _view_height/2. )
226     );
227 }
228
229 //------------------------------------------------------------------------------
230 void FGODGauge::updateStencil()
231 {
232   assert( camera );
233
234   GLbitfield mask = GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT;
235
236   if( _use_stencil)
237   {
238     camera->attach( osg::Camera::PACKED_DEPTH_STENCIL_BUFFER,
239                      GL_DEPTH_STENCIL_EXT );
240     mask |= GL_STENCIL_BUFFER_BIT;
241   }
242   else
243   {
244     camera->detach(osg::Camera::PACKED_DEPTH_STENCIL_BUFFER);
245   }
246
247   camera->setClearMask(mask);
248 }
249
250 //------------------------------------------------------------------------------
251 void FGODGauge::updateSampling()
252 {
253   assert( camera );
254   assert( texture );
255
256   texture->setFilter(
257     osg::Texture2D::MIN_FILTER,
258     _use_mipmapping ? osg::Texture2D::LINEAR_MIPMAP_NEAREST
259                     : osg::Texture2D::LINEAR
260   );
261   camera->attach(
262     osg::Camera::COLOR_BUFFER,
263     texture.get(),
264     0, 0,
265     _use_mipmapping,
266     _coverage_samples,
267     _color_samples
268   );
269 }
270
271 /**
272  * Replace a texture in the airplane model with the gauge texture.
273  */
274 class ReplaceStaticTextureVisitor:
275   public osg::NodeVisitor
276 {
277   public:
278
279     ReplaceStaticTextureVisitor( const char* name,
280                                  osg::Texture2D* new_texture ):
281         osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
282         _tex_name( osgDB::getSimpleFileName(name) ),
283         _new_texture(new_texture)
284     {}
285
286     ReplaceStaticTextureVisitor( const SGPropertyNode* placement,
287                                  osg::Texture2D* new_texture,
288                                  osg::NodeCallback* cull_callback = 0 ):
289         osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
290         _tex_name( osgDB::getSimpleFileName(
291           placement->getStringValue("texture"))
292         ),
293         _node_name( placement->getStringValue("node") ),
294         _parent_name( placement->getStringValue("parent") ),
295         _new_texture(new_texture),
296         _cull_callback(cull_callback)
297     {
298       if(    _tex_name.empty()
299           && _node_name.empty()
300           && _parent_name.empty() )
301         SG_LOG
302         (
303           SG_GL,
304           SG_WARN,
305           "No filter criterion for replacing texture. "
306           " Every texture will be replaced!"
307         );
308     }
309
310     /**
311      * Get a list of groups which have been inserted into the scene graph to
312      * replace the given texture
313      */
314     Placements& getPlacements()
315     {
316       return _placements;
317     }
318
319     virtual void apply(osg::Geode& node)
320     {
321       simgear::EffectGeode* eg = dynamic_cast<simgear::EffectGeode*>(&node);
322       if( !eg )
323         return;
324
325       osg::StateSet* ss = eg->getEffect()->getDefaultStateSet();
326       if( !ss )
327         return;
328
329       osg::Group *parent = node.getParent(0);
330       if( !_node_name.empty() && parent->getName() != _node_name )
331         return;
332
333       if( !_parent_name.empty() )
334       {
335         // Traverse nodes upwards starting at the parent node (skip current
336         // node)
337         const osg::NodePath& np = getNodePath();
338         bool found = false;
339         for( int i = static_cast<int>(np.size()) - 2; i >= 0; --i )
340         {
341           const osg::Node* path_segment = np[i];
342           const osg::Node* path_parent = path_segment->getParent(0);
343
344           // A node without a name is always the parent of the root node of
345           // the model just containing the file name
346           if( path_parent && path_parent->getName().empty() )
347             return;
348
349           if( path_segment->getName() == _parent_name )
350           {
351             found = true;
352             break;
353           }
354         }
355
356         if( !found )
357           return;
358       }
359
360       for( size_t unit = 0; unit < ss->getNumTextureAttributeLists(); ++unit )
361       {
362         osg::Texture2D* tex = dynamic_cast<osg::Texture2D*>
363         (
364           ss->getTextureAttribute(unit, osg::StateAttribute::TEXTURE)
365         );
366
367         if( !tex || !tex->getImage() || tex == _new_texture )
368           continue;
369
370         if( !_tex_name.empty() )
371         {
372           std::string tex_name = tex->getImage()->getFileName();
373           std::string tex_name_simple = osgDB::getSimpleFileName(tex_name);
374           if( !osgDB::equalCaseInsensitive(_tex_name, tex_name_simple) )
375             continue;
376         }
377
378         // insert a new group between the geode an it's parent which overrides
379         // the texture
380         osg::ref_ptr<osg::Group> group = new osg::Group;
381         group->setName("canvas texture group");
382         group->addChild(eg);
383         parent->removeChild(eg);
384         parent->addChild(group);
385
386         if( _cull_callback )
387           group->setCullCallback(_cull_callback);
388
389         _placements.push_back(group);
390
391         osg::StateSet* stateSet = group->getOrCreateStateSet();
392         stateSet->setTextureAttribute( unit, _new_texture,
393                                              osg::StateAttribute::OVERRIDE );
394         stateSet->setTextureMode( unit, GL_TEXTURE_2D,
395                                         osg::StateAttribute::ON );
396
397         SG_LOG
398         (
399           SG_GL,
400           SG_INFO,
401              "Replaced texture '" << _tex_name << "'"
402           << " for object '" << parent->getName() << "'"
403           << (!_parent_name.empty() ? " with parent '" + _parent_name + "'"
404                                     : "")
405         );
406         return;
407       }
408     }
409
410
411
412   protected:
413
414     std::string _tex_name,      ///<! Name of texture to be replaced
415                 _node_name,     ///<! Only replace if node name matches
416                 _parent_name;   ///<! Only replace if any parent node matches
417                                 ///   given name (all the tree upwards)
418     osg::Texture2D     *_new_texture;
419     osg::NodeCallback  *_cull_callback;
420
421     Placements _placements;
422 };
423
424 //------------------------------------------------------------------------------
425   Placements FGODGauge::set_texture(const char* name, osg::Texture2D* new_texture)
426 {
427   osg::Group* root = globals->get_scenery()->get_aircraft_branch();
428   ReplaceStaticTextureVisitor visitor(name, new_texture);
429   root->accept(visitor);
430   return visitor.getPlacements();
431 }
432
433 //------------------------------------------------------------------------------
434 Placements FGODGauge::set_texture( const SGPropertyNode* placement,
435                              osg::Texture2D* new_texture,
436                              osg::NodeCallback* cull_callback )
437 {
438   osg::Group* root = globals->get_scenery()->get_aircraft_branch();
439   ReplaceStaticTextureVisitor visitor(placement, new_texture, cull_callback);
440   root->accept(visitor);
441   return visitor.getPlacements();
442 }