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