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