]> git.mxchange.org Git - flightgear.git/blob - src/Viewer/renderer.cxx
Renderer: get rid of static scene references.
[flightgear.git] / src / Viewer / renderer.cxx
1 // renderer.cxx -- top level sim routines
2 //
3 // Written by Curtis Olson, started May 1997.
4 // This file contains parts of main.cxx prior to october 2004
5 //
6 // Copyright (C) 1997 - 2002  Curtis L. Olson  - http://www.flightgear.org/~curt
7 //
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21
22 #ifdef HAVE_CONFIG_H
23 #  include <config.h>
24 #endif
25
26 #ifdef HAVE_WINDOWS_H
27 #  include <windows.h>
28 #endif
29
30 #include <simgear/compiler.h>
31
32 #include <algorithm>
33 #include <iostream>
34 #include <map>
35 #include <vector>
36 #include <typeinfo>
37
38 #include <boost/foreach.hpp>
39
40 #include <osg/ref_ptr>
41 #include <osg/AlphaFunc>
42 #include <osg/BlendFunc>
43 #include <osg/Camera>
44 #include <osg/CullFace>
45 #include <osg/CullStack>
46 #include <osg/Depth>
47 #include <osg/Fog>
48 #include <osg/Group>
49 #include <osg/Hint>
50 #include <osg/Light>
51 #include <osg/LightModel>
52 #include <osg/LightSource>
53 #include <osg/Material>
54 #include <osg/Math>
55 #include <osg/NodeCallback>
56 #include <osg/Notify>
57 #include <osg/PolygonMode>
58 #include <osg/PolygonOffset>
59 #include <osg/Program>
60 #include <osg/Version>
61 #include <osg/TexEnv>
62
63 #include <osgUtil/LineSegmentIntersector>
64
65 #include <osg/io_utils>
66 #include <osgDB/WriteFile>
67 #include <osgViewer/Renderer>
68
69 #include <simgear/scene/material/matlib.hxx>
70 #include <simgear/scene/material/EffectCullVisitor.hxx>
71 #include <simgear/scene/material/Effect.hxx>
72 #include <simgear/scene/material/EffectGeode.hxx>
73 #include <simgear/scene/material/EffectBuilder.hxx>
74 #include <simgear/scene/model/animation.hxx>
75 #include <simgear/scene/model/placement.hxx>
76 #include <simgear/scene/sky/sky.hxx>
77 #include <simgear/scene/util/DeletionManager.hxx>
78 #include <simgear/scene/util/SGUpdateVisitor.hxx>
79 #include <simgear/scene/util/RenderConstants.hxx>
80 #include <simgear/scene/util/SGSceneUserData.hxx>
81 #include <simgear/scene/tgdb/GroundLightManager.hxx>
82 #include <simgear/scene/tgdb/pt_lights.hxx>
83 #include <simgear/scene/tgdb/userdata.hxx>
84 #include <simgear/structure/OSGUtils.hxx>
85 #include <simgear/props/props.hxx>
86 #include <simgear/timing/sg_time.hxx>
87 #include <simgear/ephemeris/ephemeris.hxx>
88 #include <simgear/math/sg_random.h>
89 #ifdef FG_JPEG_SERVER
90 #include <simgear/screen/jpgfactory.hxx>
91 #endif
92
93 #include <Time/light.hxx>
94 #include <Time/light.hxx>
95 #include <Cockpit/panel.hxx>
96
97 #include <Model/panelnode.hxx>
98 #include <Model/modelmgr.hxx>
99 #include <Model/acmodel.hxx>
100 #include <Scenery/scenery.hxx>
101 #include <Scenery/redout.hxx>
102 #include <GUI/new_gui.hxx>
103 #include <Instrumentation/HUD/HUD.hxx>
104 #include <Environment/precipitation_mgr.hxx>
105 #include <Environment/environment_mgr.hxx>
106
107 //#include <Main/main.hxx>
108 #include "viewer.hxx"
109 #include "viewmgr.hxx"
110 #include "splash.hxx"
111 #include "renderer.hxx"
112 #include "CameraGroup.hxx"
113 #include "FGEventHandler.hxx"
114
115 #include <plib/pu.h>
116
117 using namespace osg;
118 using namespace simgear;
119 using namespace flightgear;
120
121 class FGHintUpdateCallback : public osg::StateAttribute::Callback {
122 public:
123   FGHintUpdateCallback(const char* configNode) :
124     mConfigNode(fgGetNode(configNode, true))
125   { }
126   virtual void operator()(osg::StateAttribute* stateAttribute,
127                           osg::NodeVisitor*)
128   {
129     assert(dynamic_cast<osg::Hint*>(stateAttribute));
130     osg::Hint* hint = static_cast<osg::Hint*>(stateAttribute);
131
132     const char* value = mConfigNode->getStringValue();
133     if (!value)
134       hint->setMode(GL_DONT_CARE);
135     else if (0 == strcmp(value, "nicest"))
136       hint->setMode(GL_NICEST);
137     else if (0 == strcmp(value, "fastest"))
138       hint->setMode(GL_FASTEST);
139     else
140       hint->setMode(GL_DONT_CARE);
141   }
142 private:
143   SGPropertyNode_ptr mConfigNode;
144 };
145
146
147 class SGPuDrawable : public osg::Drawable {
148 public:
149   SGPuDrawable()
150   {
151     // Dynamic stuff, do not store geometry
152     setUseDisplayList(false);
153     setDataVariance(Object::DYNAMIC);
154
155     osg::StateSet* stateSet = getOrCreateStateSet();
156     stateSet->setRenderBinDetails(1001, "RenderBin");
157     // speed optimization?
158     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
159     // We can do translucent menus, so why not. :-)
160     stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
161     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
162     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
163
164     stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
165
166     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
167     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
168   }
169   virtual void drawImplementation(osg::RenderInfo& renderInfo) const
170   { drawImplementation(*renderInfo.getState()); }
171   void drawImplementation(osg::State& state) const
172   {
173     state.setActiveTextureUnit(0);
174     state.setClientActiveTextureUnit(0);
175
176     state.disableAllVertexArrays();
177
178     glPushAttrib(GL_ALL_ATTRIB_BITS);
179     glPushClientAttrib(~0u);
180
181     puDisplay();
182
183     glPopClientAttrib();
184     glPopAttrib();
185   }
186
187   virtual osg::Object* cloneType() const { return new SGPuDrawable; }
188   virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
189   
190 private:
191 };
192
193 class SGHUDDrawable : public osg::Drawable {
194 public:
195   SGHUDDrawable()
196   {
197     // Dynamic stuff, do not store geometry
198     setUseDisplayList(false);
199     setDataVariance(Object::DYNAMIC);
200
201     osg::StateSet* stateSet = getOrCreateStateSet();
202     stateSet->setRenderBinDetails(1000, "RenderBin");
203
204     // speed optimization?
205     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
206     stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
207     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
208     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
209     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
210
211     stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
212   }
213   virtual void drawImplementation(osg::RenderInfo& renderInfo) const
214   { drawImplementation(*renderInfo.getState()); }
215   void drawImplementation(osg::State& state) const
216   {
217     state.setActiveTextureUnit(0);
218     state.setClientActiveTextureUnit(0);
219     state.disableAllVertexArrays();
220
221     glPushAttrib(GL_ALL_ATTRIB_BITS);
222     glPushClientAttrib(~0u);
223       
224     // HUD can be NULL
225       HUD *hud = static_cast<HUD*>(globals->get_subsystem("hud"));
226       if (hud) {
227           hud->draw(state);
228       }
229       
230     glPopClientAttrib();
231     glPopAttrib();
232   }
233
234   virtual osg::Object* cloneType() const { return new SGHUDDrawable; }
235   virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDDrawable; }
236   
237 private:
238 };
239
240 class FGLightSourceUpdateCallback : public osg::NodeCallback {
241 public:
242   
243   /**
244    * @param isSun true if the light is the actual sun i.e., for
245    * illuminating the moon.
246    */
247   FGLightSourceUpdateCallback(bool isSun = false) : _isSun(isSun) {}
248   FGLightSourceUpdateCallback(const FGLightSourceUpdateCallback& nc,
249                               const CopyOp& op)
250     : NodeCallback(nc, op), _isSun(nc._isSun)
251   {}
252   META_Object(flightgear,FGLightSourceUpdateCallback);
253   
254   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
255   {
256     assert(dynamic_cast<osg::LightSource*>(node));
257     osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
258     osg::Light* light = lightSource->getLight();
259     
260     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
261       if (!l) {
262           // lighting is down during re-init
263           return;
264       }
265       
266     if (_isSun) {
267       light->setAmbient(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
268       light->setDiffuse(Vec4(1.0f, 1.0f, 1.0f, 1.0f));
269       light->setSpecular(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
270     } else {
271       light->setAmbient(toOsg(l->scene_ambient()));
272       light->setDiffuse(toOsg(l->scene_diffuse()));
273       light->setSpecular(toOsg(l->scene_specular()));
274     }
275     osg::Vec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
276     light->setPosition(position);
277
278     traverse(node, nv);
279   }
280 private:
281   const bool _isSun;
282 };
283
284 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
285 public:
286   FGWireFrameModeUpdateCallback() :
287     mWireframe(fgGetNode("/sim/rendering/wireframe", true))
288   { }
289   virtual void operator()(osg::StateAttribute* stateAttribute,
290                           osg::NodeVisitor*)
291   {
292     assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
293     osg::PolygonMode* polygonMode;
294     polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
295
296     if (mWireframe->getBoolValue())
297       polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
298                            osg::PolygonMode::LINE);
299     else
300       polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
301                            osg::PolygonMode::FILL);
302   }
303 private:
304   SGPropertyNode_ptr mWireframe;
305 };
306
307 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
308 public:
309   FGLightModelUpdateCallback() :
310     mHighlights(fgGetNode("/sim/rendering/specular-highlight", true))
311   { }
312   virtual void operator()(osg::StateAttribute* stateAttribute,
313                           osg::NodeVisitor*)
314   {
315     assert(dynamic_cast<osg::LightModel*>(stateAttribute));
316     osg::LightModel* lightModel;
317     lightModel = static_cast<osg::LightModel*>(stateAttribute);
318
319 #if 0
320     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
321     lightModel->setAmbientIntensity(toOsg(l->scene_ambient());
322 #else
323     lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
324 #endif
325     lightModel->setTwoSided(true);
326     lightModel->setLocalViewer(false);
327
328     if (mHighlights->getBoolValue()) {
329       lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
330     } else {
331       lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
332     }
333   }
334 private:
335   SGPropertyNode_ptr mHighlights;
336 };
337
338 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
339 public:
340   FGFogEnableUpdateCallback() :
341     mFogEnabled(fgGetNode("/sim/rendering/fog", true))
342   { }
343   virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
344   {
345     if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
346       stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
347     } else {
348       stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
349     }
350   }
351 private:
352   SGPropertyNode_ptr mFogEnabled;
353 };
354
355 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
356 public:
357   virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
358   {
359     assert(dynamic_cast<SGUpdateVisitor*>(nv));
360     assert(dynamic_cast<osg::Fog*>(sa));
361     SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
362     osg::Fog* fog = static_cast<osg::Fog*>(sa);
363     fog->setMode(osg::Fog::EXP2);
364     fog->setColor(toOsg(updateVisitor->getFogColor()));
365     fog->setDensity(updateVisitor->getFogExp2Density());
366   }
367 };
368
369 // update callback for the switch node guarding that splash
370 class FGScenerySwitchCallback : public osg::NodeCallback {
371 public:
372   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
373   {
374     assert(dynamic_cast<osg::Switch*>(node));
375     osg::Switch* sw = static_cast<osg::Switch*>(node);
376
377     bool enabled = scenery_enabled;
378     sw->setValue(0, enabled);
379     if (!enabled)
380       return;
381     traverse(node, nv);
382   }
383
384   static bool scenery_enabled;
385 };
386
387 bool FGScenerySwitchCallback::scenery_enabled = false;
388                                     
389 #ifdef FG_JPEG_SERVER
390 static void updateRenderer()
391 {
392     globals->get_renderer()->update();
393 }
394 #endif
395
396 FGRenderer::FGRenderer() :
397     _sky(NULL),
398     _ambientFactor( new osg::Uniform( "fg_SunAmbientColor", osg::Vec4f() ) ),
399     _sunDiffuse( new osg::Uniform( "fg_SunDiffuseColor", osg::Vec4f() ) ),
400     _sunSpecular( new osg::Uniform( "fg_SunSpecularColor", osg::Vec4f() ) ),
401     _sunDirection( new osg::Uniform( "fg_SunDirection", osg::Vec3f() ) ),
402     _planes( new osg::Uniform( "fg_Planes", osg::Vec3f() ) ),
403     _fogColor( new osg::Uniform( "fg_FogColor", osg::Vec4f(1.0, 1.0, 1.0, 1.0) ) ),
404     _fogDensity( new osg::Uniform( "fg_FogDensity", 0.0001f ) ),
405     _shadowNumber( new osg::Uniform( "fg_ShadowNumber", (int)4 ) ),
406     _shadowDistances( new osg::Uniform( "fg_ShadowDistances", osg::Vec4f(5.0, 50.0, 500.0, 5000.0 ) ) ),
407     _depthInColor( new osg::Uniform( "fg_DepthInColor", false ) )
408 {
409 #ifdef FG_JPEG_SERVER
410    jpgRenderFrame = updateRenderer;
411 #endif
412     
413     // it's not the real root, whatever that means
414     _root = new osg::Group;
415     _root->setName("fakeRoot");
416
417     _updateVisitor = new SGUpdateVisitor;
418     _root = new osg::Group;
419     _deferredRealRoot = new osg::Group;
420     
421    _numCascades = 4;
422    _cascadeFar[0] = 5.f;
423    _cascadeFar[1] = 50.f;
424    _cascadeFar[2] = 500.f;
425    _cascadeFar[3] = 5000.f;
426 }
427
428 FGRenderer::~FGRenderer()
429 {
430     SGPropertyChangeListenerVec::iterator i = _listeners.begin();
431     for (; i != _listeners.end(); ++i) {
432         delete *i;
433     }
434     
435 #ifdef FG_JPEG_SERVER
436    jpgRenderFrame = NULL;
437 #endif
438     delete _sky;
439 }
440
441 // Initialize various GL/view parameters
442 // XXX This should be called "preinit" or something, as it initializes
443 // critical parts of the scene graph in addition to the splash screen.
444 void
445 FGRenderer::splashinit( void )
446       {
447     osgViewer::Viewer* viewer = getViewer();
448     viewer->setName("osgViewer");
449     _viewerSceneRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
450     _viewerSceneRoot->setName("viewerSceneRoot");
451     
452     ref_ptr<Node> splashNode = fgCreateSplashNode();
453     if (_classicalRenderer) {
454         _viewerSceneRoot->addChild(splashNode.get());
455     } else {
456         for (   CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
457                 ii != CameraGroup::getDefault()->camerasEnd();
458                 ++ii )
459         {
460             CameraInfo* info = ii->get();
461             Camera* camera = info->getCamera(DISPLAY_CAMERA);
462             if (camera == 0) continue;
463
464             camera->addChild(splashNode.get());
465         }
466     }
467     
468     _frameStamp = viewer->getFrameStamp();
469     // Scene doesn't seem to pass the frame stamp to the update
470     // visitor automatically.
471     _updateVisitor->setFrameStamp(_frameStamp.get());
472     viewer->setUpdateVisitor(_updateVisitor.get());
473     fgSetDouble("/sim/startup/splash-alpha", 1.0);
474 }
475
476 class ShadowMapSizeListener : public SGPropertyChangeListener {
477 public:
478     virtual void valueChanged(SGPropertyNode* node) {
479         globals->get_renderer()->updateShadowMapSize(node->getIntValue());
480     }
481 };
482
483 class ShadowEnabledListener : public SGPropertyChangeListener {
484 public:
485     virtual void valueChanged(SGPropertyNode* node) {
486         globals->get_renderer()->enableShadows(node->getBoolValue());
487     }
488 };
489
490 class ShadowNumListener : public SGPropertyChangeListener {
491 public:
492     virtual void valueChanged(SGPropertyNode* node) {
493         globals->get_renderer()->updateCascadeNumber(node->getIntValue());
494     }
495 };
496
497 class ShadowRangeListener : public SGPropertyChangeListener {
498 public:
499     virtual void valueChanged(SGPropertyNode* node) {
500         globals->get_renderer()->updateCascadeFar(node->getIndex(), node->getFloatValue());
501     }
502 };
503
504 void
505 FGRenderer::addChangeListener(SGPropertyChangeListener* l, const char* path)
506 {
507     _listeners.push_back(l);
508     fgAddChangeListener(l, path);
509 }
510                                     
511 void
512 FGRenderer::init( void )
513 {
514     if (!eventHandler)
515         eventHandler = new FGEventHandler();
516
517     sgUserDataInit( globals->get_props() );
518
519     _classicalRenderer = !fgGetBool("/sim/rendering/rembrandt/enabled", false);
520     _shadowMapSize    = fgGetInt( "/sim/rendering/shadows/map-size", 4096 );
521     addChangeListener( new ShadowMapSizeListener, "/sim/rendering/shadows/map-size" );
522     addChangeListener( new ShadowEnabledListener, "/sim/rendering/shadows/enabled" );
523     ShadowRangeListener* srl = new ShadowRangeListener;
524     addChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[0]");
525     fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[1]");
526     fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[2]");
527     fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[3]");
528     addChangeListener(new ShadowNumListener, "/sim/rendering/shadows/num-cascades");
529     _numCascades = fgGetInt("/sim/rendering/shadows/num-cascades", 4);
530     _cascadeFar[0] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[0]", 5.0f);
531     _cascadeFar[1] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[1]", 50.0f);
532     _cascadeFar[2] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[2]", 500.0f);
533     _cascadeFar[3] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[3]", 5000.0f);
534     updateCascadeNumber(_numCascades);
535     updateCascadeFar(0, _cascadeFar[0]);
536     updateCascadeFar(1, _cascadeFar[1]);
537     updateCascadeFar(2, _cascadeFar[2]);
538     updateCascadeFar(3, _cascadeFar[3]);
539     _useColorForDepth = fgGetBool( "/sim/rendering/rembrandt/use-color-for-depth", false );
540     _depthInColor->set( _useColorForDepth );
541
542     _renderer         = fgGetString("/sim/rendering/rembrandt/renderer", "default-pipeline");
543     if (!_classicalRenderer)
544         _pipeline = makeRenderingPipeline(_renderer, 0);
545     _scenery_loaded   = fgGetNode("/sim/sceneryloaded", true);
546     _position_finalized = fgGetNode("/sim/position-finalized", true);
547     
548     _panel_hotspots   = fgGetNode("/sim/panel-hotspots", true);
549     _virtual_cockpit  = fgGetNode("/sim/virtual-cockpit", true);
550
551     _sim_delta_sec = fgGetNode("/sim/time/delta-sec", true);
552
553     _xsize         = fgGetNode("/sim/startup/xsize", true);
554     _ysize         = fgGetNode("/sim/startup/ysize", true);
555     _splash_alpha  = fgGetNode("/sim/startup/splash-alpha", true);
556
557     _skyblend             = fgGetNode("/sim/rendering/skyblend", true);
558     _point_sprites        = fgGetNode("/sim/rendering/point-sprites", true);
559     _enhanced_lighting    = fgGetNode("/sim/rendering/enhanced-lighting", true);
560     _distance_attenuation = fgGetNode("/sim/rendering/distance-attenuation", true);
561     _horizon_effect       = fgGetNode("/sim/rendering/horizon-effect", true);
562     _textures             = fgGetNode("/sim/rendering/textures", true);
563
564     _altitude_ft = fgGetNode("/position/altitude-ft", true);
565
566     _cloud_status = fgGetNode("/environment/clouds/status", true);
567     _visibility_m = fgGetNode("/environment/visibility-m", true);
568     
569     bool use_point_sprites = _point_sprites->getBoolValue();
570     bool enhanced_lighting = _enhanced_lighting->getBoolValue();
571     bool distance_attenuation = _distance_attenuation->getBoolValue();
572
573     SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
574                                   distance_attenuation );
575
576     if (const char* tc = fgGetString("/sim/rendering/texture-compression", NULL)) {
577       if (strcmp(tc, "false") == 0 || strcmp(tc, "off") == 0 ||
578           strcmp(tc, "0") == 0 || strcmp(tc, "no") == 0 ||
579           strcmp(tc, "none") == 0) {
580         SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::DoNotUseCompression);
581       } else if (strcmp(tc, "arb") == 0) {
582         SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseARBCompression);
583       } else if (strcmp(tc, "dxt1") == 0) {
584         SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT1Compression);
585       } else if (strcmp(tc, "dxt3") == 0) {
586         SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT3Compression);
587       } else if (strcmp(tc, "dxt5") == 0) {
588         SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT5Compression);
589       } else {
590         SG_LOG(SG_VIEW, SG_WARN, "Unknown texture compression setting!");
591       }
592     }
593     
594 // create sky, but can't build until setupView, since we depend
595 // on other subsystems to be inited, eg Ephemeris    
596     _sky = new SGSky;
597     
598     SGPath texture_path(globals->get_fg_root());
599     texture_path.append("Textures");
600     texture_path.append("Sky");
601     for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
602         SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
603         _sky->add_cloud_layer(layer);
604     }
605     
606     _sky->texture_path( texture_path.str() );
607
608     if (!_classicalRenderer) {
609         eventHandler->setChangeStatsCameraRenderOrder( true );
610         _sky->set_minimum_sky_visibility( 0.0 ); // A black sky appears for below that
611     }
612 }
613
614 void installCullVisitor(Camera* camera)
615 {
616     osgViewer::Renderer* renderer
617         = static_cast<osgViewer::Renderer*>(camera->getRenderer());
618     for (int i = 0; i < 2; ++i) {
619         osgUtil::SceneView* sceneView = renderer->getSceneView(i);
620
621         osg::ref_ptr<osgUtil::CullVisitor::Identifier> identifier;
622         identifier = sceneView->getCullVisitor()->getIdentifier();
623         sceneView->setCullVisitor(new simgear::EffectCullVisitor);
624         sceneView->getCullVisitor()->setIdentifier(identifier.get());
625
626         identifier = sceneView->getCullVisitorLeft()->getIdentifier();
627         sceneView->setCullVisitorLeft(sceneView->getCullVisitor()->clone());
628         sceneView->getCullVisitorLeft()->setIdentifier(identifier.get());
629
630         identifier = sceneView->getCullVisitorRight()->getIdentifier();
631         sceneView->setCullVisitorRight(sceneView->getCullVisitor()->clone());
632         sceneView->getCullVisitorRight()->setIdentifier(identifier.get());
633
634     }
635 }
636
637 CameraInfo*
638 FGRenderer::buildRenderingPipeline(CameraGroup* cgroup, unsigned flags, Camera* camera,
639                                    const Matrix& view,
640                                    const Matrix& projection,
641                                                                    osg::GraphicsContext* gc,
642                                    bool useMasterSceneData)
643 {
644         CameraInfo* info = 0;
645         if (!_classicalRenderer && (flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
646                 info = buildDeferredPipeline( cgroup, flags, camera, view, projection, gc );
647
648         if (info) {
649                 return info;
650         } else {
651                 if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
652                         _classicalRenderer = true;
653                 return buildClassicalPipeline( cgroup, flags, camera, view, projection, useMasterSceneData );
654         }
655 }
656
657 CameraInfo*
658 FGRenderer::buildClassicalPipeline(CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
659                                 const osg::Matrix& view,
660                                 const osg::Matrix& projection,
661                                 bool useMasterSceneData)
662 {
663     CameraInfo* info = new CameraInfo(flags);
664     // The camera group will always update the camera
665     camera->setReferenceFrame(Transform::ABSOLUTE_RF);
666     info->name = "classic";
667     
668     Camera* farCamera = 0;
669     if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0) {
670         farCamera = new Camera;
671         farCamera->setName("farCamera");
672         farCamera->setAllowEventFocus(camera->getAllowEventFocus());
673         farCamera->setGraphicsContext(camera->getGraphicsContext());
674         farCamera->setCullingMode(camera->getCullingMode());
675         farCamera->setInheritanceMask(camera->getInheritanceMask());
676         farCamera->setReferenceFrame(Transform::ABSOLUTE_RF);
677         // Each camera's viewport is written when the window is
678         // resized; if the the viewport isn't copied here, it gets updated
679         // twice and ends up with the wrong value.
680         farCamera->setViewport(simgear::clone(camera->getViewport()));
681         farCamera->setDrawBuffer(camera->getDrawBuffer());
682         farCamera->setReadBuffer(camera->getReadBuffer());
683         farCamera->setRenderTargetImplementation(
684             camera->getRenderTargetImplementation());
685         const Camera::BufferAttachmentMap& bufferMap
686             = camera->getBufferAttachmentMap();
687         if (bufferMap.count(Camera::COLOR_BUFFER) != 0) {
688             farCamera->attach(
689                 Camera::COLOR_BUFFER,
690                 bufferMap.find(Camera::COLOR_BUFFER)->second._texture.get());
691         }
692         cgroup->getViewer()->addSlave(farCamera, projection, view, useMasterSceneData);
693         installCullVisitor(farCamera);
694                 int farSlaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
695                 info->addCamera( FAR_CAMERA, farCamera, farSlaveIndex );
696         farCamera->setRenderOrder(Camera::POST_RENDER, farSlaveIndex);
697         camera->setCullMask(camera->getCullMask() & ~simgear::BACKGROUND_BIT);
698         camera->setClearMask(GL_DEPTH_BUFFER_BIT);
699     }
700     cgroup->getViewer()->addSlave(camera, projection, view, useMasterSceneData);
701     installCullVisitor(camera);
702     int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
703     info->addCamera( MAIN_CAMERA, camera, slaveIndex );
704     camera->setRenderOrder(Camera::POST_RENDER, slaveIndex);
705     cgroup->addCamera(info);
706     return info;
707 }
708
709 class FGDeferredRenderingCameraCullCallback : public osg::NodeCallback {
710 public:
711     FGDeferredRenderingCameraCullCallback( const std::string& k, CameraInfo* i, bool nd = false ) : kind( k ), info( i ), needsDuDv(nd) {}
712     virtual void operator()( osg::Node *n, osg::NodeVisitor *nv) {
713         simgear::EffectCullVisitor* cv = dynamic_cast<simgear::EffectCullVisitor*>(nv);
714         osg::Camera* camera = static_cast<osg::Camera*>(n);
715
716         cv->clearBufferList();
717         for (RenderBufferMap::iterator ii = info->buffers.begin(); ii != info->buffers.end(); ++ii) {
718             cv->addBuffer(ii->first, ii->second.texture);
719         }
720
721         if ( !info->getRenderStageInfo(kind).fullscreen )
722             info->setMatrices( camera );
723
724         if (needsDuDv) {
725             osg::Matrix projInverse;
726             info->projInverse->get( projInverse );
727
728             osg::Vec4 p0 = osg::Vec4( -1.0, -1.0, 0.0, 1.0 ) * projInverse;
729             info->du->set( osg::Vec4(  1.0, -1.0, 0.0, 1.0 ) * projInverse - p0 );
730             info->dv->set( osg::Vec4( -1.0,  1.0, 0.0, 1.0 ) * projInverse - p0 );
731         }
732
733         cv->traverse( *camera );
734
735         if ( kind == GEOMETRY_CAMERA ) {
736             // Remove transparent bins. They will be renderer in the additional light stage (side effect)
737             osgUtil::RenderStage* renderStage = cv->getRenderStage();
738             osgUtil::RenderBin::RenderBinList& rbl = renderStage->getRenderBinList();
739             for (osgUtil::RenderBin::RenderBinList::iterator rbi = rbl.begin(); rbi != rbl.end(); ) {
740                 if (rbi->second->getSortMode() == osgUtil::RenderBin::SORT_BACK_TO_FRONT) {
741                     rbl.erase( rbi++ );
742                 } else {
743                     ++rbi;
744                 }
745             }
746         } else if ( kind == LIGHTING_CAMERA ) {
747             osg::ref_ptr<osg::Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
748             if (mainShadowCamera.valid()) {
749                 osg::Switch* grp = mainShadowCamera->getChild(0)->asSwitch();
750                 for (int i = 0; i < 4; ++i ) {
751                     if (!grp->getValue(i))
752                         continue;
753
754                     osg::Camera* cascadeCam = static_cast<osg::Camera*>( grp->getChild(i) );
755                     osg::Matrixf shadowMatrix = camera->getInverseViewMatrix() *
756                                                 cascadeCam->getViewMatrix() *
757                                                 cascadeCam->getProjectionMatrix() *
758                                                 osg::Matrix::translate(1.0, 1.0, 1.0) *
759                                                 osg::Matrix::scale(0.5f, 0.5f, 0.5f);
760
761                     info->shadowMatrix[i]->set( shadowMatrix );
762                 }
763             }
764         }
765     }
766
767 private:
768     std::string kind;
769     CameraInfo* info;
770     bool needsDuDv;
771 };
772
773 osg::Texture2D* buildDeferredBuffer(GLint internalFormat, GLenum sourceFormat, GLenum sourceType, GLenum wrapMode, bool shadowComparison = false)
774 {
775     osg::Texture2D* tex = new osg::Texture2D;
776     tex->setResizeNonPowerOfTwoHint( false );
777     tex->setInternalFormat( internalFormat );
778     tex->setShadowComparison(shadowComparison);
779     if (shadowComparison) {
780         tex->setShadowTextureMode(osg::Texture2D::LUMINANCE);
781         tex->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
782     }
783     tex->setSourceFormat(sourceFormat);
784     tex->setSourceType(sourceType);
785     tex->setFilter( osg::Texture2D::MIN_FILTER, osg::Texture2D::LINEAR );
786     tex->setFilter( osg::Texture2D::MAG_FILTER, osg::Texture2D::LINEAR );
787     tex->setWrap( osg::Texture::WRAP_S, (osg::Texture::WrapMode)wrapMode );
788     tex->setWrap( osg::Texture::WRAP_T, (osg::Texture::WrapMode)wrapMode );
789         return tex;
790 }
791
792 void attachBufferToCamera( CameraInfo* info, osg::Camera* camera, osg::Camera::BufferComponent c, const std::string& ck, const std::string& bk )
793 {
794     camera->attach( c, info->getBuffer(bk) );
795     info->getRenderStageInfo(ck).buffers.insert( std::make_pair( c, bk ) );
796 }
797
798 void buildAttachments(CameraInfo* info, osg::Camera* camera, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments) {
799     BOOST_FOREACH(ref_ptr<FGRenderingPipeline::Attachment> attachment, attachments) {
800         if (attachment->valid())
801             attachBufferToCamera( info, camera, attachment->component, name, attachment->buffer );
802     }
803 }
804
805 osg::Camera* FGRenderer::buildDeferredGeometryCamera( CameraInfo* info, osg::GraphicsContext* gc, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
806 {
807     osg::Camera* camera = new osg::Camera;
808     info->addCamera(name, camera );
809
810     camera->setCullMask( ~simgear::MODELLIGHT_BIT );
811     camera->setName( "GeometryC" );
812     camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
813     camera->setGraphicsContext( gc );
814     camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( name, info ) );
815     camera->setClearMask( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
816     camera->setClearColor( osg::Vec4( 0., 0., 0., 0. ) );
817     camera->setClearDepth( 1.0 );
818     camera->setColorMask(true, true, true, true);
819     camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
820     camera->setRenderOrder(osg::Camera::NESTED_RENDER, 0);
821     camera->setViewport( new osg::Viewport );
822     buildAttachments(info, camera, name, attachments);
823     camera->setDrawBuffer(GL_FRONT);
824     camera->setReadBuffer(GL_FRONT);
825
826     osg::StateSet* ss = camera->getOrCreateStateSet();
827     ss->addUniform( _depthInColor );
828
829     camera->addChild( _deferredRealRoot.get() );
830
831     return camera;
832 }
833
834 static void setShadowCascadeStateSet( osg::Camera* cam ) {
835     osg::StateSet* ss = cam->getOrCreateStateSet();
836     ss->setAttribute( new osg::PolygonOffset( 1.1f, 5.0f ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
837     ss->setMode( GL_POLYGON_OFFSET_FILL, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
838     ss->setRenderBinDetails( 0, "RenderBin", osg::StateSet::OVERRIDE_RENDERBIN_DETAILS );
839     ss->setAttributeAndModes( new osg::AlphaFunc( osg::AlphaFunc::GREATER, 0.05 ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
840     ss->setAttributeAndModes( new osg::ColorMask( false, false, false, false ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
841     ss->setAttributeAndModes( new osg::CullFace( osg::CullFace::FRONT ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
842     osg::Program* program = new osg::Program;
843     ss->setAttribute( program, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
844     ss->setMode( GL_LIGHTING, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
845     ss->setMode( GL_BLEND, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
846     //ss->setTextureMode( 0, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
847     ss->setTextureMode( 0, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
848     ss->setTextureMode( 1, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
849     ss->setTextureMode( 1, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
850     ss->setTextureMode( 2, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
851     ss->setTextureMode( 2, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
852 }
853
854 static osg::Camera* createShadowCascadeCamera( int no, int cascadeSize ) {
855     osg::Camera* cascadeCam = new osg::Camera;
856     setShadowCascadeStateSet( cascadeCam );
857
858     std::ostringstream oss;
859     oss << "CascadeCamera" << (no + 1);
860     cascadeCam->setName( oss.str() );
861     cascadeCam->setClearMask(0);
862     cascadeCam->setCullMask( simgear::CASTSHADOW_BIT );
863     cascadeCam->setCullingMode( cascadeCam->getCullingMode() | osg::CullSettings::SMALL_FEATURE_CULLING );
864     cascadeCam->setAllowEventFocus(false);
865     cascadeCam->setReferenceFrame(osg::Transform::ABSOLUTE_RF_INHERIT_VIEWPOINT);
866     cascadeCam->setRenderOrder(osg::Camera::NESTED_RENDER);
867     cascadeCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
868     cascadeCam->setViewport( int( no / 2 ) * cascadeSize, (no & 1) * cascadeSize, cascadeSize, cascadeSize );
869     return cascadeCam;
870 }
871
872 osg::Camera* FGRenderer::buildDeferredShadowCamera( CameraInfo* info, osg::GraphicsContext* gc, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
873 {
874     osg::Camera* mainShadowCamera = new osg::Camera;
875     info->addCamera(name, mainShadowCamera, 0.0f );
876
877     mainShadowCamera->setName( "ShadowC" );
878     mainShadowCamera->setClearMask( GL_DEPTH_BUFFER_BIT );
879     mainShadowCamera->setClearDepth( 1.0 );
880     mainShadowCamera->setAllowEventFocus(false);
881     mainShadowCamera->setGraphicsContext(gc);
882     mainShadowCamera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
883     buildAttachments(info, mainShadowCamera, name, attachments);
884     mainShadowCamera->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
885     mainShadowCamera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
886     mainShadowCamera->setProjectionMatrix(osg::Matrix::identity());
887     mainShadowCamera->setCullingMode( osg::CullSettings::NO_CULLING );
888     mainShadowCamera->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
889     mainShadowCamera->setDrawBuffer(GL_FRONT);
890     mainShadowCamera->setReadBuffer(GL_FRONT);
891     mainShadowCamera->setRenderOrder(Camera::NESTED_RENDER, 1);
892
893     osg::Switch* shadowSwitch = new osg::Switch;
894     mainShadowCamera->addChild( shadowSwitch );
895
896     for (int i = 0; i < 4; ++i ) {
897         osg::Camera* cascadeCam = createShadowCascadeCamera( i, _shadowMapSize/2 );
898         cascadeCam->addChild( _deferredRealRoot.get() );
899         shadowSwitch->addChild( cascadeCam );
900     }
901     if (fgGetBool("/sim/rendering/shadows/enabled", true))
902         shadowSwitch->setAllChildrenOn();
903     else
904         shadowSwitch->setAllChildrenOff();
905
906     return mainShadowCamera;
907 }
908
909 void FGRenderer::updateShadowCascade(const CameraInfo* info, osg::Camera* camera, osg::Group* grp, int idx, double left, double right, double bottom, double top, double zNear, double f1, double f2)
910 {
911     osg::Camera* cascade = static_cast<osg::Camera*>( grp->getChild(idx) );
912     osg::Matrixd &viewMatrix = cascade->getViewMatrix();
913     osg::Matrixd &projectionMatrix = cascade->getProjectionMatrix();
914
915     osg::BoundingSphere bs;
916     bs.expandBy(osg::Vec3(left,bottom,-zNear) * f1);
917     bs.expandBy(osg::Vec3(right,top,-zNear) * f2);
918     bs.expandBy(osg::Vec3(left,bottom,-zNear) * f2);
919     bs.expandBy(osg::Vec3(right,top,-zNear) * f1);
920
921     osg::Vec4 aim = osg::Vec4(bs.center(), 1.0) * camera->getInverseViewMatrix();
922
923     projectionMatrix.makeOrtho( -bs.radius(), bs.radius(), -bs.radius(), bs.radius(), 1., 15000.0 );
924     osg::Vec3 position( aim.x(), aim.y(), aim.z() );
925     viewMatrix.makeLookAt( position + (getSunDirection() * 10000.0), position, position );
926 }
927
928 osg::Vec3 FGRenderer::getSunDirection() const
929 {
930     osg::Vec3 val;
931     _sunDirection->get( val );
932     return val;
933 }
934
935 void FGRenderer::updateShadowCamera(const CameraInfo* info, const osg::Vec3d& position)
936 {
937     ref_ptr<Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
938     if (mainShadowCamera.valid()) {
939         ref_ptr<Switch> shadowSwitch = mainShadowCamera->getChild( 0 )->asSwitch();
940         osg::Vec3d up = position,
941             dir = getSunDirection();
942         up.normalize();
943         dir.normalize();
944         // cos(100 deg) == -0.17
945         if (up * dir < -0.17 || !fgGetBool("/sim/rendering/shadows/enabled", true)) {
946             shadowSwitch->setAllChildrenOff();
947         } else {
948             double left,right,bottom,top,zNear,zFar;
949             ref_ptr<Camera> camera = info->getCamera(GEOMETRY_CAMERA);
950             camera->getProjectionMatrix().getFrustum(left,right,bottom,top,zNear,zFar);
951
952             shadowSwitch->setAllChildrenOn();
953             if (_numCascades == 1) {
954                 osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(0) );
955                 cascadeCam->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
956             } else {
957                 for (int no = 0; no < 4; ++no) {
958                     osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(no) );
959                     cascadeCam->setViewport( int( no / 2 ) * (_shadowMapSize/2), (no & 1) * (_shadowMapSize/2), (_shadowMapSize/2), (_shadowMapSize/2) );
960                 }
961             }
962             updateShadowCascade(info, camera, shadowSwitch, 0, left, right, bottom, top, zNear, 1.0, _cascadeFar[0]/zNear);
963             if (_numCascades > 1) {
964                 shadowSwitch->setValue(1, true);
965                 updateShadowCascade(info, camera, shadowSwitch, 1, left, right, bottom, top, zNear, _cascadeFar[0]/zNear, _cascadeFar[1]/zNear);
966             } else {
967                 shadowSwitch->setValue(1, false);
968             }
969             if (_numCascades > 2) {
970                 shadowSwitch->setValue(2, true);
971                 updateShadowCascade(info, camera, shadowSwitch, 2, left, right, bottom, top, zNear, _cascadeFar[1]/zNear, _cascadeFar[2]/zNear);
972             } else {
973                 shadowSwitch->setValue(2, false);
974             }
975             if (_numCascades > 3) {
976                 shadowSwitch->setValue(3, true);
977                 updateShadowCascade(info, camera, shadowSwitch, 3, left, right, bottom, top, zNear, _cascadeFar[2]/zNear, _cascadeFar[3]/zNear);
978             } else {
979                 shadowSwitch->setValue(3, false);
980             }
981             {
982             osg::Matrixd &viewMatrix = mainShadowCamera->getViewMatrix();
983
984             osg::Vec4 aim = osg::Vec4( 0.0, 0.0, 0.0, 1.0 ) * camera->getInverseViewMatrix();
985
986             osg::Vec3 position( aim.x(), aim.y(), aim.z() );
987             viewMatrix.makeLookAt( position, position + (getSunDirection() * 10000.0), position );
988             }
989         }
990     }
991 }
992
993 void FGRenderer::updateShadowMapSize(int mapSize)
994 {
995     if ( ((~( mapSize-1 )) & mapSize) != mapSize ) {
996         SG_LOG( SG_VIEW, SG_ALERT, "Map size is not a power of two" );
997         return;
998     }
999     for (   CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
1000             ii != CameraGroup::getDefault()->camerasEnd();
1001             ++ii )
1002     {
1003         CameraInfo* info = ii->get();
1004         Camera* camera = info->getCamera(SHADOW_CAMERA);
1005         if (camera == 0) continue;
1006
1007         Texture2D* tex = info->getBuffer("shadow");
1008         if (tex == 0) continue;
1009
1010         tex->setTextureSize( mapSize, mapSize );
1011         tex->dirtyTextureObject();
1012
1013         Viewport* vp = camera->getViewport();
1014         vp->width() = mapSize;
1015         vp->height() = mapSize;
1016
1017         osgViewer::Renderer* renderer
1018             = static_cast<osgViewer::Renderer*>(camera->getRenderer());
1019         for (int i = 0; i < 2; ++i) {
1020             osgUtil::SceneView* sceneView = renderer->getSceneView(i);
1021             sceneView->getRenderStage()->setFrameBufferObject(0);
1022             sceneView->getRenderStage()->setCameraRequiresSetUp(true);
1023             if (sceneView->getRenderStageLeft()) {
1024                 sceneView->getRenderStageLeft()->setFrameBufferObject(0);
1025                 sceneView->getRenderStageLeft()->setCameraRequiresSetUp(true);
1026             }
1027             if (sceneView->getRenderStageRight()) {
1028                 sceneView->getRenderStageRight()->setFrameBufferObject(0);
1029                 sceneView->getRenderStageRight()->setCameraRequiresSetUp(true);
1030             }
1031         }
1032
1033         int cascadeSize = mapSize / 2;
1034         Group* grp = camera->getChild(0)->asGroup();
1035         for (int i = 0; i < 4; ++i ) {
1036             Camera* cascadeCam = static_cast<Camera*>( grp->getChild(i) );
1037             cascadeCam->setViewport( int( i / 2 ) * cascadeSize, (i & 1) * cascadeSize, cascadeSize, cascadeSize );
1038         }
1039
1040         _shadowMapSize = mapSize;
1041     }
1042 }
1043
1044 void FGRenderer::enableShadows(bool enabled)
1045 {
1046     for (   CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
1047             ii != CameraGroup::getDefault()->camerasEnd();
1048             ++ii )
1049     {
1050         CameraInfo* info = ii->get();
1051         Camera* camera = info->getCamera(SHADOW_CAMERA);
1052         if (camera == 0) continue;
1053
1054         osg::Switch* shadowSwitch = camera->getChild(0)->asSwitch();
1055         if (enabled)
1056             shadowSwitch->setAllChildrenOn();
1057         else
1058             shadowSwitch->setAllChildrenOff();
1059     }
1060 }
1061
1062 void FGRenderer::updateCascadeFar(int index, float far_m)
1063 {
1064     if (index < 0 || index > 3)
1065         return;
1066     _cascadeFar[index] = far_m;
1067     _shadowDistances->set( osg::Vec4f(_cascadeFar[0], _cascadeFar[1], _cascadeFar[2], _cascadeFar[3]) );
1068 }
1069
1070 void FGRenderer::updateCascadeNumber(size_t num)
1071 {
1072     if (num < 1 || num > 4)
1073         return;
1074     _numCascades = num;
1075     _shadowNumber->set( (int)_numCascades );
1076 }
1077
1078 class DebugPassListener : public SGPropertyChangeListener {
1079 public:
1080     DebugPassListener(osg::Switch* sw, int i) : _switch(sw), _index(i) {}
1081     virtual void valueChanged(SGPropertyNode* node) {
1082         _switch->setValue(_index, node->getBoolValue());
1083     }
1084
1085 private:
1086     osg::ref_ptr<osg::Switch> _switch;
1087     int _index;
1088 };
1089
1090 osg::Camera*
1091 FGRenderer::buildDeferredLightingCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc, const FGRenderingPipeline::Stage* stage )
1092 {
1093     osg::Camera* camera = new osg::Camera;
1094     info->addCamera(stage->name, camera );
1095
1096     camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( stage->name, info ) );
1097     camera->setAllowEventFocus(false);
1098     camera->setGraphicsContext(gc);
1099     camera->setViewport(new Viewport);
1100     camera->setName(stage->name+"C");
1101     camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1102     camera->setRenderOrder(osg::Camera::NESTED_RENDER, stage->orderNum);
1103     camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1104     camera->setViewport( new osg::Viewport );
1105     buildAttachments(info, camera, stage->name, stage->attachments);
1106     camera->setDrawBuffer(GL_FRONT);
1107     camera->setReadBuffer(GL_FRONT);
1108     camera->setClearColor( osg::Vec4( 0.5, 0.5, 0.5, 1. ) );
1109     camera->setClearMask( GL_COLOR_BUFFER_BIT );
1110     osg::StateSet* ss = camera->getOrCreateStateSet();
1111     ss->setAttribute( new osg::Depth(osg::Depth::LESS, 0.0, 1.0, false) );
1112     ss->addUniform( _depthInColor );
1113
1114     osg::Switch* lightingGroup = new osg::Switch;
1115
1116     BOOST_FOREACH( osg::ref_ptr<FGRenderingPipeline::Pass> pass, stage->passes ) {
1117         ref_ptr<Node> node = buildPass(info, pass);
1118         if (node.valid()) {
1119             lightingGroup->addChild(node);
1120             if (!pass->debugProperty.empty()) {
1121                 lightingGroup->setValue(lightingGroup->getNumChildren()-1, fgGetBool(pass->debugProperty));
1122                 fgAddChangeListener(new DebugPassListener(lightingGroup, lightingGroup->getNumChildren()-1), pass->debugProperty);
1123             }
1124         }
1125     }
1126
1127     camera->addChild( lightingGroup );
1128
1129     return camera;
1130 }
1131
1132 CameraInfo*
1133 FGRenderer::buildDeferredPipeline(CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1134                                     const osg::Matrix& view,
1135                                     const osg::Matrix& projection,
1136                                     osg::GraphicsContext* gc)
1137 {
1138     return buildCameraFromRenderingPipeline(_pipeline, cgroup, flags, camera, view, projection, gc);
1139 }
1140
1141 osg::Camera* 
1142 FGRenderer::buildDeferredFullscreenCamera( flightgear::CameraInfo* info, const FGRenderingPipeline::Pass* pass )
1143 {
1144     osg::Camera* camera = new osg::Camera;
1145
1146     camera->setClearMask( 0 );
1147     camera->setAllowEventFocus(false);
1148     camera->setName(pass->name+"C");
1149     camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1150     camera->setRenderOrder(osg::Camera::NESTED_RENDER, pass->orderNum);
1151     camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1152     camera->setViewMatrix(osg::Matrix::identity());
1153     camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1154
1155     osg::StateSet* ss = camera->getOrCreateStateSet();
1156     ss->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1157     ss->addUniform( info->projInverse );
1158     ss->addUniform( info->viewInverse );
1159     ss->addUniform( info->view );
1160     ss->addUniform( info->bufferSize );
1161     ss->addUniform( info->worldPosCart );
1162     ss->addUniform( info->worldPosGeod );
1163     ss->addUniform( info->shadowMatrix[0] );
1164     ss->addUniform( info->shadowMatrix[1] );
1165     ss->addUniform( info->shadowMatrix[2] );
1166     ss->addUniform( info->shadowMatrix[3] );
1167     ss->addUniform( _ambientFactor );
1168     ss->addUniform( _sunDiffuse );
1169     ss->addUniform( _sunSpecular );
1170     ss->addUniform( _sunDirection );
1171     ss->addUniform( _planes );
1172     ss->addUniform( _shadowNumber );
1173     ss->addUniform( _shadowDistances );
1174     ss->addUniform( _fogColor );
1175     ss->addUniform( _fogDensity );
1176
1177     osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1178     g->setUseDisplayList(false);
1179     simgear::EffectGeode* eg = new simgear::EffectGeode;
1180     osg::ref_ptr<SGReaderWriterOptions> opt;
1181     opt = SGReaderWriterOptions::fromPath(globals->get_fg_root());
1182     opt->setPropertyNode(globals->get_props());
1183     simgear::Effect* effect = simgear::makeEffect(pass->effect, true, opt.get());
1184     if (effect) {
1185         eg->setEffect( effect );
1186     }
1187
1188     eg->setName(pass->name+"Quad");
1189     eg->setCullingActive(false);
1190     eg->addDrawable(g);
1191     camera->addChild(eg);
1192
1193     return camera;
1194 }
1195
1196 osg::Camera* 
1197 FGRenderer::buildDeferredFullscreenCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc, const FGRenderingPipeline::Stage* stage )
1198 {
1199     osg::Camera* camera = buildDeferredFullscreenCamera(info, static_cast<const FGRenderingPipeline::Pass*>(stage));
1200     info->addCamera(stage->name, camera, stage->scaleFactor, true);
1201
1202     camera->setCullCallback( new FGDeferredRenderingCameraCullCallback(stage->name, info, stage->needsDuDv) );
1203     camera->setGraphicsContext(gc);
1204     camera->setViewport(new Viewport);
1205     camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1206     buildAttachments(info, camera, stage->name, stage->attachments);
1207     camera->setDrawBuffer(GL_FRONT);
1208     camera->setReadBuffer(GL_FRONT);
1209     camera->setClearColor( osg::Vec4( 1., 1., 1., 1. ) );
1210     camera->setClearMask( GL_COLOR_BUFFER_BIT );
1211     camera->setViewMatrix(osg::Matrix::identity());
1212     camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1213
1214     osg::StateSet* ss = camera->getOrCreateStateSet();
1215     if (stage->needsDuDv) {
1216         ss->addUniform( info->du );
1217         ss->addUniform( info->dv );
1218     }
1219
1220     return camera;
1221 }
1222
1223 void
1224 FGRenderer::buildDeferredDisplayCamera( osg::Camera* camera, flightgear::CameraInfo* info, const FGRenderingPipeline::Stage* stage, osg::GraphicsContext* gc )
1225 {
1226     camera->setName( "DisplayC" );
1227     camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( stage->name, info ) );
1228     camera->setReferenceFrame(Transform::ABSOLUTE_RF);
1229     camera->setAllowEventFocus(false);
1230     osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1231     g->setUseDisplayList(false); //DEBUG
1232     simgear::EffectGeode* eg = new simgear::EffectGeode;
1233     osg::ref_ptr<SGReaderWriterOptions> opt;
1234     opt = SGReaderWriterOptions::fromPath(globals->get_fg_root());
1235     opt->setPropertyNode(globals->get_props());
1236     simgear::Effect* effect = simgear::makeEffect(stage->effect, true, opt.get());
1237     if (!effect) {
1238         SG_LOG(SG_VIEW, SG_ALERT, stage->effect + " not found");
1239         return;
1240     }
1241     eg->setEffect(effect);
1242     eg->setCullingActive(false);
1243     eg->addDrawable(g);
1244     camera->setViewMatrix(osg::Matrix::identity());
1245     camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1246     camera->addChild(eg);
1247
1248     osg::StateSet* ss = camera->getOrCreateStateSet();
1249     ss->addUniform( _depthInColor );
1250     ss->addUniform( info->projInverse );
1251     ss->addUniform( info->viewInverse );
1252     ss->addUniform( info->view );
1253     ss->addUniform( info->bufferSize );
1254     ss->addUniform( info->worldPosCart );
1255     ss->addUniform( info->worldPosGeod );
1256     ss->addUniform( info->shadowMatrix[0] );
1257     ss->addUniform( info->shadowMatrix[1] );
1258     ss->addUniform( info->shadowMatrix[2] );
1259     ss->addUniform( info->shadowMatrix[3] );
1260     ss->addUniform( _ambientFactor );
1261     ss->addUniform( _sunDiffuse );
1262     ss->addUniform( _sunSpecular );
1263     ss->addUniform( _sunDirection );
1264     ss->addUniform( _planes );
1265     ss->addUniform( _shadowNumber );
1266     ss->addUniform( _shadowDistances );
1267     ss->addUniform( _fogColor );
1268     ss->addUniform( _fogDensity );
1269 }
1270
1271 void
1272 FGRenderer::buildStage(CameraInfo* info,
1273                         FGRenderingPipeline::Stage* stage,
1274                         CameraGroup* cgroup,
1275                         osg::Camera* mainCamera,
1276                         const osg::Matrix& view, const osg::Matrix& projection, osg::GraphicsContext* gc)
1277 {
1278     if (!stage->valid())
1279         return;
1280
1281     ref_ptr<Camera> camera;
1282     bool needOffsets = false;
1283     if (stage->type == "geometry") {
1284         camera = buildDeferredGeometryCamera(info, gc, stage->name, stage->attachments);
1285         needOffsets = true;
1286     } else if (stage->type == "lighting") {
1287         camera = buildDeferredLightingCamera(info, gc, stage);
1288         needOffsets = true;
1289     } else if (stage->type == "shadow")
1290         camera = buildDeferredShadowCamera(info, gc, stage->name, stage->attachments);
1291     else if (stage->type == "fullscreen")
1292         camera = buildDeferredFullscreenCamera(info, gc, stage);
1293     else if (stage->type == "display") {
1294         camera = mainCamera;
1295         buildDeferredDisplayCamera(camera, info, stage, gc);
1296     } else
1297         throw sg_exception("Stage type is not supported");
1298
1299     if (needOffsets)
1300         cgroup->getViewer()->addSlave(camera, projection, view, false);
1301     else
1302         cgroup->getViewer()->addSlave(camera, false);
1303     installCullVisitor(camera);
1304     int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1305     if (stage->type == "display")
1306         info->addCamera( stage->type, camera, slaveIndex, true );
1307     info->getRenderStageInfo(stage->name).slaveIndex = slaveIndex;
1308 }
1309
1310 osg::Node*
1311 FGRenderer::buildLightingSkyCloudsPass(FGRenderingPipeline::Pass* pass)
1312 {
1313     Group* group = new Group;
1314     group->setName("skyCloudsGroup");
1315     group->setNodeMask(simgear::BACKGROUND_BIT);
1316     
1317     StateSet* ss = group->getOrCreateStateSet();
1318     ss->setAttributeAndModes( new osg::ColorMask( true, true, true, false ), osg::StateAttribute::ON );
1319     group->addChild( _sky->getPreRoot() );
1320     group->addChild( _sky->getCloudRoot() );
1321     return group;
1322 }
1323
1324 osg::Node*
1325 FGRenderer::buildLightingLightsPass(CameraInfo* info, FGRenderingPipeline::Pass* pass)
1326 {
1327     osg::Camera* lightCam = new osg::Camera;
1328     StateSet* ss = lightCam->getOrCreateStateSet();
1329     ss->addUniform( _planes );
1330     ss->addUniform( info->bufferSize );
1331     ss->addUniform( _fogColor );
1332     ss->addUniform( _fogDensity );
1333     lightCam->setName( "LightCamera" );
1334     lightCam->setClearMask(0);
1335     lightCam->setAllowEventFocus(false);
1336     lightCam->setReferenceFrame(osg::Transform::RELATIVE_RF);
1337     lightCam->setRenderOrder(osg::Camera::NESTED_RENDER,pass->orderNum);
1338     lightCam->setViewMatrix(osg::Matrix::identity());
1339     lightCam->setProjectionMatrix(osg::Matrix::identity());
1340     lightCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1341     lightCam->setCullMask( simgear::MODELLIGHT_BIT | simgear::PANEL2D_BIT | simgear::PERMANENTLIGHT_BIT);
1342     lightCam->setInheritanceMask( osg::CullSettings::ALL_VARIABLES & ~osg::CullSettings::CULL_MASK );
1343     lightCam->addChild( _deferredRealRoot.get() );
1344
1345     return lightCam;
1346 }
1347
1348 osg::Node*
1349 FGRenderer::buildPass(CameraInfo* info, FGRenderingPipeline::Pass* pass)
1350 {
1351     if (!pass->valid())
1352         return 0;
1353
1354     ref_ptr<Node> node;
1355     if (pass->type == "sky-clouds")
1356         node = buildLightingSkyCloudsPass(pass);
1357     else if (pass->type == "fullscreen")
1358         node = buildDeferredFullscreenCamera(info, pass);
1359     else if (pass->type == "lights")
1360         node = buildLightingLightsPass(info, pass);
1361     else
1362         throw sg_exception("Pass type is not supported");
1363
1364     return node.release();
1365 }
1366
1367 void
1368 FGRenderer::buildBuffers(FGRenderingPipeline* rpipe, CameraInfo* info)
1369 {
1370     for (size_t i = 0; i < rpipe->buffers.size(); ++i) {
1371         osg::ref_ptr<FGRenderingPipeline::Buffer> buffer = rpipe->buffers[i];
1372         if (buffer->valid()) {
1373             bool fullscreen = buffer->width == -1 && buffer->height == -1;
1374             info->addBuffer(buffer->name, buildDeferredBuffer( buffer->internalFormat,
1375                                                                 buffer->sourceFormat,
1376                                                                 buffer->sourceType,
1377                                                                 buffer->wrapMode,
1378                                                                 buffer->shadowComparison),
1379                             fullscreen ? buffer->scaleFactor : 0.0f);
1380             if (!fullscreen) {
1381                 info->getBuffer(buffer->name)->setTextureSize(buffer->width, buffer->height);
1382             }
1383         }
1384     }
1385 }
1386
1387 CameraInfo* FGRenderer::buildCameraFromRenderingPipeline(FGRenderingPipeline* rpipe, CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1388                                     const osg::Matrix& view, const osg::Matrix& projection, osg::GraphicsContext* gc)
1389 {
1390     CameraInfo* info = new CameraInfo(flags);
1391     buildBuffers(rpipe, info);
1392     
1393     for (size_t i = 0; i < rpipe->stages.size(); ++i) {
1394         osg::ref_ptr<FGRenderingPipeline::Stage> stage = rpipe->stages[i];
1395         buildStage(info, stage, cgroup, camera, view, projection, gc);
1396     }
1397
1398     cgroup->addCamera(info);
1399
1400     return info;
1401 }
1402
1403 void
1404 FGRenderer::setupView( void )
1405 {
1406     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1407     osg::initNotifyLevel();
1408
1409     // The number of polygon-offset "units" to place between layers.  In
1410     // principle, one is supposed to be enough.  In practice, I find that
1411     // my hardware/driver requires many more.
1412     osg::PolygonOffset::setUnitsMultiplier(1);
1413     osg::PolygonOffset::setFactorMultiplier(1);
1414
1415 // build the sky    
1416     // The sun and moon diameters are scaled down numbers of the
1417     // actual diameters. This was needed to fit both the sun and the
1418     // moon within the distance to the far clip plane.
1419     // Moon diameter:    3,476 kilometers
1420     // Sun diameter: 1,390,000 kilometers
1421     osg::ref_ptr<SGReaderWriterOptions> opt;
1422     opt = SGReaderWriterOptions::fromPath(globals->get_fg_root());
1423     opt->setPropertyNode(globals->get_props());
1424     _sky->build( 80000.0, 80000.0,
1425                   463.3, 361.8,
1426                   *globals->get_ephem(),
1427                   fgGetNode("/environment", true),
1428                   opt.get());
1429     
1430     viewer->getCamera()
1431         ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1432     
1433     osg::StateSet* stateSet = _root->getOrCreateStateSet();
1434
1435     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
1436     
1437     stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
1438     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1439
1440     stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
1441     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
1442     stateSet->setAttribute(new osg::BlendFunc);
1443     stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
1444
1445     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
1446     
1447     // this will be set below
1448     stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
1449
1450     osg::Material* material = new osg::Material;
1451     stateSet->setAttribute(material);
1452     
1453     stateSet->setTextureAttribute(0, new osg::TexEnv);
1454     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
1455
1456     osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
1457     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
1458     stateSet->setAttribute(hint);
1459     hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
1460     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
1461     stateSet->setAttribute(hint);
1462     hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
1463     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
1464     stateSet->setAttribute(hint);
1465     hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
1466     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
1467     stateSet->setAttribute(hint);
1468     hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
1469     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
1470     stateSet->setAttribute(hint);
1471
1472     osg::Group* sceneGroup = new osg::Group;
1473     sceneGroup->setName("rendererScene");
1474     sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
1475     sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
1476
1477     //sceneGroup->addChild(thesky->getCloudRoot());
1478
1479     stateSet = sceneGroup->getOrCreateStateSet();
1480     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1481
1482     // need to update the light on every frame
1483     // OSG LightSource objects are rather confusing. OSG only supports
1484     // the 10 lights specified by OpenGL itself; if more than one
1485     // LightSource in the scene graph have the same light number, it's
1486     // indeterminate which values will be used to render geometry that
1487     // has that light number enabled. Also, adding children to a
1488     // LightSource is just a shortcut for setting up a state set that
1489     // has the corresponding OpenGL light enabled: a LightSource will
1490     // affect geometry anywhere in the scene graph that has its light
1491     // number enabled in a state set. 
1492     LightSource* lightSource = new LightSource;
1493     lightSource->setName("FGLightSource");
1494     lightSource->getLight()->setDataVariance(Object::DYNAMIC);
1495     // relative because of CameraView being just a clever transform node
1496     lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1497     lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
1498     lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
1499     _viewerSceneRoot->addChild(lightSource);
1500     
1501     // we need a white diffuse light for the phase of the moon
1502     osg::LightSource* sunLight = new osg::LightSource;
1503     sunLight->setName("sunLightSource");
1504     sunLight->getLight()->setDataVariance(Object::DYNAMIC);
1505     sunLight->getLight()->setLightNum(1);
1506     sunLight->setUpdateCallback(new FGLightSourceUpdateCallback(true));
1507     sunLight->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1508     sunLight->setLocalStateSetModes(osg::StateAttribute::ON);
1509     
1510     // Hang a StateSet above the sky subgraph in order to turn off
1511     // light 0
1512     Group* skyGroup = new Group;
1513     skyGroup->setName("rendererSkyParent");
1514     StateSet* skySS = skyGroup->getOrCreateStateSet();
1515     skySS->setMode(GL_LIGHT0, StateAttribute::OFF);
1516     skyGroup->addChild(_sky->getPreRoot());
1517     sunLight->addChild(skyGroup);
1518     
1519     _root->addChild(sceneGroup);
1520     if ( _classicalRenderer )
1521         _root->addChild(sunLight);
1522     
1523     // Clouds are added to the scene graph later
1524     stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
1525     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
1526     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
1527     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1528
1529     // enable disable specular highlights.
1530     // is the place where we might plug in an other fragment shader ...
1531     osg::LightModel* lightModel = new osg::LightModel;
1532     lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
1533     stateSet->setAttribute(lightModel);
1534
1535     // switch to enable wireframe
1536     osg::PolygonMode* polygonMode = new osg::PolygonMode;
1537     polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
1538     stateSet->setAttributeAndModes(polygonMode);
1539
1540     // scene fog handling
1541     osg::Fog* fog = new osg::Fog;
1542     fog->setUpdateCallback(new FGFogUpdateCallback);
1543     stateSet->setAttributeAndModes(fog);
1544     stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
1545
1546     // plug in the GUI
1547     osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
1548     if (guiCamera) {
1549         
1550         osg::Geode* geode = new osg::Geode;
1551         geode->addDrawable(new SGPuDrawable);
1552         geode->addDrawable(new SGHUDDrawable);
1553         guiCamera->addChild(geode);
1554       
1555         
1556       guiCamera->addChild(FGPanelNode::create2DPanelNode());
1557     }
1558     
1559     osg::Switch* sw = new osg::Switch;
1560     sw->setName("scenerySwitch");
1561     sw->setUpdateCallback(new FGScenerySwitchCallback);
1562     sw->addChild(_root.get());
1563     _viewerSceneRoot->addChild(sw);
1564     // The clouds are attached directly to the scene graph root
1565     // because, in theory, they don't want the same default state set
1566     // as the rest of the scene. This may not be true in practice.
1567         if ( _classicalRenderer ) {
1568                 _viewerSceneRoot->addChild(_sky->getCloudRoot());
1569                 _viewerSceneRoot->addChild(FGCreateRedoutNode());
1570         }
1571     // Attach empty program to the scene root so that shader programs
1572     // don't leak into state sets (effects) that shouldn't have one.
1573     stateSet = _viewerSceneRoot->getOrCreateStateSet();
1574     stateSet->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON);
1575
1576     if ( !_classicalRenderer ) {
1577         _deferredRealRoot->addChild( _viewerSceneRoot.get() );
1578     }
1579 }
1580
1581 // Update all Visuals (redraws anything graphics related)
1582 void
1583 FGRenderer::update( ) {
1584     if (!_position_finalized || !_scenery_loaded->getBoolValue())
1585     {
1586         _splash_alpha->setDoubleValue(1.0);
1587         return;
1588     }
1589     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1590
1591     if (_splash_alpha->getDoubleValue()>0.0)
1592     {
1593         // Fade out the splash screen
1594         const double fade_time = 0.5;
1595         const double fade_steps_per_sec = 10;
1596         double delay_time = SGMiscd::min(fade_time/fade_steps_per_sec,
1597                                          (SGTimeStamp::now() - _splash_time).toSecs());
1598         _splash_time = SGTimeStamp::now();
1599         double sAlpha = _splash_alpha->getDoubleValue();
1600         sAlpha -= SGMiscd::max(0.0,delay_time/fade_time);
1601         FGScenerySwitchCallback::scenery_enabled = (sAlpha<1.0);
1602         _splash_alpha->setDoubleValue((sAlpha < 0) ? 0.0 : sAlpha);
1603     }
1604
1605     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
1606         if (!_classicalRenderer ) {
1607                 _ambientFactor->set( toOsg(l->scene_ambient()) );
1608                 _sunDiffuse->set( toOsg(l->scene_diffuse()) );
1609                 _sunSpecular->set( toOsg(l->scene_specular()) );
1610                 _sunDirection->set( osg::Vec3f(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]) );
1611         }
1612
1613     // update fog params
1614     double actual_visibility;
1615     if (_cloud_status->getBoolValue()) {
1616         actual_visibility = _sky->get_visibility();
1617     } else {
1618         actual_visibility = _visibility_m->getDoubleValue();
1619     }
1620
1621     // idle_state is now 1000 meaning we've finished all our
1622     // initializations and are running the main loop, so this will
1623     // now work without seg faulting the system.
1624
1625     FGViewer *current__view = globals->get_current_view();
1626     // Force update of center dependent values ...
1627     current__view->set_dirty();
1628   
1629     osg::Camera *camera = viewer->getCamera();
1630
1631     bool skyblend = _skyblend->getBoolValue();
1632     if ( skyblend ) {
1633         
1634         if ( _textures->getBoolValue() ) {
1635             SGVec4f clearColor(l->adj_fog_color());
1636             camera->setClearColor(toOsg(clearColor));
1637         }
1638     } else {
1639         SGVec4f clearColor(l->sky_color());
1640         camera->setClearColor(toOsg(clearColor));
1641     }
1642
1643     // update fog params if visibility has changed
1644     double visibility_meters = _visibility_m->getDoubleValue();
1645     _sky->set_visibility(visibility_meters);
1646
1647     double altitude_m = _altitude_ft->getDoubleValue() * SG_FEET_TO_METER;
1648     _sky->modify_vis( altitude_m, 0.0 /* time factor, now unused */);
1649
1650     // update the sky dome
1651     if ( skyblend ) {
1652
1653         // The sun and moon distances are scaled down versions
1654         // of the actual distance to get both the moon and the sun
1655         // within the range of the far clip plane.
1656         // Moon distance:    384,467 kilometers
1657         // Sun distance: 150,000,000 kilometers
1658
1659         double sun_horiz_eff, moon_horiz_eff;
1660         if (_horizon_effect->getBoolValue()) {
1661             sun_horiz_eff
1662                 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
1663                                              0.0),
1664                              0.33) / 3.0;
1665             moon_horiz_eff
1666                 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
1667                                              0.0),
1668                              0.33)/3.0;
1669         } else {
1670            sun_horiz_eff = moon_horiz_eff = 1.0;
1671         }
1672
1673         SGSkyState sstate;
1674         sstate.pos       = current__view->getViewPosition();
1675         sstate.pos_geod  = current__view->getPosition();
1676         sstate.ori       = current__view->getViewOrientation();
1677         sstate.spin      = l->get_sun_rotation();
1678         sstate.gst       = globals->get_time_params()->getGst();
1679         sstate.sun_dist  = 50000.0 * sun_horiz_eff;
1680         sstate.moon_dist = 40000.0 * moon_horiz_eff;
1681         sstate.sun_angle = l->get_sun_angle();
1682
1683         SGSkyColor scolor;
1684         scolor.sky_color   = SGVec3f(l->sky_color().data());
1685         scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
1686         scolor.fog_color   = SGVec3f(l->adj_fog_color().data());
1687         scolor.cloud_color = SGVec3f(l->cloud_color().data());
1688         scolor.sun_angle   = l->get_sun_angle();
1689         scolor.moon_angle  = l->get_moon_angle();
1690   
1691         double delta_time_sec = _sim_delta_sec->getDoubleValue();
1692         _sky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
1693         _sky->repaint( scolor, *globals->get_ephem() );
1694
1695             //OSGFIXME
1696 //         shadows->setupShadows(
1697 //           current__view->getLongitude_deg(),
1698 //           current__view->getLatitude_deg(),
1699 //           globals->get_time_params()->getGst(),
1700 //           globals->get_ephem()->getSunRightAscension(),
1701 //           globals->get_ephem()->getSunDeclination(),
1702 //           l->get_sun_angle());
1703
1704     }
1705
1706 //     sgEnviro.setLight(l->adj_fog_color());
1707 //     sgEnviro.startOfFrame(current__view->get_view_pos(), 
1708 //         current__view->get_world_up(),
1709 //         current__view->getLongitude_deg(),
1710 //         current__view->getLatitude_deg(),
1711 //         current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
1712 //         delta_time_sec);
1713
1714     // OSGFIXME
1715 //     sgEnviro.drawLightning();
1716
1717 //        double current_view_origin_airspeed_horiz_kt =
1718 //         fgGetDouble("/velocities/airspeed-kt", 0.0)
1719 //                        * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
1720 //                                * SGD_DEGREES_TO_RADIANS);
1721
1722     // OSGFIXME
1723 //     if( is_internal )
1724 //         shadows->endOfFrame();
1725
1726     // need to call the update visitor once
1727     _frameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
1728     _updateVisitor->setViewData(current__view->getViewPosition(),
1729                                 current__view->getViewOrientation());
1730     SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
1731     _updateVisitor->setLight(direction, l->scene_ambient(),
1732                              l->scene_diffuse(), l->scene_specular(),
1733                              l->adj_fog_color(),
1734                              l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
1735     _updateVisitor->setVisibility(actual_visibility);
1736     simgear::GroundLightManager::instance()->update(_updateVisitor.get());
1737     osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
1738     cullMask |= simgear::GroundLightManager::instance()
1739         ->getLightNodeMask(_updateVisitor.get());
1740     if (_panel_hotspots->getBoolValue())
1741         cullMask |= simgear::PICK_BIT;
1742     CameraGroup::getDefault()->setCameraCullMasks(cullMask);
1743         if ( !_classicalRenderer ) {
1744                 _fogColor->set( toOsg( l->adj_fog_color() ) );
1745                 _fogDensity->set( float( _updateVisitor->getFogExp2Density() ) );
1746         }
1747 }
1748
1749 void
1750 FGRenderer::resize( int width, int height )
1751 {
1752     int curWidth = _xsize->getIntValue(),
1753         curHeight = _ysize->getIntValue();
1754     SG_LOG(SG_VIEW, SG_DEBUG, "FGRenderer::resize: new size " << width << " x " << height);
1755     if ((curHeight != height) || (curWidth != width)) {
1756     // must guard setting these, or PLIB-PUI fails with too many live interfaces
1757         _xsize->setIntValue(width);
1758         _ysize->setIntValue(height);
1759     }
1760 }
1761
1762 typedef osgUtil::LineSegmentIntersector::Intersection Intersection;
1763 SGVec2d uvFromIntersection(const Intersection& hit)
1764 {
1765   // Taken from http://trac.openscenegraph.org/projects/osg/browser/OpenSceneGraph/trunk/examples/osgmovie/osgmovie.cpp
1766
1767   osg::Drawable* drawable = hit.drawable.get();
1768   osg::Geometry* geometry = drawable ? drawable->asGeometry() : 0;
1769   osg::Vec3Array* vertices =
1770     geometry ? dynamic_cast<osg::Vec3Array*>(geometry->getVertexArray()) : 0;
1771
1772   if( !vertices )
1773   {
1774     SG_LOG(SG_INPUT, SG_WARN, "Unable to get vertices for intersection.");
1775     return SGVec2d(-9999,-9999);
1776   }
1777
1778   // get the vertex indices.
1779   const Intersection::IndexList& indices = hit.indexList;
1780   const Intersection::RatioList& ratios = hit.ratioList;
1781
1782   if( indices.size() != 3 || ratios.size() != 3 )
1783   {
1784     SG_LOG( SG_INPUT,
1785             SG_WARN,
1786             "Intersection has insufficient indices to work with." );
1787     return SGVec2d(-9999,-9999);
1788   }
1789
1790   unsigned int i1 = indices[0];
1791   unsigned int i2 = indices[1];
1792   unsigned int i3 = indices[2];
1793
1794   float r1 = ratios[0];
1795   float r2 = ratios[1];
1796   float r3 = ratios[2];
1797
1798   osg::Array* texcoords =
1799     (geometry->getNumTexCoordArrays() > 0) ? geometry->getTexCoordArray(0) : 0;
1800   osg::Vec2Array* texcoords_Vec2Array =
1801     dynamic_cast<osg::Vec2Array*>(texcoords);
1802
1803   if( !texcoords_Vec2Array )
1804   {
1805     SG_LOG(SG_INPUT, SG_WARN, "Unable to get texcoords for intersection.");
1806     return SGVec2d(-9999,-9999);
1807   }
1808
1809   // we have tex coord array so now we can compute the final tex coord at the
1810   // point of intersection.
1811   osg::Vec2 tc1 = (*texcoords_Vec2Array)[i1];
1812   osg::Vec2 tc2 = (*texcoords_Vec2Array)[i2];
1813   osg::Vec2 tc3 = (*texcoords_Vec2Array)[i3];
1814
1815   return toSG( osg::Vec2d(tc1 * r1 + tc2 * r2 + tc3 * r3) );
1816 }
1817
1818 bool
1819 FGRenderer::pick(std::vector<SGSceneryPick>& pickList, const osg::Vec2& windowPos)
1820 {
1821     // wipe out the return ...
1822     pickList.clear();
1823     typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
1824     Intersections intersections;
1825
1826     if (!computeIntersections(CameraGroup::getDefault(), windowPos, intersections))
1827         return false;
1828     for (Intersections::iterator hit = intersections.begin(),
1829              e = intersections.end();
1830          hit != e;
1831          ++hit) {
1832         const osg::NodePath& np = hit->nodePath;
1833         osg::NodePath::const_reverse_iterator npi;
1834         
1835         for (npi = np.rbegin(); npi != np.rend(); ++npi) {
1836             SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
1837             if (!ud || (ud->getNumPickCallbacks() == 0))
1838                 continue;
1839             
1840             for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
1841                 SGPickCallback* pickCallback = ud->getPickCallback(i);
1842                 if (!pickCallback)
1843                     continue;
1844                 SGSceneryPick sceneryPick;
1845                 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
1846                 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
1847
1848                 if( pickCallback->needsUV() )
1849                   sceneryPick.info.uv = uvFromIntersection(*hit);
1850
1851                 sceneryPick.callback = pickCallback;
1852                 pickList.push_back(sceneryPick);
1853             } // of installed pick callbacks iteration
1854         } // of reverse node path walk
1855     }
1856     
1857     return !pickList.empty();
1858 }
1859
1860 void
1861 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
1862 {
1863     viewer = viewer_;
1864 }
1865
1866 void
1867 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
1868 {
1869     eventHandler = eventHandler_;
1870 }
1871
1872 void
1873 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
1874 {
1875     _viewerSceneRoot->addChild(camera);
1876 }
1877
1878 void
1879 FGRenderer::removeCamera(osg::Camera* camera)
1880 {
1881     _viewerSceneRoot->removeChild(camera);
1882 }
1883                                     
1884 void
1885 FGRenderer::setPlanes( double zNear, double zFar )
1886 {
1887         _planes->set( osg::Vec3f( - zFar, - zFar * zNear, zFar - zNear ) );
1888 }
1889
1890 bool
1891 fgDumpSceneGraphToFile(const char* filename)
1892 {
1893     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1894     return osgDB::writeNodeFile(*viewer->getSceneData(), filename);
1895 }
1896
1897 bool
1898 fgDumpTerrainBranchToFile(const char* filename)
1899 {
1900     return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
1901                                  filename );
1902 }
1903
1904 // For debugging
1905 bool
1906 fgDumpNodeToFile(osg::Node* node, const char* filename)
1907 {
1908     return osgDB::writeNodeFile(*node, filename);
1909 }
1910
1911 namespace flightgear
1912 {
1913 using namespace osg;
1914
1915 class VisibleSceneInfoVistor : public NodeVisitor, CullStack
1916 {
1917 public:
1918     VisibleSceneInfoVistor()
1919         : NodeVisitor(CULL_VISITOR, TRAVERSE_ACTIVE_CHILDREN)
1920     {
1921         setCullingMode(CullSettings::SMALL_FEATURE_CULLING
1922                        | CullSettings::VIEW_FRUSTUM_CULLING);
1923         setComputeNearFarMode(CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1924     }
1925
1926     VisibleSceneInfoVistor(const VisibleSceneInfoVistor& rhs)
1927     {
1928     }
1929
1930     META_NodeVisitor("flightgear","VisibleSceneInfoVistor")
1931
1932     typedef std::map<const std::string,int> InfoMap;
1933
1934     void getNodeInfo(Node* node)
1935     {
1936         const char* typeName = typeid(*node).name();
1937         classInfo[typeName]++;
1938         const std::string& nodeName = node->getName();
1939         if (!nodeName.empty())
1940             nodeInfo[nodeName]++;
1941     }
1942
1943     void dumpInfo()
1944     {
1945         using namespace std;
1946         typedef vector<InfoMap::iterator> FreqVector;
1947         cout << "class info:\n";
1948         FreqVector classes;
1949         for (InfoMap::iterator itr = classInfo.begin(), end = classInfo.end();
1950              itr != end;
1951              ++itr)
1952             classes.push_back(itr);
1953         sort(classes.begin(), classes.end(), freqComp);
1954         for (FreqVector::iterator itr = classes.begin(), end = classes.end();
1955              itr != end;
1956              ++itr) {
1957             cout << (*itr)->first << " " << (*itr)->second << "\n";
1958         }
1959         cout << "\nnode info:\n";
1960         FreqVector nodes;
1961         for (InfoMap::iterator itr = nodeInfo.begin(), end = nodeInfo.end();
1962              itr != end;
1963              ++itr)
1964             nodes.push_back(itr);
1965
1966         sort (nodes.begin(), nodes.end(), freqComp);
1967         for (FreqVector::iterator itr = nodes.begin(), end = nodes.end();
1968              itr != end;
1969              ++itr) {
1970             cout << (*itr)->first << " " << (*itr)->second << "\n";
1971         }
1972         cout << endl;
1973     }
1974     
1975     void doTraversal(Camera* camera, Node* root, Viewport* viewport)
1976     {
1977         ref_ptr<RefMatrix> projection
1978             = createOrReuseMatrix(camera->getProjectionMatrix());
1979         ref_ptr<RefMatrix> mv = createOrReuseMatrix(camera->getViewMatrix());
1980         if (!viewport)
1981             viewport = camera->getViewport();
1982         if (viewport)
1983             pushViewport(viewport);
1984         pushProjectionMatrix(projection.get());
1985         pushModelViewMatrix(mv.get(), Transform::ABSOLUTE_RF);
1986         root->accept(*this);
1987         popModelViewMatrix();
1988         popProjectionMatrix();
1989         if (viewport)
1990             popViewport();
1991         dumpInfo();
1992     }
1993
1994     void apply(Node& node)
1995     {
1996         if (isCulled(node))
1997             return;
1998         pushCurrentMask();
1999         getNodeInfo(&node);
2000         traverse(node);
2001         popCurrentMask();
2002     }
2003     void apply(Group& node)
2004     {
2005         if (isCulled(node))
2006             return;
2007         pushCurrentMask();
2008         getNodeInfo(&node);
2009         traverse(node);
2010         popCurrentMask();
2011     }
2012
2013     void apply(Transform& node)
2014     {
2015         if (isCulled(node))
2016             return;
2017         pushCurrentMask();
2018         ref_ptr<RefMatrix> matrix = createOrReuseMatrix(*getModelViewMatrix());
2019         node.computeLocalToWorldMatrix(*matrix,this);
2020         pushModelViewMatrix(matrix.get(), node.getReferenceFrame());
2021         getNodeInfo(&node);
2022         traverse(node);
2023         popModelViewMatrix();
2024         popCurrentMask();
2025     }
2026
2027     void apply(Camera& camera)
2028     {
2029         // Save current cull settings
2030         CullSettings saved_cull_settings(*this);
2031
2032         // set cull settings from this Camera
2033         setCullSettings(camera);
2034         // inherit the settings from above
2035         inheritCullSettings(saved_cull_settings, camera.getInheritanceMask());
2036
2037         // set the cull mask.
2038         unsigned int savedTraversalMask = getTraversalMask();
2039         bool mustSetCullMask = (camera.getInheritanceMask()
2040                                 & osg::CullSettings::CULL_MASK) == 0;
2041         if (mustSetCullMask)
2042             setTraversalMask(camera.getCullMask());
2043
2044         osg::RefMatrix* projection = 0;
2045         osg::RefMatrix* modelview = 0;
2046
2047         if (camera.getReferenceFrame()==osg::Transform::RELATIVE_RF) {
2048             if (camera.getTransformOrder()==osg::Camera::POST_MULTIPLY) {
2049                 projection = createOrReuseMatrix(*getProjectionMatrix()
2050                                                  *camera.getProjectionMatrix());
2051                 modelview = createOrReuseMatrix(*getModelViewMatrix()
2052                                                 * camera.getViewMatrix());
2053             }
2054             else {              // pre multiply 
2055                 projection = createOrReuseMatrix(camera.getProjectionMatrix()
2056                                                  * (*getProjectionMatrix()));
2057                 modelview = createOrReuseMatrix(camera.getViewMatrix()
2058                                                 * (*getModelViewMatrix()));
2059             }
2060         } else {
2061             // an absolute reference frame
2062             projection = createOrReuseMatrix(camera.getProjectionMatrix());
2063             modelview = createOrReuseMatrix(camera.getViewMatrix());
2064         }
2065         if (camera.getViewport())
2066             pushViewport(camera.getViewport());
2067
2068         pushProjectionMatrix(projection);
2069         pushModelViewMatrix(modelview, camera.getReferenceFrame());    
2070
2071         traverse(camera);
2072     
2073         // restore the previous model view matrix.
2074         popModelViewMatrix();
2075
2076         // restore the previous model view matrix.
2077         popProjectionMatrix();
2078
2079         if (camera.getViewport()) popViewport();
2080
2081         // restore the previous traversal mask settings
2082         if (mustSetCullMask)
2083             setTraversalMask(savedTraversalMask);
2084
2085         // restore the previous cull settings
2086         setCullSettings(saved_cull_settings);
2087     }
2088
2089 protected:
2090     // sort in reverse
2091     static bool freqComp(const InfoMap::iterator& lhs, const InfoMap::iterator& rhs)
2092     {
2093         return lhs->second > rhs->second;
2094     }
2095     InfoMap classInfo;
2096     InfoMap nodeInfo;
2097 };
2098
2099 bool printVisibleSceneInfo(FGRenderer* renderer)
2100 {
2101     osgViewer::Viewer* viewer = renderer->getViewer();
2102     VisibleSceneInfoVistor vsv;
2103     Viewport* vp = 0;
2104     if (!viewer->getCamera()->getViewport() && viewer->getNumSlaves() > 0) {
2105         const View::Slave& slave = viewer->getSlave(0);
2106         vp = slave._camera->getViewport();
2107     }
2108     vsv.doTraversal(viewer->getCamera(), viewer->getSceneData(), vp);
2109     return true;
2110 }
2111
2112 }
2113 // end of renderer.cxx
2114