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