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