]> git.mxchange.org Git - flightgear.git/blob - src/Main/renderer.cxx
Modified Files:
[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 // $Id$
23
24
25 #ifdef HAVE_CONFIG_H
26 #  include <config.h>
27 #endif
28
29 #include <simgear/compiler.h>
30
31 #ifdef HAVE_WINDOWS_H
32 #  include <windows.h>
33 #endif
34
35 #include <osg/ref_ptr>
36 #include <osg/AlphaFunc>
37 #include <osg/BlendFunc>
38 #include <osg/CameraNode>
39 #include <osg/CameraView>
40 #include <osg/CullFace>
41 #include <osg/Depth>
42 #include <osg/Fog>
43 #include <osg/Group>
44 #include <osg/LightModel>
45 #include <osg/NodeCallback>
46 #include <osg/Notify>
47 #include <osg/MatrixTransform>
48 #include <osg/Multisample>
49 #include <osg/Point>
50 #include <osg/PolygonMode>
51 #include <osg/ShadeModel>
52 #include <osg/TexEnv>
53 #include <osg/TexEnvCombine>
54 #include <osg/TexGen>
55 #include <osg/TexMat>
56 #include <osg/ColorMatrix>
57
58 #include <osgUtil/SceneView>
59 #include <osgUtil/UpdateVisitor>
60
61 #include <osg/io_utils>
62 #include <osgDB/WriteFile>
63 #include <osgDB/ReadFile>
64 #include <sstream>
65
66 #include <simgear/math/SGMath.hxx>
67 #include <simgear/screen/extensions.hxx>
68 #include <simgear/scene/material/matlib.hxx>
69 #include <simgear/scene/model/animation.hxx>
70 #include <simgear/scene/model/model.hxx>
71 #include <simgear/scene/model/modellib.hxx>
72 #include <simgear/scene/model/placement.hxx>
73 #include <simgear/scene/util/SGUpdateVisitor.hxx>
74 #include <simgear/scene/tgdb/pt_lights.hxx>
75 #include <simgear/props/props.hxx>
76 #include <simgear/timing/sg_time.hxx>
77 #include <simgear/ephemeris/ephemeris.hxx>
78 #include <simgear/math/sg_random.h>
79 #ifdef FG_JPEG_SERVER
80 #include <simgear/screen/jpgfactory.hxx>
81 #endif
82
83 #include <simgear/environment/visual_enviro.hxx>
84
85 #include <Scenery/tileentry.hxx>
86 #include <Time/light.hxx>
87 #include <Time/light.hxx>
88 #include <Aircraft/aircraft.hxx>
89 #include <Cockpit/panel.hxx>
90 #include <Cockpit/cockpit.hxx>
91 #include <Cockpit/hud.hxx>
92 #include <Model/panelnode.hxx>
93 #include <Model/modelmgr.hxx>
94 #include <Model/acmodel.hxx>
95 #include <Scenery/scenery.hxx>
96 #include <Scenery/tilemgr.hxx>
97 #include <ATC/ATCdisplay.hxx>
98 #include <GUI/new_gui.hxx>
99 #include <Instrumentation/instrument_mgr.hxx>
100 #include <Instrumentation/HUD/HUD.hxx>
101
102 #include "splash.hxx"
103 #include "renderer.hxx"
104 #include "main.hxx"
105
106 class SGPuDrawable : public osg::Drawable {
107 public:
108   SGPuDrawable()
109   {
110     // Dynamic stuff, do not store geometry
111     setUseDisplayList(false);
112
113     osg::StateSet* stateSet = getOrCreateStateSet();
114     // speed optimization?
115     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
116     // We can do translucent menus, so why not. :-)
117     stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
118     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
119     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
120
121     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
122     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
123   }
124   virtual void drawImplementation(osg::State& state) const
125   {
126     state.pushStateSet(getStateSet());
127     puDisplay();
128     state.popStateSet();
129   }
130
131   virtual osg::Object* cloneType() const { return new SGPuDrawable; }
132   virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
133   
134 private:
135 };
136
137
138 class FGSunLightUpdateCallback : public osg::StateAttribute::Callback {
139 public:
140   virtual void operator()(osg::StateAttribute* stateAttribute,
141                           osg::NodeVisitor*)
142   {
143     assert(dynamic_cast<osg::Light*>(stateAttribute));
144     osg::Light* light = static_cast<osg::Light*>(stateAttribute);
145
146     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
147     light->setAmbient(l->scene_ambient().osg());
148     light->setDiffuse(l->scene_diffuse().osg());
149     light->setSpecular(l->scene_specular().osg());
150     SGVec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
151     light->setPosition(position.osg());
152     SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
153     light->setDirection(direction.osg());
154     light->setSpotExponent(0);
155     light->setSpotCutoff(180);
156     light->setConstantAttenuation(1);
157     light->setLinearAttenuation(0);
158     light->setQuadraticAttenuation(0);
159   }
160 };
161
162 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
163 public:
164   FGWireFrameModeUpdateCallback() :
165     mWireframe(fgGetNode("/sim/rendering/wireframe"))
166   { }
167   virtual void operator()(osg::StateAttribute* stateAttribute,
168                           osg::NodeVisitor*)
169   {
170     assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
171     osg::PolygonMode* polygonMode;
172     polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
173
174     if (mWireframe->getBoolValue())
175       polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
176                            osg::PolygonMode::LINE);
177     else
178       polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
179                            osg::PolygonMode::FILL);
180   }
181 private:
182   SGSharedPtr<SGPropertyNode> mWireframe;
183 };
184
185 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
186 public:
187   FGLightModelUpdateCallback() :
188     mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
189   { }
190   virtual void operator()(osg::StateAttribute* stateAttribute,
191                           osg::NodeVisitor*)
192   {
193     assert(dynamic_cast<osg::LightModel*>(stateAttribute));
194     osg::LightModel* lightModel;
195     lightModel = static_cast<osg::LightModel*>(stateAttribute);
196
197 #if 0
198     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
199     lightModel->setAmbientIntensity(l->scene_ambient().osg());
200 #else
201     lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
202 #endif
203     lightModel->setTwoSided(true);
204     lightModel->setLocalViewer(false);
205
206     if (mHighlights->getBoolValue()) {
207       lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
208     } else {
209       lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
210     }
211   }
212 private:
213   SGSharedPtr<SGPropertyNode> mHighlights;
214 };
215
216 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
217 public:
218   FGFogEnableUpdateCallback() :
219     mFogEnabled(fgGetNode("/sim/rendering/fog"))
220   { }
221   virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
222   {
223     if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
224       stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
225     } else {
226       stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
227     }
228   }
229 private:
230   SGSharedPtr<SGPropertyNode> mFogEnabled;
231 };
232
233 // fog constants.  I'm a little nervous about putting actual code out
234 // here but it seems to work (?)
235 static const double m_log01 = -log( 0.01 );
236 static const double sqrt_m_log01 = sqrt( m_log01 );
237 static GLfloat fog_exp_density;
238 static GLfloat fog_exp2_density;
239 static GLfloat rwy_exp2_punch_through;
240 static GLfloat taxi_exp2_punch_through;
241 static GLfloat ground_exp2_punch_through;
242
243 // Sky structures
244 SGSky *thesky;
245
246 static osg::ref_ptr<osgUtil::SceneView> sceneView = new osgUtil::SceneView;
247 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
248
249 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
250
251 static osg::ref_ptr<osg::CameraView> mCameraView = new osg::CameraView;
252 static osg::ref_ptr<osg::CameraNode> mBackGroundCamera = new osg::CameraNode;
253 static osg::ref_ptr<osg::CameraNode> mSceneCamera = new osg::CameraNode;
254
255 static osg::ref_ptr<osg::Fog> mFog = new osg::Fog;
256 static osg::ref_ptr<osg::Fog> mRunwayLightingFog = new osg::Fog;
257 static osg::ref_ptr<osg::Fog> mTaxiLightingFog = new osg::Fog;
258 static osg::ref_ptr<osg::Fog> mGroundLightingFog = new osg::Fog;
259
260 FGRenderer::FGRenderer()
261 {
262 #ifdef FG_JPEG_SERVER
263    jpgRenderFrame = FGRenderer::update;
264 #endif
265 }
266
267 FGRenderer::~FGRenderer()
268 {
269 #ifdef FG_JPEG_SERVER
270    jpgRenderFrame = NULL;
271 #endif
272 }
273
274 // Initialize various GL/view parameters
275 void
276 FGRenderer::init( void ) {
277
278     osg::initNotifyLevel();
279
280     // Go full screen if requested ...
281     if ( fgGetBool("/sim/startup/fullscreen") )
282         fgOSFullScreen();
283
284     if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) || 
285          (!fgGetBool("/sim/rendering/shading"))) {
286         // if fastest fog requested, or if flat shading force fastest
287         glHint ( GL_FOG_HINT, GL_FASTEST );
288     } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
289         glHint ( GL_FOG_HINT, GL_DONT_CARE );
290     }
291
292     glHint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
293     glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
294     glHint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
295
296     sceneView->setDefaults(osgUtil::SceneView::COMPILE_GLOBJECTS_AT_INIT);
297
298     mFog->setMode(osg::Fog::EXP2);
299     mRunwayLightingFog->setMode(osg::Fog::EXP2);
300     mTaxiLightingFog->setMode(osg::Fog::EXP2);
301     mGroundLightingFog->setMode(osg::Fog::EXP2);
302
303     sceneView->setFrameStamp(mFrameStamp.get());
304
305     sceneView->setUpdateVisitor(new SGUpdateVisitor);
306
307     sceneView->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
308
309     sceneView->getCamera()->setViewMatrix(osg::Matrix(0, 0,-1, 0,
310                                                       1, 0, 0, 0,
311                                                       0,-1, 0, 0,
312                                                       0, 0, 0, 1));
313     sceneView->getCamera()->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
314     sceneView->getCamera()->setClearMask(GL_COLOR_BUFFER_BIT);
315
316     osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
317     stateSet->setRenderingHint(osg::StateSet::OPAQUE_BIN);
318
319     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
320     
321     stateSet->setAttribute(new osg::Depth(osg::Depth::LEQUAL));
322     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
323
324     stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
325     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
326     stateSet->setAttribute(new osg::BlendFunc);
327     stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
328
329     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
330     
331     // this will be set below
332     stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
333
334     osg::Material* material = new osg::Material;
335     stateSet->setAttribute(material);
336     
337     stateSet->setTextureAttribute(0, new osg::TexEnv);
338     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
339
340
341 //     stateSet->setAttribute(new osg::CullFace(osg::CullFace::BACK));
342 //     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::ON);
343
344
345     // need to update the light on every frame
346     osg::Light* sunLight = new osg::Light;
347     sunLight->setLightNum(0);
348     sunLight->setUpdateCallback(new FGSunLightUpdateCallback);
349     stateSet->setAttributeAndModes(sunLight, osg::StateAttribute::ON);
350     osg::LightModel* lightModel = new osg::LightModel;
351     lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
352     stateSet->setAttributeAndModes(lightModel, osg::StateAttribute::ON);
353
354     // this is the topmost scenegraph node for osg
355     mBackGroundCamera->addChild(thesky->getPreRoot());
356     mBackGroundCamera->setClearMask(0);
357
358     GLbitfield inheritanceMask = osg::CullSettings::ALL_VARIABLES;
359     inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
360     inheritanceMask &= ~osg::CullSettings::NEAR_FAR_RATIO;
361     inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
362     mBackGroundCamera->setInheritanceMask(inheritanceMask);
363     mBackGroundCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
364     mBackGroundCamera->setCullingMode(osg::CullSettings::NO_CULLING);
365
366     mBackGroundCamera->getOrCreateStateSet()->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
367
368     mRoot->addChild(mBackGroundCamera.get());
369
370     mSceneCamera->setClearMask(GL_DEPTH_BUFFER_BIT);
371     inheritanceMask = osg::CullSettings::ALL_VARIABLES;
372     inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
373     inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
374     mSceneCamera->setInheritanceMask(inheritanceMask);
375     mSceneCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
376     mSceneCamera->setCullingMode(osg::CullSettings::DEFAULT_CULLING);
377
378
379     stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
380     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
381     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
382     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
383     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
384
385     // switch to enable wireframe
386     osg::PolygonMode* polygonMode = new osg::PolygonMode;
387     polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
388     stateSet->setAttributeAndModes(polygonMode);
389
390     // scene fog handling
391     stateSet->setAttributeAndModes(mFog.get());
392     stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
393
394     mRoot->addChild(mSceneCamera.get());
395
396     // plug in the GUI
397     osg::CameraNode* guiCamera = new osg::CameraNode;
398     guiCamera->setRenderOrder(osg::CameraNode::POST_RENDER);
399     guiCamera->setClearMask(0);
400     inheritanceMask = osg::CullSettings::ALL_VARIABLES;
401     inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
402     inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
403     guiCamera->setInheritanceMask(inheritanceMask);
404     guiCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
405     guiCamera->setCullingMode(osg::CullSettings::NO_CULLING);
406     mRoot->addChild(guiCamera);
407     osg::Geode* geode = new osg::Geode;
408     geode->addDrawable(new SGPuDrawable);
409     guiCamera->addChild(geode);
410
411     mSceneCamera->addChild(globals->get_scenery()->get_scene_graph());
412
413     stateSet = mSceneCamera->getOrCreateStateSet();
414     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
415     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
416
417     // this one contains all lights, here we set the light states we did
418     // in the plib case with plain OpenGL
419     osg::Group* lightGroup = new osg::Group;
420     mSceneCamera->addChild(lightGroup);
421     lightGroup->addChild(globals->get_scenery()->get_gnd_lights_root());
422     lightGroup->addChild(globals->get_scenery()->get_vasi_lights_root());
423     lightGroup->addChild(globals->get_scenery()->get_rwy_lights_root());
424     lightGroup->addChild(globals->get_scenery()->get_taxi_lights_root());
425
426     stateSet = globals->get_scenery()->get_gnd_lights_root()->getOrCreateStateSet();
427     stateSet->setAttributeAndModes(mFog.get());
428     stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
429     stateSet = globals->get_scenery()->get_vasi_lights_root()->getOrCreateStateSet();
430     stateSet->setAttributeAndModes(mRunwayLightingFog.get());
431     stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
432     stateSet = globals->get_scenery()->get_rwy_lights_root()->getOrCreateStateSet();
433     stateSet->setAttributeAndModes(mRunwayLightingFog.get());
434     stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
435     stateSet = globals->get_scenery()->get_taxi_lights_root()->getOrCreateStateSet();
436     stateSet->setAttributeAndModes(mTaxiLightingFog.get());
437     stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
438
439     mCameraView->addChild(mRoot.get());
440     sceneView->setSceneData(mCameraView.get());
441
442     mSceneCamera->addChild(thesky->getCloudRoot());
443
444 //  sceneView->getState()->setCheckForGLErrors(osg::State::ONCE_PER_ATTRIBUTE);
445 }
446
447
448 // Update all Visuals (redraws anything graphics related)
449 void
450 FGRenderer::update( bool refresh_camera_settings ) {
451     bool scenery_loaded = fgGetBool("sim/sceneryloaded")
452                           || fgGetBool("sim/sceneryloaded-override");
453
454     if ( idle_state < 1000 || !scenery_loaded ) {
455         // still initializing, draw the splash screen
456         fgSplashUpdate(1.0);
457
458         // Keep resetting sim time while the sim is initializing
459         globals->set_sim_time_sec( 0.0 );
460         return;
461     }
462
463     bool skyblend = fgGetBool("/sim/rendering/skyblend");
464     bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
465     bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
466     bool distance_attenuation
467         = fgGetBool("/sim/rendering/distance-attenuation");
468     // OSGFIXME
469     SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
470                                   distance_attenuation );
471
472     static const SGPropertyNode *groundlevel_nearplane
473         = fgGetNode("/sim/current-view/ground-level-nearplane-m");
474
475     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
476
477     // update fog params
478     double actual_visibility;
479     if (fgGetBool("/environment/clouds/status")) {
480         actual_visibility = thesky->get_visibility();
481     } else {
482         actual_visibility = fgGetDouble("/environment/visibility-m");
483     }
484
485     static double last_visibility = -9999;
486     if ( actual_visibility != last_visibility ) {
487         last_visibility = actual_visibility;
488
489         fog_exp_density = m_log01 / actual_visibility;
490         fog_exp2_density = sqrt_m_log01 / actual_visibility;
491         ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
492         if ( actual_visibility < 8000 ) {
493             rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
494             taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
495         } else {
496             rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
497             taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
498         }
499         mFog->setDensity(fog_exp2_density);
500         mRunwayLightingFog->setDensity(rwy_exp2_punch_through);
501         mTaxiLightingFog->setDensity(taxi_exp2_punch_through);
502         mGroundLightingFog->setDensity(ground_exp2_punch_through);
503     }
504
505     // idle_state is now 1000 meaning we've finished all our
506     // initializations and are running the main loop, so this will
507     // now work without seg faulting the system.
508
509     FGViewer *current__view = globals->get_current_view();
510     // Force update of center dependent values ...
511     current__view->set_dirty();
512
513     if ( refresh_camera_settings ) {
514         // update view port
515         resize( fgGetInt("/sim/startup/xsize"),
516                 fgGetInt("/sim/startup/ysize") );
517
518         SGVec3d center = globals->get_scenery()->get_center();
519         SGVec3d position = current__view->getViewPosition();
520         SGQuatd attitude = current__view->getViewOrientation();
521         SGVec3d osgPosition = attitude.transform(center - position);
522         mCameraView->setPosition(osgPosition.osg());
523         mCameraView->setAttitude(inverse(attitude).osg());
524     }
525
526     if ( skyblend ) {
527         if ( fgGetBool("/sim/rendering/textures") ) {
528             SGVec4f clearColor(l->adj_fog_color());
529             sceneView->getCamera()->setClearColor(clearColor.osg());
530         }
531     } else {
532         SGVec4f clearColor(l->sky_color());
533         sceneView->getCamera()->setClearColor(clearColor.osg());
534     }
535
536     // update fog params if visibility has changed
537     double visibility_meters = fgGetDouble("/environment/visibility-m");
538     thesky->set_visibility(visibility_meters);
539
540     thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
541                         ( global_multi_loop * fgGetInt("/sim/speed-up") )
542                         / (double)fgGetInt("/sim/model-hz") );
543
544     // update the sky dome
545     if ( skyblend ) {
546
547         // The sun and moon distances are scaled down versions
548         // of the actual distance to get both the moon and the sun
549         // within the range of the far clip plane.
550         // Moon distance:    384,467 kilometers
551         // Sun distance: 150,000,000 kilometers
552
553         double sun_horiz_eff, moon_horiz_eff;
554         if (fgGetBool("/sim/rendering/horizon-effect")) {
555            sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
556            moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
557         } else {
558            sun_horiz_eff = moon_horiz_eff = 1.0;
559         }
560
561         static SGSkyState sstate;
562
563         sstate.view_pos  = current__view->get_view_pos();
564         sstate.zero_elev = current__view->get_zero_elev();
565         sstate.view_up   = current__view->get_world_up();
566         sstate.lon       = current__view->getLongitude_deg()
567                             * SGD_DEGREES_TO_RADIANS;
568         sstate.lat       = current__view->getLatitude_deg()
569                             * SGD_DEGREES_TO_RADIANS;
570         sstate.alt       = current__view->getAltitudeASL_ft()
571                             * SG_FEET_TO_METER;
572         sstate.spin      = l->get_sun_rotation();
573         sstate.gst       = globals->get_time_params()->getGst();
574         sstate.sun_ra    = globals->get_ephem()->getSunRightAscension();
575         sstate.sun_dec   = globals->get_ephem()->getSunDeclination();
576         sstate.sun_dist  = 50000.0 * sun_horiz_eff;
577         sstate.moon_ra   = globals->get_ephem()->getMoonRightAscension();
578         sstate.moon_dec  = globals->get_ephem()->getMoonDeclination();
579         sstate.moon_dist = 40000.0 * moon_horiz_eff;
580         sstate.sun_angle = l->get_sun_angle();
581
582
583         /*
584          SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
585          << l->sky_color()[0] << " "
586          << l->sky_color()[1] << " "
587          << l->sky_color()[2] << " "
588          << l->sky_color()[3] );
589         SG_LOG( SG_GENERAL, SG_BULK, "    fog = "
590          << l->fog_color()[0] << " "
591          << l->fog_color()[1] << " "
592          << l->fog_color()[2] << " "
593          << l->fog_color()[3] );
594         SG_LOG( SG_GENERAL, SG_BULK,
595                 "    sun_angle = " << l->sun_angle
596          << "    moon_angle = " << l->moon_angle );
597         */
598
599         static SGSkyColor scolor;
600
601         scolor.sky_color   = SGVec3f(l->sky_color().data());
602         scolor.fog_color   = SGVec3f(l->adj_fog_color().data());
603         scolor.cloud_color = SGVec3f(l->cloud_color().data());
604         scolor.sun_angle   = l->get_sun_angle();
605         scolor.moon_angle  = l->get_moon_angle();
606         scolor.nplanets    = globals->get_ephem()->getNumPlanets();
607         scolor.nstars      = globals->get_ephem()->getNumStars();
608         scolor.planet_data = globals->get_ephem()->getPlanets();
609         scolor.star_data   = globals->get_ephem()->getStars();
610
611         thesky->reposition( sstate, delta_time_sec );
612         thesky->repaint( scolor );
613
614         /*
615         SG_LOG( SG_GENERAL, SG_BULK,
616                 "thesky->reposition( view_pos = " << view_pos[0] << " "
617          << view_pos[1] << " " << view_pos[2] );
618         SG_LOG( SG_GENERAL, SG_BULK,
619                 "    zero_elev = " << zero_elev[0] << " "
620          << zero_elev[1] << " " << zero_elev[2]
621          << " lon = " << cur_fdm_state->get_Longitude()
622          << " lat = " << cur_fdm_state->get_Latitude() );
623         SG_LOG( SG_GENERAL, SG_BULK,
624                 "    sun_rot = " << l->get_sun_rotation
625          << " gst = " << SGTime::cur_time_params->getGst() );
626         SG_LOG( SG_GENERAL, SG_BULK,
627              "    sun ra = " << globals->get_ephem()->getSunRightAscension()
628           << " sun dec = " << globals->get_ephem()->getSunDeclination()
629           << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
630           << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
631         */
632
633         //OSGFIXME
634 //         shadows->setupShadows(
635 //           current__view->getLongitude_deg(),
636 //           current__view->getLatitude_deg(),
637 //           globals->get_time_params()->getGst(),
638 //           globals->get_ephem()->getSunRightAscension(),
639 //           globals->get_ephem()->getSunDeclination(),
640 //           l->get_sun_angle());
641
642     }
643
644     if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
645         SGVec4f color(l->adj_fog_color());
646         mFog->setColor(color.osg());
647         mRunwayLightingFog->setColor(color.osg());
648         mTaxiLightingFog->setColor(color.osg());
649         mGroundLightingFog->setColor(color.osg());
650     }
651
652
653 //     sgEnviro.setLight(l->adj_fog_color());
654
655     // texture parameters
656     glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
657
658     double agl = current__view->getAltitudeASL_ft()*SG_FEET_TO_METER
659       - current__view->getSGLocation()->get_cur_elev_m();
660
661     float scene_nearplane, scene_farplane;
662     if ( agl > 10.0 ) {
663         scene_nearplane = 10.0f;
664         scene_farplane = 120000.0f;
665     } else {
666         scene_nearplane = groundlevel_nearplane->getDoubleValue();
667         scene_farplane = 120000.0f;
668     }
669
670     setNearFar( scene_nearplane, scene_farplane );
671
672 //     sgEnviro.startOfFrame(current__view->get_view_pos(), 
673 //         current__view->get_world_up(),
674 //         current__view->getLongitude_deg(),
675 //         current__view->getLatitude_deg(),
676 //         current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
677 //         delta_time_sec);
678
679     // OSGFIXME
680 //     sgEnviro.drawLightning();
681
682 //        double current_view_origin_airspeed_horiz_kt =
683 //         fgGetDouble("/velocities/airspeed-kt", 0.0)
684 //                        * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
685 //                                * SGD_DEGREES_TO_RADIANS);
686        // TODO:find the real view speed, not the AC one
687 //     sgEnviro.drawPrecipitation(
688 //         fgGetDouble("/environment/metar/rain-norm", 0.0),
689 //         fgGetDouble("/environment/metar/snow-norm", 0.0),
690 //         fgGetDouble("/environment/metar/hail-norm", 0.0),
691 //         current__view->getPitch_deg() + current__view->getPitchOffset_deg(),
692 //         current__view->getRoll_deg() + current__view->getRollOffset_deg(),
693 //         - current__view->getHeadingOffset_deg(),
694 //                current_view_origin_airspeed_horiz_kt
695 //                );
696
697     // OSGFIXME
698 //     if( is_internal )
699 //         shadows->endOfFrame();
700
701     // need to call the update visitor once
702     globals->get_aircraft_model()->select( true );
703     FGTileMgr::set_tile_filter( true );
704     mFrameStamp->setReferenceTime(globals->get_sim_time_sec());
705     mFrameStamp->setFrameNumber(1+mFrameStamp->getFrameNumber());
706     mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
707     sceneView->update();
708     sceneView->cull();
709     sceneView->draw();
710
711     glPushAttrib(GL_ALL_ATTRIB_BITS);
712     glPushClientAttrib(~0u);
713
714     // display HUD && Panel
715     glDisable( GL_FOG );
716     glDisable( GL_DEPTH_TEST );
717
718     fgCockpitUpdate(sceneView->getState());
719
720     FGInstrumentMgr *instr = static_cast<FGInstrumentMgr*>(globals->get_subsystem("instrumentation"));
721     HUD *hud = static_cast<HUD*>(instr->get_subsystem("hud"));
722     hud->draw(*sceneView->getState());
723
724     // update the panel subsystem
725     if ( globals->get_current_panel() != NULL )
726         globals->get_current_panel()->update(*sceneView->getState());
727     // We don't need a state here - can be safely removed when we can pick
728     // correctly
729     fgUpdate3DPanels();
730
731     if((fgGetBool("/sim/atc/enabled"))
732        || (fgGetBool("/sim/ai-traffic/enabled")))
733       globals->get_ATC_display()->update(delta_time_sec,
734                                          *sceneView->getState());
735
736     // We can do translucent menus, so why not. :-)
737     glDisable( GL_TEXTURE_2D ) ;
738     glDisable( GL_CULL_FACE ) ;
739     glEnable( GL_BLEND ) ;
740     glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
741
742     // Fade out the splash screen over the first three seconds.
743     double t = globals->get_sim_time_sec();
744     if (t <= 2.5)
745         fgSplashUpdate((2.5 - t) / 2.5);
746
747     glPopClientAttrib();
748     glPopAttrib();
749 }
750
751
752
753 // options.cxx needs to see this for toggle_panel()
754 // Handle new window size or exposure
755 void
756 FGRenderer::resize( int width, int height ) {
757     int view_h;
758
759     if ( (!fgGetBool("/sim/virtual-cockpit"))
760          && fgPanelVisible() && idle_state == 1000 ) {
761         view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
762                              globals->get_current_panel()->getYOffset()) / 768.0);
763     } else {
764         view_h = height;
765     }
766
767     sceneView->getViewport()->setViewport(0, height - view_h, width, view_h);
768
769     static int lastwidth = 0;
770     static int lastheight = 0;
771     if (width != lastwidth)
772         fgSetInt("/sim/startup/xsize", lastwidth = width);
773     if (height != lastheight)
774         fgSetInt("/sim/startup/ysize", lastheight = height);
775
776     guiInitMouse(width, height);
777
778     // for all views
779     FGViewMgr *viewmgr = globals->get_viewmgr();
780     if (viewmgr) {
781       for ( int i = 0; i < viewmgr->size(); ++i ) {
782         viewmgr->get_view(i)->
783           set_aspect_ratio((float)view_h / (float)width);
784       }
785
786       setFOV( viewmgr->get_current_view()->get_h_fov(),
787               viewmgr->get_current_view()->get_v_fov() );
788       // cout << "setFOV(" << viewmgr->get_current_view()->get_h_fov()
789       //      << ", " << viewmgr->get_current_view()->get_v_fov() << ")"
790       //      << endl;
791     }
792 }
793
794
795 // These are wrapper functions around ssgSetNearFar() and ssgSetFOV()
796 // which will post process and rewrite the resulting frustum if we
797 // want to do asymmetric view frustums.
798
799 static void fgHackFrustum() {
800
801     // specify a percent of the configured view frustum to actually
802     // display.  This is a bit of a hack to achieve asymmetric view
803     // frustums.  For instance, if you want to display two monitors
804     // side by side, you could specify each with a double fov, a 0.5
805     // aspect ratio multiplier, and then the left side monitor would
806     // have a left_pct = 0.0, a right_pct = 0.5, a bottom_pct = 0.0,
807     // and a top_pct = 1.0.  The right side monitor would have a
808     // left_pct = 0.5 and a right_pct = 1.0.
809
810     static SGPropertyNode *left_pct
811         = fgGetNode("/sim/current-view/frustum-left-pct");
812     static SGPropertyNode *right_pct
813         = fgGetNode("/sim/current-view/frustum-right-pct");
814     static SGPropertyNode *bottom_pct
815         = fgGetNode("/sim/current-view/frustum-bottom-pct");
816     static SGPropertyNode *top_pct
817         = fgGetNode("/sim/current-view/frustum-top-pct");
818
819     double left, right;
820     double bottom, top;
821     double zNear, zFar;
822     sceneView->getProjectionMatrixAsFrustum(left, right, bottom, top, zNear, zFar);
823     // cout << " l = " << f->getLeft()
824     //      << " r = " << f->getRight()
825     //      << " b = " << f->getBot()
826     //      << " t = " << f->getTop()
827     //      << " n = " << f->getNear()
828     //      << " f = " << f->getFar()
829     //      << endl;
830
831     double width = right - left;
832     double height = top - bottom;
833
834     double l, r, t, b;
835
836     if ( left_pct != NULL ) {
837         l = left + width * left_pct->getDoubleValue();
838     } else {
839         l = left;
840     }
841
842     if ( right_pct != NULL ) {
843         r = left + width * right_pct->getDoubleValue();
844     } else {
845         r = right;
846     }
847
848     if ( bottom_pct != NULL ) {
849         b = bottom + height * bottom_pct->getDoubleValue();
850     } else {
851         b = bottom;
852     }
853
854     if ( top_pct != NULL ) {
855         t = bottom + height * top_pct->getDoubleValue();
856     } else {
857         t = top;
858     }
859
860     sceneView->setProjectionMatrixAsFrustum(l, r, b, t, zNear, zFar);
861 }
862
863
864 // we need some static storage space for these values.  However, we
865 // can't store it in a renderer class object because the functions
866 // that manipulate these are static.  They are static so they can
867 // interface to the display callback system.  There's probably a
868 // better way, there has to be a better way, but I'm not seeing it
869 // right now.
870 static float fov_width = 55.0;
871 static float fov_height = 42.0;
872 static float fov_near = 1.0;
873 static float fov_far = 1000.0;
874
875
876 /** FlightGear code should use this routine to set the FOV rather than
877  *  calling the ssg routine directly
878  */
879 void FGRenderer::setFOV( float w, float h ) {
880     fov_width = w;
881     fov_height = h;
882
883     sceneView->setProjectionMatrixAsPerspective(fov_height,
884                                                 fov_width/fov_height,
885                                                 fov_near, fov_far);
886     // fully specify the view frustum before hacking it (so we don't
887     // accumulate hacked effects
888     fgHackFrustum();
889 //     sgEnviro.setFOV( w, h );
890 }
891
892
893 /** FlightGear code should use this routine to set the Near/Far clip
894  *  planes rather than calling the ssg routine directly
895  */
896 void FGRenderer::setNearFar( float n, float f ) {
897 // OSGFIXME: we have currently too much z-buffer fights
898 n = 0.2;
899     fov_near = n;
900     fov_far = f;
901
902     sceneView->setProjectionMatrixAsPerspective(fov_height,
903                                                 fov_width/fov_height,
904                                                 fov_near, fov_far);
905
906     sceneView->getCamera()->setNearFarRatio(fov_near/fov_far);
907     mSceneCamera->setNearFarRatio(fov_near/fov_far);
908
909     // fully specify the view frustum before hacking it (so we don't
910     // accumulate hacked effects
911     fgHackFrustum();
912 }
913
914 bool FGRenderer::getPickInfo( SGVec3d& pt, SGVec3d& dir,
915                               unsigned x, unsigned y )
916 {
917   // Get the matrices involved in the transform from global to screen
918   // coordinates.
919   osg::Matrix pm = sceneView->getCamera()->getProjectionMatrix();
920
921   osg::Matrix mv;
922   osg::NodePathList paths;
923   paths = globals->get_scenery()->get_scene_graph()->getParentalNodePaths();
924   if (!paths.empty()) {
925     // Ok, we know that this should not have multiple parents ...
926     // FIXME: is this allways true?
927     mv = osg::computeLocalToEye(sceneView->getCamera()->getViewMatrix(),
928                                 paths.front(), false);
929   }
930   
931   // Compose and invert
932   osg::Matrix m = osg::Matrix::inverse(mv*pm);
933   
934   // Get the width and height of the display to be able to normalize the
935   // mouse coordinate
936   float width = fgGetInt("/sim/startup/xsize");
937   float height = fgGetInt("/sim/startup/ysize");
938   
939   // Compute some coordinates of in the line from the eyepoint to the
940   // mouse click coodinates.
941   // First build the normalized projection coordinates
942   osg::Vec4 normPt((2*x - width)/width, -(2*y - height)/height, 1, 1);
943   // Transform them into the real world
944   osg::Vec4 worldPt4 = m.preMult(normPt);
945   if (fabs(worldPt4[3]) < SGLimitsf::min())
946     return false;
947   SGVec3f worldPt(worldPt4[0]/worldPt4[3],
948                   worldPt4[1]/worldPt4[3],
949                   worldPt4[2]/worldPt4[3]);
950
951   // Now build a direction from the point
952   FGViewer* view = globals->get_current_view();
953   dir = normalize(toVec3d(worldPt - SGVec3f(view->get_view_pos())));
954
955   // Copy the start point
956   pt = SGVec3d(view->get_absolute_view_pos());
957
958   // OSGFIXME: ist this sufficient??? especially the precision problems here??
959 // bool mSceneView->projectWindowXYIntoObject(int x,int y,osg::Vec3& near_point,osg::Vec3& far_point) const;
960
961
962   return true;
963 }
964
965 // end of renderer.cxx
966