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/model.hxx>
70 #include <simgear/scene/model/modellib.hxx>
71 #include <simgear/scene/model/placement.hxx>
72 #include <simgear/scene/util/SGUpdateVisitor.hxx>
73 #include <simgear/scene/util/RenderConstants.hxx>
74 #include <simgear/scene/tgdb/GroundLightManager.hxx>
75 #include <simgear/scene/tgdb/pt_lights.hxx>
76 #include <simgear/props/props.hxx>
77 #include <simgear/timing/sg_time.hxx>
78 #include <simgear/ephemeris/ephemeris.hxx>
79 #include <simgear/math/sg_random.h>
81 #include <simgear/screen/jpgfactory.hxx>
84 #include <simgear/environment/visual_enviro.hxx>
86 #include <Scenery/tileentry.hxx>
87 #include <Time/light.hxx>
88 #include <Time/light.hxx>
89 #include <Aircraft/aircraft.hxx>
90 #include <Cockpit/panel.hxx>
91 #include <Cockpit/cockpit.hxx>
92 #include <Cockpit/hud.hxx>
93 #include <Model/panelnode.hxx>
94 #include <Model/modelmgr.hxx>
95 #include <Model/acmodel.hxx>
96 #include <Scenery/scenery.hxx>
97 #include <Scenery/redout.hxx>
98 #include <Scenery/tilemgr.hxx>
99 #include <GUI/new_gui.hxx>
100 #include <Instrumentation/instrument_mgr.hxx>
101 #include <Instrumentation/HUD/HUD.hxx>
103 #include <Include/general.hxx>
104 #include "splash.hxx"
105 #include "renderer.hxx"
107 #include "ViewPartitionNode.hxx"
109 // XXX Make this go away when OSG 2.2 is released.
110 #if (FG_OSG_VERSION >= 21004)
111 #define UPDATE_VISITOR_IN_VIEWER 1
114 class FGHintUpdateCallback : public osg::StateAttribute::Callback {
116 FGHintUpdateCallback(const char* configNode) :
117 mConfigNode(fgGetNode(configNode, true))
119 virtual void operator()(osg::StateAttribute* stateAttribute,
122 assert(dynamic_cast<osg::Hint*>(stateAttribute));
123 osg::Hint* hint = static_cast<osg::Hint*>(stateAttribute);
125 const char* value = mConfigNode->getStringValue();
127 hint->setMode(GL_DONT_CARE);
128 else if (0 == strcmp(value, "nicest"))
129 hint->setMode(GL_NICEST);
130 else if (0 == strcmp(value, "fastest"))
131 hint->setMode(GL_FASTEST);
133 hint->setMode(GL_DONT_CARE);
136 SGSharedPtr<SGPropertyNode> mConfigNode;
140 class SGPuDrawable : public osg::Drawable {
144 // Dynamic stuff, do not store geometry
145 setUseDisplayList(false);
147 osg::StateSet* stateSet = getOrCreateStateSet();
148 stateSet->setRenderBinDetails(1001, "RenderBin");
149 // speed optimization?
150 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
151 // We can do translucent menus, so why not. :-)
152 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
153 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
154 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
156 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
158 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
159 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
161 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
162 { drawImplementation(*renderInfo.getState()); }
163 void drawImplementation(osg::State& state) const
165 if (!fgOSIsMainContext(state.getGraphicsContext()))
168 state.pushStateSet(getStateSet());
170 state.setActiveTextureUnit(0);
171 state.setClientActiveTextureUnit(0);
172 state.disableAllVertexArrays();
174 glPushAttrib(GL_ALL_ATTRIB_BITS);
175 glPushClientAttrib(~0u);
183 state.dirtyAllModes();
184 state.dirtyAllAttributes();
185 state.dirtyAllVertexArrays();
188 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
189 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
194 class SGHUDAndPanelDrawable : public osg::Drawable {
196 SGHUDAndPanelDrawable()
198 // Dynamic stuff, do not store geometry
199 setUseDisplayList(false);
201 osg::StateSet* stateSet = getOrCreateStateSet();
202 stateSet->setRenderBinDetails(1000, "RenderBin");
204 // speed optimization?
205 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
206 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
207 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
208 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
209 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
211 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
213 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
214 { drawImplementation(*renderInfo.getState()); }
215 void drawImplementation(osg::State& state) const
217 // std::cout << state.getGraphicsContext() << std::endl;
218 if (!fgOSIsMainContext(state.getGraphicsContext()))
221 state.pushStateSet(getStateSet());
223 state.setActiveTextureUnit(0);
224 state.setClientActiveTextureUnit(0);
225 state.disableAllVertexArrays();
227 glPushAttrib(GL_ALL_ATTRIB_BITS);
228 glPushClientAttrib(~0u);
230 fgCockpitUpdate(&state);
232 FGInstrumentMgr *instr = static_cast<FGInstrumentMgr*>(globals->get_subsystem("instrumentation"));
233 HUD *hud = static_cast<HUD*>(instr->get_subsystem("hud"));
236 // update the panel subsystem
237 if ( globals->get_current_panel() != NULL )
238 globals->get_current_panel()->update(state);
239 // We don't need a state here - can be safely removed when we can pick
247 state.dirtyAllModes();
248 state.dirtyAllAttributes();
249 state.dirtyAllVertexArrays();
252 virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
253 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
258 class FGLightSourceUpdateCallback : public osg::NodeCallback {
260 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
262 assert(dynamic_cast<osg::LightSource*>(node));
263 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
264 osg::Light* light = lightSource->getLight();
266 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
267 light->setAmbient(l->scene_ambient().osg());
268 light->setDiffuse(l->scene_diffuse().osg());
269 light->setSpecular(l->scene_specular().osg());
270 SGVec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
271 light->setPosition(position.osg());
272 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
273 light->setDirection(direction.osg());
274 light->setSpotExponent(0);
275 light->setSpotCutoff(180);
276 light->setConstantAttenuation(1);
277 light->setLinearAttenuation(0);
278 light->setQuadraticAttenuation(0);
284 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
286 FGWireFrameModeUpdateCallback() :
287 mWireframe(fgGetNode("/sim/rendering/wireframe"))
289 virtual void operator()(osg::StateAttribute* stateAttribute,
292 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
293 osg::PolygonMode* polygonMode;
294 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
296 if (mWireframe->getBoolValue())
297 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
298 osg::PolygonMode::LINE);
300 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
301 osg::PolygonMode::FILL);
304 SGSharedPtr<SGPropertyNode> mWireframe;
307 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
309 FGLightModelUpdateCallback() :
310 mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
312 virtual void operator()(osg::StateAttribute* stateAttribute,
315 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
316 osg::LightModel* lightModel;
317 lightModel = static_cast<osg::LightModel*>(stateAttribute);
320 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
321 lightModel->setAmbientIntensity(l->scene_ambient().osg());
323 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
325 lightModel->setTwoSided(true);
326 lightModel->setLocalViewer(false);
328 if (mHighlights->getBoolValue()) {
329 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
331 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
335 SGSharedPtr<SGPropertyNode> mHighlights;
338 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
340 FGFogEnableUpdateCallback() :
341 mFogEnabled(fgGetNode("/sim/rendering/fog"))
343 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
345 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
346 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
348 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
352 SGSharedPtr<SGPropertyNode> mFogEnabled;
355 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
357 virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
359 assert(dynamic_cast<SGUpdateVisitor*>(nv));
360 assert(dynamic_cast<osg::Fog*>(sa));
361 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
362 osg::Fog* fog = static_cast<osg::Fog*>(sa);
363 fog->setMode(osg::Fog::EXP2);
364 fog->setColor(updateVisitor->getFogColor().osg());
365 fog->setDensity(updateVisitor->getFogExp2Density());
369 // update callback for the switch node guarding that splash
370 class FGScenerySwitchCallback : public osg::NodeCallback {
372 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
374 assert(dynamic_cast<osg::Switch*>(node));
375 osg::Switch* sw = static_cast<osg::Switch*>(node);
377 double t = globals->get_sim_time_sec();
378 bool enabled = 0 < t;
379 sw->setValue(0, enabled);
389 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
390 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
392 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
394 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
396 static osg::ref_ptr<ViewPartitionNode> viewPartition = new ViewPartitionNode;
398 FGRenderer::FGRenderer()
400 #ifdef FG_JPEG_SERVER
401 jpgRenderFrame = FGRenderer::update;
403 manipulator = new FGManipulator;
406 FGRenderer::~FGRenderer()
408 #ifdef FG_JPEG_SERVER
409 jpgRenderFrame = NULL;
413 // Initialize various GL/view parameters
414 // XXX This should be called "preinit" or something, as it initializes
415 // critical parts of the scene graph in addition to the splash screen.
417 FGRenderer::splashinit( void ) {
418 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
419 mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
420 mRealRoot->addChild(fgCreateSplashNode());
421 mFrameStamp = viewer->getFrameStamp();
422 // Scene doesn't seem to pass the frame stamp to the update
423 // visitor automatically.
424 mUpdateVisitor->setFrameStamp(mFrameStamp.get());
425 #ifdef UPDATE_VISITOR_IN_VIEWER
426 viewer->setUpdateVisitor(mUpdateVisitor.get());
428 osgViewer::Scene* scene = viewer->getScene();
429 scene->setUpdateVisitor(mUpdateVisitor.get());
434 FGRenderer::init( void ) {
435 // The viewer can call this before the graphics context is current
436 // in the main thread; indeed, in a multithreaded setup it might
437 // never be current in the main thread.
439 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
440 osg::initNotifyLevel();
442 // The number of polygon-offset "units" to place between layers. In
443 // principle, one is supposed to be enough. In practice, I find that
444 // my hardware/driver requires many more.
445 osg::PolygonOffset::setUnitsMultiplier(1);
446 osg::PolygonOffset::setFactorMultiplier(1);
448 // Go full screen if requested ...
449 if ( fgGetBool("/sim/startup/fullscreen") )
453 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
455 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
457 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
459 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
460 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
462 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
463 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
464 stateSet->setAttribute(new osg::BlendFunc);
465 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
467 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
469 // this will be set below
470 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
472 osg::Material* material = new osg::Material;
473 stateSet->setAttribute(material);
475 stateSet->setTextureAttribute(0, new osg::TexEnv);
476 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
478 osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
479 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
480 stateSet->setAttribute(hint);
481 hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
482 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
483 stateSet->setAttribute(hint);
484 hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
485 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
486 stateSet->setAttribute(hint);
487 hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
488 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
489 stateSet->setAttribute(hint);
490 hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
491 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
492 stateSet->setAttribute(hint);
494 // this is the topmost scenegraph node for osg
496 mBackGroundCamera->addChild(thesky->getPreRoot());
497 mBackGroundCamera->setClearMask(0);
499 GLbitfield inheritanceMask = osg::CullSettings::ALL_VARIABLES;
500 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
501 inheritanceMask &= ~osg::CullSettings::NEAR_FAR_RATIO;
502 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
503 mBackGroundCamera->setInheritanceMask(inheritanceMask);
504 mBackGroundCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
505 mBackGroundCamera->setCullingMode(osg::CullSettings::NO_CULLING);
506 mBackGroundCamera->setRenderOrder(osg::Camera::NESTED_RENDER);
508 stateSet = mBackGroundCamera->getOrCreateStateSet();
509 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
511 osg::Group* sceneGroup = new osg::Group;
512 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
513 sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
515 //sceneGroup->addChild(thesky->getCloudRoot());
517 stateSet = sceneGroup->getOrCreateStateSet();
518 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
519 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
521 // need to update the light on every frame
522 osg::LightSource* lightSource = new osg::LightSource;
523 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
524 // relative because of CameraView being just a clever transform node
525 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
526 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
528 lightSource->addChild(sceneGroup);
529 lightSource->addChild(thesky->getPreRoot());
530 mRoot->addChild(lightSource);
532 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
533 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
534 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
535 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
536 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
538 // enable disable specular highlights.
539 // is the place where we might plug in an other fragment shader ...
540 osg::LightModel* lightModel = new osg::LightModel;
541 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
542 stateSet->setAttribute(lightModel);
544 // switch to enable wireframe
545 osg::PolygonMode* polygonMode = new osg::PolygonMode;
546 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
547 stateSet->setAttributeAndModes(polygonMode);
549 // scene fog handling
550 osg::Fog* fog = new osg::Fog;
551 fog->setUpdateCallback(new FGFogUpdateCallback);
552 stateSet->setAttributeAndModes(fog);
553 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
556 osg::Camera* guiCamera = new osg::Camera;
557 guiCamera->setRenderOrder(osg::Camera::POST_RENDER, 100);
558 guiCamera->setClearMask(0);
559 GLbitfield inheritanceMask = osg::CullSettings::ALL_VARIABLES;
560 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
561 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
562 guiCamera->setInheritanceMask(inheritanceMask);
563 guiCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
564 guiCamera->setCullingMode(osg::CullSettings::NO_CULLING);
565 osg::Geode* geode = new osg::Geode;
566 geode->addDrawable(new SGPuDrawable);
567 geode->addDrawable(new SGHUDAndPanelDrawable);
568 guiCamera->addChild(geode);
570 osg::Switch* sw = new osg::Switch;
571 sw->setUpdateCallback(new FGScenerySwitchCallback);
572 sw->addChild(mRoot.get());
573 viewPartition->addChild(sw);
574 viewPartition->addChild(thesky->getCloudRoot());
576 mRealRoot->addChild(viewPartition.get());
577 mRealRoot->addChild(FGCreateRedoutNode());
578 mRealRoot->addChild(guiCamera);
582 // Update all Visuals (redraws anything graphics related)
584 FGRenderer::update( bool refresh_camera_settings ) {
585 bool scenery_loaded = fgGetBool("sim/sceneryloaded")
586 || fgGetBool("sim/sceneryloaded-override");
587 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
588 if ( idle_state < 1000 || !scenery_loaded ) {
589 fgSetDouble("/sim/startup/splash-alpha", 1.0);
591 // Keep resetting sim time while the sim is initializing
592 // the splash screen is now in the scenegraph
593 globals->set_sim_time_sec( 0.0 );
597 // Fade out the splash screen over the first three seconds.
598 double sAlpha = SGMiscd::max(0, (2.5 - globals->get_sim_time_sec()) / 2.5);
599 fgSetDouble("/sim/startup/splash-alpha", sAlpha);
601 bool skyblend = fgGetBool("/sim/rendering/skyblend");
602 bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
603 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
604 bool distance_attenuation
605 = fgGetBool("/sim/rendering/distance-attenuation");
607 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
608 distance_attenuation );
610 static const SGPropertyNode *groundlevel_nearplane
611 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
613 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
616 double actual_visibility;
617 if (fgGetBool("/environment/clouds/status")) {
618 actual_visibility = thesky->get_visibility();
620 actual_visibility = fgGetDouble("/environment/visibility-m");
623 // idle_state is now 1000 meaning we've finished all our
624 // initializations and are running the main loop, so this will
625 // now work without seg faulting the system.
627 FGViewer *current__view = globals->get_current_view();
628 // Force update of center dependent values ...
629 current__view->set_dirty();
631 if ( refresh_camera_settings ) {
633 resize( fgGetInt("/sim/startup/xsize"),
634 fgGetInt("/sim/startup/ysize") );
636 SGVec3d position = current__view->getViewPosition();
637 SGQuatd attitude = current__view->getViewOrientation();
638 SGVec3d osgPosition = attitude.transform(-position);
640 FGManipulator *manipulator = globals->get_renderer()->getManipulator();
641 manipulator->setPosition(position.osg());
642 manipulator->setAttitude(attitude.osg());
644 osg::Camera *camera = viewer->getCamera();
648 if ( fgGetBool("/sim/rendering/textures") ) {
649 SGVec4f clearColor(l->adj_fog_color());
650 camera->setClearColor(clearColor.osg());
653 SGVec4f clearColor(l->sky_color());
654 camera->setClearColor(clearColor.osg());
657 // update fog params if visibility has changed
658 double visibility_meters = fgGetDouble("/environment/visibility-m");
659 thesky->set_visibility(visibility_meters);
661 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
662 ( global_multi_loop * fgGetInt("/sim/speed-up") )
663 / (double)fgGetInt("/sim/model-hz") );
665 // update the sky dome
668 // The sun and moon distances are scaled down versions
669 // of the actual distance to get both the moon and the sun
670 // within the range of the far clip plane.
671 // Moon distance: 384,467 kilometers
672 // Sun distance: 150,000,000 kilometers
674 double sun_horiz_eff, moon_horiz_eff;
675 if (fgGetBool("/sim/rendering/horizon-effect")) {
676 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
677 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
679 sun_horiz_eff = moon_horiz_eff = 1.0;
682 static SGSkyState sstate;
684 sstate.view_pos = toVec3f(current__view->get_view_pos());
685 sstate.zero_elev = toVec3f(current__view->get_zero_elev());
686 sstate.view_up = current__view->get_world_up();
687 sstate.lon = current__view->getLongitude_deg()
688 * SGD_DEGREES_TO_RADIANS;
689 sstate.lat = current__view->getLatitude_deg()
690 * SGD_DEGREES_TO_RADIANS;
691 sstate.alt = current__view->getAltitudeASL_ft()
693 sstate.spin = l->get_sun_rotation();
694 sstate.gst = globals->get_time_params()->getGst();
695 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
696 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
697 sstate.sun_dist = 50000.0 * sun_horiz_eff;
698 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
699 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
700 sstate.moon_dist = 40000.0 * moon_horiz_eff;
701 sstate.sun_angle = l->get_sun_angle();
705 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
706 << l->sky_color()[0] << " "
707 << l->sky_color()[1] << " "
708 << l->sky_color()[2] << " "
709 << l->sky_color()[3] );
710 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
711 << l->fog_color()[0] << " "
712 << l->fog_color()[1] << " "
713 << l->fog_color()[2] << " "
714 << l->fog_color()[3] );
715 SG_LOG( SG_GENERAL, SG_BULK,
716 " sun_angle = " << l->sun_angle
717 << " moon_angle = " << l->moon_angle );
720 static SGSkyColor scolor;
722 scolor.sky_color = SGVec3f(l->sky_color().data());
723 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
724 scolor.cloud_color = SGVec3f(l->cloud_color().data());
725 scolor.sun_angle = l->get_sun_angle();
726 scolor.moon_angle = l->get_moon_angle();
727 scolor.nplanets = globals->get_ephem()->getNumPlanets();
728 scolor.nstars = globals->get_ephem()->getNumStars();
729 scolor.planet_data = globals->get_ephem()->getPlanets();
730 scolor.star_data = globals->get_ephem()->getStars();
732 thesky->reposition( sstate, delta_time_sec );
733 thesky->repaint( scolor );
736 SG_LOG( SG_GENERAL, SG_BULK,
737 "thesky->reposition( view_pos = " << view_pos[0] << " "
738 << view_pos[1] << " " << view_pos[2] );
739 SG_LOG( SG_GENERAL, SG_BULK,
740 " zero_elev = " << zero_elev[0] << " "
741 << zero_elev[1] << " " << zero_elev[2]
742 << " lon = " << cur_fdm_state->get_Longitude()
743 << " lat = " << cur_fdm_state->get_Latitude() );
744 SG_LOG( SG_GENERAL, SG_BULK,
745 " sun_rot = " << l->get_sun_rotation
746 << " gst = " << SGTime::cur_time_params->getGst() );
747 SG_LOG( SG_GENERAL, SG_BULK,
748 " sun ra = " << globals->get_ephem()->getSunRightAscension()
749 << " sun dec = " << globals->get_ephem()->getSunDeclination()
750 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
751 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
755 // shadows->setupShadows(
756 // current__view->getLongitude_deg(),
757 // current__view->getLatitude_deg(),
758 // globals->get_time_params()->getGst(),
759 // globals->get_ephem()->getSunRightAscension(),
760 // globals->get_ephem()->getSunDeclination(),
761 // l->get_sun_angle());
765 // sgEnviro.setLight(l->adj_fog_color());
767 double agl = current__view->getAltitudeASL_ft()*SG_FEET_TO_METER
768 - current__view->getSGLocation()->get_cur_elev_m();
770 float scene_nearplane, scene_farplane;
772 scene_nearplane = 10.0f;
773 scene_farplane = 120000.0f;
775 scene_nearplane = groundlevel_nearplane->getDoubleValue();
776 scene_farplane = 120000.0f;
778 setNearFar( scene_nearplane, scene_farplane );
780 // sgEnviro.startOfFrame(current__view->get_view_pos(),
781 // current__view->get_world_up(),
782 // current__view->getLongitude_deg(),
783 // current__view->getLatitude_deg(),
784 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
788 // sgEnviro.drawLightning();
790 // double current_view_origin_airspeed_horiz_kt =
791 // fgGetDouble("/velocities/airspeed-kt", 0.0)
792 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
793 // * SGD_DEGREES_TO_RADIANS);
794 // TODO:find the real view speed, not the AC one
795 // sgEnviro.drawPrecipitation(
796 // fgGetDouble("/environment/metar/rain-norm", 0.0),
797 // fgGetDouble("/environment/metar/snow-norm", 0.0),
798 // fgGetDouble("/environment/metar/hail-norm", 0.0),
799 // current__view->getPitch_deg() + current__view->getPitchOffset_deg(),
800 // current__view->getRoll_deg() + current__view->getRollOffset_deg(),
801 // - current__view->getHeadingOffset_deg(),
802 // current_view_origin_airspeed_horiz_kt
807 // shadows->endOfFrame();
809 // need to call the update visitor once
810 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
811 mUpdateVisitor->setViewData(current__view->getViewPosition(),
812 current__view->getViewOrientation());
813 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
814 mUpdateVisitor->setLight(direction, l->scene_ambient(),
815 l->scene_diffuse(), l->scene_specular(),
817 l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
818 mUpdateVisitor->setVisibility(actual_visibility);
819 viewPartition->setVisibility(actual_visibility);
820 simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
821 bool hotspots = fgGetBool("/sim/panel-hotspots");
822 osg::Node::NodeMask cullMask = (~simgear::LIGHTS_BITS & ~simgear::PICK_BIT
823 & ~simgear::BACKGROUND_BIT);
824 cullMask |= simgear::GroundLightManager::instance()
825 ->getLightNodeMask(mUpdateVisitor.get());
827 cullMask |= simgear::PICK_BIT;
828 camera->setCullMask(cullMask);
830 for (int i = 0; i < viewer->getNumSlaves(); ++i)
831 viewer->getSlave(i)._camera->setCullMask(cullMask);
836 // options.cxx needs to see this for toggle_panel()
837 // Handle new window size or exposure
839 FGRenderer::resize( int width, int height ) {
842 if ( (!fgGetBool("/sim/virtual-cockpit"))
843 && fgPanelVisible() && idle_state == 1000 ) {
844 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
845 globals->get_current_panel()->getYOffset()) / 768.0);
850 static int lastwidth = 0;
851 static int lastheight = 0;
852 if (width != lastwidth)
853 fgSetInt("/sim/startup/xsize", lastwidth = width);
854 if (height != lastheight)
855 fgSetInt("/sim/startup/ysize", lastheight = height);
857 guiInitMouse(width, height);
860 FGViewMgr *viewmgr = globals->get_viewmgr();
862 for ( int i = 0; i < viewmgr->size(); ++i ) {
863 viewmgr->get_view(i)->
864 set_aspect_ratio((float)view_h / (float)width);
867 setFOV( viewmgr->get_current_view()->get_h_fov(),
868 viewmgr->get_current_view()->get_v_fov() );
873 // we need some static storage space for these values. However, we
874 // can't store it in a renderer class object because the functions
875 // that manipulate these are static. They are static so they can
876 // interface to the display callback system. There's probably a
877 // better way, there has to be a better way, but I'm not seeing it
879 static float fov_width = 55.0;
880 static float fov_height = 42.0;
881 static float fov_near = 1.0;
882 static float fov_far = 1000.0;
885 /** FlightGear code should use this routine to set the FOV rather than
886 * calling the ssg routine directly
888 void FGRenderer::setFOV( float w, float h ) {
891 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
892 viewer->getCamera()->setProjectionMatrixAsPerspective(fov_height, 4.0/3.0,
897 /** FlightGear code should use this routine to set the Near/Far clip
898 * planes rather than calling the ssg routine directly
900 void FGRenderer::setNearFar( float n, float f ) {
901 // OSGFIXME: we have currently too much z-buffer fights
905 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
906 viewer->getCamera()->setProjectionMatrixAsPerspective(fov_height, 4.0/3.0,
911 FGRenderer::pick( unsigned x, unsigned y,
912 std::vector<SGSceneryPick>& pickList,
913 const osgGA::GUIEventAdapter* ea )
915 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
916 // wipe out the return ...
920 // just compute intersections in the viewers method ...
921 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
922 Intersections intersections;
923 viewer->computeIntersections(ea->getX(), ea->getY(), intersections);
925 Intersections::iterator hit;
926 for (hit = intersections.begin(); hit != intersections.end(); ++hit) {
927 const osg::NodePath& np = hit->nodePath;
928 osg::NodePath::const_reverse_iterator npi;
929 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
930 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
933 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
934 SGPickCallback* pickCallback = ud->getPickCallback(i);
937 SGSceneryPick sceneryPick;
938 sceneryPick.info.local = SGVec3d(hit->getLocalIntersectPoint());
939 sceneryPick.info.wgs84 = SGVec3d(hit->getWorldIntersectPoint());
940 sceneryPick.callback = pickCallback;
941 pickList.push_back(sceneryPick);
945 return !pickList.empty();
946 } else { // we can get called early ...
952 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
954 mRealRoot->addChild(camera);
958 fgDumpSceneGraphToFile(const char* filename)
960 return osgDB::writeNodeFile(*mRealRoot.get(), filename);
964 fgDumpTerrainBranchToFile(const char* filename)
966 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
972 fgDumpNodeToFile(osg::Node* node, const char* filename)
974 return osgDB::writeNodeFile(*node, filename);
976 // end of renderer.cxx