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.
30 #include <simgear/compiler.h>
38 #include <osg/ref_ptr>
39 #include <osg/AlphaFunc>
40 #include <osg/BlendFunc>
42 #include <osg/CullFace>
43 #include <osg/CullStack>
49 #include <osg/LightModel>
50 #include <osg/LightSource>
51 #include <osg/Material>
53 #include <osg/NodeCallback>
55 #include <osg/PolygonMode>
56 #include <osg/PolygonOffset>
57 #include <osg/Program>
58 #include <osg/Version>
61 #include <osgUtil/LineSegmentIntersector>
63 #include <osg/io_utils>
64 #include <osgDB/WriteFile>
66 #include <simgear/math/SGMath.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/sky/sky.hxx>
71 #include <simgear/scene/util/SGUpdateVisitor.hxx>
72 #include <simgear/scene/util/RenderConstants.hxx>
73 #include <simgear/scene/util/SGSceneUserData.hxx>
74 #include <simgear/scene/tgdb/GroundLightManager.hxx>
75 #include <simgear/scene/tgdb/pt_lights.hxx>
76 #include <simgear/structure/OSGUtils.hxx>
77 #include <simgear/props/props.hxx>
78 #include <simgear/timing/sg_time.hxx>
79 #include <simgear/ephemeris/ephemeris.hxx>
80 #include <simgear/math/sg_random.h>
82 #include <simgear/screen/jpgfactory.hxx>
85 #include <Time/light.hxx>
86 #include <Time/light.hxx>
87 #include <Cockpit/panel.hxx>
88 #include <Model/panelnode.hxx>
89 #include <Model/modelmgr.hxx>
90 #include <Model/acmodel.hxx>
91 #include <Scenery/scenery.hxx>
92 #include <Scenery/redout.hxx>
93 #include <GUI/new_gui.hxx>
94 #include <Instrumentation/HUD/HUD.hxx>
95 #include <Environment/precipitation_mgr.hxx>
98 #include "renderer.hxx"
100 #include "CameraGroup.hxx"
101 #include "FGEventHandler.hxx"
102 #include <Main/viewer.hxx>
103 #include <Main/viewmgr.hxx>
106 using namespace simgear;
107 using namespace flightgear;
109 class FGHintUpdateCallback : public osg::StateAttribute::Callback {
111 FGHintUpdateCallback(const char* configNode) :
112 mConfigNode(fgGetNode(configNode, true))
114 virtual void operator()(osg::StateAttribute* stateAttribute,
117 assert(dynamic_cast<osg::Hint*>(stateAttribute));
118 osg::Hint* hint = static_cast<osg::Hint*>(stateAttribute);
120 const char* value = mConfigNode->getStringValue();
122 hint->setMode(GL_DONT_CARE);
123 else if (0 == strcmp(value, "nicest"))
124 hint->setMode(GL_NICEST);
125 else if (0 == strcmp(value, "fastest"))
126 hint->setMode(GL_FASTEST);
128 hint->setMode(GL_DONT_CARE);
131 SGPropertyNode_ptr mConfigNode;
135 class SGPuDrawable : public osg::Drawable {
139 // Dynamic stuff, do not store geometry
140 setUseDisplayList(false);
141 setDataVariance(Object::DYNAMIC);
143 osg::StateSet* stateSet = getOrCreateStateSet();
144 stateSet->setRenderBinDetails(1001, "RenderBin");
145 // speed optimization?
146 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
147 // We can do translucent menus, so why not. :-)
148 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
149 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
150 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
152 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
154 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
155 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
157 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
158 { drawImplementation(*renderInfo.getState()); }
159 void drawImplementation(osg::State& state) const
161 state.setActiveTextureUnit(0);
162 state.setClientActiveTextureUnit(0);
164 state.disableAllVertexArrays();
166 glPushAttrib(GL_ALL_ATTRIB_BITS);
167 glPushClientAttrib(~0u);
175 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
176 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
181 class SGHUDAndPanelDrawable : public osg::Drawable {
183 SGHUDAndPanelDrawable()
185 // Dynamic stuff, do not store geometry
186 setUseDisplayList(false);
187 setDataVariance(Object::DYNAMIC);
189 osg::StateSet* stateSet = getOrCreateStateSet();
190 stateSet->setRenderBinDetails(1000, "RenderBin");
192 // speed optimization?
193 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
194 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
195 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
196 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
197 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
199 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
201 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
202 { drawImplementation(*renderInfo.getState()); }
203 void drawImplementation(osg::State& state) const
205 state.setActiveTextureUnit(0);
206 state.setClientActiveTextureUnit(0);
207 state.disableAllVertexArrays();
209 glPushAttrib(GL_ALL_ATTRIB_BITS);
210 glPushClientAttrib(~0u);
212 HUD *hud = static_cast<HUD*>(globals->get_subsystem("hud"));
215 // update the panel subsystem
216 if ( globals->get_current_panel() != NULL )
217 globals->get_current_panel()->update(state);
218 // We don't need a state here - can be safely removed when we can pick
227 virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
228 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
233 class FGLightSourceUpdateCallback : public osg::NodeCallback {
237 * @param isSun true if the light is the actual sun i.e., for
238 * illuminating the moon.
240 FGLightSourceUpdateCallback(bool isSun = false) : _isSun(isSun) {}
241 FGLightSourceUpdateCallback(const FGLightSourceUpdateCallback& nc,
243 : NodeCallback(nc, op), _isSun(nc._isSun)
245 META_Object(flightgear,FGLightSourceUpdateCallback);
247 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
249 assert(dynamic_cast<osg::LightSource*>(node));
250 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
251 osg::Light* light = lightSource->getLight();
253 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
255 light->setAmbient(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
256 light->setDiffuse(Vec4(1.0f, 1.0f, 1.0f, 1.0f));
257 light->setSpecular(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
259 light->setAmbient(toOsg(l->scene_ambient()));
260 light->setDiffuse(toOsg(l->scene_diffuse()));
261 light->setSpecular(toOsg(l->scene_specular()));
263 osg::Vec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
264 light->setPosition(position);
272 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
274 FGWireFrameModeUpdateCallback() :
275 mWireframe(fgGetNode("/sim/rendering/wireframe", true))
277 virtual void operator()(osg::StateAttribute* stateAttribute,
280 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
281 osg::PolygonMode* polygonMode;
282 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
284 if (mWireframe->getBoolValue())
285 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
286 osg::PolygonMode::LINE);
288 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
289 osg::PolygonMode::FILL);
292 SGPropertyNode_ptr mWireframe;
295 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
297 FGLightModelUpdateCallback() :
298 mHighlights(fgGetNode("/sim/rendering/specular-highlight", true))
300 virtual void operator()(osg::StateAttribute* stateAttribute,
303 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
304 osg::LightModel* lightModel;
305 lightModel = static_cast<osg::LightModel*>(stateAttribute);
308 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
309 lightModel->setAmbientIntensity(toOsg(l->scene_ambient());
311 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
313 lightModel->setTwoSided(true);
314 lightModel->setLocalViewer(false);
316 if (mHighlights->getBoolValue()) {
317 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
319 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
323 SGPropertyNode_ptr mHighlights;
326 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
328 FGFogEnableUpdateCallback() :
329 mFogEnabled(fgGetNode("/sim/rendering/fog", true))
331 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
333 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
334 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
336 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
340 SGPropertyNode_ptr mFogEnabled;
343 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
345 virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
347 assert(dynamic_cast<SGUpdateVisitor*>(nv));
348 assert(dynamic_cast<osg::Fog*>(sa));
349 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
350 osg::Fog* fog = static_cast<osg::Fog*>(sa);
351 fog->setMode(osg::Fog::EXP2);
352 fog->setColor(toOsg(updateVisitor->getFogColor()));
353 fog->setDensity(updateVisitor->getFogExp2Density());
357 // update callback for the switch node guarding that splash
358 class FGScenerySwitchCallback : public osg::NodeCallback {
360 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
362 assert(dynamic_cast<osg::Switch*>(node));
363 osg::Switch* sw = static_cast<osg::Switch*>(node);
365 bool enabled = scenery_enabled;
366 sw->setValue(0, enabled);
372 static bool scenery_enabled;
375 bool FGScenerySwitchCallback::scenery_enabled = false;
380 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
381 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
383 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
385 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
387 FGRenderer::FGRenderer()
389 #ifdef FG_JPEG_SERVER
390 jpgRenderFrame = FGRenderer::update;
392 eventHandler = new FGEventHandler;
395 FGRenderer::~FGRenderer()
397 #ifdef FG_JPEG_SERVER
398 jpgRenderFrame = NULL;
402 // Initialize various GL/view parameters
403 // XXX This should be called "preinit" or something, as it initializes
404 // critical parts of the scene graph in addition to the splash screen.
406 FGRenderer::splashinit( void ) {
407 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
408 mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
409 mRealRoot->addChild(fgCreateSplashNode());
410 mFrameStamp = viewer->getFrameStamp();
411 // Scene doesn't seem to pass the frame stamp to the update
412 // visitor automatically.
413 mUpdateVisitor->setFrameStamp(mFrameStamp.get());
414 viewer->setUpdateVisitor(mUpdateVisitor.get());
415 fgSetDouble("/sim/startup/splash-alpha", 1.0);
419 FGRenderer::init( void )
421 _scenery_loaded = fgGetNode("/sim/sceneryloaded", true);
422 _scenery_override = fgGetNode("/sim/sceneryloaded-override", true);
423 _panel_hotspots = fgGetNode("/sim/panel-hotspots", true);
424 _virtual_cockpit = fgGetNode("/sim/virtual-cockpit", true);
426 _sim_delta_sec = fgGetNode("/sim/time/delta-sec", true);
428 _xsize = fgGetNode("/sim/startup/xsize", true);
429 _ysize = fgGetNode("/sim/startup/ysize", true);
430 _splash_alpha = fgGetNode("/sim/startup/splash-alpha", true);
432 _skyblend = fgGetNode("/sim/rendering/skyblend", true);
433 _point_sprites = fgGetNode("/sim/rendering/point-sprites", true);
434 _enhanced_lighting = fgGetNode("/sim/rendering/enhanced-lighting", true);
435 _distance_attenuation = fgGetNode("/sim/rendering/distance-attenuation", true);
436 _horizon_effect = fgGetNode("/sim/rendering/horizon-effect", true);
437 _textures = fgGetNode("/sim/rendering/textures", true);
439 _altitude_ft = fgGetNode("/position/altitude-ft", true);
441 _cloud_status = fgGetNode("/environment/clouds/status", true);
442 _visibility_m = fgGetNode("/environment/visibility-m", true);
446 FGRenderer::setupView( void )
448 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
449 osg::initNotifyLevel();
451 // The number of polygon-offset "units" to place between layers. In
452 // principle, one is supposed to be enough. In practice, I find that
453 // my hardware/driver requires many more.
454 osg::PolygonOffset::setUnitsMultiplier(1);
455 osg::PolygonOffset::setFactorMultiplier(1);
457 // Go full screen if requested ...
458 if ( fgGetBool("/sim/startup/fullscreen") )
462 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
464 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
466 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
468 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
469 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
471 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
472 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
473 stateSet->setAttribute(new osg::BlendFunc);
474 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
476 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
478 // this will be set below
479 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
481 osg::Material* material = new osg::Material;
482 stateSet->setAttribute(material);
484 stateSet->setTextureAttribute(0, new osg::TexEnv);
485 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
487 osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
488 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
489 stateSet->setAttribute(hint);
490 hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
491 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
492 stateSet->setAttribute(hint);
493 hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
494 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
495 stateSet->setAttribute(hint);
496 hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
497 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
498 stateSet->setAttribute(hint);
499 hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
500 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
501 stateSet->setAttribute(hint);
503 osg::Group* sceneGroup = new osg::Group;
504 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
505 sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
507 //sceneGroup->addChild(thesky->getCloudRoot());
509 stateSet = sceneGroup->getOrCreateStateSet();
510 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
512 // need to update the light on every frame
513 // OSG LightSource objects are rather confusing. OSG only supports
514 // the 10 lights specified by OpenGL itself; if more than one
515 // LightSource in the scene graph have the same light number, it's
516 // indeterminate which values will be used to render geometry that
517 // has that light number enabled. Also, adding children to a
518 // LightSource is just a shortcut for setting up a state set that
519 // has the corresponding OpenGL light enabled: a LightSource will
520 // affect geometry anywhere in the scene graph that has its light
521 // number enabled in a state set.
522 LightSource* lightSource = new LightSource;
523 lightSource->getLight()->setDataVariance(Object::DYNAMIC);
524 // relative because of CameraView being just a clever transform node
525 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
526 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
527 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
528 mRealRoot->addChild(lightSource);
529 // we need a white diffuse light for the phase of the moon
530 osg::LightSource* sunLight = new osg::LightSource;
531 sunLight->getLight()->setDataVariance(Object::DYNAMIC);
532 sunLight->getLight()->setLightNum(1);
533 sunLight->setUpdateCallback(new FGLightSourceUpdateCallback(true));
534 sunLight->setReferenceFrame(osg::LightSource::RELATIVE_RF);
535 sunLight->setLocalStateSetModes(osg::StateAttribute::ON);
536 // Hang a StateSet above the sky subgraph in order to turn off
538 Group* skyGroup = new Group;
539 StateSet* skySS = skyGroup->getOrCreateStateSet();
540 skySS->setMode(GL_LIGHT0, StateAttribute::OFF);
541 skyGroup->addChild(thesky->getPreRoot());
542 sunLight->addChild(skyGroup);
543 mRoot->addChild(sceneGroup);
544 mRoot->addChild(sunLight);
545 // Clouds are added to the scene graph later
546 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
547 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
548 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
549 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
551 // enable disable specular highlights.
552 // is the place where we might plug in an other fragment shader ...
553 osg::LightModel* lightModel = new osg::LightModel;
554 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
555 stateSet->setAttribute(lightModel);
557 // switch to enable wireframe
558 osg::PolygonMode* polygonMode = new osg::PolygonMode;
559 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
560 stateSet->setAttributeAndModes(polygonMode);
562 // scene fog handling
563 osg::Fog* fog = new osg::Fog;
564 fog->setUpdateCallback(new FGFogUpdateCallback);
565 stateSet->setAttributeAndModes(fog);
566 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
569 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
571 osg::Geode* geode = new osg::Geode;
572 geode->addDrawable(new SGPuDrawable);
573 geode->addDrawable(new SGHUDAndPanelDrawable);
574 guiCamera->addChild(geode);
576 osg::Switch* sw = new osg::Switch;
577 sw->setUpdateCallback(new FGScenerySwitchCallback);
578 sw->addChild(mRoot.get());
579 mRealRoot->addChild(sw);
580 // The clouds are attached directly to the scene graph root
581 // because, in theory, they don't want the same default state set
582 // as the rest of the scene. This may not be true in practice.
583 mRealRoot->addChild(thesky->getCloudRoot());
584 mRealRoot->addChild(FGCreateRedoutNode());
585 // Attach empty program to the scene root so that shader programs
586 // don't leak into state sets (effects) that shouldn't have one.
587 stateSet = mRealRoot->getOrCreateStateSet();
588 stateSet->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON);
594 globals->get_renderer()->update(true);
597 // Update all Visuals (redraws anything graphics related)
599 FGRenderer::update( bool refresh_camera_settings ) {
600 if (!(_scenery_loaded->getBoolValue() ||
601 _scenery_override->getBoolValue()))
603 _splash_alpha->setDoubleValue(1.0);
606 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
608 if (_splash_alpha->getDoubleValue()>0.0)
610 // Fade out the splash screen
611 const double fade_time = 0.8;
612 const double fade_steps_per_sec = 20;
613 double delay_time = SGMiscd::min(fade_time/fade_steps_per_sec,
614 (SGTimeStamp::now() - _splash_time).toSecs());
615 _splash_time = SGTimeStamp::now();
616 double sAlpha = _splash_alpha->getDoubleValue();
617 sAlpha -= SGMiscd::max(0.0,delay_time/fade_time);
618 FGScenerySwitchCallback::scenery_enabled = (sAlpha<1.0);
619 _splash_alpha->setDoubleValue(sAlpha);
622 bool skyblend = _skyblend->getBoolValue();
623 bool use_point_sprites = _point_sprites->getBoolValue();
624 bool enhanced_lighting = _enhanced_lighting->getBoolValue();
625 bool distance_attenuation = _distance_attenuation->getBoolValue();
628 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
629 distance_attenuation );
631 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
634 double actual_visibility;
635 if (_cloud_status->getBoolValue()) {
636 actual_visibility = thesky->get_visibility();
638 actual_visibility = _visibility_m->getDoubleValue();
641 // idle_state is now 1000 meaning we've finished all our
642 // initializations and are running the main loop, so this will
643 // now work without seg faulting the system.
645 FGViewer *current__view = globals->get_current_view();
646 // Force update of center dependent values ...
647 current__view->set_dirty();
649 if ( refresh_camera_settings ) {
651 resize( _xsize->getIntValue(),
652 _ysize->getIntValue() );
654 osg::Camera *camera = viewer->getCamera();
658 if ( _textures->getBoolValue() ) {
659 SGVec4f clearColor(l->adj_fog_color());
660 camera->setClearColor(toOsg(clearColor));
663 SGVec4f clearColor(l->sky_color());
664 camera->setClearColor(toOsg(clearColor));
667 // update fog params if visibility has changed
668 double visibility_meters = _visibility_m->getDoubleValue();
669 thesky->set_visibility(visibility_meters);
671 double altitude_m = _altitude_ft->getDoubleValue() * SG_FEET_TO_METER;
672 thesky->modify_vis( altitude_m, 0.0 /* time factor, now unused */);
674 // update the sky dome
677 // The sun and moon distances are scaled down versions
678 // of the actual distance to get both the moon and the sun
679 // within the range of the far clip plane.
680 // Moon distance: 384,467 kilometers
681 // Sun distance: 150,000,000 kilometers
683 double sun_horiz_eff, moon_horiz_eff;
684 if (_horizon_effect->getBoolValue()) {
686 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
690 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
694 sun_horiz_eff = moon_horiz_eff = 1.0;
698 sstate.pos = current__view->getViewPosition();
699 sstate.pos_geod = current__view->getPosition();
700 sstate.ori = current__view->getViewOrientation();
701 sstate.spin = l->get_sun_rotation();
702 sstate.gst = globals->get_time_params()->getGst();
703 sstate.sun_dist = 50000.0 * sun_horiz_eff;
704 sstate.moon_dist = 40000.0 * moon_horiz_eff;
705 sstate.sun_angle = l->get_sun_angle();
708 scolor.sky_color = SGVec3f(l->sky_color().data());
709 scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
710 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
711 scolor.cloud_color = SGVec3f(l->cloud_color().data());
712 scolor.sun_angle = l->get_sun_angle();
713 scolor.moon_angle = l->get_moon_angle();
715 double delta_time_sec = _sim_delta_sec->getDoubleValue();
716 thesky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
717 thesky->repaint( scolor, *globals->get_ephem() );
720 // shadows->setupShadows(
721 // current__view->getLongitude_deg(),
722 // current__view->getLatitude_deg(),
723 // globals->get_time_params()->getGst(),
724 // globals->get_ephem()->getSunRightAscension(),
725 // globals->get_ephem()->getSunDeclination(),
726 // l->get_sun_angle());
730 // sgEnviro.setLight(l->adj_fog_color());
731 // sgEnviro.startOfFrame(current__view->get_view_pos(),
732 // current__view->get_world_up(),
733 // current__view->getLongitude_deg(),
734 // current__view->getLatitude_deg(),
735 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
739 // sgEnviro.drawLightning();
741 // double current_view_origin_airspeed_horiz_kt =
742 // fgGetDouble("/velocities/airspeed-kt", 0.0)
743 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
744 // * SGD_DEGREES_TO_RADIANS);
748 // shadows->endOfFrame();
750 // need to call the update visitor once
751 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
752 mUpdateVisitor->setViewData(current__view->getViewPosition(),
753 current__view->getViewOrientation());
754 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
755 mUpdateVisitor->setLight(direction, l->scene_ambient(),
756 l->scene_diffuse(), l->scene_specular(),
758 l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
759 mUpdateVisitor->setVisibility(actual_visibility);
760 simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
761 osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
762 cullMask |= simgear::GroundLightManager::instance()
763 ->getLightNodeMask(mUpdateVisitor.get());
764 if (_panel_hotspots->getBoolValue())
765 cullMask |= simgear::PICK_BIT;
766 CameraGroup::getDefault()->setCameraCullMasks(cullMask);
771 // options.cxx needs to see this for toggle_panel()
772 // Handle new window size or exposure
774 FGRenderer::resize( int width, int height ) {
776 // the following breaks aspect-ratio of the main 3D scenery window when 2D panels are moved
777 // in y direction - causing issues for aircraft with 2D panels (/sim/virtual_cockpit=false).
778 // Disabling for now. Seems this useful for the pre-OSG time only.
779 // if ( (!_virtual_cockpit->getBoolValue())
780 // && fgPanelVisible() && idle_state == 1000 ) {
781 // view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
782 // globals->get_current_panel()->getYOffset()) / 768.0);
785 int curWidth = _xsize->getIntValue(),
786 curHeight = _ysize->getIntValue();
788 _xsize->setIntValue(width);
789 _ysize->setIntValue(height);
790 double aspect = height / (double) width;
793 FGViewMgr *viewmgr = globals->get_viewmgr();
795 for ( int i = 0; i < viewmgr->size(); ++i ) {
796 viewmgr->get_view(i)->set_aspect_ratio(aspect);
802 FGRenderer::pick(std::vector<SGSceneryPick>& pickList,
803 const osgGA::GUIEventAdapter* ea)
805 // wipe out the return ...
807 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
808 Intersections intersections;
810 if (!computeIntersections(CameraGroup::getDefault(), ea, intersections))
812 for (Intersections::iterator hit = intersections.begin(),
813 e = intersections.end();
816 const osg::NodePath& np = hit->nodePath;
817 osg::NodePath::const_reverse_iterator npi;
818 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
819 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
822 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
823 SGPickCallback* pickCallback = ud->getPickCallback(i);
826 SGSceneryPick sceneryPick;
827 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
828 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
829 sceneryPick.callback = pickCallback;
830 pickList.push_back(sceneryPick);
834 return !pickList.empty();
838 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
844 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
846 eventHandler = eventHandler_;
850 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
852 mRealRoot->addChild(camera);
856 fgDumpSceneGraphToFile(const char* filename)
858 return osgDB::writeNodeFile(*mRealRoot.get(), filename);
862 fgDumpTerrainBranchToFile(const char* filename)
864 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
870 fgDumpNodeToFile(osg::Node* node, const char* filename)
872 return osgDB::writeNodeFile(*node, filename);
879 class VisibleSceneInfoVistor : public NodeVisitor, CullStack
882 VisibleSceneInfoVistor()
883 : NodeVisitor(CULL_VISITOR, TRAVERSE_ACTIVE_CHILDREN)
885 setCullingMode(CullSettings::SMALL_FEATURE_CULLING
886 | CullSettings::VIEW_FRUSTUM_CULLING);
887 setComputeNearFarMode(CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
890 VisibleSceneInfoVistor(const VisibleSceneInfoVistor& rhs)
894 META_NodeVisitor("flightgear","VisibleSceneInfoVistor")
896 typedef std::map<const std::string,int> InfoMap;
898 void getNodeInfo(Node* node)
900 const char* typeName = typeid(*node).name();
901 classInfo[typeName]++;
902 const std::string& nodeName = node->getName();
903 if (!nodeName.empty())
904 nodeInfo[nodeName]++;
910 typedef vector<InfoMap::iterator> FreqVector;
911 cout << "class info:\n";
913 for (InfoMap::iterator itr = classInfo.begin(), end = classInfo.end();
916 classes.push_back(itr);
917 sort(classes.begin(), classes.end(), freqComp);
918 for (FreqVector::iterator itr = classes.begin(), end = classes.end();
921 cout << (*itr)->first << " " << (*itr)->second << "\n";
923 cout << "\nnode info:\n";
925 for (InfoMap::iterator itr = nodeInfo.begin(), end = nodeInfo.end();
928 nodes.push_back(itr);
930 sort (nodes.begin(), nodes.end(), freqComp);
931 for (FreqVector::iterator itr = nodes.begin(), end = nodes.end();
934 cout << (*itr)->first << " " << (*itr)->second << "\n";
939 void doTraversal(Camera* camera, Node* root, Viewport* viewport)
941 ref_ptr<RefMatrix> projection
942 = createOrReuseMatrix(camera->getProjectionMatrix());
943 ref_ptr<RefMatrix> mv = createOrReuseMatrix(camera->getViewMatrix());
945 viewport = camera->getViewport();
947 pushViewport(viewport);
948 pushProjectionMatrix(projection.get());
949 pushModelViewMatrix(mv.get(), Transform::ABSOLUTE_RF);
951 popModelViewMatrix();
952 popProjectionMatrix();
958 void apply(Node& node)
967 void apply(Group& node)
977 void apply(Transform& node)
982 ref_ptr<RefMatrix> matrix = createOrReuseMatrix(*getModelViewMatrix());
983 node.computeLocalToWorldMatrix(*matrix,this);
984 pushModelViewMatrix(matrix.get(), node.getReferenceFrame());
987 popModelViewMatrix();
991 void apply(Camera& camera)
993 // Save current cull settings
994 CullSettings saved_cull_settings(*this);
996 // set cull settings from this Camera
997 setCullSettings(camera);
998 // inherit the settings from above
999 inheritCullSettings(saved_cull_settings, camera.getInheritanceMask());
1001 // set the cull mask.
1002 unsigned int savedTraversalMask = getTraversalMask();
1003 bool mustSetCullMask = (camera.getInheritanceMask()
1004 & osg::CullSettings::CULL_MASK) == 0;
1005 if (mustSetCullMask)
1006 setTraversalMask(camera.getCullMask());
1008 osg::RefMatrix* projection = 0;
1009 osg::RefMatrix* modelview = 0;
1011 if (camera.getReferenceFrame()==osg::Transform::RELATIVE_RF) {
1012 if (camera.getTransformOrder()==osg::Camera::POST_MULTIPLY) {
1013 projection = createOrReuseMatrix(*getProjectionMatrix()
1014 *camera.getProjectionMatrix());
1015 modelview = createOrReuseMatrix(*getModelViewMatrix()
1016 * camera.getViewMatrix());
1018 else { // pre multiply
1019 projection = createOrReuseMatrix(camera.getProjectionMatrix()
1020 * (*getProjectionMatrix()));
1021 modelview = createOrReuseMatrix(camera.getViewMatrix()
1022 * (*getModelViewMatrix()));
1025 // an absolute reference frame
1026 projection = createOrReuseMatrix(camera.getProjectionMatrix());
1027 modelview = createOrReuseMatrix(camera.getViewMatrix());
1029 if (camera.getViewport())
1030 pushViewport(camera.getViewport());
1032 pushProjectionMatrix(projection);
1033 pushModelViewMatrix(modelview, camera.getReferenceFrame());
1037 // restore the previous model view matrix.
1038 popModelViewMatrix();
1040 // restore the previous model view matrix.
1041 popProjectionMatrix();
1043 if (camera.getViewport()) popViewport();
1045 // restore the previous traversal mask settings
1046 if (mustSetCullMask)
1047 setTraversalMask(savedTraversalMask);
1049 // restore the previous cull settings
1050 setCullSettings(saved_cull_settings);
1055 static bool freqComp(const InfoMap::iterator& lhs, const InfoMap::iterator& rhs)
1057 return lhs->second > rhs->second;
1063 bool printVisibleSceneInfo(FGRenderer* renderer)
1065 osgViewer::Viewer* viewer = renderer->getViewer();
1066 VisibleSceneInfoVistor vsv;
1068 if (!viewer->getCamera()->getViewport() && viewer->getNumSlaves() > 0) {
1069 const View::Slave& slave = viewer->getSlave(0);
1070 vp = slave._camera->getViewport();
1072 vsv.doTraversal(viewer->getCamera(), viewer->getSceneData(), vp);
1076 // end of renderer.cxx