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