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