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