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