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>
96 #include <Environment/environment_mgr.hxx>
99 #include "renderer.hxx"
101 #include "CameraGroup.hxx"
102 #include "FGEventHandler.hxx"
103 #include <Main/viewer.hxx>
104 #include <Main/viewmgr.hxx>
107 using namespace simgear;
108 using namespace flightgear;
110 class FGHintUpdateCallback : public osg::StateAttribute::Callback {
112 FGHintUpdateCallback(const char* configNode) :
113 mConfigNode(fgGetNode(configNode, true))
115 virtual void operator()(osg::StateAttribute* stateAttribute,
118 assert(dynamic_cast<osg::Hint*>(stateAttribute));
119 osg::Hint* hint = static_cast<osg::Hint*>(stateAttribute);
121 const char* value = mConfigNode->getStringValue();
123 hint->setMode(GL_DONT_CARE);
124 else if (0 == strcmp(value, "nicest"))
125 hint->setMode(GL_NICEST);
126 else if (0 == strcmp(value, "fastest"))
127 hint->setMode(GL_FASTEST);
129 hint->setMode(GL_DONT_CARE);
132 SGPropertyNode_ptr mConfigNode;
136 class SGPuDrawable : public osg::Drawable {
140 // Dynamic stuff, do not store geometry
141 setUseDisplayList(false);
142 setDataVariance(Object::DYNAMIC);
144 osg::StateSet* stateSet = getOrCreateStateSet();
145 stateSet->setRenderBinDetails(1001, "RenderBin");
146 // speed optimization?
147 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
148 // We can do translucent menus, so why not. :-)
149 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
150 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
151 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
153 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
155 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
156 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
158 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
159 { drawImplementation(*renderInfo.getState()); }
160 void drawImplementation(osg::State& state) const
162 state.setActiveTextureUnit(0);
163 state.setClientActiveTextureUnit(0);
165 state.disableAllVertexArrays();
167 glPushAttrib(GL_ALL_ATTRIB_BITS);
168 glPushClientAttrib(~0u);
176 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
177 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
182 class SGHUDAndPanelDrawable : public osg::Drawable {
184 SGHUDAndPanelDrawable()
186 // Dynamic stuff, do not store geometry
187 setUseDisplayList(false);
188 setDataVariance(Object::DYNAMIC);
190 osg::StateSet* stateSet = getOrCreateStateSet();
191 stateSet->setRenderBinDetails(1000, "RenderBin");
193 // speed optimization?
194 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
195 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
196 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
197 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
198 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
200 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
202 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
203 { drawImplementation(*renderInfo.getState()); }
204 void drawImplementation(osg::State& state) const
206 state.setActiveTextureUnit(0);
207 state.setClientActiveTextureUnit(0);
208 state.disableAllVertexArrays();
210 glPushAttrib(GL_ALL_ATTRIB_BITS);
211 glPushClientAttrib(~0u);
213 HUD *hud = static_cast<HUD*>(globals->get_subsystem("hud"));
216 // update the panel subsystem
217 if ( globals->get_current_panel() != NULL )
218 globals->get_current_panel()->update(state);
219 // We don't need a state here - can be safely removed when we can pick
228 virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
229 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
234 class FGLightSourceUpdateCallback : public osg::NodeCallback {
238 * @param isSun true if the light is the actual sun i.e., for
239 * illuminating the moon.
241 FGLightSourceUpdateCallback(bool isSun = false) : _isSun(isSun) {}
242 FGLightSourceUpdateCallback(const FGLightSourceUpdateCallback& nc,
244 : NodeCallback(nc, op), _isSun(nc._isSun)
246 META_Object(flightgear,FGLightSourceUpdateCallback);
248 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
250 assert(dynamic_cast<osg::LightSource*>(node));
251 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
252 osg::Light* light = lightSource->getLight();
254 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
256 light->setAmbient(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
257 light->setDiffuse(Vec4(1.0f, 1.0f, 1.0f, 1.0f));
258 light->setSpecular(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
260 light->setAmbient(toOsg(l->scene_ambient()));
261 light->setDiffuse(toOsg(l->scene_diffuse()));
262 light->setSpecular(toOsg(l->scene_specular()));
264 osg::Vec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
265 light->setPosition(position);
273 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
275 FGWireFrameModeUpdateCallback() :
276 mWireframe(fgGetNode("/sim/rendering/wireframe", true))
278 virtual void operator()(osg::StateAttribute* stateAttribute,
281 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
282 osg::PolygonMode* polygonMode;
283 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
285 if (mWireframe->getBoolValue())
286 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
287 osg::PolygonMode::LINE);
289 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
290 osg::PolygonMode::FILL);
293 SGPropertyNode_ptr mWireframe;
296 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
298 FGLightModelUpdateCallback() :
299 mHighlights(fgGetNode("/sim/rendering/specular-highlight", true))
301 virtual void operator()(osg::StateAttribute* stateAttribute,
304 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
305 osg::LightModel* lightModel;
306 lightModel = static_cast<osg::LightModel*>(stateAttribute);
309 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
310 lightModel->setAmbientIntensity(toOsg(l->scene_ambient());
312 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
314 lightModel->setTwoSided(true);
315 lightModel->setLocalViewer(false);
317 if (mHighlights->getBoolValue()) {
318 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
320 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
324 SGPropertyNode_ptr mHighlights;
327 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
329 FGFogEnableUpdateCallback() :
330 mFogEnabled(fgGetNode("/sim/rendering/fog", true))
332 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
334 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
335 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
337 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
341 SGPropertyNode_ptr mFogEnabled;
344 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
346 virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
348 assert(dynamic_cast<SGUpdateVisitor*>(nv));
349 assert(dynamic_cast<osg::Fog*>(sa));
350 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
351 osg::Fog* fog = static_cast<osg::Fog*>(sa);
352 fog->setMode(osg::Fog::EXP2);
353 fog->setColor(toOsg(updateVisitor->getFogColor()));
354 fog->setDensity(updateVisitor->getFogExp2Density());
358 // update callback for the switch node guarding that splash
359 class FGScenerySwitchCallback : public osg::NodeCallback {
361 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
363 assert(dynamic_cast<osg::Switch*>(node));
364 osg::Switch* sw = static_cast<osg::Switch*>(node);
366 bool enabled = scenery_enabled;
367 sw->setValue(0, enabled);
373 static bool scenery_enabled;
376 bool FGScenerySwitchCallback::scenery_enabled = false;
378 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
379 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
381 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
383 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
385 #ifdef FG_JPEG_SERVER
386 static void updateRenderer()
388 globals->get_renderer()->update();
392 FGRenderer::FGRenderer() :
395 #ifdef FG_JPEG_SERVER
396 jpgRenderFrame = updateRenderer;
398 eventHandler = new FGEventHandler;
401 FGRenderer::~FGRenderer()
403 #ifdef FG_JPEG_SERVER
404 jpgRenderFrame = NULL;
409 // Initialize various GL/view parameters
410 // XXX This should be called "preinit" or something, as it initializes
411 // critical parts of the scene graph in addition to the splash screen.
413 FGRenderer::splashinit( void ) {
414 osgViewer::Viewer* viewer = getViewer();
415 mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
416 mRealRoot->addChild(fgCreateSplashNode());
417 mFrameStamp = viewer->getFrameStamp();
418 // Scene doesn't seem to pass the frame stamp to the update
419 // visitor automatically.
420 mUpdateVisitor->setFrameStamp(mFrameStamp.get());
421 viewer->setUpdateVisitor(mUpdateVisitor.get());
422 fgSetDouble("/sim/startup/splash-alpha", 1.0);
426 FGRenderer::init( void )
428 _scenery_loaded = fgGetNode("/sim/sceneryloaded", true);
429 _scenery_override = fgGetNode("/sim/sceneryloaded-override", true);
430 _panel_hotspots = fgGetNode("/sim/panel-hotspots", true);
431 _virtual_cockpit = fgGetNode("/sim/virtual-cockpit", true);
433 _sim_delta_sec = fgGetNode("/sim/time/delta-sec", true);
435 _xsize = fgGetNode("/sim/startup/xsize", true);
436 _ysize = fgGetNode("/sim/startup/ysize", true);
437 _splash_alpha = fgGetNode("/sim/startup/splash-alpha", true);
439 _skyblend = fgGetNode("/sim/rendering/skyblend", true);
440 _point_sprites = fgGetNode("/sim/rendering/point-sprites", true);
441 _enhanced_lighting = fgGetNode("/sim/rendering/enhanced-lighting", true);
442 _distance_attenuation = fgGetNode("/sim/rendering/distance-attenuation", true);
443 _horizon_effect = fgGetNode("/sim/rendering/horizon-effect", true);
444 _textures = fgGetNode("/sim/rendering/textures", true);
446 _altitude_ft = fgGetNode("/position/altitude-ft", true);
448 _cloud_status = fgGetNode("/environment/clouds/status", true);
449 _visibility_m = fgGetNode("/environment/visibility-m", true);
451 bool use_point_sprites = _point_sprites->getBoolValue();
452 bool enhanced_lighting = _enhanced_lighting->getBoolValue();
453 bool distance_attenuation = _distance_attenuation->getBoolValue();
455 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
456 distance_attenuation );
458 if (const char* tc = fgGetString("/sim/rendering/texture-compression", NULL)) {
459 if (strcmp(tc, "false") == 0 || strcmp(tc, "off") == 0 ||
460 strcmp(tc, "0") == 0 || strcmp(tc, "no") == 0 ||
461 strcmp(tc, "none") == 0) {
462 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::DoNotUseCompression);
463 } else if (strcmp(tc, "arb") == 0) {
464 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseARBCompression);
465 } else if (strcmp(tc, "dxt1") == 0) {
466 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT1Compression);
467 } else if (strcmp(tc, "dxt3") == 0) {
468 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT3Compression);
469 } else if (strcmp(tc, "dxt5") == 0) {
470 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT5Compression);
472 SG_LOG(SG_VIEW, SG_WARN, "Unknown texture compression setting!");
476 // create sky, but can't build until setupView, since we depend
477 // on other subsystems to be inited, eg Ephemeris
480 SGPath texture_path(globals->get_fg_root());
481 texture_path.append("Textures");
482 texture_path.append("Sky");
483 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
484 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
485 _sky->add_cloud_layer(layer);
488 _sky->texture_path( texture_path.str() );
492 FGRenderer::setupView( void )
494 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
495 osg::initNotifyLevel();
497 // The number of polygon-offset "units" to place between layers. In
498 // principle, one is supposed to be enough. In practice, I find that
499 // my hardware/driver requires many more.
500 osg::PolygonOffset::setUnitsMultiplier(1);
501 osg::PolygonOffset::setFactorMultiplier(1);
503 // Go full screen if requested ...
504 if ( fgGetBool("/sim/startup/fullscreen") )
508 // The sun and moon diameters are scaled down numbers of the
509 // actual diameters. This was needed to fit both the sun and the
510 // moon within the distance to the far clip plane.
511 // Moon diameter: 3,476 kilometers
512 // Sun diameter: 1,390,000 kilometers
513 _sky->build( 80000.0, 80000.0,
515 *globals->get_ephem(),
516 fgGetNode("/environment", true));
519 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
521 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
523 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
525 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
526 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
528 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
529 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
530 stateSet->setAttribute(new osg::BlendFunc);
531 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
533 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
535 // this will be set below
536 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
538 osg::Material* material = new osg::Material;
539 stateSet->setAttribute(material);
541 stateSet->setTextureAttribute(0, new osg::TexEnv);
542 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
544 osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
545 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
546 stateSet->setAttribute(hint);
547 hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
548 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
549 stateSet->setAttribute(hint);
550 hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
551 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
552 stateSet->setAttribute(hint);
553 hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
554 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
555 stateSet->setAttribute(hint);
556 hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
557 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
558 stateSet->setAttribute(hint);
560 osg::Group* sceneGroup = new osg::Group;
561 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
562 sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
564 //sceneGroup->addChild(thesky->getCloudRoot());
566 stateSet = sceneGroup->getOrCreateStateSet();
567 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
569 // need to update the light on every frame
570 // OSG LightSource objects are rather confusing. OSG only supports
571 // the 10 lights specified by OpenGL itself; if more than one
572 // LightSource in the scene graph have the same light number, it's
573 // indeterminate which values will be used to render geometry that
574 // has that light number enabled. Also, adding children to a
575 // LightSource is just a shortcut for setting up a state set that
576 // has the corresponding OpenGL light enabled: a LightSource will
577 // affect geometry anywhere in the scene graph that has its light
578 // number enabled in a state set.
579 LightSource* lightSource = new LightSource;
580 lightSource->getLight()->setDataVariance(Object::DYNAMIC);
581 // relative because of CameraView being just a clever transform node
582 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
583 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
584 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
585 mRealRoot->addChild(lightSource);
586 // we need a white diffuse light for the phase of the moon
587 osg::LightSource* sunLight = new osg::LightSource;
588 sunLight->getLight()->setDataVariance(Object::DYNAMIC);
589 sunLight->getLight()->setLightNum(1);
590 sunLight->setUpdateCallback(new FGLightSourceUpdateCallback(true));
591 sunLight->setReferenceFrame(osg::LightSource::RELATIVE_RF);
592 sunLight->setLocalStateSetModes(osg::StateAttribute::ON);
594 // Hang a StateSet above the sky subgraph in order to turn off
596 Group* skyGroup = new Group;
597 StateSet* skySS = skyGroup->getOrCreateStateSet();
598 skySS->setMode(GL_LIGHT0, StateAttribute::OFF);
599 skyGroup->addChild(_sky->getPreRoot());
600 sunLight->addChild(skyGroup);
601 mRoot->addChild(sceneGroup);
602 mRoot->addChild(sunLight);
604 // Clouds are added to the scene graph later
605 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
606 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
607 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
608 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
610 // enable disable specular highlights.
611 // is the place where we might plug in an other fragment shader ...
612 osg::LightModel* lightModel = new osg::LightModel;
613 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
614 stateSet->setAttribute(lightModel);
616 // switch to enable wireframe
617 osg::PolygonMode* polygonMode = new osg::PolygonMode;
618 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
619 stateSet->setAttributeAndModes(polygonMode);
621 // scene fog handling
622 osg::Fog* fog = new osg::Fog;
623 fog->setUpdateCallback(new FGFogUpdateCallback);
624 stateSet->setAttributeAndModes(fog);
625 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
628 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
630 osg::Geode* geode = new osg::Geode;
631 geode->addDrawable(new SGPuDrawable);
632 geode->addDrawable(new SGHUDAndPanelDrawable);
633 guiCamera->addChild(geode);
635 osg::Switch* sw = new osg::Switch;
636 sw->setUpdateCallback(new FGScenerySwitchCallback);
637 sw->addChild(mRoot.get());
638 mRealRoot->addChild(sw);
639 // The clouds are attached directly to the scene graph root
640 // because, in theory, they don't want the same default state set
641 // as the rest of the scene. This may not be true in practice.
642 mRealRoot->addChild(_sky->getCloudRoot());
643 mRealRoot->addChild(FGCreateRedoutNode());
644 // Attach empty program to the scene root so that shader programs
645 // don't leak into state sets (effects) that shouldn't have one.
646 stateSet = mRealRoot->getOrCreateStateSet();
647 stateSet->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON);
650 // Update all Visuals (redraws anything graphics related)
652 FGRenderer::update( ) {
653 if (!(_scenery_loaded->getBoolValue() ||
654 _scenery_override->getBoolValue()))
656 _splash_alpha->setDoubleValue(1.0);
659 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
661 if (_splash_alpha->getDoubleValue()>0.0)
663 // Fade out the splash screen
664 const double fade_time = 0.8;
665 const double fade_steps_per_sec = 20;
666 double delay_time = SGMiscd::min(fade_time/fade_steps_per_sec,
667 (SGTimeStamp::now() - _splash_time).toSecs());
668 _splash_time = SGTimeStamp::now();
669 double sAlpha = _splash_alpha->getDoubleValue();
670 sAlpha -= SGMiscd::max(0.0,delay_time/fade_time);
671 FGScenerySwitchCallback::scenery_enabled = (sAlpha<1.0);
672 _splash_alpha->setDoubleValue(sAlpha);
675 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
678 double actual_visibility;
679 if (_cloud_status->getBoolValue()) {
680 actual_visibility = _sky->get_visibility();
682 actual_visibility = _visibility_m->getDoubleValue();
685 // idle_state is now 1000 meaning we've finished all our
686 // initializations and are running the main loop, so this will
687 // now work without seg faulting the system.
689 FGViewer *current__view = globals->get_current_view();
690 // Force update of center dependent values ...
691 current__view->set_dirty();
693 osg::Camera *camera = viewer->getCamera();
695 bool skyblend = _skyblend->getBoolValue();
698 if ( _textures->getBoolValue() ) {
699 SGVec4f clearColor(l->adj_fog_color());
700 camera->setClearColor(toOsg(clearColor));
703 SGVec4f clearColor(l->sky_color());
704 camera->setClearColor(toOsg(clearColor));
707 // update fog params if visibility has changed
708 double visibility_meters = _visibility_m->getDoubleValue();
709 _sky->set_visibility(visibility_meters);
711 double altitude_m = _altitude_ft->getDoubleValue() * SG_FEET_TO_METER;
712 _sky->modify_vis( altitude_m, 0.0 /* time factor, now unused */);
714 // update the sky dome
717 // The sun and moon distances are scaled down versions
718 // of the actual distance to get both the moon and the sun
719 // within the range of the far clip plane.
720 // Moon distance: 384,467 kilometers
721 // Sun distance: 150,000,000 kilometers
723 double sun_horiz_eff, moon_horiz_eff;
724 if (_horizon_effect->getBoolValue()) {
726 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
730 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
734 sun_horiz_eff = moon_horiz_eff = 1.0;
738 sstate.pos = current__view->getViewPosition();
739 sstate.pos_geod = current__view->getPosition();
740 sstate.ori = current__view->getViewOrientation();
741 sstate.spin = l->get_sun_rotation();
742 sstate.gst = globals->get_time_params()->getGst();
743 sstate.sun_dist = 50000.0 * sun_horiz_eff;
744 sstate.moon_dist = 40000.0 * moon_horiz_eff;
745 sstate.sun_angle = l->get_sun_angle();
748 scolor.sky_color = SGVec3f(l->sky_color().data());
749 scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
750 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
751 scolor.cloud_color = SGVec3f(l->cloud_color().data());
752 scolor.sun_angle = l->get_sun_angle();
753 scolor.moon_angle = l->get_moon_angle();
755 double delta_time_sec = _sim_delta_sec->getDoubleValue();
756 _sky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
757 _sky->repaint( scolor, *globals->get_ephem() );
760 // shadows->setupShadows(
761 // current__view->getLongitude_deg(),
762 // current__view->getLatitude_deg(),
763 // globals->get_time_params()->getGst(),
764 // globals->get_ephem()->getSunRightAscension(),
765 // globals->get_ephem()->getSunDeclination(),
766 // l->get_sun_angle());
770 // sgEnviro.setLight(l->adj_fog_color());
771 // sgEnviro.startOfFrame(current__view->get_view_pos(),
772 // current__view->get_world_up(),
773 // current__view->getLongitude_deg(),
774 // current__view->getLatitude_deg(),
775 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
779 // sgEnviro.drawLightning();
781 // double current_view_origin_airspeed_horiz_kt =
782 // fgGetDouble("/velocities/airspeed-kt", 0.0)
783 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
784 // * SGD_DEGREES_TO_RADIANS);
788 // shadows->endOfFrame();
790 // need to call the update visitor once
791 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
792 mUpdateVisitor->setViewData(current__view->getViewPosition(),
793 current__view->getViewOrientation());
794 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
795 mUpdateVisitor->setLight(direction, l->scene_ambient(),
796 l->scene_diffuse(), l->scene_specular(),
798 l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
799 mUpdateVisitor->setVisibility(actual_visibility);
800 simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
801 osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
802 cullMask |= simgear::GroundLightManager::instance()
803 ->getLightNodeMask(mUpdateVisitor.get());
804 if (_panel_hotspots->getBoolValue())
805 cullMask |= simgear::PICK_BIT;
806 CameraGroup::getDefault()->setCameraCullMasks(cullMask);
810 FGRenderer::resize( int width, int height )
812 int curWidth = _xsize->getIntValue(),
813 curHeight = _ysize->getIntValue();
814 SG_LOG(SG_VIEW, SG_DEBUG, "FGRenderer::resize: new size " << width << " x " << height);
815 if ((curHeight != height) || (curWidth != width)) {
816 // must guard setting these, or PLIB-PUI fails with too many live interfaces
817 _xsize->setIntValue(width);
818 _ysize->setIntValue(height);
823 FGRenderer::pick(std::vector<SGSceneryPick>& pickList,
824 const osgGA::GUIEventAdapter* ea)
826 // wipe out the return ...
828 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
829 Intersections intersections;
831 if (!computeIntersections(CameraGroup::getDefault(), ea, intersections))
833 for (Intersections::iterator hit = intersections.begin(),
834 e = intersections.end();
837 const osg::NodePath& np = hit->nodePath;
838 osg::NodePath::const_reverse_iterator npi;
839 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
840 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
843 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
844 SGPickCallback* pickCallback = ud->getPickCallback(i);
847 SGSceneryPick sceneryPick;
848 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
849 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
850 sceneryPick.callback = pickCallback;
851 pickList.push_back(sceneryPick);
855 return !pickList.empty();
859 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
865 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
867 eventHandler = eventHandler_;
871 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
873 mRealRoot->addChild(camera);
877 fgDumpSceneGraphToFile(const char* filename)
879 return osgDB::writeNodeFile(*mRealRoot.get(), filename);
883 fgDumpTerrainBranchToFile(const char* filename)
885 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
891 fgDumpNodeToFile(osg::Node* node, const char* filename)
893 return osgDB::writeNodeFile(*node, filename);
900 class VisibleSceneInfoVistor : public NodeVisitor, CullStack
903 VisibleSceneInfoVistor()
904 : NodeVisitor(CULL_VISITOR, TRAVERSE_ACTIVE_CHILDREN)
906 setCullingMode(CullSettings::SMALL_FEATURE_CULLING
907 | CullSettings::VIEW_FRUSTUM_CULLING);
908 setComputeNearFarMode(CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
911 VisibleSceneInfoVistor(const VisibleSceneInfoVistor& rhs)
915 META_NodeVisitor("flightgear","VisibleSceneInfoVistor")
917 typedef std::map<const std::string,int> InfoMap;
919 void getNodeInfo(Node* node)
921 const char* typeName = typeid(*node).name();
922 classInfo[typeName]++;
923 const std::string& nodeName = node->getName();
924 if (!nodeName.empty())
925 nodeInfo[nodeName]++;
931 typedef vector<InfoMap::iterator> FreqVector;
932 cout << "class info:\n";
934 for (InfoMap::iterator itr = classInfo.begin(), end = classInfo.end();
937 classes.push_back(itr);
938 sort(classes.begin(), classes.end(), freqComp);
939 for (FreqVector::iterator itr = classes.begin(), end = classes.end();
942 cout << (*itr)->first << " " << (*itr)->second << "\n";
944 cout << "\nnode info:\n";
946 for (InfoMap::iterator itr = nodeInfo.begin(), end = nodeInfo.end();
949 nodes.push_back(itr);
951 sort (nodes.begin(), nodes.end(), freqComp);
952 for (FreqVector::iterator itr = nodes.begin(), end = nodes.end();
955 cout << (*itr)->first << " " << (*itr)->second << "\n";
960 void doTraversal(Camera* camera, Node* root, Viewport* viewport)
962 ref_ptr<RefMatrix> projection
963 = createOrReuseMatrix(camera->getProjectionMatrix());
964 ref_ptr<RefMatrix> mv = createOrReuseMatrix(camera->getViewMatrix());
966 viewport = camera->getViewport();
968 pushViewport(viewport);
969 pushProjectionMatrix(projection.get());
970 pushModelViewMatrix(mv.get(), Transform::ABSOLUTE_RF);
972 popModelViewMatrix();
973 popProjectionMatrix();
979 void apply(Node& node)
988 void apply(Group& node)
998 void apply(Transform& node)
1003 ref_ptr<RefMatrix> matrix = createOrReuseMatrix(*getModelViewMatrix());
1004 node.computeLocalToWorldMatrix(*matrix,this);
1005 pushModelViewMatrix(matrix.get(), node.getReferenceFrame());
1008 popModelViewMatrix();
1012 void apply(Camera& camera)
1014 // Save current cull settings
1015 CullSettings saved_cull_settings(*this);
1017 // set cull settings from this Camera
1018 setCullSettings(camera);
1019 // inherit the settings from above
1020 inheritCullSettings(saved_cull_settings, camera.getInheritanceMask());
1022 // set the cull mask.
1023 unsigned int savedTraversalMask = getTraversalMask();
1024 bool mustSetCullMask = (camera.getInheritanceMask()
1025 & osg::CullSettings::CULL_MASK) == 0;
1026 if (mustSetCullMask)
1027 setTraversalMask(camera.getCullMask());
1029 osg::RefMatrix* projection = 0;
1030 osg::RefMatrix* modelview = 0;
1032 if (camera.getReferenceFrame()==osg::Transform::RELATIVE_RF) {
1033 if (camera.getTransformOrder()==osg::Camera::POST_MULTIPLY) {
1034 projection = createOrReuseMatrix(*getProjectionMatrix()
1035 *camera.getProjectionMatrix());
1036 modelview = createOrReuseMatrix(*getModelViewMatrix()
1037 * camera.getViewMatrix());
1039 else { // pre multiply
1040 projection = createOrReuseMatrix(camera.getProjectionMatrix()
1041 * (*getProjectionMatrix()));
1042 modelview = createOrReuseMatrix(camera.getViewMatrix()
1043 * (*getModelViewMatrix()));
1046 // an absolute reference frame
1047 projection = createOrReuseMatrix(camera.getProjectionMatrix());
1048 modelview = createOrReuseMatrix(camera.getViewMatrix());
1050 if (camera.getViewport())
1051 pushViewport(camera.getViewport());
1053 pushProjectionMatrix(projection);
1054 pushModelViewMatrix(modelview, camera.getReferenceFrame());
1058 // restore the previous model view matrix.
1059 popModelViewMatrix();
1061 // restore the previous model view matrix.
1062 popProjectionMatrix();
1064 if (camera.getViewport()) popViewport();
1066 // restore the previous traversal mask settings
1067 if (mustSetCullMask)
1068 setTraversalMask(savedTraversalMask);
1070 // restore the previous cull settings
1071 setCullSettings(saved_cull_settings);
1076 static bool freqComp(const InfoMap::iterator& lhs, const InfoMap::iterator& rhs)
1078 return lhs->second > rhs->second;
1084 bool printVisibleSceneInfo(FGRenderer* renderer)
1086 osgViewer::Viewer* viewer = renderer->getViewer();
1087 VisibleSceneInfoVistor vsv;
1089 if (!viewer->getCamera()->getViewport() && viewer->getNumSlaves() > 0) {
1090 const View::Slave& slave = viewer->getSlave(0);
1091 vp = slave._camera->getViewport();
1093 vsv.doTraversal(viewer->getCamera(), viewer->getSceneData(), vp);
1097 // end of renderer.cxx