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>
38 #include <osg/CameraNode>
39 #include <osg/CameraView>
40 #include <osg/CullFace>
45 #include <osg/LightModel>
46 #include <osg/LightSource>
47 #include <osg/NodeCallback>
49 #include <osg/MatrixTransform>
50 #include <osg/Multisample>
52 #include <osg/PolygonMode>
53 #include <osg/ShadeModel>
55 #include <osg/TexEnvCombine>
58 #include <osg/ColorMatrix>
60 #include <osgUtil/SceneView>
61 #include <osgUtil/UpdateVisitor>
63 #include <osg/io_utils>
64 #include <osgDB/WriteFile>
65 #include <osgDB/ReadFile>
68 #include <simgear/math/SGMath.hxx>
69 #include <simgear/screen/extensions.hxx>
70 #include <simgear/scene/material/matlib.hxx>
71 #include <simgear/scene/model/animation.hxx>
72 #include <simgear/scene/model/model.hxx>
73 #include <simgear/scene/model/modellib.hxx>
74 #include <simgear/scene/model/placement.hxx>
75 #include <simgear/scene/util/SGUpdateVisitor.hxx>
76 #include <simgear/scene/tgdb/pt_lights.hxx>
77 #include <simgear/props/props.hxx>
78 #include <simgear/timing/sg_time.hxx>
79 #include <simgear/ephemeris/ephemeris.hxx>
80 #include <simgear/math/sg_random.h>
82 #include <simgear/screen/jpgfactory.hxx>
85 #include <simgear/environment/visual_enviro.hxx>
87 #include <Scenery/tileentry.hxx>
88 #include <Time/light.hxx>
89 #include <Time/light.hxx>
90 #include <Aircraft/aircraft.hxx>
91 #include <Cockpit/panel.hxx>
92 #include <Cockpit/cockpit.hxx>
93 #include <Cockpit/hud.hxx>
94 #include <Model/panelnode.hxx>
95 #include <Model/modelmgr.hxx>
96 #include <Model/acmodel.hxx>
97 #include <Scenery/scenery.hxx>
98 #include <Scenery/tilemgr.hxx>
99 #include <ATC/ATCdisplay.hxx>
100 #include <GUI/new_gui.hxx>
101 #include <Instrumentation/instrument_mgr.hxx>
102 #include <Instrumentation/HUD/HUD.hxx>
104 #include "splash.hxx"
105 #include "renderer.hxx"
108 class SGPuDrawable : public osg::Drawable {
112 // Dynamic stuff, do not store geometry
113 setUseDisplayList(false);
115 osg::StateSet* stateSet = getOrCreateStateSet();
116 stateSet->setRenderBinDetails(1001, "RenderBin");
117 // speed optimization?
118 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
119 // We can do translucent menus, so why not. :-)
120 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
121 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
122 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
124 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
126 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
127 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
129 virtual void drawImplementation(osg::State& state) const
131 state.pushStateSet(getStateSet());
135 if((fgGetBool("/sim/atc/enabled"))
136 || (fgGetBool("/sim/ai-traffic/enabled")))
137 globals->get_ATC_display()->update(delta_time_sec, state);
142 // Fade out the splash screen over the first three seconds.
143 double t = globals->get_sim_time_sec();
145 glPushAttrib(GL_ALL_ATTRIB_BITS);
146 glPushClientAttrib(~0u);
148 fgSplashUpdate((2.5 - t) / 2.5);
157 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
158 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
163 class SGHUDAndPanelDrawable : public osg::Drawable {
165 SGHUDAndPanelDrawable()
167 // Dynamic stuff, do not store geometry
168 setUseDisplayList(false);
170 osg::StateSet* stateSet = getOrCreateStateSet();
171 stateSet->setRenderBinDetails(1000, "RenderBin");
173 // speed optimization?
174 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
175 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
176 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
177 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
178 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
180 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
182 virtual void drawImplementation(osg::State& state) const
184 state.pushStateSet(getStateSet());
187 glPushAttrib(GL_ALL_ATTRIB_BITS);
188 glPushClientAttrib(~0u);
190 fgCockpitUpdate(&state);
192 FGInstrumentMgr *instr = static_cast<FGInstrumentMgr*>(globals->get_subsystem("instrumentation"));
193 HUD *hud = static_cast<HUD*>(instr->get_subsystem("hud"));
196 // update the panel subsystem
197 if ( globals->get_current_panel() != NULL )
198 globals->get_current_panel()->update(state);
199 // We don't need a state here - can be safely removed when we can pick
209 virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
210 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
215 class FGLightSourceUpdateCallback : public osg::NodeCallback {
217 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
219 assert(dynamic_cast<osg::LightSource*>(node));
220 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
221 osg::Light* light = lightSource->getLight();
223 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
224 light->setAmbient(l->scene_ambient().osg());
225 light->setDiffuse(l->scene_diffuse().osg());
226 light->setSpecular(l->scene_specular().osg());
227 SGVec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
228 light->setPosition(position.osg());
229 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
230 light->setDirection(direction.osg());
231 light->setSpotExponent(0);
232 light->setSpotCutoff(180);
233 light->setConstantAttenuation(1);
234 light->setLinearAttenuation(0);
235 light->setQuadraticAttenuation(0);
241 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
243 FGWireFrameModeUpdateCallback() :
244 mWireframe(fgGetNode("/sim/rendering/wireframe"))
246 virtual void operator()(osg::StateAttribute* stateAttribute,
249 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
250 osg::PolygonMode* polygonMode;
251 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
253 if (mWireframe->getBoolValue())
254 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
255 osg::PolygonMode::LINE);
257 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
258 osg::PolygonMode::FILL);
261 SGSharedPtr<SGPropertyNode> mWireframe;
264 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
266 FGLightModelUpdateCallback() :
267 mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
269 virtual void operator()(osg::StateAttribute* stateAttribute,
272 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
273 osg::LightModel* lightModel;
274 lightModel = static_cast<osg::LightModel*>(stateAttribute);
277 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
278 lightModel->setAmbientIntensity(l->scene_ambient().osg());
280 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
282 lightModel->setTwoSided(true);
283 lightModel->setLocalViewer(false);
285 if (mHighlights->getBoolValue()) {
286 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
288 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
292 SGSharedPtr<SGPropertyNode> mHighlights;
295 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
297 FGFogEnableUpdateCallback() :
298 mFogEnabled(fgGetNode("/sim/rendering/fog"))
300 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
302 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
303 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
305 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
309 SGSharedPtr<SGPropertyNode> mFogEnabled;
312 // fog constants. I'm a little nervous about putting actual code out
313 // here but it seems to work (?)
314 static const double m_log01 = -log( 0.01 );
315 static const double sqrt_m_log01 = sqrt( m_log01 );
316 static GLfloat fog_exp_density;
317 static GLfloat fog_exp2_density;
318 static GLfloat rwy_exp2_punch_through;
319 static GLfloat taxi_exp2_punch_through;
320 static GLfloat ground_exp2_punch_through;
325 static osg::ref_ptr<osgUtil::SceneView> sceneView = new osgUtil::SceneView;
326 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
327 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
329 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
331 static osg::ref_ptr<osg::CameraView> mCameraView = new osg::CameraView;
332 static osg::ref_ptr<osg::CameraNode> mBackGroundCamera = new osg::CameraNode;
333 osg::ref_ptr<osg::CameraNode> mSceneCamera = new osg::CameraNode;
335 static osg::ref_ptr<osg::Fog> mFog = new osg::Fog;
336 static osg::ref_ptr<osg::Fog> mRunwayLightingFog = new osg::Fog;
337 static osg::ref_ptr<osg::Fog> mTaxiLightingFog = new osg::Fog;
338 static osg::ref_ptr<osg::Fog> mGroundLightingFog = new osg::Fog;
340 FGRenderer::FGRenderer()
342 #ifdef FG_JPEG_SERVER
343 jpgRenderFrame = FGRenderer::update;
347 FGRenderer::~FGRenderer()
349 #ifdef FG_JPEG_SERVER
350 jpgRenderFrame = NULL;
354 // Initialize various GL/view parameters
356 FGRenderer::init( void ) {
358 osg::initNotifyLevel();
360 // Go full screen if requested ...
361 if ( fgGetBool("/sim/startup/fullscreen") )
364 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
365 (!fgGetBool("/sim/rendering/shading"))) {
366 // if fastest fog requested, or if flat shading force fastest
367 glHint ( GL_FOG_HINT, GL_FASTEST );
368 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
369 glHint ( GL_FOG_HINT, GL_DONT_CARE );
372 glHint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
373 glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
374 glHint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
376 sceneView->setDefaults(osgUtil::SceneView::COMPILE_GLOBJECTS_AT_INIT);
378 mFog->setMode(osg::Fog::EXP2);
379 mRunwayLightingFog->setMode(osg::Fog::EXP2);
380 mTaxiLightingFog->setMode(osg::Fog::EXP2);
381 mGroundLightingFog->setMode(osg::Fog::EXP2);
383 sceneView->setFrameStamp(mFrameStamp.get());
385 mUpdateVisitor = new SGUpdateVisitor;
386 sceneView->setUpdateVisitor(mUpdateVisitor.get());
388 sceneView->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
389 sceneView->getCamera()->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
390 sceneView->getCamera()->setClearMask(GL_COLOR_BUFFER_BIT);
392 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
394 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
396 stateSet->setAttribute(new osg::Depth(osg::Depth::LEQUAL));
397 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
399 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
400 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
401 stateSet->setAttribute(new osg::BlendFunc);
402 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
404 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
406 // this will be set below
407 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
409 osg::Material* material = new osg::Material;
410 stateSet->setAttribute(material);
412 stateSet->setTextureAttribute(0, new osg::TexEnv);
413 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
416 // stateSet->setAttribute(new osg::CullFace(osg::CullFace::BACK));
417 // stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::ON);
420 // this is the topmost scenegraph node for osg
421 mBackGroundCamera->addChild(thesky->getPreRoot());
422 mBackGroundCamera->setClearMask(0);
424 GLbitfield inheritanceMask = osg::CullSettings::ALL_VARIABLES;
425 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
426 inheritanceMask &= ~osg::CullSettings::NEAR_FAR_RATIO;
427 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
428 mBackGroundCamera->setInheritanceMask(inheritanceMask);
429 mBackGroundCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
430 mBackGroundCamera->setCullingMode(osg::CullSettings::NO_CULLING);
431 mBackGroundCamera->setRenderOrder(osg::CameraNode::NESTED_RENDER);
433 mBackGroundCamera->getOrCreateStateSet()->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
435 mRoot->addChild(mBackGroundCamera.get());
437 mSceneCamera->setClearMask(GL_DEPTH_BUFFER_BIT);
438 inheritanceMask = osg::CullSettings::ALL_VARIABLES;
439 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
440 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
441 mSceneCamera->setInheritanceMask(inheritanceMask);
442 mSceneCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
443 mSceneCamera->setCullingMode(osg::CullSettings::DEFAULT_CULLING);
444 mSceneCamera->setRenderOrder(osg::CameraNode::NESTED_RENDER);
445 mRoot->addChild(mSceneCamera.get());
447 stateSet = mSceneCamera->getOrCreateStateSet();
448 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
449 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
451 // need to update the light on every frame
452 osg::LightSource* lightSource = new osg::LightSource;
453 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
454 // relative because of CameraView being just a clever transform node
455 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
456 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
457 mSceneCamera->addChild(lightSource);
459 lightSource->addChild(globals->get_scenery()->get_scene_graph());
460 lightSource->addChild(thesky->getCloudRoot());
462 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
463 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
464 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
465 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
466 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
468 // enable disable specular highlights.
469 // is the place where we might plug in an other fragment shader ...
470 osg::LightModel* lightModel = new osg::LightModel;
471 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
472 stateSet->setAttribute(lightModel);
474 // switch to enable wireframe
475 osg::PolygonMode* polygonMode = new osg::PolygonMode;
476 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
477 stateSet->setAttributeAndModes(polygonMode);
479 // scene fog handling
480 stateSet->setAttributeAndModes(mFog.get());
481 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
484 osg::CameraNode* guiCamera = new osg::CameraNode;
485 guiCamera->setRenderOrder(osg::CameraNode::POST_RENDER);
486 guiCamera->setClearMask(0);
487 inheritanceMask = osg::CullSettings::ALL_VARIABLES;
488 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
489 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
490 guiCamera->setInheritanceMask(inheritanceMask);
491 guiCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
492 guiCamera->setCullingMode(osg::CullSettings::NO_CULLING);
493 mRoot->addChild(guiCamera);
494 osg::Geode* geode = new osg::Geode;
495 geode->addDrawable(new SGPuDrawable);
496 geode->addDrawable(new SGHUDAndPanelDrawable);
497 guiCamera->addChild(geode);
499 // this one contains all lights, here we set the light states we did
500 // in the plib case with plain OpenGL
501 osg::Group* lightGroup = new osg::Group;
502 mSceneCamera->addChild(lightGroup);
503 lightGroup->addChild(globals->get_scenery()->get_gnd_lights_root());
504 lightGroup->addChild(globals->get_scenery()->get_vasi_lights_root());
505 lightGroup->addChild(globals->get_scenery()->get_rwy_lights_root());
506 lightGroup->addChild(globals->get_scenery()->get_taxi_lights_root());
508 stateSet = globals->get_scenery()->get_gnd_lights_root()->getOrCreateStateSet();
509 stateSet->setAttributeAndModes(mFog.get());
510 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
511 stateSet = globals->get_scenery()->get_vasi_lights_root()->getOrCreateStateSet();
512 stateSet->setAttributeAndModes(mRunwayLightingFog.get());
513 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
514 stateSet = globals->get_scenery()->get_rwy_lights_root()->getOrCreateStateSet();
515 stateSet->setAttributeAndModes(mRunwayLightingFog.get());
516 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
517 stateSet = globals->get_scenery()->get_taxi_lights_root()->getOrCreateStateSet();
518 stateSet->setAttributeAndModes(mTaxiLightingFog.get());
519 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
521 mCameraView->addChild(mRoot.get());
522 sceneView->setSceneData(mCameraView.get());
524 // sceneView->getState()->setCheckForGLErrors(osg::State::ONCE_PER_ATTRIBUTE);
528 // Update all Visuals (redraws anything graphics related)
530 FGRenderer::update( bool refresh_camera_settings ) {
531 bool scenery_loaded = fgGetBool("sim/sceneryloaded")
532 || fgGetBool("sim/sceneryloaded-override");
534 if ( idle_state < 1000 || !scenery_loaded ) {
535 // still initializing, draw the splash screen
536 glPushAttrib(GL_ALL_ATTRIB_BITS);
537 glPushClientAttrib(~0u);
544 // Keep resetting sim time while the sim is initializing
545 globals->set_sim_time_sec( 0.0 );
549 bool skyblend = fgGetBool("/sim/rendering/skyblend");
550 bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
551 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
552 bool distance_attenuation
553 = fgGetBool("/sim/rendering/distance-attenuation");
555 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
556 distance_attenuation );
558 static const SGPropertyNode *groundlevel_nearplane
559 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
561 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
564 double actual_visibility;
565 if (fgGetBool("/environment/clouds/status")) {
566 actual_visibility = thesky->get_visibility();
568 actual_visibility = fgGetDouble("/environment/visibility-m");
571 static double last_visibility = -9999;
572 if ( actual_visibility != last_visibility ) {
573 last_visibility = actual_visibility;
575 fog_exp_density = m_log01 / actual_visibility;
576 fog_exp2_density = sqrt_m_log01 / actual_visibility;
577 ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
578 if ( actual_visibility < 8000 ) {
579 rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
580 taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
582 rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
583 taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
585 mFog->setDensity(fog_exp2_density);
586 mRunwayLightingFog->setDensity(rwy_exp2_punch_through);
587 mTaxiLightingFog->setDensity(taxi_exp2_punch_through);
588 mGroundLightingFog->setDensity(ground_exp2_punch_through);
591 // idle_state is now 1000 meaning we've finished all our
592 // initializations and are running the main loop, so this will
593 // now work without seg faulting the system.
595 FGViewer *current__view = globals->get_current_view();
596 // Force update of center dependent values ...
597 current__view->set_dirty();
599 if ( refresh_camera_settings ) {
601 resize( fgGetInt("/sim/startup/xsize"),
602 fgGetInt("/sim/startup/ysize") );
604 SGVec3d center = globals->get_scenery()->get_center();
605 SGVec3d position = current__view->getViewPosition();
606 SGQuatd attitude = current__view->getViewOrientation();
607 SGVec3d osgPosition = attitude.transform(center - position);
608 mCameraView->setPosition(osgPosition.osg());
609 mCameraView->setAttitude(inverse(attitude).osg());
613 if ( fgGetBool("/sim/rendering/textures") ) {
614 SGVec4f clearColor(l->adj_fog_color());
615 sceneView->getCamera()->setClearColor(clearColor.osg());
618 SGVec4f clearColor(l->sky_color());
619 sceneView->getCamera()->setClearColor(clearColor.osg());
622 // update fog params if visibility has changed
623 double visibility_meters = fgGetDouble("/environment/visibility-m");
624 thesky->set_visibility(visibility_meters);
626 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
627 ( global_multi_loop * fgGetInt("/sim/speed-up") )
628 / (double)fgGetInt("/sim/model-hz") );
630 // update the sky dome
633 // The sun and moon distances are scaled down versions
634 // of the actual distance to get both the moon and the sun
635 // within the range of the far clip plane.
636 // Moon distance: 384,467 kilometers
637 // Sun distance: 150,000,000 kilometers
639 double sun_horiz_eff, moon_horiz_eff;
640 if (fgGetBool("/sim/rendering/horizon-effect")) {
641 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
642 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
644 sun_horiz_eff = moon_horiz_eff = 1.0;
647 static SGSkyState sstate;
649 sstate.view_pos = current__view->get_view_pos();
650 sstate.zero_elev = current__view->get_zero_elev();
651 sstate.view_up = current__view->get_world_up();
652 sstate.lon = current__view->getLongitude_deg()
653 * SGD_DEGREES_TO_RADIANS;
654 sstate.lat = current__view->getLatitude_deg()
655 * SGD_DEGREES_TO_RADIANS;
656 sstate.alt = current__view->getAltitudeASL_ft()
658 sstate.spin = l->get_sun_rotation();
659 sstate.gst = globals->get_time_params()->getGst();
660 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
661 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
662 sstate.sun_dist = 50000.0 * sun_horiz_eff;
663 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
664 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
665 sstate.moon_dist = 40000.0 * moon_horiz_eff;
666 sstate.sun_angle = l->get_sun_angle();
670 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
671 << l->sky_color()[0] << " "
672 << l->sky_color()[1] << " "
673 << l->sky_color()[2] << " "
674 << l->sky_color()[3] );
675 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
676 << l->fog_color()[0] << " "
677 << l->fog_color()[1] << " "
678 << l->fog_color()[2] << " "
679 << l->fog_color()[3] );
680 SG_LOG( SG_GENERAL, SG_BULK,
681 " sun_angle = " << l->sun_angle
682 << " moon_angle = " << l->moon_angle );
685 static SGSkyColor scolor;
687 scolor.sky_color = SGVec3f(l->sky_color().data());
688 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
689 scolor.cloud_color = SGVec3f(l->cloud_color().data());
690 scolor.sun_angle = l->get_sun_angle();
691 scolor.moon_angle = l->get_moon_angle();
692 scolor.nplanets = globals->get_ephem()->getNumPlanets();
693 scolor.nstars = globals->get_ephem()->getNumStars();
694 scolor.planet_data = globals->get_ephem()->getPlanets();
695 scolor.star_data = globals->get_ephem()->getStars();
697 thesky->reposition( sstate, delta_time_sec );
698 thesky->repaint( scolor );
701 SG_LOG( SG_GENERAL, SG_BULK,
702 "thesky->reposition( view_pos = " << view_pos[0] << " "
703 << view_pos[1] << " " << view_pos[2] );
704 SG_LOG( SG_GENERAL, SG_BULK,
705 " zero_elev = " << zero_elev[0] << " "
706 << zero_elev[1] << " " << zero_elev[2]
707 << " lon = " << cur_fdm_state->get_Longitude()
708 << " lat = " << cur_fdm_state->get_Latitude() );
709 SG_LOG( SG_GENERAL, SG_BULK,
710 " sun_rot = " << l->get_sun_rotation
711 << " gst = " << SGTime::cur_time_params->getGst() );
712 SG_LOG( SG_GENERAL, SG_BULK,
713 " sun ra = " << globals->get_ephem()->getSunRightAscension()
714 << " sun dec = " << globals->get_ephem()->getSunDeclination()
715 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
716 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
720 // shadows->setupShadows(
721 // current__view->getLongitude_deg(),
722 // current__view->getLatitude_deg(),
723 // globals->get_time_params()->getGst(),
724 // globals->get_ephem()->getSunRightAscension(),
725 // globals->get_ephem()->getSunDeclination(),
726 // l->get_sun_angle());
730 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
731 SGVec4f color(l->adj_fog_color());
732 mFog->setColor(color.osg());
733 mRunwayLightingFog->setColor(color.osg());
734 mTaxiLightingFog->setColor(color.osg());
735 mGroundLightingFog->setColor(color.osg());
739 // sgEnviro.setLight(l->adj_fog_color());
741 // texture parameters
742 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
744 double agl = current__view->getAltitudeASL_ft()*SG_FEET_TO_METER
745 - current__view->getSGLocation()->get_cur_elev_m();
747 float scene_nearplane, scene_farplane;
749 scene_nearplane = 10.0f;
750 scene_farplane = 120000.0f;
752 scene_nearplane = groundlevel_nearplane->getDoubleValue();
753 scene_farplane = 120000.0f;
756 setNearFar( scene_nearplane, scene_farplane );
758 // sgEnviro.startOfFrame(current__view->get_view_pos(),
759 // current__view->get_world_up(),
760 // current__view->getLongitude_deg(),
761 // current__view->getLatitude_deg(),
762 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
766 // sgEnviro.drawLightning();
768 // double current_view_origin_airspeed_horiz_kt =
769 // fgGetDouble("/velocities/airspeed-kt", 0.0)
770 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
771 // * SGD_DEGREES_TO_RADIANS);
772 // TODO:find the real view speed, not the AC one
773 // sgEnviro.drawPrecipitation(
774 // fgGetDouble("/environment/metar/rain-norm", 0.0),
775 // fgGetDouble("/environment/metar/snow-norm", 0.0),
776 // fgGetDouble("/environment/metar/hail-norm", 0.0),
777 // current__view->getPitch_deg() + current__view->getPitchOffset_deg(),
778 // current__view->getRoll_deg() + current__view->getRollOffset_deg(),
779 // - current__view->getHeadingOffset_deg(),
780 // current_view_origin_airspeed_horiz_kt
785 // shadows->endOfFrame();
787 // need to call the update visitor once
788 globals->get_aircraft_model()->select( true );
789 FGTileMgr::set_tile_filter( true );
790 mFrameStamp->setReferenceTime(globals->get_sim_time_sec());
791 mFrameStamp->setFrameNumber(1+mFrameStamp->getFrameNumber());
792 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
793 mUpdateVisitor->setViewData(current__view->getViewPosition(),
794 current__view->getViewOrientation());
795 mUpdateVisitor->setSceneryCenter(globals->get_scenery()->get_center());
796 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
797 mUpdateVisitor->setLight(direction, l->scene_ambient(),
798 l->scene_diffuse(), l->scene_specular());
799 mUpdateVisitor->setVisibility(actual_visibility);
807 // options.cxx needs to see this for toggle_panel()
808 // Handle new window size or exposure
810 FGRenderer::resize( int width, int height ) {
813 if ( (!fgGetBool("/sim/virtual-cockpit"))
814 && fgPanelVisible() && idle_state == 1000 ) {
815 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
816 globals->get_current_panel()->getYOffset()) / 768.0);
821 sceneView->getViewport()->setViewport(0, height - view_h, width, view_h);
823 static int lastwidth = 0;
824 static int lastheight = 0;
825 if (width != lastwidth)
826 fgSetInt("/sim/startup/xsize", lastwidth = width);
827 if (height != lastheight)
828 fgSetInt("/sim/startup/ysize", lastheight = height);
830 guiInitMouse(width, height);
833 FGViewMgr *viewmgr = globals->get_viewmgr();
835 for ( int i = 0; i < viewmgr->size(); ++i ) {
836 viewmgr->get_view(i)->
837 set_aspect_ratio((float)view_h / (float)width);
840 setFOV( viewmgr->get_current_view()->get_h_fov(),
841 viewmgr->get_current_view()->get_v_fov() );
842 // cout << "setFOV(" << viewmgr->get_current_view()->get_h_fov()
843 // << ", " << viewmgr->get_current_view()->get_v_fov() << ")"
849 // These are wrapper functions around ssgSetNearFar() and ssgSetFOV()
850 // which will post process and rewrite the resulting frustum if we
851 // want to do asymmetric view frustums.
853 static void fgHackFrustum() {
855 // specify a percent of the configured view frustum to actually
856 // display. This is a bit of a hack to achieve asymmetric view
857 // frustums. For instance, if you want to display two monitors
858 // side by side, you could specify each with a double fov, a 0.5
859 // aspect ratio multiplier, and then the left side monitor would
860 // have a left_pct = 0.0, a right_pct = 0.5, a bottom_pct = 0.0,
861 // and a top_pct = 1.0. The right side monitor would have a
862 // left_pct = 0.5 and a right_pct = 1.0.
864 static SGPropertyNode *left_pct
865 = fgGetNode("/sim/current-view/frustum-left-pct");
866 static SGPropertyNode *right_pct
867 = fgGetNode("/sim/current-view/frustum-right-pct");
868 static SGPropertyNode *bottom_pct
869 = fgGetNode("/sim/current-view/frustum-bottom-pct");
870 static SGPropertyNode *top_pct
871 = fgGetNode("/sim/current-view/frustum-top-pct");
876 sceneView->getProjectionMatrixAsFrustum(left, right, bottom, top, zNear, zFar);
877 // cout << " l = " << f->getLeft()
878 // << " r = " << f->getRight()
879 // << " b = " << f->getBot()
880 // << " t = " << f->getTop()
881 // << " n = " << f->getNear()
882 // << " f = " << f->getFar()
885 double width = right - left;
886 double height = top - bottom;
890 if ( left_pct != NULL ) {
891 l = left + width * left_pct->getDoubleValue();
896 if ( right_pct != NULL ) {
897 r = left + width * right_pct->getDoubleValue();
902 if ( bottom_pct != NULL ) {
903 b = bottom + height * bottom_pct->getDoubleValue();
908 if ( top_pct != NULL ) {
909 t = bottom + height * top_pct->getDoubleValue();
914 sceneView->setProjectionMatrixAsFrustum(l, r, b, t, zNear, zFar);
918 // we need some static storage space for these values. However, we
919 // can't store it in a renderer class object because the functions
920 // that manipulate these are static. They are static so they can
921 // interface to the display callback system. There's probably a
922 // better way, there has to be a better way, but I'm not seeing it
924 static float fov_width = 55.0;
925 static float fov_height = 42.0;
926 static float fov_near = 1.0;
927 static float fov_far = 1000.0;
930 /** FlightGear code should use this routine to set the FOV rather than
931 * calling the ssg routine directly
933 void FGRenderer::setFOV( float w, float h ) {
937 sceneView->setProjectionMatrixAsPerspective(fov_height,
938 fov_width/fov_height,
940 // fully specify the view frustum before hacking it (so we don't
941 // accumulate hacked effects
943 // sgEnviro.setFOV( w, h );
947 /** FlightGear code should use this routine to set the Near/Far clip
948 * planes rather than calling the ssg routine directly
950 void FGRenderer::setNearFar( float n, float f ) {
951 // OSGFIXME: we have currently too much z-buffer fights
956 sceneView->setProjectionMatrixAsPerspective(fov_height,
957 fov_width/fov_height,
960 sceneView->getCamera()->setNearFarRatio(fov_near/fov_far);
961 mSceneCamera->setNearFarRatio(fov_near/fov_far);
963 // fully specify the view frustum before hacking it (so we don't
964 // accumulate hacked effects
968 bool FGRenderer::getPickInfo( SGVec3d& pt, SGVec3d& dir,
969 unsigned x, unsigned y )
971 // Get the matrices involved in the transform from global to screen
973 osg::Matrix pm = sceneView->getCamera()->getProjectionMatrix();
976 osg::NodePathList paths;
977 paths = globals->get_scenery()->get_scene_graph()->getParentalNodePaths();
978 if (!paths.empty()) {
979 // Ok, we know that this should not have multiple parents ...
980 // FIXME: is this allways true?
981 mv = osg::computeLocalToEye(sceneView->getCamera()->getViewMatrix(),
982 paths.front(), false);
985 // Compose and invert
986 osg::Matrix m = osg::Matrix::inverse(mv*pm);
988 // Get the width and height of the display to be able to normalize the
990 float width = fgGetInt("/sim/startup/xsize");
991 float height = fgGetInt("/sim/startup/ysize");
993 // Compute some coordinates of in the line from the eyepoint to the
994 // mouse click coodinates.
995 // First build the normalized projection coordinates
996 osg::Vec4 normPt((2*x - width)/width, -(2*y - height)/height, 1, 1);
997 // Transform them into the real world
998 osg::Vec4 worldPt4 = m.preMult(normPt);
999 if (fabs(worldPt4[3]) < SGLimitsf::min())
1001 SGVec3f worldPt(worldPt4[0]/worldPt4[3],
1002 worldPt4[1]/worldPt4[3],
1003 worldPt4[2]/worldPt4[3]);
1005 // Now build a direction from the point
1006 FGViewer* view = globals->get_current_view();
1007 dir = normalize(toVec3d(worldPt - SGVec3f(view->get_view_pos())));
1009 // Copy the start point
1010 pt = SGVec3d(view->get_absolute_view_pos());
1012 // OSGFIXME: ist this sufficient??? especially the precision problems here??
1013 // bool mSceneView->projectWindowXYIntoObject(int x,int y,osg::Vec3& near_point,osg::Vec3& far_point) const;
1019 // end of renderer.cxx