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