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