1 // renderer.cxx -- top level sim routines
3 // Written by Curtis Olson, started May 1997.
4 // This file contains parts of main.cxx prior to october 2004
6 // Copyright (C) 1997 - 2002 Curtis L. Olson - http://www.flightgear.org/~curt
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.
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.
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.
29 #include <simgear/compiler.h>
35 #include <osg/ref_ptr>
36 #include <osg/AlphaFunc>
37 #include <osg/BlendFunc>
39 #include <osg/CameraView>
40 #include <osg/CullFace>
45 #include <osg/LightModel>
46 #include <osg/LightSource>
47 #include <osg/NodeCallback>
49 #include <osg/PolygonMode>
50 #include <osg/PolygonOffset>
51 #include <osg/ShadeModel>
54 #include <osgUtil/SceneView>
55 #include <osgUtil/UpdateVisitor>
56 #include <osgUtil/IntersectVisitor>
58 #include <osg/io_utils>
59 #include <osgDB/WriteFile>
60 #include <osgDB/ReadFile>
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>
77 #include <simgear/screen/jpgfactory.hxx>
80 #include <simgear/environment/visual_enviro.hxx>
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/redout.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>
100 #include "splash.hxx"
101 #include "renderer.hxx"
104 class SGPuDrawable : public osg::Drawable {
108 // Dynamic stuff, do not store geometry
109 setUseDisplayList(false);
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);
120 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
122 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
123 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
125 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
126 { drawImplementation(*renderInfo.getState()); }
127 void drawImplementation(osg::State& state) const
129 state.pushStateSet(getStateSet());
131 state.setActiveTextureUnit(0);
132 state.setClientActiveTextureUnit(0);
133 state.disableAllVertexArrays();
135 glPushAttrib(GL_ALL_ATTRIB_BITS);
136 glPushClientAttrib(~0u);
138 if((fgGetBool("/sim/atc/enabled"))
139 || (fgGetBool("/sim/ai-traffic/enabled")))
140 globals->get_ATC_display()->update(delta_time_sec, state);
148 state.dirtyAllModes();
149 state.dirtyAllAttributes();
150 state.dirtyAllVertexArrays();
153 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
154 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
159 class SGHUDAndPanelDrawable : public osg::Drawable {
161 SGHUDAndPanelDrawable()
163 // Dynamic stuff, do not store geometry
164 setUseDisplayList(false);
166 osg::StateSet* stateSet = getOrCreateStateSet();
167 stateSet->setRenderBinDetails(1000, "RenderBin");
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);
176 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
178 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
179 { drawImplementation(*renderInfo.getState()); }
180 void drawImplementation(osg::State& state) const
182 state.pushStateSet(getStateSet());
184 state.setActiveTextureUnit(0);
185 state.setClientActiveTextureUnit(0);
186 state.disableAllVertexArrays();
188 glPushAttrib(GL_ALL_ATTRIB_BITS);
189 glPushClientAttrib(~0u);
191 fgCockpitUpdate(&state);
193 FGInstrumentMgr *instr = static_cast<FGInstrumentMgr*>(globals->get_subsystem("instrumentation"));
194 HUD *hud = static_cast<HUD*>(instr->get_subsystem("hud"));
197 // update the panel subsystem
198 if ( globals->get_current_panel() != NULL )
199 globals->get_current_panel()->update(state);
200 // We don't need a state here - can be safely removed when we can pick
208 state.dirtyAllModes();
209 state.dirtyAllAttributes();
210 state.dirtyAllVertexArrays();
213 virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
214 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
219 class FGLightSourceUpdateCallback : public osg::NodeCallback {
221 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
223 assert(dynamic_cast<osg::LightSource*>(node));
224 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
225 osg::Light* light = lightSource->getLight();
227 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
228 light->setAmbient(l->scene_ambient().osg());
229 light->setDiffuse(l->scene_diffuse().osg());
230 light->setSpecular(l->scene_specular().osg());
231 SGVec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
232 light->setPosition(position.osg());
233 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
234 light->setDirection(direction.osg());
235 light->setSpotExponent(0);
236 light->setSpotCutoff(180);
237 light->setConstantAttenuation(1);
238 light->setLinearAttenuation(0);
239 light->setQuadraticAttenuation(0);
245 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
247 FGWireFrameModeUpdateCallback() :
248 mWireframe(fgGetNode("/sim/rendering/wireframe"))
250 virtual void operator()(osg::StateAttribute* stateAttribute,
253 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
254 osg::PolygonMode* polygonMode;
255 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
257 if (mWireframe->getBoolValue())
258 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
259 osg::PolygonMode::LINE);
261 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
262 osg::PolygonMode::FILL);
265 SGSharedPtr<SGPropertyNode> mWireframe;
268 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
270 FGLightModelUpdateCallback() :
271 mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
273 virtual void operator()(osg::StateAttribute* stateAttribute,
276 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
277 osg::LightModel* lightModel;
278 lightModel = static_cast<osg::LightModel*>(stateAttribute);
281 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
282 lightModel->setAmbientIntensity(l->scene_ambient().osg());
284 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
286 lightModel->setTwoSided(true);
287 lightModel->setLocalViewer(false);
289 if (mHighlights->getBoolValue()) {
290 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
292 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
296 SGSharedPtr<SGPropertyNode> mHighlights;
299 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
301 FGFogEnableUpdateCallback() :
302 mFogEnabled(fgGetNode("/sim/rendering/fog"))
304 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
306 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
307 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
309 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
313 SGSharedPtr<SGPropertyNode> mFogEnabled;
316 // update callback for the switch node guarding that splash
317 class FGScenerySwitchCallback : public osg::NodeCallback {
319 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
321 assert(dynamic_cast<osg::Switch*>(node));
322 osg::Switch* sw = static_cast<osg::Switch*>(node);
324 double t = globals->get_sim_time_sec();
325 bool enabled = 0 < t;
326 sw->setValue(0, enabled);
333 // fog constants. I'm a little nervous about putting actual code out
334 // here but it seems to work (?)
335 static const double m_log01 = -log( 0.01 );
336 static const double sqrt_m_log01 = sqrt( m_log01 );
337 static GLfloat fog_exp_density;
338 static GLfloat fog_exp2_density;
339 static GLfloat rwy_exp2_punch_through;
340 static GLfloat taxi_exp2_punch_through;
341 static GLfloat ground_exp2_punch_through;
346 osg::ref_ptr<osgUtil::SceneView> sceneView = new osgUtil::SceneView; // This SceneView is used by class FGJpegHttpd ( jpg-httpd.cxx )
347 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
348 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
350 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
352 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
354 static osg::ref_ptr<osg::CameraView> mCameraView = new osg::CameraView;
355 static osg::ref_ptr<osg::Camera> mBackGroundCamera = new osg::Camera;
357 static osg::ref_ptr<osg::Fog> mFog = new osg::Fog;
358 static osg::ref_ptr<osg::Fog> mRunwayLightingFog = new osg::Fog;
359 static osg::ref_ptr<osg::Fog> mTaxiLightingFog = new osg::Fog;
360 static osg::ref_ptr<osg::Fog> mGroundLightingFog = new osg::Fog;
362 FGRenderer::FGRenderer()
364 #ifdef FG_JPEG_SERVER
365 jpgRenderFrame = FGRenderer::update;
369 FGRenderer::~FGRenderer()
371 #ifdef FG_JPEG_SERVER
372 jpgRenderFrame = NULL;
376 // Initialize various GL/view parameters
378 FGRenderer::splashinit( void ) {
379 // Add the splash screen node
380 mRealRoot->addChild(fgCreateSplashNode());
381 sceneView->setSceneData(mRealRoot.get());
383 sceneView->setDefaults(osgUtil::SceneView::COMPILE_GLOBJECTS_AT_INIT);
384 sceneView->setFrameStamp(mFrameStamp.get());
385 sceneView->setUpdateVisitor(mUpdateVisitor.get());
389 FGRenderer::init( void ) {
391 osg::initNotifyLevel();
393 // The number of polygon-offset "units" to place between layers. In
394 // principle, one is supposed to be enough. In practice, I find that
395 // my hardware/driver requires many more.
396 osg::PolygonOffset::setUnitsMultiplier(1);
397 osg::PolygonOffset::setFactorMultiplier(1);
399 // Go full screen if requested ...
400 if ( fgGetBool("/sim/startup/fullscreen") )
403 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
404 (!fgGetBool("/sim/rendering/shading"))) {
405 // if fastest fog requested, or if flat shading force fastest
406 glHint ( GL_FOG_HINT, GL_FASTEST );
407 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
408 glHint ( GL_FOG_HINT, GL_DONT_CARE );
411 glHint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
412 glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
413 glHint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
415 mFog->setMode(osg::Fog::EXP2);
416 mRunwayLightingFog->setMode(osg::Fog::EXP2);
417 mTaxiLightingFog->setMode(osg::Fog::EXP2);
418 mGroundLightingFog->setMode(osg::Fog::EXP2);
420 sceneView->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
421 sceneView->getCamera()->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
424 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
426 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
428 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
429 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
431 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
432 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
433 stateSet->setAttribute(new osg::BlendFunc);
434 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
436 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
438 // this will be set below
439 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
441 osg::Material* material = new osg::Material;
442 stateSet->setAttribute(material);
444 stateSet->setTextureAttribute(0, new osg::TexEnv);
445 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
448 // stateSet->setAttribute(new osg::CullFace(osg::CullFace::BACK));
449 // stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::ON);
451 // this is the topmost scenegraph node for osg
452 mBackGroundCamera->addChild(thesky->getPreRoot());
453 mBackGroundCamera->setClearMask(0);
455 GLbitfield inheritanceMask = osg::CullSettings::ALL_VARIABLES;
456 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
457 inheritanceMask &= ~osg::CullSettings::NEAR_FAR_RATIO;
458 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
459 mBackGroundCamera->setInheritanceMask(inheritanceMask);
460 mBackGroundCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
461 mBackGroundCamera->setCullingMode(osg::CullSettings::NO_CULLING);
462 mBackGroundCamera->setRenderOrder(osg::Camera::NESTED_RENDER);
464 stateSet = mBackGroundCamera->getOrCreateStateSet();
465 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
467 osg::Group* sceneGroup = new osg::Group;
468 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
469 sceneGroup->addChild(thesky->getCloudRoot());
471 stateSet = sceneGroup->getOrCreateStateSet();
472 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
473 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
475 // need to update the light on every frame
476 osg::LightSource* lightSource = new osg::LightSource;
477 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
478 // relative because of CameraView being just a clever transform node
479 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
480 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
481 mRoot->addChild(lightSource);
483 lightSource->addChild(mBackGroundCamera.get());
484 lightSource->addChild(sceneGroup);
487 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
488 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
489 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
490 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
491 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
493 // enable disable specular highlights.
494 // is the place where we might plug in an other fragment shader ...
495 osg::LightModel* lightModel = new osg::LightModel;
496 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
497 stateSet->setAttribute(lightModel);
499 // switch to enable wireframe
500 osg::PolygonMode* polygonMode = new osg::PolygonMode;
501 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
502 stateSet->setAttributeAndModes(polygonMode);
504 // scene fog handling
505 stateSet->setAttributeAndModes(mFog.get());
506 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
509 osg::Camera* guiCamera = new osg::Camera;
510 guiCamera->setRenderOrder(osg::Camera::POST_RENDER, 100);
511 guiCamera->setClearMask(0);
512 inheritanceMask = osg::CullSettings::ALL_VARIABLES;
513 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
514 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
515 guiCamera->setInheritanceMask(inheritanceMask);
516 guiCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
517 guiCamera->setCullingMode(osg::CullSettings::NO_CULLING);
518 osg::Geode* geode = new osg::Geode;
519 geode->addDrawable(new SGPuDrawable);
520 geode->addDrawable(new SGHUDAndPanelDrawable);
521 guiCamera->addChild(geode);
523 // this one contains all lights, here we set the light states we did
524 // in the plib case with plain OpenGL
525 osg::Group* lightGroup = new osg::Group;
526 sceneGroup->addChild(lightGroup);
527 lightGroup->addChild(globals->get_scenery()->get_gnd_lights_root());
528 lightGroup->addChild(globals->get_scenery()->get_vasi_lights_root());
529 lightGroup->addChild(globals->get_scenery()->get_rwy_lights_root());
530 lightGroup->addChild(globals->get_scenery()->get_taxi_lights_root());
532 stateSet = globals->get_scenery()->get_gnd_lights_root()->getOrCreateStateSet();
533 stateSet->setAttributeAndModes(mFog.get());
534 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
535 stateSet = globals->get_scenery()->get_vasi_lights_root()->getOrCreateStateSet();
536 stateSet->setAttributeAndModes(mRunwayLightingFog.get());
537 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
538 stateSet = globals->get_scenery()->get_rwy_lights_root()->getOrCreateStateSet();
539 stateSet->setAttributeAndModes(mRunwayLightingFog.get());
540 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
541 stateSet = globals->get_scenery()->get_taxi_lights_root()->getOrCreateStateSet();
542 stateSet->setAttributeAndModes(mTaxiLightingFog.get());
543 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
545 mCameraView->addChild(mRoot.get());
547 osg::Switch* sw = new osg::Switch;
548 sw->setUpdateCallback(new FGScenerySwitchCallback);
549 sw->addChild(mCameraView.get());
551 mRealRoot->addChild(sw);
552 mRealRoot->addChild(FGCreateRedoutNode());
553 mRealRoot->addChild(guiCamera);
557 // Update all Visuals (redraws anything graphics related)
559 FGRenderer::update( bool refresh_camera_settings ) {
560 bool scenery_loaded = fgGetBool("sim/sceneryloaded")
561 || fgGetBool("sim/sceneryloaded-override");
563 if ( idle_state < 1000 || !scenery_loaded ) {
564 fgSetDouble("/sim/startup/splash-alpha", 1.0);
566 // Keep resetting sim time while the sim is initializing
567 globals->set_sim_time_sec( 0.0 );
569 // the splash screen is now in the scenegraph
577 // Fade out the splash screen over the first three seconds.
578 double sAlpha = SGMiscd::max(0, (2.5 - globals->get_sim_time_sec()) / 2.5);
579 fgSetDouble("/sim/startup/splash-alpha", sAlpha);
581 bool skyblend = fgGetBool("/sim/rendering/skyblend");
582 bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
583 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
584 bool distance_attenuation
585 = fgGetBool("/sim/rendering/distance-attenuation");
587 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
588 distance_attenuation );
590 static const SGPropertyNode *groundlevel_nearplane
591 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
593 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
596 double actual_visibility;
597 if (fgGetBool("/environment/clouds/status")) {
598 actual_visibility = thesky->get_visibility();
600 actual_visibility = fgGetDouble("/environment/visibility-m");
603 static double last_visibility = -9999;
604 if ( actual_visibility != last_visibility ) {
605 last_visibility = actual_visibility;
607 fog_exp_density = m_log01 / actual_visibility;
608 fog_exp2_density = sqrt_m_log01 / actual_visibility;
609 ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
610 if ( actual_visibility < 8000 ) {
611 rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
612 taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
614 rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
615 taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
617 mFog->setDensity(fog_exp2_density);
618 mRunwayLightingFog->setDensity(rwy_exp2_punch_through);
619 mTaxiLightingFog->setDensity(taxi_exp2_punch_through);
620 mGroundLightingFog->setDensity(ground_exp2_punch_through);
623 // idle_state is now 1000 meaning we've finished all our
624 // initializations and are running the main loop, so this will
625 // now work without seg faulting the system.
627 FGViewer *current__view = globals->get_current_view();
628 // Force update of center dependent values ...
629 current__view->set_dirty();
631 if ( refresh_camera_settings ) {
633 resize( fgGetInt("/sim/startup/xsize"),
634 fgGetInt("/sim/startup/ysize") );
636 SGVec3d center = globals->get_scenery()->get_center();
637 SGVec3d position = current__view->getViewPosition();
638 SGQuatd attitude = current__view->getViewOrientation();
639 SGVec3d osgPosition = attitude.transform(center - position);
640 mCameraView->setPosition(osgPosition.osg());
641 mCameraView->setAttitude(inverse(attitude).osg());
645 if ( fgGetBool("/sim/rendering/textures") ) {
646 SGVec4f clearColor(l->adj_fog_color());
647 sceneView->getCamera()->setClearColor(clearColor.osg());
650 SGVec4f clearColor(l->sky_color());
651 sceneView->getCamera()->setClearColor(clearColor.osg());
654 // update fog params if visibility has changed
655 double visibility_meters = fgGetDouble("/environment/visibility-m");
656 thesky->set_visibility(visibility_meters);
658 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
659 ( global_multi_loop * fgGetInt("/sim/speed-up") )
660 / (double)fgGetInt("/sim/model-hz") );
662 // update the sky dome
665 // The sun and moon distances are scaled down versions
666 // of the actual distance to get both the moon and the sun
667 // within the range of the far clip plane.
668 // Moon distance: 384,467 kilometers
669 // Sun distance: 150,000,000 kilometers
671 double sun_horiz_eff, moon_horiz_eff;
672 if (fgGetBool("/sim/rendering/horizon-effect")) {
673 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
674 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
676 sun_horiz_eff = moon_horiz_eff = 1.0;
679 static SGSkyState sstate;
681 sstate.view_pos = current__view->get_view_pos();
682 sstate.zero_elev = current__view->get_zero_elev();
683 sstate.view_up = current__view->get_world_up();
684 sstate.lon = current__view->getLongitude_deg()
685 * SGD_DEGREES_TO_RADIANS;
686 sstate.lat = current__view->getLatitude_deg()
687 * SGD_DEGREES_TO_RADIANS;
688 sstate.alt = current__view->getAltitudeASL_ft()
690 sstate.spin = l->get_sun_rotation();
691 sstate.gst = globals->get_time_params()->getGst();
692 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
693 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
694 sstate.sun_dist = 50000.0 * sun_horiz_eff;
695 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
696 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
697 sstate.moon_dist = 40000.0 * moon_horiz_eff;
698 sstate.sun_angle = l->get_sun_angle();
702 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
703 << l->sky_color()[0] << " "
704 << l->sky_color()[1] << " "
705 << l->sky_color()[2] << " "
706 << l->sky_color()[3] );
707 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
708 << l->fog_color()[0] << " "
709 << l->fog_color()[1] << " "
710 << l->fog_color()[2] << " "
711 << l->fog_color()[3] );
712 SG_LOG( SG_GENERAL, SG_BULK,
713 " sun_angle = " << l->sun_angle
714 << " moon_angle = " << l->moon_angle );
717 static SGSkyColor scolor;
719 scolor.sky_color = SGVec3f(l->sky_color().data());
720 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
721 scolor.cloud_color = SGVec3f(l->cloud_color().data());
722 scolor.sun_angle = l->get_sun_angle();
723 scolor.moon_angle = l->get_moon_angle();
724 scolor.nplanets = globals->get_ephem()->getNumPlanets();
725 scolor.nstars = globals->get_ephem()->getNumStars();
726 scolor.planet_data = globals->get_ephem()->getPlanets();
727 scolor.star_data = globals->get_ephem()->getStars();
729 thesky->reposition( sstate, delta_time_sec );
730 thesky->repaint( scolor );
733 SG_LOG( SG_GENERAL, SG_BULK,
734 "thesky->reposition( view_pos = " << view_pos[0] << " "
735 << view_pos[1] << " " << view_pos[2] );
736 SG_LOG( SG_GENERAL, SG_BULK,
737 " zero_elev = " << zero_elev[0] << " "
738 << zero_elev[1] << " " << zero_elev[2]
739 << " lon = " << cur_fdm_state->get_Longitude()
740 << " lat = " << cur_fdm_state->get_Latitude() );
741 SG_LOG( SG_GENERAL, SG_BULK,
742 " sun_rot = " << l->get_sun_rotation
743 << " gst = " << SGTime::cur_time_params->getGst() );
744 SG_LOG( SG_GENERAL, SG_BULK,
745 " sun ra = " << globals->get_ephem()->getSunRightAscension()
746 << " sun dec = " << globals->get_ephem()->getSunDeclination()
747 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
748 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
752 // shadows->setupShadows(
753 // current__view->getLongitude_deg(),
754 // current__view->getLatitude_deg(),
755 // globals->get_time_params()->getGst(),
756 // globals->get_ephem()->getSunRightAscension(),
757 // globals->get_ephem()->getSunDeclination(),
758 // l->get_sun_angle());
762 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
763 SGVec4f color(l->adj_fog_color());
764 mFog->setColor(color.osg());
765 mRunwayLightingFog->setColor(color.osg());
766 mTaxiLightingFog->setColor(color.osg());
767 mGroundLightingFog->setColor(color.osg());
771 // sgEnviro.setLight(l->adj_fog_color());
773 // texture parameters
774 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
776 double agl = current__view->getAltitudeASL_ft()*SG_FEET_TO_METER
777 - current__view->getSGLocation()->get_cur_elev_m();
779 float scene_nearplane, scene_farplane;
781 scene_nearplane = 10.0f;
782 scene_farplane = 120000.0f;
784 scene_nearplane = groundlevel_nearplane->getDoubleValue();
785 scene_farplane = 120000.0f;
787 setNearFar( scene_nearplane, scene_farplane );
789 // sgEnviro.startOfFrame(current__view->get_view_pos(),
790 // current__view->get_world_up(),
791 // current__view->getLongitude_deg(),
792 // current__view->getLatitude_deg(),
793 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
797 // sgEnviro.drawLightning();
799 // double current_view_origin_airspeed_horiz_kt =
800 // fgGetDouble("/velocities/airspeed-kt", 0.0)
801 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
802 // * SGD_DEGREES_TO_RADIANS);
803 // TODO:find the real view speed, not the AC one
804 // sgEnviro.drawPrecipitation(
805 // fgGetDouble("/environment/metar/rain-norm", 0.0),
806 // fgGetDouble("/environment/metar/snow-norm", 0.0),
807 // fgGetDouble("/environment/metar/hail-norm", 0.0),
808 // current__view->getPitch_deg() + current__view->getPitchOffset_deg(),
809 // current__view->getRoll_deg() + current__view->getRollOffset_deg(),
810 // - current__view->getHeadingOffset_deg(),
811 // current_view_origin_airspeed_horiz_kt
816 // shadows->endOfFrame();
818 // need to call the update visitor once
819 globals->get_aircraft_model()->select( true );
820 FGTileMgr::set_tile_filter( true );
821 mFrameStamp->setReferenceTime(globals->get_sim_time_sec());
822 mFrameStamp->setFrameNumber(1+mFrameStamp->getFrameNumber());
823 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
824 mUpdateVisitor->setViewData(current__view->getViewPosition(),
825 current__view->getViewOrientation());
826 mUpdateVisitor->setSceneryCenter(globals->get_scenery()->get_center());
827 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
828 mUpdateVisitor->setLight(direction, l->scene_ambient(),
829 l->scene_diffuse(), l->scene_specular());
830 mUpdateVisitor->setVisibility(actual_visibility);
832 if (fgGetBool("/sim/panel-hotspots"))
833 sceneView->setCullMask(sceneView->getCullMask()|SG_NODEMASK_PICK_BIT);
835 sceneView->setCullMask(sceneView->getCullMask()&(~SG_NODEMASK_PICK_BIT));
844 // options.cxx needs to see this for toggle_panel()
845 // Handle new window size or exposure
847 FGRenderer::resize( int width, int height ) {
850 if ( (!fgGetBool("/sim/virtual-cockpit"))
851 && fgPanelVisible() && idle_state == 1000 ) {
852 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
853 globals->get_current_panel()->getYOffset()) / 768.0);
858 sceneView->getViewport()->setViewport(0, height - view_h, width, view_h);
860 static int lastwidth = 0;
861 static int lastheight = 0;
862 if (width != lastwidth)
863 fgSetInt("/sim/startup/xsize", lastwidth = width);
864 if (height != lastheight)
865 fgSetInt("/sim/startup/ysize", lastheight = height);
867 guiInitMouse(width, height);
870 FGViewMgr *viewmgr = globals->get_viewmgr();
872 for ( int i = 0; i < viewmgr->size(); ++i ) {
873 viewmgr->get_view(i)->
874 set_aspect_ratio((float)view_h / (float)width);
877 setFOV( viewmgr->get_current_view()->get_h_fov(),
878 viewmgr->get_current_view()->get_v_fov() );
883 // These are wrapper functions around ssgSetNearFar() and ssgSetFOV()
884 // which will post process and rewrite the resulting frustum if we
885 // want to do asymmetric view frustums.
887 static void fgHackFrustum() {
889 // specify a percent of the configured view frustum to actually
890 // display. This is a bit of a hack to achieve asymmetric view
891 // frustums. For instance, if you want to display two monitors
892 // side by side, you could specify each with a double fov, a 0.5
893 // aspect ratio multiplier, and then the left side monitor would
894 // have a left_pct = 0.0, a right_pct = 0.5, a bottom_pct = 0.0,
895 // and a top_pct = 1.0. The right side monitor would have a
896 // left_pct = 0.5 and a right_pct = 1.0.
898 static SGPropertyNode *left_pct
899 = fgGetNode("/sim/current-view/frustum-left-pct");
900 static SGPropertyNode *right_pct
901 = fgGetNode("/sim/current-view/frustum-right-pct");
902 static SGPropertyNode *bottom_pct
903 = fgGetNode("/sim/current-view/frustum-bottom-pct");
904 static SGPropertyNode *top_pct
905 = fgGetNode("/sim/current-view/frustum-top-pct");
910 sceneView->getProjectionMatrixAsFrustum(left, right, bottom, top, zNear, zFar);
911 // cout << " l = " << f->getLeft()
912 // << " r = " << f->getRight()
913 // << " b = " << f->getBot()
914 // << " t = " << f->getTop()
915 // << " n = " << f->getNear()
916 // << " f = " << f->getFar()
919 double width = right - left;
920 double height = top - bottom;
924 if ( left_pct != NULL ) {
925 l = left + width * left_pct->getDoubleValue();
930 if ( right_pct != NULL ) {
931 r = left + width * right_pct->getDoubleValue();
936 if ( bottom_pct != NULL ) {
937 b = bottom + height * bottom_pct->getDoubleValue();
942 if ( top_pct != NULL ) {
943 t = bottom + height * top_pct->getDoubleValue();
948 sceneView->setProjectionMatrixAsFrustum(l, r, b, t, zNear, zFar);
952 // we need some static storage space for these values. However, we
953 // can't store it in a renderer class object because the functions
954 // that manipulate these are static. They are static so they can
955 // interface to the display callback system. There's probably a
956 // better way, there has to be a better way, but I'm not seeing it
958 static float fov_width = 55.0;
959 static float fov_height = 42.0;
960 static float fov_near = 1.0;
961 static float fov_far = 1000.0;
964 /** FlightGear code should use this routine to set the FOV rather than
965 * calling the ssg routine directly
967 void FGRenderer::setFOV( float w, float h ) {
971 sceneView->setProjectionMatrixAsPerspective(fov_height,
972 fov_width/fov_height,
974 // fully specify the view frustum before hacking it (so we don't
975 // accumulate hacked effects
977 // sgEnviro.setFOV( w, h );
981 /** FlightGear code should use this routine to set the Near/Far clip
982 * planes rather than calling the ssg routine directly
984 void FGRenderer::setNearFar( float n, float f ) {
985 // OSGFIXME: we have currently too much z-buffer fights
990 sceneView->setProjectionMatrixAsPerspective(fov_height,
991 fov_width/fov_height,
994 // fully specify the view frustum before hacking it (so we don't
995 // accumulate hacked effects
1000 FGRenderer::pick( unsigned x, unsigned y,
1001 std::vector<SGSceneryPick>& pickList )
1003 // wipe out the return ...
1006 // we can get called early ...
1007 if (!sceneView.valid())
1010 osg::Node* sceneData = globals->get_scenery()->get_scene_graph();
1013 osg::Viewport* viewport = sceneView->getViewport();
1017 // good old scenery center
1018 SGVec3d center = globals->get_scenery()->get_center();
1020 // don't know why, but the update has partly happened somehow,
1021 // so update the scenery part of the viewer
1022 FGViewer *current_view = globals->get_current_view();
1023 // Force update of center dependent values ...
1024 current_view->set_dirty();
1025 SGVec3d position = current_view->getViewPosition();
1026 SGQuatd attitude = current_view->getViewOrientation();
1027 SGVec3d osgPosition = attitude.transform(center - position);
1028 mCameraView->setPosition(osgPosition.osg());
1029 mCameraView->setAttitude(inverse(attitude).osg());
1031 osg::Matrix projection(sceneView->getProjectionMatrix());
1032 osg::Matrix modelview(sceneView->getViewMatrix());
1034 osg::NodePathList nodePath = sceneData->getParentalNodePaths();
1035 // modify the view matrix so that it accounts for this nodePath's
1036 // accumulated transform
1037 if (!nodePath.empty())
1038 modelview.preMult(computeLocalToWorld(nodePath.front()));
1040 // swap the y values ...
1041 y = viewport->height() - y;
1042 // set up the pick visitor
1043 osgUtil::PickVisitor pickVisitor(viewport, projection, modelview, x, y);
1044 sceneData->accept(pickVisitor);
1045 if (!pickVisitor.hits())
1048 // collect all interaction callbacks on the pick ray.
1049 // They get stored in the pickCallbacks list where they are sorted back
1050 // to front and croasest to finest wrt the scenery node they are attached to
1051 osgUtil::PickVisitor::LineSegmentHitListMap::const_iterator mi;
1052 for (mi = pickVisitor.getSegHitList().begin();
1053 mi != pickVisitor.getSegHitList().end();
1055 osgUtil::IntersectVisitor::HitList::const_iterator hi;
1056 for (hi = mi->second.begin(); hi != mi->second.end(); ++hi) {
1057 // ok, go back the nodes and ask for intersection callbacks,
1058 // execute them in top down order
1059 const osg::NodePath& np = hi->getNodePath();
1060 osg::NodePath::const_reverse_iterator npi;
1061 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
1062 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
1065 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
1066 SGPickCallback* pickCallback = ud->getPickCallback(i);
1069 SGSceneryPick sceneryPick;
1070 /// note that this is done totally in doubles instead of
1071 /// just using getWorldIntersectionPoint
1072 osg::Vec3d localPt = hi->getLocalIntersectPoint();
1073 sceneryPick.info.local = SGVec3d(localPt);
1074 if (hi->getMatrix())
1075 sceneryPick.info.wgs84 = SGVec3d(localPt*(*hi->getMatrix()));
1077 sceneryPick.info.wgs84 = SGVec3d(localPt);
1078 sceneryPick.info.wgs84 += globals->get_scenery()->get_center();
1079 sceneryPick.callback = pickCallback;
1080 pickList.push_back(sceneryPick);
1086 return !pickList.empty();
1089 // end of renderer.cxx