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 <GUI/new_gui.hxx>
96 #include <Instrumentation/instrument_mgr.hxx>
97 #include <Instrumentation/HUD/HUD.hxx>
100 #include "renderer.hxx"
103 class SGPuDrawable : public osg::Drawable {
107 // Dynamic stuff, do not store geometry
108 setUseDisplayList(false);
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);
119 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
121 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
122 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
124 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
125 { drawImplementation(*renderInfo.getState()); }
126 void drawImplementation(osg::State& state) const
128 state.pushStateSet(getStateSet());
130 state.setActiveTextureUnit(0);
131 state.setClientActiveTextureUnit(0);
132 state.disableAllVertexArrays();
134 glPushAttrib(GL_ALL_ATTRIB_BITS);
135 glPushClientAttrib(~0u);
143 state.dirtyAllModes();
144 state.dirtyAllAttributes();
145 state.dirtyAllVertexArrays();
148 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
149 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
154 class SGHUDAndPanelDrawable : public osg::Drawable {
156 SGHUDAndPanelDrawable()
158 // Dynamic stuff, do not store geometry
159 setUseDisplayList(false);
161 osg::StateSet* stateSet = getOrCreateStateSet();
162 stateSet->setRenderBinDetails(1000, "RenderBin");
164 // speed optimization?
165 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
166 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
167 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
168 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
169 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
171 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
173 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
174 { drawImplementation(*renderInfo.getState()); }
175 void drawImplementation(osg::State& state) const
177 state.pushStateSet(getStateSet());
179 state.setActiveTextureUnit(0);
180 state.setClientActiveTextureUnit(0);
181 state.disableAllVertexArrays();
183 glPushAttrib(GL_ALL_ATTRIB_BITS);
184 glPushClientAttrib(~0u);
186 fgCockpitUpdate(&state);
188 FGInstrumentMgr *instr = static_cast<FGInstrumentMgr*>(globals->get_subsystem("instrumentation"));
189 HUD *hud = static_cast<HUD*>(instr->get_subsystem("hud"));
192 // update the panel subsystem
193 if ( globals->get_current_panel() != NULL )
194 globals->get_current_panel()->update(state);
195 // We don't need a state here - can be safely removed when we can pick
203 state.dirtyAllModes();
204 state.dirtyAllAttributes();
205 state.dirtyAllVertexArrays();
208 virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
209 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
214 class FGLightSourceUpdateCallback : public osg::NodeCallback {
216 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
218 assert(dynamic_cast<osg::LightSource*>(node));
219 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
220 osg::Light* light = lightSource->getLight();
222 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
223 light->setAmbient(l->scene_ambient().osg());
224 light->setDiffuse(l->scene_diffuse().osg());
225 light->setSpecular(l->scene_specular().osg());
226 SGVec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
227 light->setPosition(position.osg());
228 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
229 light->setDirection(direction.osg());
230 light->setSpotExponent(0);
231 light->setSpotCutoff(180);
232 light->setConstantAttenuation(1);
233 light->setLinearAttenuation(0);
234 light->setQuadraticAttenuation(0);
240 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
242 FGWireFrameModeUpdateCallback() :
243 mWireframe(fgGetNode("/sim/rendering/wireframe"))
245 virtual void operator()(osg::StateAttribute* stateAttribute,
248 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
249 osg::PolygonMode* polygonMode;
250 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
252 if (mWireframe->getBoolValue())
253 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
254 osg::PolygonMode::LINE);
256 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
257 osg::PolygonMode::FILL);
260 SGSharedPtr<SGPropertyNode> mWireframe;
263 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
265 FGLightModelUpdateCallback() :
266 mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
268 virtual void operator()(osg::StateAttribute* stateAttribute,
271 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
272 osg::LightModel* lightModel;
273 lightModel = static_cast<osg::LightModel*>(stateAttribute);
276 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
277 lightModel->setAmbientIntensity(l->scene_ambient().osg());
279 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
281 lightModel->setTwoSided(true);
282 lightModel->setLocalViewer(false);
284 if (mHighlights->getBoolValue()) {
285 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
287 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
291 SGSharedPtr<SGPropertyNode> mHighlights;
294 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
296 FGFogEnableUpdateCallback() :
297 mFogEnabled(fgGetNode("/sim/rendering/fog"))
299 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
301 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
302 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
304 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
308 SGSharedPtr<SGPropertyNode> mFogEnabled;
311 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
313 virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
315 assert(dynamic_cast<SGUpdateVisitor*>(nv));
316 assert(dynamic_cast<osg::Fog*>(sa));
317 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
318 osg::Fog* fog = static_cast<osg::Fog*>(sa);
319 fog->setMode(osg::Fog::EXP2);
320 fog->setColor(updateVisitor->getFogColor().osg());
321 fog->setDensity(updateVisitor->getFogExp2Density());
325 // update callback for the switch node guarding that splash
326 class FGScenerySwitchCallback : public osg::NodeCallback {
328 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
330 assert(dynamic_cast<osg::Switch*>(node));
331 osg::Switch* sw = static_cast<osg::Switch*>(node);
333 double t = globals->get_sim_time_sec();
334 bool enabled = 0 < t;
335 sw->setValue(0, enabled);
345 osg::ref_ptr<osgUtil::SceneView> sceneView = new osgUtil::SceneView; // This SceneView is used by class FGJpegHttpd ( jpg-httpd.cxx )
346 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
347 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
349 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
351 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
353 static osg::ref_ptr<osg::CameraView> mCameraView = new osg::CameraView;
354 static osg::ref_ptr<osg::Camera> mBackGroundCamera = new osg::Camera;
356 FGRenderer::FGRenderer()
358 #ifdef FG_JPEG_SERVER
359 jpgRenderFrame = FGRenderer::update;
363 FGRenderer::~FGRenderer()
365 #ifdef FG_JPEG_SERVER
366 jpgRenderFrame = NULL;
370 // Initialize various GL/view parameters
372 FGRenderer::splashinit( void ) {
373 // Add the splash screen node
374 mRealRoot->addChild(fgCreateSplashNode());
375 sceneView->setSceneData(mRealRoot.get());
377 sceneView->setDefaults(osgUtil::SceneView::COMPILE_GLOBJECTS_AT_INIT);
378 sceneView->setFrameStamp(mFrameStamp.get());
379 sceneView->setUpdateVisitor(mUpdateVisitor.get());
383 FGRenderer::init( void ) {
385 osg::initNotifyLevel();
387 // The number of polygon-offset "units" to place between layers. In
388 // principle, one is supposed to be enough. In practice, I find that
389 // my hardware/driver requires many more.
390 osg::PolygonOffset::setUnitsMultiplier(1);
391 osg::PolygonOffset::setFactorMultiplier(1);
393 // Go full screen if requested ...
394 if ( fgGetBool("/sim/startup/fullscreen") )
397 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
398 (!fgGetBool("/sim/rendering/shading"))) {
399 // if fastest fog requested, or if flat shading force fastest
400 glHint ( GL_FOG_HINT, GL_FASTEST );
401 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
402 glHint ( GL_FOG_HINT, GL_DONT_CARE );
405 glHint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
406 glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
407 glHint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
410 sceneView->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
411 sceneView->getCamera()->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
414 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
416 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
418 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
419 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
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);
426 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
428 // this will be set below
429 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
431 osg::Material* material = new osg::Material;
432 stateSet->setAttribute(material);
434 stateSet->setTextureAttribute(0, new osg::TexEnv);
435 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
438 // stateSet->setAttribute(new osg::CullFace(osg::CullFace::BACK));
439 // stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::ON);
441 // this is the topmost scenegraph node for osg
442 mBackGroundCamera->addChild(thesky->getPreRoot());
443 mBackGroundCamera->setClearMask(0);
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);
454 stateSet = mBackGroundCamera->getOrCreateStateSet();
455 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
457 osg::Group* sceneGroup = new osg::Group;
458 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
459 sceneGroup->addChild(thesky->getCloudRoot());
461 stateSet = sceneGroup->getOrCreateStateSet();
462 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
463 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
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);
473 lightSource->addChild(mBackGroundCamera.get());
474 lightSource->addChild(sceneGroup);
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);
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);
489 // switch to enable wireframe
490 osg::PolygonMode* polygonMode = new osg::PolygonMode;
491 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
492 stateSet->setAttributeAndModes(polygonMode);
494 // scene fog handling
495 osg::Fog* fog = new osg::Fog;
496 fog->setUpdateCallback(new FGFogUpdateCallback);
497 stateSet->setAttributeAndModes(fog);
498 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
501 osg::Camera* guiCamera = new osg::Camera;
502 guiCamera->setRenderOrder(osg::Camera::POST_RENDER, 100);
503 guiCamera->setClearMask(0);
504 inheritanceMask = osg::CullSettings::ALL_VARIABLES;
505 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
506 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
507 guiCamera->setInheritanceMask(inheritanceMask);
508 guiCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
509 guiCamera->setCullingMode(osg::CullSettings::NO_CULLING);
510 osg::Geode* geode = new osg::Geode;
511 geode->addDrawable(new SGPuDrawable);
512 geode->addDrawable(new SGHUDAndPanelDrawable);
513 guiCamera->addChild(geode);
515 mCameraView->addChild(mRoot.get());
517 osg::Switch* sw = new osg::Switch;
518 sw->setUpdateCallback(new FGScenerySwitchCallback);
519 sw->addChild(mCameraView.get());
521 mRealRoot->addChild(sw);
522 mRealRoot->addChild(FGCreateRedoutNode());
523 mRealRoot->addChild(guiCamera);
527 // Update all Visuals (redraws anything graphics related)
529 FGRenderer::update( bool refresh_camera_settings ) {
530 bool scenery_loaded = fgGetBool("sim/sceneryloaded")
531 || fgGetBool("sim/sceneryloaded-override");
533 if ( idle_state < 1000 || !scenery_loaded ) {
534 fgSetDouble("/sim/startup/splash-alpha", 1.0);
536 // Keep resetting sim time while the sim is initializing
537 globals->set_sim_time_sec( 0.0 );
539 // the splash screen is now in the scenegraph
547 // Fade out the splash screen over the first three seconds.
548 double sAlpha = SGMiscd::max(0, (2.5 - globals->get_sim_time_sec()) / 2.5);
549 fgSetDouble("/sim/startup/splash-alpha", sAlpha);
551 bool skyblend = fgGetBool("/sim/rendering/skyblend");
552 bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
553 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
554 bool distance_attenuation
555 = fgGetBool("/sim/rendering/distance-attenuation");
557 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
558 distance_attenuation );
560 static const SGPropertyNode *groundlevel_nearplane
561 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
563 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
566 double actual_visibility;
567 if (fgGetBool("/environment/clouds/status")) {
568 actual_visibility = thesky->get_visibility();
570 actual_visibility = fgGetDouble("/environment/visibility-m");
573 // idle_state is now 1000 meaning we've finished all our
574 // initializations and are running the main loop, so this will
575 // now work without seg faulting the system.
577 FGViewer *current__view = globals->get_current_view();
578 // Force update of center dependent values ...
579 current__view->set_dirty();
581 if ( refresh_camera_settings ) {
583 resize( fgGetInt("/sim/startup/xsize"),
584 fgGetInt("/sim/startup/ysize") );
586 SGVec3d position = current__view->getViewPosition();
587 SGQuatd attitude = current__view->getViewOrientation();
588 SGVec3d osgPosition = attitude.transform(-position);
589 mCameraView->setPosition(osgPosition.osg());
590 mCameraView->setAttitude(inverse(attitude).osg());
594 if ( fgGetBool("/sim/rendering/textures") ) {
595 SGVec4f clearColor(l->adj_fog_color());
596 sceneView->getCamera()->setClearColor(clearColor.osg());
599 SGVec4f clearColor(l->sky_color());
600 sceneView->getCamera()->setClearColor(clearColor.osg());
603 // update fog params if visibility has changed
604 double visibility_meters = fgGetDouble("/environment/visibility-m");
605 thesky->set_visibility(visibility_meters);
607 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
608 ( global_multi_loop * fgGetInt("/sim/speed-up") )
609 / (double)fgGetInt("/sim/model-hz") );
611 // update the sky dome
614 // The sun and moon distances are scaled down versions
615 // of the actual distance to get both the moon and the sun
616 // within the range of the far clip plane.
617 // Moon distance: 384,467 kilometers
618 // Sun distance: 150,000,000 kilometers
620 double sun_horiz_eff, moon_horiz_eff;
621 if (fgGetBool("/sim/rendering/horizon-effect")) {
622 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
623 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
625 sun_horiz_eff = moon_horiz_eff = 1.0;
628 static SGSkyState sstate;
630 sstate.view_pos = toVec3f(current__view->get_view_pos());
631 sstate.zero_elev = toVec3f(current__view->get_zero_elev());
632 sstate.view_up = current__view->get_world_up();
633 sstate.lon = current__view->getLongitude_deg()
634 * SGD_DEGREES_TO_RADIANS;
635 sstate.lat = current__view->getLatitude_deg()
636 * SGD_DEGREES_TO_RADIANS;
637 sstate.alt = current__view->getAltitudeASL_ft()
639 sstate.spin = l->get_sun_rotation();
640 sstate.gst = globals->get_time_params()->getGst();
641 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
642 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
643 sstate.sun_dist = 50000.0 * sun_horiz_eff;
644 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
645 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
646 sstate.moon_dist = 40000.0 * moon_horiz_eff;
647 sstate.sun_angle = l->get_sun_angle();
651 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
652 << l->sky_color()[0] << " "
653 << l->sky_color()[1] << " "
654 << l->sky_color()[2] << " "
655 << l->sky_color()[3] );
656 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
657 << l->fog_color()[0] << " "
658 << l->fog_color()[1] << " "
659 << l->fog_color()[2] << " "
660 << l->fog_color()[3] );
661 SG_LOG( SG_GENERAL, SG_BULK,
662 " sun_angle = " << l->sun_angle
663 << " moon_angle = " << l->moon_angle );
666 static SGSkyColor scolor;
668 scolor.sky_color = SGVec3f(l->sky_color().data());
669 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
670 scolor.cloud_color = SGVec3f(l->cloud_color().data());
671 scolor.sun_angle = l->get_sun_angle();
672 scolor.moon_angle = l->get_moon_angle();
673 scolor.nplanets = globals->get_ephem()->getNumPlanets();
674 scolor.nstars = globals->get_ephem()->getNumStars();
675 scolor.planet_data = globals->get_ephem()->getPlanets();
676 scolor.star_data = globals->get_ephem()->getStars();
678 thesky->reposition( sstate, delta_time_sec );
679 thesky->repaint( scolor );
682 SG_LOG( SG_GENERAL, SG_BULK,
683 "thesky->reposition( view_pos = " << view_pos[0] << " "
684 << view_pos[1] << " " << view_pos[2] );
685 SG_LOG( SG_GENERAL, SG_BULK,
686 " zero_elev = " << zero_elev[0] << " "
687 << zero_elev[1] << " " << zero_elev[2]
688 << " lon = " << cur_fdm_state->get_Longitude()
689 << " lat = " << cur_fdm_state->get_Latitude() );
690 SG_LOG( SG_GENERAL, SG_BULK,
691 " sun_rot = " << l->get_sun_rotation
692 << " gst = " << SGTime::cur_time_params->getGst() );
693 SG_LOG( SG_GENERAL, SG_BULK,
694 " sun ra = " << globals->get_ephem()->getSunRightAscension()
695 << " sun dec = " << globals->get_ephem()->getSunDeclination()
696 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
697 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
701 // shadows->setupShadows(
702 // current__view->getLongitude_deg(),
703 // current__view->getLatitude_deg(),
704 // globals->get_time_params()->getGst(),
705 // globals->get_ephem()->getSunRightAscension(),
706 // globals->get_ephem()->getSunDeclination(),
707 // l->get_sun_angle());
711 // sgEnviro.setLight(l->adj_fog_color());
713 // texture parameters
714 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
716 double agl = current__view->getAltitudeASL_ft()*SG_FEET_TO_METER
717 - current__view->getSGLocation()->get_cur_elev_m();
719 float scene_nearplane, scene_farplane;
721 scene_nearplane = 10.0f;
722 scene_farplane = 120000.0f;
724 scene_nearplane = groundlevel_nearplane->getDoubleValue();
725 scene_farplane = 120000.0f;
727 setNearFar( scene_nearplane, scene_farplane );
729 // sgEnviro.startOfFrame(current__view->get_view_pos(),
730 // current__view->get_world_up(),
731 // current__view->getLongitude_deg(),
732 // current__view->getLatitude_deg(),
733 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
737 // sgEnviro.drawLightning();
739 // double current_view_origin_airspeed_horiz_kt =
740 // fgGetDouble("/velocities/airspeed-kt", 0.0)
741 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
742 // * SGD_DEGREES_TO_RADIANS);
743 // TODO:find the real view speed, not the AC one
744 // sgEnviro.drawPrecipitation(
745 // fgGetDouble("/environment/metar/rain-norm", 0.0),
746 // fgGetDouble("/environment/metar/snow-norm", 0.0),
747 // fgGetDouble("/environment/metar/hail-norm", 0.0),
748 // current__view->getPitch_deg() + current__view->getPitchOffset_deg(),
749 // current__view->getRoll_deg() + current__view->getRollOffset_deg(),
750 // - current__view->getHeadingOffset_deg(),
751 // current_view_origin_airspeed_horiz_kt
756 // shadows->endOfFrame();
758 // need to call the update visitor once
759 mFrameStamp->setReferenceTime(globals->get_sim_time_sec());
760 mFrameStamp->setFrameNumber(1+mFrameStamp->getFrameNumber());
761 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
762 mUpdateVisitor->setViewData(current__view->getViewPosition(),
763 current__view->getViewOrientation());
764 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
765 mUpdateVisitor->setLight(direction, l->scene_ambient(),
766 l->scene_diffuse(), l->scene_specular(),
768 l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
769 mUpdateVisitor->setVisibility(actual_visibility);
771 if (fgGetBool("/sim/panel-hotspots"))
772 sceneView->setCullMask(sceneView->getCullMask()|SG_NODEMASK_PICK_BIT);
774 sceneView->setCullMask(sceneView->getCullMask()&(~SG_NODEMASK_PICK_BIT));
783 // options.cxx needs to see this for toggle_panel()
784 // Handle new window size or exposure
786 FGRenderer::resize( int width, int height ) {
789 if ( (!fgGetBool("/sim/virtual-cockpit"))
790 && fgPanelVisible() && idle_state == 1000 ) {
791 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
792 globals->get_current_panel()->getYOffset()) / 768.0);
797 sceneView->getViewport()->setViewport(0, height - view_h, width, view_h);
799 static int lastwidth = 0;
800 static int lastheight = 0;
801 if (width != lastwidth)
802 fgSetInt("/sim/startup/xsize", lastwidth = width);
803 if (height != lastheight)
804 fgSetInt("/sim/startup/ysize", lastheight = height);
806 guiInitMouse(width, height);
809 FGViewMgr *viewmgr = globals->get_viewmgr();
811 for ( int i = 0; i < viewmgr->size(); ++i ) {
812 viewmgr->get_view(i)->
813 set_aspect_ratio((float)view_h / (float)width);
816 setFOV( viewmgr->get_current_view()->get_h_fov(),
817 viewmgr->get_current_view()->get_v_fov() );
822 // These are wrapper functions around ssgSetNearFar() and ssgSetFOV()
823 // which will post process and rewrite the resulting frustum if we
824 // want to do asymmetric view frustums.
826 static void fgHackFrustum() {
828 // specify a percent of the configured view frustum to actually
829 // display. This is a bit of a hack to achieve asymmetric view
830 // frustums. For instance, if you want to display two monitors
831 // side by side, you could specify each with a double fov, a 0.5
832 // aspect ratio multiplier, and then the left side monitor would
833 // have a left_pct = 0.0, a right_pct = 0.5, a bottom_pct = 0.0,
834 // and a top_pct = 1.0. The right side monitor would have a
835 // left_pct = 0.5 and a right_pct = 1.0.
837 static SGPropertyNode *left_pct
838 = fgGetNode("/sim/current-view/frustum-left-pct");
839 static SGPropertyNode *right_pct
840 = fgGetNode("/sim/current-view/frustum-right-pct");
841 static SGPropertyNode *bottom_pct
842 = fgGetNode("/sim/current-view/frustum-bottom-pct");
843 static SGPropertyNode *top_pct
844 = fgGetNode("/sim/current-view/frustum-top-pct");
849 sceneView->getProjectionMatrixAsFrustum(left, right, bottom, top, zNear, zFar);
850 // cout << " l = " << f->getLeft()
851 // << " r = " << f->getRight()
852 // << " b = " << f->getBot()
853 // << " t = " << f->getTop()
854 // << " n = " << f->getNear()
855 // << " f = " << f->getFar()
858 double width = right - left;
859 double height = top - bottom;
863 if ( left_pct != NULL ) {
864 l = left + width * left_pct->getDoubleValue();
869 if ( right_pct != NULL ) {
870 r = left + width * right_pct->getDoubleValue();
875 if ( bottom_pct != NULL ) {
876 b = bottom + height * bottom_pct->getDoubleValue();
881 if ( top_pct != NULL ) {
882 t = bottom + height * top_pct->getDoubleValue();
887 sceneView->setProjectionMatrixAsFrustum(l, r, b, t, zNear, zFar);
891 // we need some static storage space for these values. However, we
892 // can't store it in a renderer class object because the functions
893 // that manipulate these are static. They are static so they can
894 // interface to the display callback system. There's probably a
895 // better way, there has to be a better way, but I'm not seeing it
897 static float fov_width = 55.0;
898 static float fov_height = 42.0;
899 static float fov_near = 1.0;
900 static float fov_far = 1000.0;
903 /** FlightGear code should use this routine to set the FOV rather than
904 * calling the ssg routine directly
906 void FGRenderer::setFOV( float w, float h ) {
910 sceneView->setProjectionMatrixAsPerspective(fov_height,
911 fov_width/fov_height,
913 // fully specify the view frustum before hacking it (so we don't
914 // accumulate hacked effects
916 // sgEnviro.setFOV( w, h );
920 /** FlightGear code should use this routine to set the Near/Far clip
921 * planes rather than calling the ssg routine directly
923 void FGRenderer::setNearFar( float n, float f ) {
924 // OSGFIXME: we have currently too much z-buffer fights
929 sceneView->setProjectionMatrixAsPerspective(fov_height,
930 fov_width/fov_height,
933 // fully specify the view frustum before hacking it (so we don't
934 // accumulate hacked effects
939 FGRenderer::pick( unsigned x, unsigned y,
940 std::vector<SGSceneryPick>& pickList )
942 // wipe out the return ...
945 // we can get called early ...
946 if (!sceneView.valid())
949 osg::Node* sceneData = globals->get_scenery()->get_scene_graph();
952 osg::Viewport* viewport = sceneView->getViewport();
956 // don't know why, but the update has partly happened somehow,
957 // so update the scenery part of the viewer
958 FGViewer *current_view = globals->get_current_view();
959 // Force update of center dependent values ...
960 current_view->set_dirty();
961 SGVec3d position = current_view->getViewPosition();
962 SGQuatd attitude = current_view->getViewOrientation();
963 SGVec3d osgPosition = attitude.transform(-position);
964 mCameraView->setPosition(osgPosition.osg());
965 mCameraView->setAttitude(inverse(attitude).osg());
967 osg::Matrix projection(sceneView->getProjectionMatrix());
968 osg::Matrix modelview(sceneView->getViewMatrix());
970 osg::NodePathList nodePath = sceneData->getParentalNodePaths();
971 // modify the view matrix so that it accounts for this nodePath's
972 // accumulated transform
973 if (!nodePath.empty())
974 modelview.preMult(computeLocalToWorld(nodePath.front()));
976 // swap the y values ...
977 y = viewport->height() - y;
978 // set up the pick visitor
979 osgUtil::PickVisitor pickVisitor(viewport, projection, modelview, x, y);
980 sceneData->accept(pickVisitor);
981 if (!pickVisitor.hits())
984 // collect all interaction callbacks on the pick ray.
985 // They get stored in the pickCallbacks list where they are sorted back
986 // to front and croasest to finest wrt the scenery node they are attached to
987 osgUtil::PickVisitor::LineSegmentHitListMap::const_iterator mi;
988 for (mi = pickVisitor.getSegHitList().begin();
989 mi != pickVisitor.getSegHitList().end();
991 osgUtil::IntersectVisitor::HitList::const_iterator hi;
992 for (hi = mi->second.begin(); hi != mi->second.end(); ++hi) {
993 // ok, go back the nodes and ask for intersection callbacks,
994 // execute them in top down order
995 const osg::NodePath& np = hi->getNodePath();
996 osg::NodePath::const_reverse_iterator npi;
997 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
998 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
1001 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
1002 SGPickCallback* pickCallback = ud->getPickCallback(i);
1005 SGSceneryPick sceneryPick;
1006 /// note that this is done totally in doubles instead of
1007 /// just using getWorldIntersectionPoint
1008 osg::Vec3d localPt = hi->getLocalIntersectPoint();
1009 sceneryPick.info.local = SGVec3d(localPt);
1010 if (hi->getMatrix())
1011 sceneryPick.info.wgs84 = SGVec3d(localPt*(*hi->getMatrix()));
1013 sceneryPick.info.wgs84 = SGVec3d(localPt);
1014 sceneryPick.callback = pickCallback;
1015 pickList.push_back(sceneryPick);
1021 return !pickList.empty();
1024 // end of renderer.cxx