]> git.mxchange.org Git - flightgear.git/blob - src/Main/renderer.cxx
Merge commit 'refs/merge-requests/7' of git://gitorious.org/fg/flightgear into topics...
[flightgear.git] / src / Main / renderer.cxx
1 // renderer.cxx -- top level sim routines
2 //
3 // Written by Curtis Olson, started May 1997.
4 // This file contains parts of main.cxx prior to october 2004
5 //
6 // Copyright (C) 1997 - 2002  Curtis L. Olson  - http://www.flightgear.org/~curt
7 //
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21
22 #ifdef HAVE_CONFIG_H
23 #  include <config.h>
24 #endif
25
26 #ifdef HAVE_WINDOWS_H
27 #  include <windows.h>
28 #endif
29
30 #include <simgear/compiler.h>
31
32 #include <osg/ref_ptr>
33 #include <osg/AlphaFunc>
34 #include <osg/BlendFunc>
35 #include <osg/Camera>
36 #include <osg/CullFace>
37 #include <osg/Depth>
38 #include <osg/Fog>
39 #include <osg/Group>
40 #include <osg/Hint>
41 #include <osg/Light>
42 #include <osg/LightModel>
43 #include <osg/LightSource>
44 #include <osg/Material>
45 #include <osg/Math>
46 #include <osg/NodeCallback>
47 #include <osg/Notify>
48 #include <osg/PolygonMode>
49 #include <osg/PolygonOffset>
50 #include <osg/Program>
51 #include <osg/Version>
52 #include <osg/TexEnv>
53
54 #include <osgUtil/LineSegmentIntersector>
55
56 #include <osg/io_utils>
57 #include <osgDB/WriteFile>
58
59 #include <simgear/math/SGMath.hxx>
60 #include <simgear/scene/material/matlib.hxx>
61 #include <simgear/scene/model/animation.hxx>
62 #include <simgear/scene/model/placement.hxx>
63 #include <simgear/scene/sky/sky.hxx>
64 #include <simgear/scene/util/SGUpdateVisitor.hxx>
65 #include <simgear/scene/util/RenderConstants.hxx>
66 #include <simgear/scene/util/SGSceneUserData.hxx>
67 #include <simgear/scene/tgdb/GroundLightManager.hxx>
68 #include <simgear/scene/tgdb/pt_lights.hxx>
69 #include <simgear/structure/OSGUtils.hxx>
70 #include <simgear/props/props.hxx>
71 #include <simgear/timing/sg_time.hxx>
72 #include <simgear/ephemeris/ephemeris.hxx>
73 #include <simgear/math/sg_random.h>
74 #ifdef FG_JPEG_SERVER
75 #include <simgear/screen/jpgfactory.hxx>
76 #endif
77
78 #include <simgear/environment/visual_enviro.hxx>
79
80 #include <Time/light.hxx>
81 #include <Time/light.hxx>
82 #include <Cockpit/panel.hxx>
83 #include <Cockpit/cockpit.hxx>
84 #include <Cockpit/hud.hxx>
85 #include <Model/panelnode.hxx>
86 #include <Model/modelmgr.hxx>
87 #include <Model/acmodel.hxx>
88 #include <Scenery/scenery.hxx>
89 #include <Scenery/redout.hxx>
90 #include <Scenery/tilemgr.hxx>
91 #include <GUI/new_gui.hxx>
92 #include <Instrumentation/instrument_mgr.hxx>
93 #include <Instrumentation/HUD/HUD.hxx>
94 #include <Environment/precipitation_mgr.hxx>
95
96 #include "splash.hxx"
97 #include "renderer.hxx"
98 #include "main.hxx"
99 #include "CameraGroup.hxx"
100 #include "FGEventHandler.hxx"
101 #include <Main/viewer.hxx>
102
103 using namespace osg;
104 using namespace simgear;
105 using namespace flightgear;
106
107 class FGHintUpdateCallback : public osg::StateAttribute::Callback {
108 public:
109   FGHintUpdateCallback(const char* configNode) :
110     mConfigNode(fgGetNode(configNode, true))
111   { }
112   virtual void operator()(osg::StateAttribute* stateAttribute,
113                           osg::NodeVisitor*)
114   {
115     assert(dynamic_cast<osg::Hint*>(stateAttribute));
116     osg::Hint* hint = static_cast<osg::Hint*>(stateAttribute);
117
118     const char* value = mConfigNode->getStringValue();
119     if (!value)
120       hint->setMode(GL_DONT_CARE);
121     else if (0 == strcmp(value, "nicest"))
122       hint->setMode(GL_NICEST);
123     else if (0 == strcmp(value, "fastest"))
124       hint->setMode(GL_FASTEST);
125     else
126       hint->setMode(GL_DONT_CARE);
127   }
128 private:
129   SGSharedPtr<SGPropertyNode> mConfigNode;
130 };
131
132
133 class SGPuDrawable : public osg::Drawable {
134 public:
135   SGPuDrawable()
136   {
137     // Dynamic stuff, do not store geometry
138     setUseDisplayList(false);
139     setDataVariance(Object::DYNAMIC);
140
141     osg::StateSet* stateSet = getOrCreateStateSet();
142     stateSet->setRenderBinDetails(1001, "RenderBin");
143     // speed optimization?
144     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
145     // We can do translucent menus, so why not. :-)
146     stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
147     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
148     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
149
150     stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
151
152     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
153     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
154   }
155   virtual void drawImplementation(osg::RenderInfo& renderInfo) const
156   { drawImplementation(*renderInfo.getState()); }
157   void drawImplementation(osg::State& state) const
158   {
159     state.setActiveTextureUnit(0);
160     state.setClientActiveTextureUnit(0);
161
162     state.disableAllVertexArrays();
163
164     glPushAttrib(GL_ALL_ATTRIB_BITS);
165     glPushClientAttrib(~0u);
166
167     puDisplay();
168
169     glPopClientAttrib();
170     glPopAttrib();
171   }
172
173   virtual osg::Object* cloneType() const { return new SGPuDrawable; }
174   virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
175   
176 private:
177 };
178
179 class SGHUDAndPanelDrawable : public osg::Drawable {
180 public:
181   SGHUDAndPanelDrawable()
182   {
183     // Dynamic stuff, do not store geometry
184     setUseDisplayList(false);
185     setDataVariance(Object::DYNAMIC);
186
187     osg::StateSet* stateSet = getOrCreateStateSet();
188     stateSet->setRenderBinDetails(1000, "RenderBin");
189
190     // speed optimization?
191     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
192     stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
193     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
194     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
195     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
196
197     stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
198   }
199   virtual void drawImplementation(osg::RenderInfo& renderInfo) const
200   { drawImplementation(*renderInfo.getState()); }
201   void drawImplementation(osg::State& state) const
202   {
203     state.setActiveTextureUnit(0);
204     state.setClientActiveTextureUnit(0);
205     state.disableAllVertexArrays();
206
207     glPushAttrib(GL_ALL_ATTRIB_BITS);
208     glPushClientAttrib(~0u);
209
210     fgCockpitUpdate(&state);
211
212     FGInstrumentMgr *instr = static_cast<FGInstrumentMgr*>(globals->get_subsystem("instrumentation"));
213     HUD *hud = static_cast<HUD*>(instr->get_subsystem("hud"));
214     hud->draw(state);
215
216     // update the panel subsystem
217     if ( globals->get_current_panel() != NULL )
218         globals->get_current_panel()->update(state);
219     // We don't need a state here - can be safely removed when we can pick
220     // correctly
221     fgUpdate3DPanels();
222
223     glPopClientAttrib();
224     glPopAttrib();
225
226   }
227
228   virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
229   virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
230   
231 private:
232 };
233
234 class FGLightSourceUpdateCallback : public osg::NodeCallback {
235 public:
236   
237   /**
238    * @param isSun true if the light is the actual sun i.e., for
239    * illuminating the moon.
240    */
241   FGLightSourceUpdateCallback(bool isSun = false) : _isSun(isSun) {}
242   FGLightSourceUpdateCallback(const FGLightSourceUpdateCallback& nc,
243                               const CopyOp& op)
244     : NodeCallback(nc, op), _isSun(nc._isSun)
245   {}
246   META_Object(flightgear,FGLightSourceUpdateCallback);
247   
248   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
249   {
250     assert(dynamic_cast<osg::LightSource*>(node));
251     osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
252     osg::Light* light = lightSource->getLight();
253     
254     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
255     if (_isSun) {
256       light->setAmbient(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
257       light->setDiffuse(Vec4(1.0f, 1.0f, 1.0f, 1.0f));
258       light->setSpecular(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
259     } else {
260       light->setAmbient(toOsg(l->scene_ambient()));
261       light->setDiffuse(toOsg(l->scene_diffuse()));
262       light->setSpecular(toOsg(l->scene_specular()));
263     }
264     osg::Vec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
265     light->setPosition(position);
266
267     traverse(node, nv);
268   }
269 private:
270   const bool _isSun;
271 };
272
273 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
274 public:
275   FGWireFrameModeUpdateCallback() :
276     mWireframe(fgGetNode("/sim/rendering/wireframe"))
277   { }
278   virtual void operator()(osg::StateAttribute* stateAttribute,
279                           osg::NodeVisitor*)
280   {
281     assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
282     osg::PolygonMode* polygonMode;
283     polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
284
285     if (mWireframe->getBoolValue())
286       polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
287                            osg::PolygonMode::LINE);
288     else
289       polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
290                            osg::PolygonMode::FILL);
291   }
292 private:
293   SGSharedPtr<SGPropertyNode> mWireframe;
294 };
295
296 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
297 public:
298   FGLightModelUpdateCallback() :
299     mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
300   { }
301   virtual void operator()(osg::StateAttribute* stateAttribute,
302                           osg::NodeVisitor*)
303   {
304     assert(dynamic_cast<osg::LightModel*>(stateAttribute));
305     osg::LightModel* lightModel;
306     lightModel = static_cast<osg::LightModel*>(stateAttribute);
307
308 #if 0
309     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
310     lightModel->setAmbientIntensity(toOsg(l->scene_ambient());
311 #else
312     lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
313 #endif
314     lightModel->setTwoSided(true);
315     lightModel->setLocalViewer(false);
316
317     if (mHighlights->getBoolValue()) {
318       lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
319     } else {
320       lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
321     }
322   }
323 private:
324   SGSharedPtr<SGPropertyNode> mHighlights;
325 };
326
327 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
328 public:
329   FGFogEnableUpdateCallback() :
330     mFogEnabled(fgGetNode("/sim/rendering/fog"))
331   { }
332   virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
333   {
334     if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
335       stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
336     } else {
337       stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
338     }
339   }
340 private:
341   SGSharedPtr<SGPropertyNode> mFogEnabled;
342 };
343
344 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
345 public:
346   virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
347   {
348     assert(dynamic_cast<SGUpdateVisitor*>(nv));
349     assert(dynamic_cast<osg::Fog*>(sa));
350     SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
351     osg::Fog* fog = static_cast<osg::Fog*>(sa);
352     fog->setMode(osg::Fog::EXP2);
353     fog->setColor(toOsg(updateVisitor->getFogColor()));
354     fog->setDensity(updateVisitor->getFogExp2Density());
355   }
356 };
357
358 // update callback for the switch node guarding that splash
359 class FGScenerySwitchCallback : public osg::NodeCallback {
360 public:
361   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
362   {
363     assert(dynamic_cast<osg::Switch*>(node));
364     osg::Switch* sw = static_cast<osg::Switch*>(node);
365
366     double t = globals->get_sim_time_sec();
367     bool enabled = 0 < t;
368     sw->setValue(0, enabled);
369     if (!enabled)
370       return;
371     traverse(node, nv);
372   }
373 };
374
375 // Sky structures
376 SGSky *thesky;
377
378 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
379 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
380
381 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
382
383 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
384
385 FGRenderer::FGRenderer()
386 {
387 #ifdef FG_JPEG_SERVER
388    jpgRenderFrame = FGRenderer::update;
389 #endif
390    eventHandler = new FGEventHandler;
391 }
392
393 FGRenderer::~FGRenderer()
394 {
395 #ifdef FG_JPEG_SERVER
396    jpgRenderFrame = NULL;
397 #endif
398 }
399
400 // Initialize various GL/view parameters
401 // XXX This should be called "preinit" or something, as it initializes
402 // critical parts of the scene graph in addition to the splash screen.
403 void
404 FGRenderer::splashinit( void ) {
405     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
406     mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
407     mRealRoot->addChild(fgCreateSplashNode());
408     mFrameStamp = viewer->getFrameStamp();
409     // Scene doesn't seem to pass the frame stamp to the update
410     // visitor automatically.
411     mUpdateVisitor->setFrameStamp(mFrameStamp.get());
412     viewer->setUpdateVisitor(mUpdateVisitor.get());
413 }
414
415 void
416 FGRenderer::init( void )
417 {
418     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
419     osg::initNotifyLevel();
420
421     // The number of polygon-offset "units" to place between layers.  In
422     // principle, one is supposed to be enough.  In practice, I find that
423     // my hardware/driver requires many more.
424     osg::PolygonOffset::setUnitsMultiplier(1);
425     osg::PolygonOffset::setFactorMultiplier(1);
426
427     // Go full screen if requested ...
428     if ( fgGetBool("/sim/startup/fullscreen") )
429         fgOSFullScreen();
430
431     viewer->getCamera()
432         ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
433     
434     osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
435
436     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
437     
438     stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
439     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
440
441     stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
442     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
443     stateSet->setAttribute(new osg::BlendFunc);
444     stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
445
446     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
447     
448     // this will be set below
449     stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
450
451     osg::Material* material = new osg::Material;
452     stateSet->setAttribute(material);
453     
454     stateSet->setTextureAttribute(0, new osg::TexEnv);
455     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
456
457     osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
458     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
459     stateSet->setAttribute(hint);
460     hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
461     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
462     stateSet->setAttribute(hint);
463     hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
464     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
465     stateSet->setAttribute(hint);
466     hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
467     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
468     stateSet->setAttribute(hint);
469     hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
470     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
471     stateSet->setAttribute(hint);
472
473     osg::Group* sceneGroup = new osg::Group;
474     sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
475     sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
476
477     //sceneGroup->addChild(thesky->getCloudRoot());
478
479     stateSet = sceneGroup->getOrCreateStateSet();
480     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
481
482     // need to update the light on every frame
483     // OSG LightSource objects are rather confusing. OSG only supports
484     // the 10 lights specified by OpenGL itself; if more than one
485     // LightSource in the scene graph have the same light number, it's
486     // indeterminate which values will be used to render geometry that
487     // has that light number enabled. Also, adding children to a
488     // LightSource is just a shortcut for setting up a state set that
489     // has the corresponding OpenGL light enabled: a LightSource will
490     // affect geometry anywhere in the scene graph that has its light
491     // number enabled in a state set. 
492     LightSource* lightSource = new LightSource;
493     lightSource->getLight()->setDataVariance(Object::DYNAMIC);
494     // relative because of CameraView being just a clever transform node
495     lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
496     lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
497     lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
498     mRealRoot->addChild(lightSource);
499     // we need a white diffuse light for the phase of the moon
500     osg::LightSource* sunLight = new osg::LightSource;
501     sunLight->getLight()->setDataVariance(Object::DYNAMIC);
502     sunLight->getLight()->setLightNum(1);
503     sunLight->setUpdateCallback(new FGLightSourceUpdateCallback(true));
504     sunLight->setReferenceFrame(osg::LightSource::RELATIVE_RF);
505     sunLight->setLocalStateSetModes(osg::StateAttribute::ON);
506     // Hang a StateSet above the sky subgraph in order to turn off
507     // light 0
508     Group* skyGroup = new Group;
509     StateSet* skySS = skyGroup->getOrCreateStateSet();
510     skySS->setMode(GL_LIGHT0, StateAttribute::OFF);
511     skyGroup->addChild(thesky->getPreRoot());
512     sunLight->addChild(skyGroup);
513     mRoot->addChild(sceneGroup);
514     mRoot->addChild(sunLight);
515     // Clouds are added to the scene graph later
516     stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
517     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
518     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
519     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
520
521     // enable disable specular highlights.
522     // is the place where we might plug in an other fragment shader ...
523     osg::LightModel* lightModel = new osg::LightModel;
524     lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
525     stateSet->setAttribute(lightModel);
526
527     // switch to enable wireframe
528     osg::PolygonMode* polygonMode = new osg::PolygonMode;
529     polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
530     stateSet->setAttributeAndModes(polygonMode);
531
532     // scene fog handling
533     osg::Fog* fog = new osg::Fog;
534     fog->setUpdateCallback(new FGFogUpdateCallback);
535     stateSet->setAttributeAndModes(fog);
536     stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
537
538     // plug in the GUI
539     osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
540     if (guiCamera) {
541         osg::Geode* geode = new osg::Geode;
542         geode->addDrawable(new SGPuDrawable);
543         geode->addDrawable(new SGHUDAndPanelDrawable);
544         guiCamera->addChild(geode);
545     }
546     osg::Switch* sw = new osg::Switch;
547     sw->setUpdateCallback(new FGScenerySwitchCallback);
548     sw->addChild(mRoot.get());
549     mRealRoot->addChild(sw);
550     // The clouds are attached directly to the scene graph root
551     // because, in theory, they don't want the same default state set
552     // as the rest of the scene. This may not be true in practice.
553     mRealRoot->addChild(thesky->getCloudRoot());
554     mRealRoot->addChild(FGCreateRedoutNode());
555     // Attach empty program to the scene root so that shader programs
556     // don't leak into state sets (effects) that shouldn't have one.
557     stateSet = mRealRoot->getOrCreateStateSet();
558     stateSet->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON);
559 }
560
561
562 // Update all Visuals (redraws anything graphics related)
563 void
564 FGRenderer::update( bool refresh_camera_settings ) {
565     bool scenery_loaded = fgGetBool("sim/sceneryloaded", false)
566                           || fgGetBool("sim/sceneryloaded-override");
567     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
568     if (!scenery_loaded) {
569       fgSetDouble("/sim/startup/splash-alpha", 1.0);
570       return;
571     }
572
573     // Fade out the splash screen over the first three seconds.
574     double sAlpha = SGMiscd::max(0, (2.5 - globals->get_sim_time_sec()) / 2.5);
575     fgSetDouble("/sim/startup/splash-alpha", sAlpha);
576
577     bool skyblend = fgGetBool("/sim/rendering/skyblend");
578     bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
579     bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
580     bool distance_attenuation
581         = fgGetBool("/sim/rendering/distance-attenuation");
582     // OSGFIXME
583     SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
584                                   distance_attenuation );
585
586     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
587
588     // update fog params
589     double actual_visibility;
590     if (fgGetBool("/environment/clouds/status")) {
591         actual_visibility = thesky->get_visibility();
592     } else {
593         actual_visibility = fgGetDouble("/environment/visibility-m");
594     }
595
596     // idle_state is now 1000 meaning we've finished all our
597     // initializations and are running the main loop, so this will
598     // now work without seg faulting the system.
599
600     FGViewer *current__view = globals->get_current_view();
601     // Force update of center dependent values ...
602     current__view->set_dirty();
603
604     if ( refresh_camera_settings ) {
605         // update view port
606         resize( fgGetInt("/sim/startup/xsize"),
607                 fgGetInt("/sim/startup/ysize") );
608     }
609     osg::Camera *camera = viewer->getCamera();
610
611     if ( skyblend ) {
612         
613         if ( fgGetBool("/sim/rendering/textures") ) {
614             SGVec4f clearColor(l->adj_fog_color());
615             camera->setClearColor(toOsg(clearColor));
616         }
617     } else {
618         SGVec4f clearColor(l->sky_color());
619         camera->setClearColor(toOsg(clearColor));
620     }
621
622     // update fog params if visibility has changed
623     double visibility_meters = fgGetDouble("/environment/visibility-m");
624     thesky->set_visibility(visibility_meters);
625
626     double altitude_m = fgGetDouble("/position/altitude-ft") * SG_FEET_TO_METER;
627     thesky->modify_vis( altitude_m, 0.0 /* time factor, now unused */);
628
629     // update the sky dome
630     if ( skyblend ) {
631
632         // The sun and moon distances are scaled down versions
633         // of the actual distance to get both the moon and the sun
634         // within the range of the far clip plane.
635         // Moon distance:    384,467 kilometers
636         // Sun distance: 150,000,000 kilometers
637
638         double sun_horiz_eff, moon_horiz_eff;
639         if (fgGetBool("/sim/rendering/horizon-effect")) {
640             sun_horiz_eff
641                 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
642                                              0.0),
643                              0.33) / 3.0;
644             moon_horiz_eff
645                 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
646                                              0.0),
647                              0.33)/3.0;
648         } else {
649            sun_horiz_eff = moon_horiz_eff = 1.0;
650         }
651
652         SGSkyState sstate;
653         sstate.pos       = current__view->getViewPosition();
654         sstate.pos_geod  = current__view->getPosition();
655         sstate.ori       = current__view->getViewOrientation();
656         sstate.spin      = l->get_sun_rotation();
657         sstate.gst       = globals->get_time_params()->getGst();
658         sstate.sun_dist  = 50000.0 * sun_horiz_eff;
659         sstate.moon_dist = 40000.0 * moon_horiz_eff;
660         sstate.sun_angle = l->get_sun_angle();
661
662         SGSkyColor scolor;
663         scolor.sky_color   = SGVec3f(l->sky_color().data());
664         scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
665         scolor.fog_color   = SGVec3f(l->adj_fog_color().data());
666         scolor.cloud_color = SGVec3f(l->cloud_color().data());
667         scolor.sun_angle   = l->get_sun_angle();
668         scolor.moon_angle  = l->get_moon_angle();
669   
670         double delta_time_sec = fgGetDouble("/sim/time/delta-sec");
671         thesky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
672         thesky->repaint( scolor, *globals->get_ephem() );
673
674             //OSGFIXME
675 //         shadows->setupShadows(
676 //           current__view->getLongitude_deg(),
677 //           current__view->getLatitude_deg(),
678 //           globals->get_time_params()->getGst(),
679 //           globals->get_ephem()->getSunRightAscension(),
680 //           globals->get_ephem()->getSunDeclination(),
681 //           l->get_sun_angle());
682
683     }
684
685 //     sgEnviro.setLight(l->adj_fog_color());
686 //     sgEnviro.startOfFrame(current__view->get_view_pos(), 
687 //         current__view->get_world_up(),
688 //         current__view->getLongitude_deg(),
689 //         current__view->getLatitude_deg(),
690 //         current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
691 //         delta_time_sec);
692
693     // OSGFIXME
694 //     sgEnviro.drawLightning();
695
696 //        double current_view_origin_airspeed_horiz_kt =
697 //         fgGetDouble("/velocities/airspeed-kt", 0.0)
698 //                        * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
699 //                                * SGD_DEGREES_TO_RADIANS);
700
701     // OSGFIXME
702 //     if( is_internal )
703 //         shadows->endOfFrame();
704
705     // need to call the update visitor once
706     mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
707     mUpdateVisitor->setViewData(current__view->getViewPosition(),
708                                 current__view->getViewOrientation());
709     SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
710     mUpdateVisitor->setLight(direction, l->scene_ambient(),
711                              l->scene_diffuse(), l->scene_specular(),
712                              l->adj_fog_color(),
713                              l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
714     mUpdateVisitor->setVisibility(actual_visibility);
715     simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
716     bool hotspots = fgGetBool("/sim/panel-hotspots");
717     osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
718     cullMask |= simgear::GroundLightManager::instance()
719         ->getLightNodeMask(mUpdateVisitor.get());
720     if (hotspots)
721         cullMask |= simgear::PICK_BIT;
722     CameraGroup::getDefault()->setCameraCullMasks(cullMask);
723 }
724
725
726
727 // options.cxx needs to see this for toggle_panel()
728 // Handle new window size or exposure
729 void
730 FGRenderer::resize( int width, int height ) {
731     int view_h;
732
733     if ( (!fgGetBool("/sim/virtual-cockpit"))
734          && fgPanelVisible() && idle_state == 1000 ) {
735         view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
736                              globals->get_current_panel()->getYOffset()) / 768.0);
737     } else {
738         view_h = height;
739     }
740
741     static int lastwidth = 0;
742     static int lastheight = 0;
743     if (width != lastwidth)
744         fgSetInt("/sim/startup/xsize", lastwidth = width);
745     if (height != lastheight)
746         fgSetInt("/sim/startup/ysize", lastheight = height);
747
748     // for all views
749     FGViewMgr *viewmgr = globals->get_viewmgr();
750     if (viewmgr) {
751       for ( int i = 0; i < viewmgr->size(); ++i ) {
752         viewmgr->get_view(i)->
753           set_aspect_ratio((float)view_h / (float)width);
754       }
755     }
756 }
757
758 bool
759 FGRenderer::pick(std::vector<SGSceneryPick>& pickList,
760                  const osgGA::GUIEventAdapter* ea)
761 {
762     // wipe out the return ...
763     pickList.clear();
764     typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
765     Intersections intersections;
766
767     if (!computeIntersections(CameraGroup::getDefault(), ea, intersections))
768         return false;
769     for (Intersections::iterator hit = intersections.begin(),
770              e = intersections.end();
771          hit != e;
772          ++hit) {
773         const osg::NodePath& np = hit->nodePath;
774         osg::NodePath::const_reverse_iterator npi;
775         for (npi = np.rbegin(); npi != np.rend(); ++npi) {
776             SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
777             if (!ud)
778                 continue;
779             for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
780                 SGPickCallback* pickCallback = ud->getPickCallback(i);
781                 if (!pickCallback)
782                     continue;
783                 SGSceneryPick sceneryPick;
784                 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
785                 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
786                 sceneryPick.callback = pickCallback;
787                 pickList.push_back(sceneryPick);
788             }
789         }
790     }
791     return !pickList.empty();
792 }
793
794 void
795 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
796 {
797     viewer = viewer_;
798 }
799
800 void
801 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
802 {
803     eventHandler = eventHandler_;
804 }
805
806 void
807 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
808 {
809     mRealRoot->addChild(camera);
810 }
811
812 bool
813 fgDumpSceneGraphToFile(const char* filename)
814 {
815     return osgDB::writeNodeFile(*mRealRoot.get(), filename);
816 }
817
818 bool
819 fgDumpTerrainBranchToFile(const char* filename)
820 {
821     return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
822                                  filename );
823 }
824
825 // For debugging
826 bool
827 fgDumpNodeToFile(osg::Node* node, const char* filename)
828 {
829     return osgDB::writeNodeFile(*node, filename);
830 }
831 // end of renderer.cxx
832