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