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