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