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