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