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