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