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