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 <simgear/environment/visual_enviro.hxx>
87 #include <Time/light.hxx>
88 #include <Time/light.hxx>
89 #include <Cockpit/panel.hxx>
90 #include <Model/panelnode.hxx>
91 #include <Model/modelmgr.hxx>
92 #include <Model/acmodel.hxx>
93 #include <Scenery/scenery.hxx>
94 #include <Scenery/redout.hxx>
95 #include <GUI/new_gui.hxx>
96 #include <Instrumentation/HUD/HUD.hxx>
97 #include <Environment/precipitation_mgr.hxx>
100 #include "renderer.hxx"
102 #include "CameraGroup.hxx"
103 #include "FGEventHandler.hxx"
104 #include <Main/viewer.hxx>
105 #include <Main/viewmgr.hxx>
108 using namespace simgear;
109 using namespace flightgear;
111 class FGHintUpdateCallback : public osg::StateAttribute::Callback {
113 FGHintUpdateCallback(const char* configNode) :
114 mConfigNode(fgGetNode(configNode, true))
116 virtual void operator()(osg::StateAttribute* stateAttribute,
119 assert(dynamic_cast<osg::Hint*>(stateAttribute));
120 osg::Hint* hint = static_cast<osg::Hint*>(stateAttribute);
122 const char* value = mConfigNode->getStringValue();
124 hint->setMode(GL_DONT_CARE);
125 else if (0 == strcmp(value, "nicest"))
126 hint->setMode(GL_NICEST);
127 else if (0 == strcmp(value, "fastest"))
128 hint->setMode(GL_FASTEST);
130 hint->setMode(GL_DONT_CARE);
133 SGSharedPtr<SGPropertyNode> mConfigNode;
137 class SGPuDrawable : public osg::Drawable {
141 // Dynamic stuff, do not store geometry
142 setUseDisplayList(false);
143 setDataVariance(Object::DYNAMIC);
145 osg::StateSet* stateSet = getOrCreateStateSet();
146 stateSet->setRenderBinDetails(1001, "RenderBin");
147 // speed optimization?
148 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
149 // We can do translucent menus, so why not. :-)
150 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
151 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
152 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
154 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
156 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
157 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
159 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
160 { drawImplementation(*renderInfo.getState()); }
161 void drawImplementation(osg::State& state) const
163 state.setActiveTextureUnit(0);
164 state.setClientActiveTextureUnit(0);
166 state.disableAllVertexArrays();
168 glPushAttrib(GL_ALL_ATTRIB_BITS);
169 glPushClientAttrib(~0u);
177 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
178 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
183 class SGHUDAndPanelDrawable : public osg::Drawable {
185 SGHUDAndPanelDrawable()
187 // Dynamic stuff, do not store geometry
188 setUseDisplayList(false);
189 setDataVariance(Object::DYNAMIC);
191 osg::StateSet* stateSet = getOrCreateStateSet();
192 stateSet->setRenderBinDetails(1000, "RenderBin");
194 // speed optimization?
195 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
196 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
197 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
198 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
199 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
201 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
203 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
204 { drawImplementation(*renderInfo.getState()); }
205 void drawImplementation(osg::State& state) const
207 state.setActiveTextureUnit(0);
208 state.setClientActiveTextureUnit(0);
209 state.disableAllVertexArrays();
211 glPushAttrib(GL_ALL_ATTRIB_BITS);
212 glPushClientAttrib(~0u);
214 HUD *hud = static_cast<HUD*>(globals->get_subsystem("hud"));
217 // update the panel subsystem
218 if ( globals->get_current_panel() != NULL )
219 globals->get_current_panel()->update(state);
220 // We don't need a state here - can be safely removed when we can pick
229 virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
230 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
235 class FGLightSourceUpdateCallback : public osg::NodeCallback {
239 * @param isSun true if the light is the actual sun i.e., for
240 * illuminating the moon.
242 FGLightSourceUpdateCallback(bool isSun = false) : _isSun(isSun) {}
243 FGLightSourceUpdateCallback(const FGLightSourceUpdateCallback& nc,
245 : NodeCallback(nc, op), _isSun(nc._isSun)
247 META_Object(flightgear,FGLightSourceUpdateCallback);
249 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
251 assert(dynamic_cast<osg::LightSource*>(node));
252 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
253 osg::Light* light = lightSource->getLight();
255 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
257 light->setAmbient(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
258 light->setDiffuse(Vec4(1.0f, 1.0f, 1.0f, 1.0f));
259 light->setSpecular(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
261 light->setAmbient(toOsg(l->scene_ambient()));
262 light->setDiffuse(toOsg(l->scene_diffuse()));
263 light->setSpecular(toOsg(l->scene_specular()));
265 osg::Vec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
266 light->setPosition(position);
274 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
276 FGWireFrameModeUpdateCallback() :
277 mWireframe(fgGetNode("/sim/rendering/wireframe"))
279 virtual void operator()(osg::StateAttribute* stateAttribute,
282 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
283 osg::PolygonMode* polygonMode;
284 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
286 if (mWireframe->getBoolValue())
287 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
288 osg::PolygonMode::LINE);
290 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
291 osg::PolygonMode::FILL);
294 SGSharedPtr<SGPropertyNode> mWireframe;
297 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
299 FGLightModelUpdateCallback() :
300 mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
302 virtual void operator()(osg::StateAttribute* stateAttribute,
305 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
306 osg::LightModel* lightModel;
307 lightModel = static_cast<osg::LightModel*>(stateAttribute);
310 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
311 lightModel->setAmbientIntensity(toOsg(l->scene_ambient());
313 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
315 lightModel->setTwoSided(true);
316 lightModel->setLocalViewer(false);
318 if (mHighlights->getBoolValue()) {
319 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
321 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
325 SGSharedPtr<SGPropertyNode> mHighlights;
328 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
330 FGFogEnableUpdateCallback() :
331 mFogEnabled(fgGetNode("/sim/rendering/fog"))
333 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
335 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
336 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
338 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
342 SGSharedPtr<SGPropertyNode> mFogEnabled;
345 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
347 virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
349 assert(dynamic_cast<SGUpdateVisitor*>(nv));
350 assert(dynamic_cast<osg::Fog*>(sa));
351 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
352 osg::Fog* fog = static_cast<osg::Fog*>(sa);
353 fog->setMode(osg::Fog::EXP2);
354 fog->setColor(toOsg(updateVisitor->getFogColor()));
355 fog->setDensity(updateVisitor->getFogExp2Density());
359 // update callback for the switch node guarding that splash
360 class FGScenerySwitchCallback : public osg::NodeCallback {
362 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
364 assert(dynamic_cast<osg::Switch*>(node));
365 osg::Switch* sw = static_cast<osg::Switch*>(node);
367 double t = globals->get_sim_time_sec();
368 bool enabled = 0 < t;
369 sw->setValue(0, enabled);
379 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
380 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
382 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
384 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
386 FGRenderer::FGRenderer()
388 #ifdef FG_JPEG_SERVER
389 jpgRenderFrame = FGRenderer::update;
391 eventHandler = new FGEventHandler;
394 FGRenderer::~FGRenderer()
396 #ifdef FG_JPEG_SERVER
397 jpgRenderFrame = NULL;
401 // Initialize various GL/view parameters
402 // XXX This should be called "preinit" or something, as it initializes
403 // critical parts of the scene graph in addition to the splash screen.
405 FGRenderer::splashinit( void ) {
406 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
407 mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
408 mRealRoot->addChild(fgCreateSplashNode());
409 mFrameStamp = viewer->getFrameStamp();
410 // Scene doesn't seem to pass the frame stamp to the update
411 // visitor automatically.
412 mUpdateVisitor->setFrameStamp(mFrameStamp.get());
413 viewer->setUpdateVisitor(mUpdateVisitor.get());
417 FGRenderer::init( void )
419 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
420 osg::initNotifyLevel();
422 // The number of polygon-offset "units" to place between layers. In
423 // principle, one is supposed to be enough. In practice, I find that
424 // my hardware/driver requires many more.
425 osg::PolygonOffset::setUnitsMultiplier(1);
426 osg::PolygonOffset::setFactorMultiplier(1);
428 // Go full screen if requested ...
429 if ( fgGetBool("/sim/startup/fullscreen") )
433 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
435 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
437 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
439 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
440 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
442 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
443 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
444 stateSet->setAttribute(new osg::BlendFunc);
445 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
447 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
449 // this will be set below
450 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
452 osg::Material* material = new osg::Material;
453 stateSet->setAttribute(material);
455 stateSet->setTextureAttribute(0, new osg::TexEnv);
456 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
458 osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
459 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
460 stateSet->setAttribute(hint);
461 hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
462 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
463 stateSet->setAttribute(hint);
464 hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
465 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
466 stateSet->setAttribute(hint);
467 hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
468 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
469 stateSet->setAttribute(hint);
470 hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
471 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
472 stateSet->setAttribute(hint);
474 osg::Group* sceneGroup = new osg::Group;
475 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
476 sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
478 //sceneGroup->addChild(thesky->getCloudRoot());
480 stateSet = sceneGroup->getOrCreateStateSet();
481 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
483 // need to update the light on every frame
484 // OSG LightSource objects are rather confusing. OSG only supports
485 // the 10 lights specified by OpenGL itself; if more than one
486 // LightSource in the scene graph have the same light number, it's
487 // indeterminate which values will be used to render geometry that
488 // has that light number enabled. Also, adding children to a
489 // LightSource is just a shortcut for setting up a state set that
490 // has the corresponding OpenGL light enabled: a LightSource will
491 // affect geometry anywhere in the scene graph that has its light
492 // number enabled in a state set.
493 LightSource* lightSource = new LightSource;
494 lightSource->getLight()->setDataVariance(Object::DYNAMIC);
495 // relative because of CameraView being just a clever transform node
496 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
497 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
498 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
499 mRealRoot->addChild(lightSource);
500 // we need a white diffuse light for the phase of the moon
501 osg::LightSource* sunLight = new osg::LightSource;
502 sunLight->getLight()->setDataVariance(Object::DYNAMIC);
503 sunLight->getLight()->setLightNum(1);
504 sunLight->setUpdateCallback(new FGLightSourceUpdateCallback(true));
505 sunLight->setReferenceFrame(osg::LightSource::RELATIVE_RF);
506 sunLight->setLocalStateSetModes(osg::StateAttribute::ON);
507 // Hang a StateSet above the sky subgraph in order to turn off
509 Group* skyGroup = new Group;
510 StateSet* skySS = skyGroup->getOrCreateStateSet();
511 skySS->setMode(GL_LIGHT0, StateAttribute::OFF);
512 skyGroup->addChild(thesky->getPreRoot());
513 sunLight->addChild(skyGroup);
514 mRoot->addChild(sceneGroup);
515 mRoot->addChild(sunLight);
516 // Clouds are added to the scene graph later
517 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
518 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
519 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
520 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
522 // enable disable specular highlights.
523 // is the place where we might plug in an other fragment shader ...
524 osg::LightModel* lightModel = new osg::LightModel;
525 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
526 stateSet->setAttribute(lightModel);
528 // switch to enable wireframe
529 osg::PolygonMode* polygonMode = new osg::PolygonMode;
530 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
531 stateSet->setAttributeAndModes(polygonMode);
533 // scene fog handling
534 osg::Fog* fog = new osg::Fog;
535 fog->setUpdateCallback(new FGFogUpdateCallback);
536 stateSet->setAttributeAndModes(fog);
537 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
540 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
542 osg::Geode* geode = new osg::Geode;
543 geode->addDrawable(new SGPuDrawable);
544 geode->addDrawable(new SGHUDAndPanelDrawable);
545 guiCamera->addChild(geode);
547 osg::Switch* sw = new osg::Switch;
548 sw->setUpdateCallback(new FGScenerySwitchCallback);
549 sw->addChild(mRoot.get());
550 mRealRoot->addChild(sw);
551 // The clouds are attached directly to the scene graph root
552 // because, in theory, they don't want the same default state set
553 // as the rest of the scene. This may not be true in practice.
554 mRealRoot->addChild(thesky->getCloudRoot());
555 mRealRoot->addChild(FGCreateRedoutNode());
556 // Attach empty program to the scene root so that shader programs
557 // don't leak into state sets (effects) that shouldn't have one.
558 stateSet = mRealRoot->getOrCreateStateSet();
559 stateSet->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON);
563 // Update all Visuals (redraws anything graphics related)
565 FGRenderer::update( bool refresh_camera_settings ) {
566 bool scenery_loaded = fgGetBool("sim/sceneryloaded", false)
567 || fgGetBool("sim/sceneryloaded-override");
568 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
569 if (!scenery_loaded) {
570 fgSetDouble("/sim/startup/splash-alpha", 1.0);
574 // Fade out the splash screen over the first three seconds.
575 double sAlpha = SGMiscd::max(0, (2.5 - globals->get_sim_time_sec()) / 2.5);
576 fgSetDouble("/sim/startup/splash-alpha", sAlpha);
578 bool skyblend = fgGetBool("/sim/rendering/skyblend");
579 bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
580 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
581 bool distance_attenuation
582 = fgGetBool("/sim/rendering/distance-attenuation");
584 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
585 distance_attenuation );
587 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
590 double actual_visibility;
591 if (fgGetBool("/environment/clouds/status")) {
592 actual_visibility = thesky->get_visibility();
594 actual_visibility = fgGetDouble("/environment/visibility-m");
597 // idle_state is now 1000 meaning we've finished all our
598 // initializations and are running the main loop, so this will
599 // now work without seg faulting the system.
601 FGViewer *current__view = globals->get_current_view();
602 // Force update of center dependent values ...
603 current__view->set_dirty();
605 if ( refresh_camera_settings ) {
607 resize( fgGetInt("/sim/startup/xsize"),
608 fgGetInt("/sim/startup/ysize") );
610 osg::Camera *camera = viewer->getCamera();
614 if ( fgGetBool("/sim/rendering/textures") ) {
615 SGVec4f clearColor(l->adj_fog_color());
616 camera->setClearColor(toOsg(clearColor));
619 SGVec4f clearColor(l->sky_color());
620 camera->setClearColor(toOsg(clearColor));
623 // update fog params if visibility has changed
624 double visibility_meters = fgGetDouble("/environment/visibility-m");
625 thesky->set_visibility(visibility_meters);
627 double altitude_m = fgGetDouble("/position/altitude-ft") * SG_FEET_TO_METER;
628 thesky->modify_vis( altitude_m, 0.0 /* time factor, now unused */);
630 // update the sky dome
633 // The sun and moon distances are scaled down versions
634 // of the actual distance to get both the moon and the sun
635 // within the range of the far clip plane.
636 // Moon distance: 384,467 kilometers
637 // Sun distance: 150,000,000 kilometers
639 double sun_horiz_eff, moon_horiz_eff;
640 if (fgGetBool("/sim/rendering/horizon-effect")) {
642 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
646 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
650 sun_horiz_eff = moon_horiz_eff = 1.0;
654 sstate.pos = current__view->getViewPosition();
655 sstate.pos_geod = current__view->getPosition();
656 sstate.ori = current__view->getViewOrientation();
657 sstate.spin = l->get_sun_rotation();
658 sstate.gst = globals->get_time_params()->getGst();
659 sstate.sun_dist = 50000.0 * sun_horiz_eff;
660 sstate.moon_dist = 40000.0 * moon_horiz_eff;
661 sstate.sun_angle = l->get_sun_angle();
664 scolor.sky_color = SGVec3f(l->sky_color().data());
665 scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
666 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
667 scolor.cloud_color = SGVec3f(l->cloud_color().data());
668 scolor.sun_angle = l->get_sun_angle();
669 scolor.moon_angle = l->get_moon_angle();
671 double delta_time_sec = fgGetDouble("/sim/time/delta-sec");
672 thesky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
673 thesky->repaint( scolor, *globals->get_ephem() );
676 // shadows->setupShadows(
677 // current__view->getLongitude_deg(),
678 // current__view->getLatitude_deg(),
679 // globals->get_time_params()->getGst(),
680 // globals->get_ephem()->getSunRightAscension(),
681 // globals->get_ephem()->getSunDeclination(),
682 // l->get_sun_angle());
686 // sgEnviro.setLight(l->adj_fog_color());
687 // sgEnviro.startOfFrame(current__view->get_view_pos(),
688 // current__view->get_world_up(),
689 // current__view->getLongitude_deg(),
690 // current__view->getLatitude_deg(),
691 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
695 // sgEnviro.drawLightning();
697 // double current_view_origin_airspeed_horiz_kt =
698 // fgGetDouble("/velocities/airspeed-kt", 0.0)
699 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
700 // * SGD_DEGREES_TO_RADIANS);
704 // shadows->endOfFrame();
706 // need to call the update visitor once
707 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
708 mUpdateVisitor->setViewData(current__view->getViewPosition(),
709 current__view->getViewOrientation());
710 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
711 mUpdateVisitor->setLight(direction, l->scene_ambient(),
712 l->scene_diffuse(), l->scene_specular(),
714 l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
715 mUpdateVisitor->setVisibility(actual_visibility);
716 simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
717 bool hotspots = fgGetBool("/sim/panel-hotspots");
718 osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
719 cullMask |= simgear::GroundLightManager::instance()
720 ->getLightNodeMask(mUpdateVisitor.get());
722 cullMask |= simgear::PICK_BIT;
723 CameraGroup::getDefault()->setCameraCullMasks(cullMask);
728 // options.cxx needs to see this for toggle_panel()
729 // Handle new window size or exposure
731 FGRenderer::resize( int width, int height ) {
734 if ( (!fgGetBool("/sim/virtual-cockpit"))
735 && fgPanelVisible() && idle_state == 1000 ) {
736 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
737 globals->get_current_panel()->getYOffset()) / 768.0);
742 static int lastwidth = 0;
743 static int lastheight = 0;
744 if (width != lastwidth)
745 fgSetInt("/sim/startup/xsize", lastwidth = width);
746 if (height != lastheight)
747 fgSetInt("/sim/startup/ysize", lastheight = height);
750 FGViewMgr *viewmgr = globals->get_viewmgr();
752 for ( int i = 0; i < viewmgr->size(); ++i ) {
753 viewmgr->get_view(i)->
754 set_aspect_ratio((float)view_h / (float)width);
760 FGRenderer::pick(std::vector<SGSceneryPick>& pickList,
761 const osgGA::GUIEventAdapter* ea)
763 // wipe out the return ...
765 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
766 Intersections intersections;
768 if (!computeIntersections(CameraGroup::getDefault(), ea, intersections))
770 for (Intersections::iterator hit = intersections.begin(),
771 e = intersections.end();
774 const osg::NodePath& np = hit->nodePath;
775 osg::NodePath::const_reverse_iterator npi;
776 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
777 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
780 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
781 SGPickCallback* pickCallback = ud->getPickCallback(i);
784 SGSceneryPick sceneryPick;
785 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
786 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
787 sceneryPick.callback = pickCallback;
788 pickList.push_back(sceneryPick);
792 return !pickList.empty();
796 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
802 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
804 eventHandler = eventHandler_;
808 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
810 mRealRoot->addChild(camera);
814 fgDumpSceneGraphToFile(const char* filename)
816 return osgDB::writeNodeFile(*mRealRoot.get(), filename);
820 fgDumpTerrainBranchToFile(const char* filename)
822 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
828 fgDumpNodeToFile(osg::Node* node, const char* filename)
830 return osgDB::writeNodeFile(*node, filename);
837 class VisibleSceneInfoVistor : public NodeVisitor, CullStack
840 VisibleSceneInfoVistor()
841 : NodeVisitor(CULL_VISITOR, TRAVERSE_ACTIVE_CHILDREN)
843 setCullingMode(CullSettings::SMALL_FEATURE_CULLING
844 | CullSettings::VIEW_FRUSTUM_CULLING);
845 setComputeNearFarMode(CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
848 VisibleSceneInfoVistor(const VisibleSceneInfoVistor& rhs)
852 META_NodeVisitor("flightgear","VisibleSceneInfoVistor")
854 typedef std::map<const std::string,int> InfoMap;
856 void getNodeInfo(Node* node)
858 const char* typeName = typeid(*node).name();
859 classInfo[typeName]++;
860 const std::string& nodeName = node->getName();
861 if (!nodeName.empty())
862 nodeInfo[nodeName]++;
868 typedef vector<InfoMap::iterator> FreqVector;
869 cout << "class info:\n";
871 for (InfoMap::iterator itr = classInfo.begin(), end = classInfo.end();
874 classes.push_back(itr);
875 sort(classes.begin(), classes.end(), freqComp);
876 for (FreqVector::iterator itr = classes.begin(), end = classes.end();
879 cout << (*itr)->first << " " << (*itr)->second << "\n";
881 cout << "\nnode info:\n";
883 for (InfoMap::iterator itr = nodeInfo.begin(), end = nodeInfo.end();
886 nodes.push_back(itr);
888 sort (nodes.begin(), nodes.end(), freqComp);
889 for (FreqVector::iterator itr = nodes.begin(), end = nodes.end();
892 cout << (*itr)->first << " " << (*itr)->second << "\n";
897 void doTraversal(Camera* camera, Node* root, Viewport* viewport)
899 ref_ptr<RefMatrix> projection
900 = createOrReuseMatrix(camera->getProjectionMatrix());
901 ref_ptr<RefMatrix> mv = createOrReuseMatrix(camera->getViewMatrix());
903 viewport = camera->getViewport();
905 pushViewport(viewport);
906 pushProjectionMatrix(projection.get());
907 pushModelViewMatrix(mv.get(), Transform::ABSOLUTE_RF);
909 popModelViewMatrix();
910 popProjectionMatrix();
916 void apply(Node& node)
925 void apply(Group& node)
935 void apply(Transform& node)
940 ref_ptr<RefMatrix> matrix = createOrReuseMatrix(*getModelViewMatrix());
941 node.computeLocalToWorldMatrix(*matrix,this);
942 pushModelViewMatrix(matrix.get(), node.getReferenceFrame());
945 popModelViewMatrix();
949 void apply(Camera& camera)
951 // Save current cull settings
952 CullSettings saved_cull_settings(*this);
954 // set cull settings from this Camera
955 setCullSettings(camera);
956 // inherit the settings from above
957 inheritCullSettings(saved_cull_settings, camera.getInheritanceMask());
959 // set the cull mask.
960 unsigned int savedTraversalMask = getTraversalMask();
961 bool mustSetCullMask = (camera.getInheritanceMask()
962 & osg::CullSettings::CULL_MASK) == 0;
964 setTraversalMask(camera.getCullMask());
966 osg::RefMatrix* projection = 0;
967 osg::RefMatrix* modelview = 0;
969 if (camera.getReferenceFrame()==osg::Transform::RELATIVE_RF) {
970 if (camera.getTransformOrder()==osg::Camera::POST_MULTIPLY) {
971 projection = createOrReuseMatrix(*getProjectionMatrix()
972 *camera.getProjectionMatrix());
973 modelview = createOrReuseMatrix(*getModelViewMatrix()
974 * camera.getViewMatrix());
976 else { // pre multiply
977 projection = createOrReuseMatrix(camera.getProjectionMatrix()
978 * (*getProjectionMatrix()));
979 modelview = createOrReuseMatrix(camera.getViewMatrix()
980 * (*getModelViewMatrix()));
983 // an absolute reference frame
984 projection = createOrReuseMatrix(camera.getProjectionMatrix());
985 modelview = createOrReuseMatrix(camera.getViewMatrix());
987 if (camera.getViewport())
988 pushViewport(camera.getViewport());
990 pushProjectionMatrix(projection);
991 pushModelViewMatrix(modelview, camera.getReferenceFrame());
995 // restore the previous model view matrix.
996 popModelViewMatrix();
998 // restore the previous model view matrix.
999 popProjectionMatrix();
1001 if (camera.getViewport()) popViewport();
1003 // restore the previous traversal mask settings
1004 if (mustSetCullMask)
1005 setTraversalMask(savedTraversalMask);
1007 // restore the previous cull settings
1008 setCullSettings(saved_cull_settings);
1013 static bool freqComp(const InfoMap::iterator& lhs, const InfoMap::iterator& rhs)
1015 return lhs->second > rhs->second;
1021 bool printVisibleSceneInfo(FGRenderer* renderer)
1023 osgViewer::Viewer* viewer = renderer->getViewer();
1024 VisibleSceneInfoVistor vsv;
1026 if (!viewer->getCamera()->getViewport() && viewer->getNumSlaves() > 0) {
1027 const View::Slave& slave = viewer->getSlave(0);
1028 vp = slave._camera->getViewport();
1030 vsv.doTraversal(viewer->getCamera(), viewer->getSceneData(), vp);
1034 // end of renderer.cxx