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