]> 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/CameraNode>
39 #include <osg/CameraView>
40 #include <osg/CullFace>
41 #include <osg/ClearNode>
42 #include <osg/Depth>
43 #include <osg/Fog>
44 #include <osg/Group>
45 #include <osg/Light>
46 #include <osg/LightModel>
47 #include <osg/LightSource>
48 #include <osg/NodeCallback>
49 #include <osg/Notify>
50 #include <osg/PolygonMode>
51 #include <osg/PolygonOffset>
52 #include <osg/ShadeModel>
53 #include <osg/TexEnv>
54
55 #include <osgUtil/SceneView>
56 #include <osgUtil/UpdateVisitor>
57 #include <osgUtil/IntersectVisitor>
58
59 #include <osg/io_utils>
60 #include <osgDB/WriteFile>
61 #include <osgDB/ReadFile>
62 #include <sstream>
63
64 #include <simgear/math/SGMath.hxx>
65 #include <simgear/screen/extensions.hxx>
66 #include <simgear/scene/material/matlib.hxx>
67 #include <simgear/scene/model/animation.hxx>
68 #include <simgear/scene/model/model.hxx>
69 #include <simgear/scene/model/modellib.hxx>
70 #include <simgear/scene/model/placement.hxx>
71 #include <simgear/scene/util/SGUpdateVisitor.hxx>
72 #include <simgear/scene/tgdb/pt_lights.hxx>
73 #include <simgear/props/props.hxx>
74 #include <simgear/timing/sg_time.hxx>
75 #include <simgear/ephemeris/ephemeris.hxx>
76 #include <simgear/math/sg_random.h>
77 #ifdef FG_JPEG_SERVER
78 #include <simgear/screen/jpgfactory.hxx>
79 #endif
80
81 #include <simgear/environment/visual_enviro.hxx>
82
83 #include <Scenery/tileentry.hxx>
84 #include <Time/light.hxx>
85 #include <Time/light.hxx>
86 #include <Aircraft/aircraft.hxx>
87 #include <Cockpit/panel.hxx>
88 #include <Cockpit/cockpit.hxx>
89 #include <Cockpit/hud.hxx>
90 #include <Model/panelnode.hxx>
91 #include <Model/modelmgr.hxx>
92 #include <Model/acmodel.hxx>
93 #include <Scenery/scenery.hxx>
94 #include <Scenery/tilemgr.hxx>
95 #include <ATC/ATCdisplay.hxx>
96 #include <GUI/new_gui.hxx>
97 #include <Instrumentation/instrument_mgr.hxx>
98 #include <Instrumentation/HUD/HUD.hxx>
99
100 #include "splash.hxx"
101 #include "renderer.hxx"
102 #include "main.hxx"
103
104 class SGPuDrawable : public osg::Drawable {
105 public:
106   SGPuDrawable()
107   {
108     // Dynamic stuff, do not store geometry
109     setUseDisplayList(false);
110
111     osg::StateSet* stateSet = getOrCreateStateSet();
112     stateSet->setRenderBinDetails(1001, "RenderBin");
113     // speed optimization?
114     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
115     // We can do translucent menus, so why not. :-)
116     stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
117     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
118     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
119
120     stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
121
122     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
123     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
124   }
125   virtual void drawImplementation(osg::State& state) const
126   {
127     state.pushStateSet(getStateSet());
128     state.apply();
129     state.setActiveTextureUnit(0);
130     state.setClientActiveTextureUnit(0);
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   }
152
153   virtual osg::Object* cloneType() const { return new SGPuDrawable; }
154   virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
155   
156 private:
157 };
158
159 class SGHUDAndPanelDrawable : public osg::Drawable {
160 public:
161   SGHUDAndPanelDrawable()
162   {
163     // Dynamic stuff, do not store geometry
164     setUseDisplayList(false);
165
166     osg::StateSet* stateSet = getOrCreateStateSet();
167     stateSet->setRenderBinDetails(1000, "RenderBin");
168
169     // speed optimization?
170     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
171     stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
172     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
173     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
174     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
175
176     stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
177   }
178   virtual void drawImplementation(osg::State& state) const
179   {
180     state.pushStateSet(getStateSet());
181     state.apply();
182     state.setActiveTextureUnit(0);
183     state.setClientActiveTextureUnit(0);
184
185     glPushAttrib(GL_ALL_ATTRIB_BITS);
186     glPushClientAttrib(~0u);
187
188     fgCockpitUpdate(&state);
189
190     FGInstrumentMgr *instr = static_cast<FGInstrumentMgr*>(globals->get_subsystem("instrumentation"));
191     HUD *hud = static_cast<HUD*>(instr->get_subsystem("hud"));
192     hud->draw(state);
193
194     // update the panel subsystem
195     if ( globals->get_current_panel() != NULL )
196         globals->get_current_panel()->update(state);
197     // We don't need a state here - can be safely removed when we can pick
198     // correctly
199     fgUpdate3DPanels();
200
201     glPopClientAttrib();
202     glPopAttrib();
203
204     state.popStateSet();
205   }
206
207   virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
208   virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
209   
210 private:
211 };
212
213 class FGLightSourceUpdateCallback : public osg::NodeCallback {
214 public:
215   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
216   {
217     assert(dynamic_cast<osg::LightSource*>(node));
218     osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
219     osg::Light* light = lightSource->getLight();
220     
221     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
222     light->setAmbient(l->scene_ambient().osg());
223     light->setDiffuse(l->scene_diffuse().osg());
224     light->setSpecular(l->scene_specular().osg());
225     SGVec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
226     light->setPosition(position.osg());
227     SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
228     light->setDirection(direction.osg());
229     light->setSpotExponent(0);
230     light->setSpotCutoff(180);
231     light->setConstantAttenuation(1);
232     light->setLinearAttenuation(0);
233     light->setQuadraticAttenuation(0);
234
235     traverse(node, nv);
236   }
237 };
238
239 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
240 public:
241   FGWireFrameModeUpdateCallback() :
242     mWireframe(fgGetNode("/sim/rendering/wireframe"))
243   { }
244   virtual void operator()(osg::StateAttribute* stateAttribute,
245                           osg::NodeVisitor*)
246   {
247     assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
248     osg::PolygonMode* polygonMode;
249     polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
250
251     if (mWireframe->getBoolValue())
252       polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
253                            osg::PolygonMode::LINE);
254     else
255       polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
256                            osg::PolygonMode::FILL);
257   }
258 private:
259   SGSharedPtr<SGPropertyNode> mWireframe;
260 };
261
262 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
263 public:
264   FGLightModelUpdateCallback() :
265     mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
266   { }
267   virtual void operator()(osg::StateAttribute* stateAttribute,
268                           osg::NodeVisitor*)
269   {
270     assert(dynamic_cast<osg::LightModel*>(stateAttribute));
271     osg::LightModel* lightModel;
272     lightModel = static_cast<osg::LightModel*>(stateAttribute);
273
274 #if 0
275     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
276     lightModel->setAmbientIntensity(l->scene_ambient().osg());
277 #else
278     lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
279 #endif
280     lightModel->setTwoSided(true);
281     lightModel->setLocalViewer(false);
282
283     if (mHighlights->getBoolValue()) {
284       lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
285     } else {
286       lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
287     }
288   }
289 private:
290   SGSharedPtr<SGPropertyNode> mHighlights;
291 };
292
293 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
294 public:
295   FGFogEnableUpdateCallback() :
296     mFogEnabled(fgGetNode("/sim/rendering/fog"))
297   { }
298   virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
299   {
300     if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
301       stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
302     } else {
303       stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
304     }
305   }
306 private:
307   SGSharedPtr<SGPropertyNode> mFogEnabled;
308 };
309
310 // fog constants.  I'm a little nervous about putting actual code out
311 // here but it seems to work (?)
312 static const double m_log01 = -log( 0.01 );
313 static const double sqrt_m_log01 = sqrt( m_log01 );
314 static GLfloat fog_exp_density;
315 static GLfloat fog_exp2_density;
316 static GLfloat rwy_exp2_punch_through;
317 static GLfloat taxi_exp2_punch_through;
318 static GLfloat ground_exp2_punch_through;
319
320 // Sky structures
321 SGSky *thesky;
322
323 static osg::ref_ptr<osgUtil::SceneView> sceneView = new osgUtil::SceneView;
324 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
325 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
326
327 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
328
329 static osg::ref_ptr<osg::CameraView> mCameraView = new osg::CameraView;
330 static osg::ref_ptr<osg::CameraNode> mBackGroundCamera = new osg::CameraNode;
331 osg::ref_ptr<osg::CameraNode> mSceneCamera = new osg::CameraNode;
332
333 static osg::ref_ptr<osg::Fog> mFog = new osg::Fog;
334 static osg::ref_ptr<osg::Fog> mRunwayLightingFog = new osg::Fog;
335 static osg::ref_ptr<osg::Fog> mTaxiLightingFog = new osg::Fog;
336 static osg::ref_ptr<osg::Fog> mGroundLightingFog = new osg::Fog;
337
338 FGRenderer::FGRenderer()
339 {
340 #ifdef FG_JPEG_SERVER
341    jpgRenderFrame = FGRenderer::update;
342 #endif
343 }
344
345 FGRenderer::~FGRenderer()
346 {
347 #ifdef FG_JPEG_SERVER
348    jpgRenderFrame = NULL;
349 #endif
350 }
351
352 // Initialize various GL/view parameters
353 void
354 FGRenderer::init( void ) {
355
356     osg::initNotifyLevel();
357
358     // The number of polygon-offset "units" to place between layers.  In
359     // principle, one is supposed to be enough.  In practice, I find that
360     // my hardware/driver requires many more.
361     osg::PolygonOffset::setUnitsMultiplier(1);
362     osg::PolygonOffset::setFactorMultiplier(1);
363
364     // Go full screen if requested ...
365     if ( fgGetBool("/sim/startup/fullscreen") )
366         fgOSFullScreen();
367
368     if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) || 
369          (!fgGetBool("/sim/rendering/shading"))) {
370         // if fastest fog requested, or if flat shading force fastest
371         glHint ( GL_FOG_HINT, GL_FASTEST );
372     } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
373         glHint ( GL_FOG_HINT, GL_DONT_CARE );
374     }
375
376     glHint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
377     glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
378     glHint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
379
380     sceneView->setDefaults(osgUtil::SceneView::COMPILE_GLOBJECTS_AT_INIT);
381
382     mFog->setMode(osg::Fog::EXP2);
383     mRunwayLightingFog->setMode(osg::Fog::EXP2);
384     mTaxiLightingFog->setMode(osg::Fog::EXP2);
385     mGroundLightingFog->setMode(osg::Fog::EXP2);
386
387     sceneView->setFrameStamp(mFrameStamp.get());
388
389     mUpdateVisitor = new SGUpdateVisitor;
390     sceneView->setUpdateVisitor(mUpdateVisitor.get());
391
392     sceneView->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
393     sceneView->getCamera()->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
394     sceneView->getCamera()->setClearMask(GL_COLOR_BUFFER_BIT);
395
396     osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
397
398     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
399     
400     stateSet->setAttribute(new osg::Depth(osg::Depth::LEQUAL));
401     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
402
403     stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
404     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
405     stateSet->setAttribute(new osg::BlendFunc);
406     stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
407
408     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
409     
410     // this will be set below
411     stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
412
413     osg::Material* material = new osg::Material;
414     stateSet->setAttribute(material);
415     
416     stateSet->setTextureAttribute(0, new osg::TexEnv);
417     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
418
419
420 //     stateSet->setAttribute(new osg::CullFace(osg::CullFace::BACK));
421 //     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::ON);
422
423
424     // this is the topmost scenegraph node for osg
425     mBackGroundCamera->addChild(thesky->getPreRoot());
426     mBackGroundCamera->setClearMask(0);
427
428     GLbitfield inheritanceMask = osg::CullSettings::ALL_VARIABLES;
429     inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
430     inheritanceMask &= ~osg::CullSettings::NEAR_FAR_RATIO;
431     inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
432     mBackGroundCamera->setInheritanceMask(inheritanceMask);
433     mBackGroundCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
434     mBackGroundCamera->setCullingMode(osg::CullSettings::NO_CULLING);
435     mBackGroundCamera->setRenderOrder(osg::CameraNode::NESTED_RENDER);
436
437     mBackGroundCamera->getOrCreateStateSet()->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
438
439
440     mSceneCamera->setClearMask(GL_DEPTH_BUFFER_BIT);
441     inheritanceMask = osg::CullSettings::ALL_VARIABLES;
442     inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
443     inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
444     mSceneCamera->setInheritanceMask(inheritanceMask);
445     mSceneCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
446     mSceneCamera->setCullingMode(osg::CullSettings::DEFAULT_CULLING);
447     mSceneCamera->setRenderOrder(osg::CameraNode::NESTED_RENDER);
448     mSceneCamera->addChild(globals->get_scenery()->get_scene_graph());
449     mSceneCamera->addChild(thesky->getCloudRoot());
450
451     stateSet = mSceneCamera->getOrCreateStateSet();
452     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
453     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
454
455     // need to update the light on every frame
456     osg::LightSource* lightSource = new osg::LightSource;
457     lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
458     // relative because of CameraView being just a clever transform node
459     lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
460     lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
461     mRoot->addChild(lightSource);
462
463     lightSource->addChild(mBackGroundCamera.get());
464 //     lightSource->addChild(mSceneCamera.get());
465     // Hmm, I would think that this should be included in the camera, but ...
466     osg::ClearNode* clearNode = new osg::ClearNode;
467     clearNode->addChild(mSceneCamera.get());
468     clearNode->setClearMask(GL_DEPTH_BUFFER_BIT);
469     lightSource->addChild(clearNode);
470
471
472     stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
473     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
474     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
475     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
476     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
477
478     // enable disable specular highlights.
479     // is the place where we might plug in an other fragment shader ...
480     osg::LightModel* lightModel = new osg::LightModel;
481     lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
482     stateSet->setAttribute(lightModel);
483
484     // switch to enable wireframe
485     osg::PolygonMode* polygonMode = new osg::PolygonMode;
486     polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
487     stateSet->setAttributeAndModes(polygonMode);
488
489     // scene fog handling
490     stateSet->setAttributeAndModes(mFog.get());
491     stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
492
493     // plug in the GUI
494     osg::CameraNode* guiCamera = new osg::CameraNode;
495     guiCamera->setRenderOrder(osg::CameraNode::POST_RENDER);
496     guiCamera->setClearMask(0);
497     inheritanceMask = osg::CullSettings::ALL_VARIABLES;
498     inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
499     inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
500     guiCamera->setInheritanceMask(inheritanceMask);
501     guiCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
502     guiCamera->setCullingMode(osg::CullSettings::NO_CULLING);
503     mRoot->addChild(guiCamera);
504     osg::Geode* geode = new osg::Geode;
505     geode->addDrawable(new SGPuDrawable);
506     geode->addDrawable(new SGHUDAndPanelDrawable);
507     guiCamera->addChild(geode);
508
509     // this one contains all lights, here we set the light states we did
510     // in the plib case with plain OpenGL
511     osg::Group* lightGroup = new osg::Group;
512     mSceneCamera->addChild(lightGroup);
513     lightGroup->addChild(globals->get_scenery()->get_gnd_lights_root());
514     lightGroup->addChild(globals->get_scenery()->get_vasi_lights_root());
515     lightGroup->addChild(globals->get_scenery()->get_rwy_lights_root());
516     lightGroup->addChild(globals->get_scenery()->get_taxi_lights_root());
517
518     stateSet = globals->get_scenery()->get_gnd_lights_root()->getOrCreateStateSet();
519     stateSet->setAttributeAndModes(mFog.get());
520     stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
521     stateSet = globals->get_scenery()->get_vasi_lights_root()->getOrCreateStateSet();
522     stateSet->setAttributeAndModes(mRunwayLightingFog.get());
523     stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
524     stateSet = globals->get_scenery()->get_rwy_lights_root()->getOrCreateStateSet();
525     stateSet->setAttributeAndModes(mRunwayLightingFog.get());
526     stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
527     stateSet = globals->get_scenery()->get_taxi_lights_root()->getOrCreateStateSet();
528     stateSet->setAttributeAndModes(mTaxiLightingFog.get());
529     stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
530
531     mCameraView->addChild(mRoot.get());
532     sceneView->setSceneData(mCameraView.get());
533
534 //  sceneView->getState()->setCheckForGLErrors(osg::State::ONCE_PER_ATTRIBUTE);
535 }
536
537
538 // Update all Visuals (redraws anything graphics related)
539 void
540 FGRenderer::update( bool refresh_camera_settings ) {
541     bool scenery_loaded = fgGetBool("sim/sceneryloaded")
542                           || fgGetBool("sim/sceneryloaded-override");
543
544     if ( idle_state < 1000 || !scenery_loaded ) {
545         if (sceneView.valid() && sceneView->getState()) {
546             sceneView->getState()->setActiveTextureUnit(0);
547             sceneView->getState()->setClientActiveTextureUnit(0);
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
770     setNearFar( scene_nearplane, scene_farplane );
771
772 //     sgEnviro.startOfFrame(current__view->get_view_pos(), 
773 //         current__view->get_world_up(),
774 //         current__view->getLongitude_deg(),
775 //         current__view->getLatitude_deg(),
776 //         current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
777 //         delta_time_sec);
778
779     // OSGFIXME
780 //     sgEnviro.drawLightning();
781
782 //        double current_view_origin_airspeed_horiz_kt =
783 //         fgGetDouble("/velocities/airspeed-kt", 0.0)
784 //                        * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
785 //                                * SGD_DEGREES_TO_RADIANS);
786        // TODO:find the real view speed, not the AC one
787 //     sgEnviro.drawPrecipitation(
788 //         fgGetDouble("/environment/metar/rain-norm", 0.0),
789 //         fgGetDouble("/environment/metar/snow-norm", 0.0),
790 //         fgGetDouble("/environment/metar/hail-norm", 0.0),
791 //         current__view->getPitch_deg() + current__view->getPitchOffset_deg(),
792 //         current__view->getRoll_deg() + current__view->getRollOffset_deg(),
793 //         - current__view->getHeadingOffset_deg(),
794 //                current_view_origin_airspeed_horiz_kt
795 //                );
796
797     // OSGFIXME
798 //     if( is_internal )
799 //         shadows->endOfFrame();
800
801     // need to call the update visitor once
802     globals->get_aircraft_model()->select( true );
803     FGTileMgr::set_tile_filter( true );
804     mFrameStamp->setReferenceTime(globals->get_sim_time_sec());
805     mFrameStamp->setFrameNumber(1+mFrameStamp->getFrameNumber());
806     mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
807     mUpdateVisitor->setViewData(current__view->getViewPosition(),
808                                 current__view->getViewOrientation());
809     mUpdateVisitor->setSceneryCenter(globals->get_scenery()->get_center());
810     SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
811     mUpdateVisitor->setLight(direction, l->scene_ambient(),
812                              l->scene_diffuse(), l->scene_specular());
813     mUpdateVisitor->setVisibility(actual_visibility);
814
815     if (fgGetBool("/sim/panel-hotspots"))
816       sceneView->setCullMask(~0u);
817     else
818       sceneView->setCullMask(~SG_NODEMASK_PICK_BIT);
819
820     sceneView->update();
821     sceneView->cull();
822     sceneView->draw();
823 }
824
825
826
827 // options.cxx needs to see this for toggle_panel()
828 // Handle new window size or exposure
829 void
830 FGRenderer::resize( int width, int height ) {
831     int view_h;
832
833     if ( (!fgGetBool("/sim/virtual-cockpit"))
834          && fgPanelVisible() && idle_state == 1000 ) {
835         view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
836                              globals->get_current_panel()->getYOffset()) / 768.0);
837     } else {
838         view_h = height;
839     }
840
841     sceneView->getViewport()->setViewport(0, height - view_h, width, view_h);
842
843     static int lastwidth = 0;
844     static int lastheight = 0;
845     if (width != lastwidth)
846         fgSetInt("/sim/startup/xsize", lastwidth = width);
847     if (height != lastheight)
848         fgSetInt("/sim/startup/ysize", lastheight = height);
849
850     guiInitMouse(width, height);
851
852     // for all views
853     FGViewMgr *viewmgr = globals->get_viewmgr();
854     if (viewmgr) {
855       for ( int i = 0; i < viewmgr->size(); ++i ) {
856         viewmgr->get_view(i)->
857           set_aspect_ratio((float)view_h / (float)width);
858       }
859
860       setFOV( viewmgr->get_current_view()->get_h_fov(),
861               viewmgr->get_current_view()->get_v_fov() );
862     }
863 }
864
865
866 // These are wrapper functions around ssgSetNearFar() and ssgSetFOV()
867 // which will post process and rewrite the resulting frustum if we
868 // want to do asymmetric view frustums.
869
870 static void fgHackFrustum() {
871
872     // specify a percent of the configured view frustum to actually
873     // display.  This is a bit of a hack to achieve asymmetric view
874     // frustums.  For instance, if you want to display two monitors
875     // side by side, you could specify each with a double fov, a 0.5
876     // aspect ratio multiplier, and then the left side monitor would
877     // have a left_pct = 0.0, a right_pct = 0.5, a bottom_pct = 0.0,
878     // and a top_pct = 1.0.  The right side monitor would have a
879     // left_pct = 0.5 and a right_pct = 1.0.
880
881     static SGPropertyNode *left_pct
882         = fgGetNode("/sim/current-view/frustum-left-pct");
883     static SGPropertyNode *right_pct
884         = fgGetNode("/sim/current-view/frustum-right-pct");
885     static SGPropertyNode *bottom_pct
886         = fgGetNode("/sim/current-view/frustum-bottom-pct");
887     static SGPropertyNode *top_pct
888         = fgGetNode("/sim/current-view/frustum-top-pct");
889
890     double left, right;
891     double bottom, top;
892     double zNear, zFar;
893     sceneView->getProjectionMatrixAsFrustum(left, right, bottom, top, zNear, zFar);
894     // cout << " l = " << f->getLeft()
895     //      << " r = " << f->getRight()
896     //      << " b = " << f->getBot()
897     //      << " t = " << f->getTop()
898     //      << " n = " << f->getNear()
899     //      << " f = " << f->getFar()
900     //      << endl;
901
902     double width = right - left;
903     double height = top - bottom;
904
905     double l, r, t, b;
906
907     if ( left_pct != NULL ) {
908         l = left + width * left_pct->getDoubleValue();
909     } else {
910         l = left;
911     }
912
913     if ( right_pct != NULL ) {
914         r = left + width * right_pct->getDoubleValue();
915     } else {
916         r = right;
917     }
918
919     if ( bottom_pct != NULL ) {
920         b = bottom + height * bottom_pct->getDoubleValue();
921     } else {
922         b = bottom;
923     }
924
925     if ( top_pct != NULL ) {
926         t = bottom + height * top_pct->getDoubleValue();
927     } else {
928         t = top;
929     }
930
931     sceneView->setProjectionMatrixAsFrustum(l, r, b, t, zNear, zFar);
932 }
933
934
935 // we need some static storage space for these values.  However, we
936 // can't store it in a renderer class object because the functions
937 // that manipulate these are static.  They are static so they can
938 // interface to the display callback system.  There's probably a
939 // better way, there has to be a better way, but I'm not seeing it
940 // right now.
941 static float fov_width = 55.0;
942 static float fov_height = 42.0;
943 static float fov_near = 1.0;
944 static float fov_far = 1000.0;
945
946
947 /** FlightGear code should use this routine to set the FOV rather than
948  *  calling the ssg routine directly
949  */
950 void FGRenderer::setFOV( float w, float h ) {
951     fov_width = w;
952     fov_height = h;
953
954     sceneView->setProjectionMatrixAsPerspective(fov_height,
955                                                 fov_width/fov_height,
956                                                 fov_near, fov_far);
957     // fully specify the view frustum before hacking it (so we don't
958     // accumulate hacked effects
959     fgHackFrustum();
960 //     sgEnviro.setFOV( w, h );
961 }
962
963
964 /** FlightGear code should use this routine to set the Near/Far clip
965  *  planes rather than calling the ssg routine directly
966  */
967 void FGRenderer::setNearFar( float n, float f ) {
968 // OSGFIXME: we have currently too much z-buffer fights
969 n = 0.2;
970     fov_near = n;
971     fov_far = f;
972
973     sceneView->setProjectionMatrixAsPerspective(fov_height,
974                                                 fov_width/fov_height,
975                                                 fov_near, fov_far);
976
977     sceneView->getCamera()->setNearFarRatio(fov_near/fov_far);
978     mSceneCamera->setNearFarRatio(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 scneery 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