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