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/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>
52 #include <osg/Version>
55 #include <osgUtil/SceneView>
56 #include <osgUtil/UpdateVisitor>
57 #include <osgUtil/IntersectVisitor>
58 #include <osgUtil/LineSegmentIntersector>
60 #include <osg/io_utils>
61 #include <osgDB/WriteFile>
62 #include <osgDB/ReadFile>
65 #include <simgear/math/SGMath.hxx>
66 #include <simgear/screen/extensions.hxx>
67 #include <simgear/scene/material/matlib.hxx>
68 #include <simgear/scene/model/animation.hxx>
69 #include <simgear/scene/model/placement.hxx>
70 #include <simgear/scene/util/SGUpdateVisitor.hxx>
71 #include <simgear/scene/util/RenderConstants.hxx>
72 #include <simgear/scene/tgdb/GroundLightManager.hxx>
73 #include <simgear/scene/tgdb/pt_lights.hxx>
74 #include <simgear/props/props.hxx>
75 #include <simgear/timing/sg_time.hxx>
76 #include <simgear/ephemeris/ephemeris.hxx>
77 #include <simgear/math/sg_random.h>
79 #include <simgear/screen/jpgfactory.hxx>
82 #include <simgear/environment/visual_enviro.hxx>
84 #include <Scenery/tileentry.hxx>
85 #include <Time/light.hxx>
86 #include <Time/light.hxx>
87 #include <Aircraft/aircraft.hxx>
88 #include <Cockpit/panel.hxx>
89 #include <Cockpit/cockpit.hxx>
90 #include <Cockpit/hud.hxx>
91 #include <Model/panelnode.hxx>
92 #include <Model/modelmgr.hxx>
93 #include <Model/acmodel.hxx>
94 #include <Scenery/scenery.hxx>
95 #include <Scenery/redout.hxx>
96 #include <Scenery/tilemgr.hxx>
97 #include <GUI/new_gui.hxx>
98 #include <Instrumentation/instrument_mgr.hxx>
99 #include <Instrumentation/HUD/HUD.hxx>
100 #include <Environment/precipitation_mgr.hxx>
102 #include <Include/general.hxx>
103 #include "splash.hxx"
104 #include "renderer.hxx"
106 #include "ViewPartitionNode.hxx"
108 // XXX Make this go away when OSG 2.2 is released.
109 #if (FG_OSG_VERSION >= 21004)
110 #define UPDATE_VISITOR_IN_VIEWER 1
113 class FGHintUpdateCallback : public osg::StateAttribute::Callback {
115 FGHintUpdateCallback(const char* configNode) :
116 mConfigNode(fgGetNode(configNode, true))
118 virtual void operator()(osg::StateAttribute* stateAttribute,
121 assert(dynamic_cast<osg::Hint*>(stateAttribute));
122 osg::Hint* hint = static_cast<osg::Hint*>(stateAttribute);
124 const char* value = mConfigNode->getStringValue();
126 hint->setMode(GL_DONT_CARE);
127 else if (0 == strcmp(value, "nicest"))
128 hint->setMode(GL_NICEST);
129 else if (0 == strcmp(value, "fastest"))
130 hint->setMode(GL_FASTEST);
132 hint->setMode(GL_DONT_CARE);
135 SGSharedPtr<SGPropertyNode> mConfigNode;
139 class SGPuDrawable : public osg::Drawable {
143 // Dynamic stuff, do not store geometry
144 setUseDisplayList(false);
146 osg::StateSet* stateSet = getOrCreateStateSet();
147 stateSet->setRenderBinDetails(1001, "RenderBin");
148 // speed optimization?
149 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
150 // We can do translucent menus, so why not. :-)
151 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
152 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
153 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
155 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
157 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
158 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
160 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
161 { drawImplementation(*renderInfo.getState()); }
162 void drawImplementation(osg::State& state) const
164 if (!fgOSIsMainContext(state.getGraphicsContext()))
167 state.pushStateSet(getStateSet());
169 state.setActiveTextureUnit(0);
170 state.setClientActiveTextureUnit(0);
171 state.disableAllVertexArrays();
173 glPushAttrib(GL_ALL_ATTRIB_BITS);
174 glPushClientAttrib(~0u);
182 state.dirtyAllModes();
183 state.dirtyAllAttributes();
184 state.dirtyAllVertexArrays();
187 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
188 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
193 class SGHUDAndPanelDrawable : public osg::Drawable {
195 SGHUDAndPanelDrawable()
197 // Dynamic stuff, do not store geometry
198 setUseDisplayList(false);
200 osg::StateSet* stateSet = getOrCreateStateSet();
201 stateSet->setRenderBinDetails(1000, "RenderBin");
203 // speed optimization?
204 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
205 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
206 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
207 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
208 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
210 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
212 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
213 { drawImplementation(*renderInfo.getState()); }
214 void drawImplementation(osg::State& state) const
216 // std::cout << state.getGraphicsContext() << std::endl;
217 if (!fgOSIsMainContext(state.getGraphicsContext()))
220 state.pushStateSet(getStateSet());
222 state.setActiveTextureUnit(0);
223 state.setClientActiveTextureUnit(0);
224 state.disableAllVertexArrays();
226 glPushAttrib(GL_ALL_ATTRIB_BITS);
227 glPushClientAttrib(~0u);
229 fgCockpitUpdate(&state);
231 FGInstrumentMgr *instr = static_cast<FGInstrumentMgr*>(globals->get_subsystem("instrumentation"));
232 HUD *hud = static_cast<HUD*>(instr->get_subsystem("hud"));
235 // update the panel subsystem
236 if ( globals->get_current_panel() != NULL )
237 globals->get_current_panel()->update(state);
238 // We don't need a state here - can be safely removed when we can pick
246 state.dirtyAllModes();
247 state.dirtyAllAttributes();
248 state.dirtyAllVertexArrays();
251 virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
252 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
257 class FGLightSourceUpdateCallback : public osg::NodeCallback {
259 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
261 assert(dynamic_cast<osg::LightSource*>(node));
262 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
263 osg::Light* light = lightSource->getLight();
265 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
266 light->setAmbient(l->scene_ambient().osg());
267 light->setDiffuse(l->scene_diffuse().osg());
268 light->setSpecular(l->scene_specular().osg());
269 SGVec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
270 light->setPosition(position.osg());
271 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
272 light->setDirection(direction.osg());
273 light->setSpotExponent(0);
274 light->setSpotCutoff(180);
275 light->setConstantAttenuation(1);
276 light->setLinearAttenuation(0);
277 light->setQuadraticAttenuation(0);
283 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
285 FGWireFrameModeUpdateCallback() :
286 mWireframe(fgGetNode("/sim/rendering/wireframe"))
288 virtual void operator()(osg::StateAttribute* stateAttribute,
291 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
292 osg::PolygonMode* polygonMode;
293 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
295 if (mWireframe->getBoolValue())
296 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
297 osg::PolygonMode::LINE);
299 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
300 osg::PolygonMode::FILL);
303 SGSharedPtr<SGPropertyNode> mWireframe;
306 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
308 FGLightModelUpdateCallback() :
309 mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
311 virtual void operator()(osg::StateAttribute* stateAttribute,
314 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
315 osg::LightModel* lightModel;
316 lightModel = static_cast<osg::LightModel*>(stateAttribute);
319 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
320 lightModel->setAmbientIntensity(l->scene_ambient().osg());
322 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
324 lightModel->setTwoSided(true);
325 lightModel->setLocalViewer(false);
327 if (mHighlights->getBoolValue()) {
328 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
330 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
334 SGSharedPtr<SGPropertyNode> mHighlights;
337 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
339 FGFogEnableUpdateCallback() :
340 mFogEnabled(fgGetNode("/sim/rendering/fog"))
342 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
344 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
345 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
347 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
351 SGSharedPtr<SGPropertyNode> mFogEnabled;
354 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
356 virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
358 assert(dynamic_cast<SGUpdateVisitor*>(nv));
359 assert(dynamic_cast<osg::Fog*>(sa));
360 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
361 osg::Fog* fog = static_cast<osg::Fog*>(sa);
362 fog->setMode(osg::Fog::EXP2);
363 fog->setColor(updateVisitor->getFogColor().osg());
364 fog->setDensity(updateVisitor->getFogExp2Density());
368 // update callback for the switch node guarding that splash
369 class FGScenerySwitchCallback : public osg::NodeCallback {
371 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
373 assert(dynamic_cast<osg::Switch*>(node));
374 osg::Switch* sw = static_cast<osg::Switch*>(node);
376 double t = globals->get_sim_time_sec();
377 bool enabled = 0 < t;
378 sw->setValue(0, enabled);
388 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
389 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
391 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
393 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
395 static osg::ref_ptr<ViewPartitionNode> viewPartition = new ViewPartitionNode;
397 FGRenderer::FGRenderer()
399 #ifdef FG_JPEG_SERVER
400 jpgRenderFrame = FGRenderer::update;
402 manipulator = new FGManipulator;
405 FGRenderer::~FGRenderer()
407 #ifdef FG_JPEG_SERVER
408 jpgRenderFrame = NULL;
412 // Initialize various GL/view parameters
413 // XXX This should be called "preinit" or something, as it initializes
414 // critical parts of the scene graph in addition to the splash screen.
416 FGRenderer::splashinit( void ) {
417 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
418 mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
419 mRealRoot->addChild(fgCreateSplashNode());
420 mFrameStamp = viewer->getFrameStamp();
421 // Scene doesn't seem to pass the frame stamp to the update
422 // visitor automatically.
423 mUpdateVisitor->setFrameStamp(mFrameStamp.get());
424 #ifdef UPDATE_VISITOR_IN_VIEWER
425 viewer->setUpdateVisitor(mUpdateVisitor.get());
427 osgViewer::Scene* scene = viewer->getScene();
428 scene->setUpdateVisitor(mUpdateVisitor.get());
433 FGRenderer::init( void ) {
434 // The viewer can call this before the graphics context is current
435 // in the main thread; indeed, in a multithreaded setup it might
436 // never be current in the main thread.
438 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
439 osg::initNotifyLevel();
441 // The number of polygon-offset "units" to place between layers. In
442 // principle, one is supposed to be enough. In practice, I find that
443 // my hardware/driver requires many more.
444 osg::PolygonOffset::setUnitsMultiplier(1);
445 osg::PolygonOffset::setFactorMultiplier(1);
447 // Go full screen if requested ...
448 if ( fgGetBool("/sim/startup/fullscreen") )
452 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
454 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
456 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
458 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
459 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
461 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
462 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
463 stateSet->setAttribute(new osg::BlendFunc);
464 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
466 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
468 // this will be set below
469 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
471 osg::Material* material = new osg::Material;
472 stateSet->setAttribute(material);
474 stateSet->setTextureAttribute(0, new osg::TexEnv);
475 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
477 osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
478 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
479 stateSet->setAttribute(hint);
480 hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
481 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
482 stateSet->setAttribute(hint);
483 hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
484 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
485 stateSet->setAttribute(hint);
486 hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
487 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
488 stateSet->setAttribute(hint);
489 hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
490 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
491 stateSet->setAttribute(hint);
493 osg::Group* sceneGroup = new osg::Group;
494 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
495 sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
497 //sceneGroup->addChild(thesky->getCloudRoot());
499 stateSet = sceneGroup->getOrCreateStateSet();
500 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
501 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
503 // need to update the light on every frame
504 osg::LightSource* lightSource = new osg::LightSource;
505 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
506 // relative because of CameraView being just a clever transform node
507 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
508 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
510 lightSource->addChild(sceneGroup);
511 lightSource->addChild(thesky->getPreRoot());
512 mRoot->addChild(lightSource);
514 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
515 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
516 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
517 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
518 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
520 // enable disable specular highlights.
521 // is the place where we might plug in an other fragment shader ...
522 osg::LightModel* lightModel = new osg::LightModel;
523 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
524 stateSet->setAttribute(lightModel);
526 // switch to enable wireframe
527 osg::PolygonMode* polygonMode = new osg::PolygonMode;
528 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
529 stateSet->setAttributeAndModes(polygonMode);
531 // scene fog handling
532 osg::Fog* fog = new osg::Fog;
533 fog->setUpdateCallback(new FGFogUpdateCallback);
534 stateSet->setAttributeAndModes(fog);
535 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
538 osg::Camera* guiCamera = new osg::Camera;
539 guiCamera->setRenderOrder(osg::Camera::POST_RENDER, 100);
540 guiCamera->setClearMask(0);
541 GLbitfield inheritanceMask = osg::CullSettings::ALL_VARIABLES;
542 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
543 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
544 guiCamera->setInheritanceMask(inheritanceMask);
545 guiCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
546 guiCamera->setCullingMode(osg::CullSettings::NO_CULLING);
547 osg::Geode* geode = new osg::Geode;
548 geode->addDrawable(new SGPuDrawable);
549 geode->addDrawable(new SGHUDAndPanelDrawable);
550 guiCamera->addChild(geode);
552 osg::Switch* sw = new osg::Switch;
553 sw->setUpdateCallback(new FGScenerySwitchCallback);
554 sw->addChild(mRoot.get());
555 viewPartition->addChild(sw);
556 viewPartition->addChild(thesky->getCloudRoot());
558 mRealRoot->addChild(viewPartition.get());
559 mRealRoot->addChild(FGCreateRedoutNode());
560 mRealRoot->addChild(guiCamera);
564 // Update all Visuals (redraws anything graphics related)
566 FGRenderer::update( bool refresh_camera_settings ) {
567 bool scenery_loaded = fgGetBool("sim/sceneryloaded")
568 || fgGetBool("sim/sceneryloaded-override");
569 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
570 if ( idle_state < 1000 || !scenery_loaded ) {
571 fgSetDouble("/sim/startup/splash-alpha", 1.0);
573 // Keep resetting sim time while the sim is initializing
574 // the splash screen is now in the scenegraph
575 globals->set_sim_time_sec( 0.0 );
579 // Fade out the splash screen over the first three seconds.
580 double sAlpha = SGMiscd::max(0, (2.5 - globals->get_sim_time_sec()) / 2.5);
581 fgSetDouble("/sim/startup/splash-alpha", sAlpha);
583 bool skyblend = fgGetBool("/sim/rendering/skyblend");
584 bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
585 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
586 bool distance_attenuation
587 = fgGetBool("/sim/rendering/distance-attenuation");
589 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
590 distance_attenuation );
592 static const SGPropertyNode *groundlevel_nearplane
593 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
595 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
598 double actual_visibility;
599 if (fgGetBool("/environment/clouds/status")) {
600 actual_visibility = thesky->get_visibility();
602 actual_visibility = fgGetDouble("/environment/visibility-m");
605 // idle_state is now 1000 meaning we've finished all our
606 // initializations and are running the main loop, so this will
607 // now work without seg faulting the system.
609 FGViewer *current__view = globals->get_current_view();
610 // Force update of center dependent values ...
611 current__view->set_dirty();
613 if ( refresh_camera_settings ) {
615 resize( fgGetInt("/sim/startup/xsize"),
616 fgGetInt("/sim/startup/ysize") );
618 SGVec3d position = current__view->getViewPosition();
619 SGQuatd attitude = current__view->getViewOrientation();
620 SGVec3d osgPosition = attitude.transform(-position);
622 FGManipulator *manipulator = globals->get_renderer()->getManipulator();
623 manipulator->setPosition(position.osg());
624 manipulator->setAttitude(attitude.osg());
626 osg::Camera *camera = viewer->getCamera();
630 if ( fgGetBool("/sim/rendering/textures") ) {
631 SGVec4f clearColor(l->adj_fog_color());
632 camera->setClearColor(clearColor.osg());
635 SGVec4f clearColor(l->sky_color());
636 camera->setClearColor(clearColor.osg());
639 // update fog params if visibility has changed
640 double visibility_meters = fgGetDouble("/environment/visibility-m");
641 thesky->set_visibility(visibility_meters);
643 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
644 ( global_multi_loop * fgGetInt("/sim/speed-up") )
645 / (double)fgGetInt("/sim/model-hz") );
647 // update the sky dome
650 // The sun and moon distances are scaled down versions
651 // of the actual distance to get both the moon and the sun
652 // within the range of the far clip plane.
653 // Moon distance: 384,467 kilometers
654 // Sun distance: 150,000,000 kilometers
656 double sun_horiz_eff, moon_horiz_eff;
657 if (fgGetBool("/sim/rendering/horizon-effect")) {
658 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
659 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
661 sun_horiz_eff = moon_horiz_eff = 1.0;
664 static SGSkyState sstate;
666 sstate.view_pos = toVec3f(current__view->get_view_pos());
667 sstate.zero_elev = toVec3f(current__view->get_zero_elev());
668 sstate.view_up = current__view->get_world_up();
669 sstate.lon = current__view->getLongitude_deg()
670 * SGD_DEGREES_TO_RADIANS;
671 sstate.lat = current__view->getLatitude_deg()
672 * SGD_DEGREES_TO_RADIANS;
673 sstate.alt = current__view->getAltitudeASL_ft()
675 sstate.spin = l->get_sun_rotation();
676 sstate.gst = globals->get_time_params()->getGst();
677 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
678 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
679 sstate.sun_dist = 50000.0 * sun_horiz_eff;
680 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
681 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
682 sstate.moon_dist = 40000.0 * moon_horiz_eff;
683 sstate.sun_angle = l->get_sun_angle();
687 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
688 << l->sky_color()[0] << " "
689 << l->sky_color()[1] << " "
690 << l->sky_color()[2] << " "
691 << l->sky_color()[3] );
692 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
693 << l->fog_color()[0] << " "
694 << l->fog_color()[1] << " "
695 << l->fog_color()[2] << " "
696 << l->fog_color()[3] );
697 SG_LOG( SG_GENERAL, SG_BULK,
698 " sun_angle = " << l->sun_angle
699 << " moon_angle = " << l->moon_angle );
702 static SGSkyColor scolor;
704 scolor.sky_color = SGVec3f(l->sky_color().data());
705 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
706 scolor.cloud_color = SGVec3f(l->cloud_color().data());
707 scolor.sun_angle = l->get_sun_angle();
708 scolor.moon_angle = l->get_moon_angle();
709 scolor.nplanets = globals->get_ephem()->getNumPlanets();
710 scolor.nstars = globals->get_ephem()->getNumStars();
711 scolor.planet_data = globals->get_ephem()->getPlanets();
712 scolor.star_data = globals->get_ephem()->getStars();
714 thesky->reposition( sstate, delta_time_sec );
715 thesky->repaint( scolor );
718 SG_LOG( SG_GENERAL, SG_BULK,
719 "thesky->reposition( view_pos = " << view_pos[0] << " "
720 << view_pos[1] << " " << view_pos[2] );
721 SG_LOG( SG_GENERAL, SG_BULK,
722 " zero_elev = " << zero_elev[0] << " "
723 << zero_elev[1] << " " << zero_elev[2]
724 << " lon = " << cur_fdm_state->get_Longitude()
725 << " lat = " << cur_fdm_state->get_Latitude() );
726 SG_LOG( SG_GENERAL, SG_BULK,
727 " sun_rot = " << l->get_sun_rotation
728 << " gst = " << SGTime::cur_time_params->getGst() );
729 SG_LOG( SG_GENERAL, SG_BULK,
730 " sun ra = " << globals->get_ephem()->getSunRightAscension()
731 << " sun dec = " << globals->get_ephem()->getSunDeclination()
732 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
733 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
737 // shadows->setupShadows(
738 // current__view->getLongitude_deg(),
739 // current__view->getLatitude_deg(),
740 // globals->get_time_params()->getGst(),
741 // globals->get_ephem()->getSunRightAscension(),
742 // globals->get_ephem()->getSunDeclination(),
743 // l->get_sun_angle());
747 // sgEnviro.setLight(l->adj_fog_color());
749 double agl = current__view->getAltitudeASL_ft()*SG_FEET_TO_METER
750 - current__view->getSGLocation()->get_cur_elev_m();
752 float scene_nearplane, scene_farplane;
753 // XXX Given that the own airplane model is part of the scene
754 // graph, should this business be ripped out? The near plane is
755 // ignored by setCameraParameters.
757 scene_nearplane = 10.0f;
758 scene_farplane = 120000.0f;
760 scene_nearplane = groundlevel_nearplane->getDoubleValue();
761 scene_farplane = 120000.0f;
763 setCameraParameters(current__view->get_v_fov(),
764 current__view->get_aspect_ratio(),
765 scene_nearplane, scene_farplane);
767 // sgEnviro.startOfFrame(current__view->get_view_pos(),
768 // current__view->get_world_up(),
769 // current__view->getLongitude_deg(),
770 // current__view->getLatitude_deg(),
771 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
775 // sgEnviro.drawLightning();
777 // double current_view_origin_airspeed_horiz_kt =
778 // fgGetDouble("/velocities/airspeed-kt", 0.0)
779 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
780 // * SGD_DEGREES_TO_RADIANS);
784 // shadows->endOfFrame();
786 // need to call the update visitor once
787 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
788 mUpdateVisitor->setViewData(current__view->getViewPosition(),
789 current__view->getViewOrientation());
790 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
791 mUpdateVisitor->setLight(direction, l->scene_ambient(),
792 l->scene_diffuse(), l->scene_specular(),
794 l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
795 mUpdateVisitor->setVisibility(actual_visibility);
796 viewPartition->setVisibility(actual_visibility);
797 simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
798 bool hotspots = fgGetBool("/sim/panel-hotspots");
799 osg::Node::NodeMask cullMask = (~simgear::LIGHTS_BITS & ~simgear::PICK_BIT
800 & ~simgear::BACKGROUND_BIT);
801 cullMask |= simgear::GroundLightManager::instance()
802 ->getLightNodeMask(mUpdateVisitor.get());
804 cullMask |= simgear::PICK_BIT;
805 camera->setCullMask(cullMask);
807 for (int i = 0; i < viewer->getNumSlaves(); ++i)
808 viewer->getSlave(i)._camera->setCullMask(cullMask);
813 // options.cxx needs to see this for toggle_panel()
814 // Handle new window size or exposure
816 FGRenderer::resize( int width, int height ) {
819 if ( (!fgGetBool("/sim/virtual-cockpit"))
820 && fgPanelVisible() && idle_state == 1000 ) {
821 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
822 globals->get_current_panel()->getYOffset()) / 768.0);
827 static int lastwidth = 0;
828 static int lastheight = 0;
829 if (width != lastwidth)
830 fgSetInt("/sim/startup/xsize", lastwidth = width);
831 if (height != lastheight)
832 fgSetInt("/sim/startup/ysize", lastheight = height);
834 guiInitMouse(width, height);
837 FGViewMgr *viewmgr = globals->get_viewmgr();
839 for ( int i = 0; i < viewmgr->size(); ++i ) {
840 viewmgr->get_view(i)->
841 set_aspect_ratio((float)view_h / (float)width);
846 void FGRenderer::setCameraParameters(float vfov, float aspectRatio,
847 float zNear, float zFar)
850 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
851 viewer->getCamera()->setProjectionMatrixAsPerspective(vfov,
857 FGRenderer::pick( unsigned x, unsigned y,
858 std::vector<SGSceneryPick>& pickList,
859 const osgGA::GUIEventAdapter* ea )
861 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
862 // wipe out the return ...
866 // just compute intersections in the viewers method ...
867 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
868 Intersections intersections;
869 viewer->computeIntersections(ea->getX(), ea->getY(), intersections);
871 Intersections::iterator hit;
872 for (hit = intersections.begin(); hit != intersections.end(); ++hit) {
873 const osg::NodePath& np = hit->nodePath;
874 osg::NodePath::const_reverse_iterator npi;
875 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
876 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
879 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
880 SGPickCallback* pickCallback = ud->getPickCallback(i);
883 SGSceneryPick sceneryPick;
884 sceneryPick.info.local = SGVec3d(hit->getLocalIntersectPoint());
885 sceneryPick.info.wgs84 = SGVec3d(hit->getWorldIntersectPoint());
886 sceneryPick.callback = pickCallback;
887 pickList.push_back(sceneryPick);
891 return !pickList.empty();
892 } else { // we can get called early ...
898 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
900 mRealRoot->addChild(camera);
904 fgDumpSceneGraphToFile(const char* filename)
906 return osgDB::writeNodeFile(*mRealRoot.get(), filename);
910 fgDumpTerrainBranchToFile(const char* filename)
912 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
918 fgDumpNodeToFile(osg::Node* node, const char* filename)
920 return osgDB::writeNodeFile(*node, filename);
922 // end of renderer.cxx