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