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