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 SGSharedPtr<SGPropertyNode> 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"))
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 SGSharedPtr<SGPropertyNode> mWireframe;
295 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
297 FGLightModelUpdateCallback() :
298 mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
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 SGSharedPtr<SGPropertyNode> mHighlights;
326 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
328 FGFogEnableUpdateCallback() :
329 mFogEnabled(fgGetNode("/sim/rendering/fog"))
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 SGSharedPtr<SGPropertyNode> 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 double t = globals->get_sim_time_sec();
366 bool enabled = 0 < t;
367 sw->setValue(0, enabled);
377 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
378 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
380 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
382 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
384 FGRenderer::FGRenderer()
386 #ifdef FG_JPEG_SERVER
387 jpgRenderFrame = FGRenderer::update;
389 eventHandler = new FGEventHandler;
392 FGRenderer::~FGRenderer()
394 #ifdef FG_JPEG_SERVER
395 jpgRenderFrame = NULL;
399 // Initialize various GL/view parameters
400 // XXX This should be called "preinit" or something, as it initializes
401 // critical parts of the scene graph in addition to the splash screen.
403 FGRenderer::splashinit( void ) {
404 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
405 mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
406 mRealRoot->addChild(fgCreateSplashNode());
407 mFrameStamp = viewer->getFrameStamp();
408 // Scene doesn't seem to pass the frame stamp to the update
409 // visitor automatically.
410 mUpdateVisitor->setFrameStamp(mFrameStamp.get());
411 viewer->setUpdateVisitor(mUpdateVisitor.get());
415 FGRenderer::init( void )
417 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
418 osg::initNotifyLevel();
420 // The number of polygon-offset "units" to place between layers. In
421 // principle, one is supposed to be enough. In practice, I find that
422 // my hardware/driver requires many more.
423 osg::PolygonOffset::setUnitsMultiplier(1);
424 osg::PolygonOffset::setFactorMultiplier(1);
426 // Go full screen if requested ...
427 if ( fgGetBool("/sim/startup/fullscreen") )
431 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
433 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
435 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
437 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
438 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
440 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
441 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
442 stateSet->setAttribute(new osg::BlendFunc);
443 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
445 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
447 // this will be set below
448 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
450 osg::Material* material = new osg::Material;
451 stateSet->setAttribute(material);
453 stateSet->setTextureAttribute(0, new osg::TexEnv);
454 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
456 osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
457 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
458 stateSet->setAttribute(hint);
459 hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
460 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
461 stateSet->setAttribute(hint);
462 hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
463 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
464 stateSet->setAttribute(hint);
465 hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
466 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
467 stateSet->setAttribute(hint);
468 hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
469 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
470 stateSet->setAttribute(hint);
472 osg::Group* sceneGroup = new osg::Group;
473 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
474 sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
476 //sceneGroup->addChild(thesky->getCloudRoot());
478 stateSet = sceneGroup->getOrCreateStateSet();
479 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
481 // need to update the light on every frame
482 // OSG LightSource objects are rather confusing. OSG only supports
483 // the 10 lights specified by OpenGL itself; if more than one
484 // LightSource in the scene graph have the same light number, it's
485 // indeterminate which values will be used to render geometry that
486 // has that light number enabled. Also, adding children to a
487 // LightSource is just a shortcut for setting up a state set that
488 // has the corresponding OpenGL light enabled: a LightSource will
489 // affect geometry anywhere in the scene graph that has its light
490 // number enabled in a state set.
491 LightSource* lightSource = new LightSource;
492 lightSource->getLight()->setDataVariance(Object::DYNAMIC);
493 // relative because of CameraView being just a clever transform node
494 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
495 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
496 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
497 mRealRoot->addChild(lightSource);
498 // we need a white diffuse light for the phase of the moon
499 osg::LightSource* sunLight = new osg::LightSource;
500 sunLight->getLight()->setDataVariance(Object::DYNAMIC);
501 sunLight->getLight()->setLightNum(1);
502 sunLight->setUpdateCallback(new FGLightSourceUpdateCallback(true));
503 sunLight->setReferenceFrame(osg::LightSource::RELATIVE_RF);
504 sunLight->setLocalStateSetModes(osg::StateAttribute::ON);
505 // Hang a StateSet above the sky subgraph in order to turn off
507 Group* skyGroup = new Group;
508 StateSet* skySS = skyGroup->getOrCreateStateSet();
509 skySS->setMode(GL_LIGHT0, StateAttribute::OFF);
510 skyGroup->addChild(thesky->getPreRoot());
511 sunLight->addChild(skyGroup);
512 mRoot->addChild(sceneGroup);
513 mRoot->addChild(sunLight);
514 // Clouds are added to the scene graph later
515 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
516 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
517 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
518 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
520 // enable disable specular highlights.
521 // is the place where we might plug in an other fragment shader ...
522 osg::LightModel* lightModel = new osg::LightModel;
523 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
524 stateSet->setAttribute(lightModel);
526 // switch to enable wireframe
527 osg::PolygonMode* polygonMode = new osg::PolygonMode;
528 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
529 stateSet->setAttributeAndModes(polygonMode);
531 // scene fog handling
532 osg::Fog* fog = new osg::Fog;
533 fog->setUpdateCallback(new FGFogUpdateCallback);
534 stateSet->setAttributeAndModes(fog);
535 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
538 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
540 osg::Geode* geode = new osg::Geode;
541 geode->addDrawable(new SGPuDrawable);
542 geode->addDrawable(new SGHUDAndPanelDrawable);
543 guiCamera->addChild(geode);
545 osg::Switch* sw = new osg::Switch;
546 sw->setUpdateCallback(new FGScenerySwitchCallback);
547 sw->addChild(mRoot.get());
548 mRealRoot->addChild(sw);
549 // The clouds are attached directly to the scene graph root
550 // because, in theory, they don't want the same default state set
551 // as the rest of the scene. This may not be true in practice.
552 mRealRoot->addChild(thesky->getCloudRoot());
553 mRealRoot->addChild(FGCreateRedoutNode());
554 // Attach empty program to the scene root so that shader programs
555 // don't leak into state sets (effects) that shouldn't have one.
556 stateSet = mRealRoot->getOrCreateStateSet();
557 stateSet->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON);
561 // Update all Visuals (redraws anything graphics related)
563 FGRenderer::update( bool refresh_camera_settings ) {
564 bool scenery_loaded = fgGetBool("sim/sceneryloaded", false)
565 || fgGetBool("sim/sceneryloaded-override");
566 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
567 if (!scenery_loaded) {
568 fgSetDouble("/sim/startup/splash-alpha", 1.0);
572 // Fade out the splash screen over the first three seconds.
573 double sAlpha = SGMiscd::max(0, (2.5 - globals->get_sim_time_sec()) / 2.5);
574 fgSetDouble("/sim/startup/splash-alpha", sAlpha);
576 bool skyblend = fgGetBool("/sim/rendering/skyblend");
577 bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
578 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
579 bool distance_attenuation
580 = fgGetBool("/sim/rendering/distance-attenuation");
582 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
583 distance_attenuation );
585 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
588 double actual_visibility;
589 if (fgGetBool("/environment/clouds/status")) {
590 actual_visibility = thesky->get_visibility();
592 actual_visibility = fgGetDouble("/environment/visibility-m");
595 // idle_state is now 1000 meaning we've finished all our
596 // initializations and are running the main loop, so this will
597 // now work without seg faulting the system.
599 FGViewer *current__view = globals->get_current_view();
600 // Force update of center dependent values ...
601 current__view->set_dirty();
603 if ( refresh_camera_settings ) {
605 resize( fgGetInt("/sim/startup/xsize"),
606 fgGetInt("/sim/startup/ysize") );
608 osg::Camera *camera = viewer->getCamera();
612 if ( fgGetBool("/sim/rendering/textures") ) {
613 SGVec4f clearColor(l->adj_fog_color());
614 camera->setClearColor(toOsg(clearColor));
617 SGVec4f clearColor(l->sky_color());
618 camera->setClearColor(toOsg(clearColor));
621 // update fog params if visibility has changed
622 double visibility_meters = fgGetDouble("/environment/visibility-m");
623 thesky->set_visibility(visibility_meters);
625 double altitude_m = fgGetDouble("/position/altitude-ft") * SG_FEET_TO_METER;
626 thesky->modify_vis( altitude_m, 0.0 /* time factor, now unused */);
628 // update the sky dome
631 // The sun and moon distances are scaled down versions
632 // of the actual distance to get both the moon and the sun
633 // within the range of the far clip plane.
634 // Moon distance: 384,467 kilometers
635 // Sun distance: 150,000,000 kilometers
637 double sun_horiz_eff, moon_horiz_eff;
638 if (fgGetBool("/sim/rendering/horizon-effect")) {
640 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
644 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
648 sun_horiz_eff = moon_horiz_eff = 1.0;
652 sstate.pos = current__view->getViewPosition();
653 sstate.pos_geod = current__view->getPosition();
654 sstate.ori = current__view->getViewOrientation();
655 sstate.spin = l->get_sun_rotation();
656 sstate.gst = globals->get_time_params()->getGst();
657 sstate.sun_dist = 50000.0 * sun_horiz_eff;
658 sstate.moon_dist = 40000.0 * moon_horiz_eff;
659 sstate.sun_angle = l->get_sun_angle();
662 scolor.sky_color = SGVec3f(l->sky_color().data());
663 scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
664 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
665 scolor.cloud_color = SGVec3f(l->cloud_color().data());
666 scolor.sun_angle = l->get_sun_angle();
667 scolor.moon_angle = l->get_moon_angle();
669 double delta_time_sec = fgGetDouble("/sim/time/delta-sec");
670 thesky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
671 thesky->repaint( scolor, *globals->get_ephem() );
674 // shadows->setupShadows(
675 // current__view->getLongitude_deg(),
676 // current__view->getLatitude_deg(),
677 // globals->get_time_params()->getGst(),
678 // globals->get_ephem()->getSunRightAscension(),
679 // globals->get_ephem()->getSunDeclination(),
680 // l->get_sun_angle());
684 // sgEnviro.setLight(l->adj_fog_color());
685 // sgEnviro.startOfFrame(current__view->get_view_pos(),
686 // current__view->get_world_up(),
687 // current__view->getLongitude_deg(),
688 // current__view->getLatitude_deg(),
689 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
693 // sgEnviro.drawLightning();
695 // double current_view_origin_airspeed_horiz_kt =
696 // fgGetDouble("/velocities/airspeed-kt", 0.0)
697 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
698 // * SGD_DEGREES_TO_RADIANS);
702 // shadows->endOfFrame();
704 // need to call the update visitor once
705 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
706 mUpdateVisitor->setViewData(current__view->getViewPosition(),
707 current__view->getViewOrientation());
708 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
709 mUpdateVisitor->setLight(direction, l->scene_ambient(),
710 l->scene_diffuse(), l->scene_specular(),
712 l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
713 mUpdateVisitor->setVisibility(actual_visibility);
714 simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
715 bool hotspots = fgGetBool("/sim/panel-hotspots");
716 osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
717 cullMask |= simgear::GroundLightManager::instance()
718 ->getLightNodeMask(mUpdateVisitor.get());
720 cullMask |= simgear::PICK_BIT;
721 CameraGroup::getDefault()->setCameraCullMasks(cullMask);
726 // options.cxx needs to see this for toggle_panel()
727 // Handle new window size or exposure
729 FGRenderer::resize( int width, int height ) {
732 if ( (!fgGetBool("/sim/virtual-cockpit"))
733 && fgPanelVisible() && idle_state == 1000 ) {
734 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
735 globals->get_current_panel()->getYOffset()) / 768.0);
740 static int lastwidth = 0;
741 static int lastheight = 0;
742 if (width != lastwidth)
743 fgSetInt("/sim/startup/xsize", lastwidth = width);
744 if (height != lastheight)
745 fgSetInt("/sim/startup/ysize", lastheight = height);
748 FGViewMgr *viewmgr = globals->get_viewmgr();
750 for ( int i = 0; i < viewmgr->size(); ++i ) {
751 viewmgr->get_view(i)->
752 set_aspect_ratio((float)view_h / (float)width);
758 FGRenderer::pick(std::vector<SGSceneryPick>& pickList,
759 const osgGA::GUIEventAdapter* ea)
761 // wipe out the return ...
763 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
764 Intersections intersections;
766 if (!computeIntersections(CameraGroup::getDefault(), ea, intersections))
768 for (Intersections::iterator hit = intersections.begin(),
769 e = intersections.end();
772 const osg::NodePath& np = hit->nodePath;
773 osg::NodePath::const_reverse_iterator npi;
774 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
775 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
778 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
779 SGPickCallback* pickCallback = ud->getPickCallback(i);
782 SGSceneryPick sceneryPick;
783 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
784 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
785 sceneryPick.callback = pickCallback;
786 pickList.push_back(sceneryPick);
790 return !pickList.empty();
794 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
800 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
802 eventHandler = eventHandler_;
806 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
808 mRealRoot->addChild(camera);
812 fgDumpSceneGraphToFile(const char* filename)
814 return osgDB::writeNodeFile(*mRealRoot.get(), filename);
818 fgDumpTerrainBranchToFile(const char* filename)
820 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
826 fgDumpNodeToFile(osg::Node* node, const char* filename)
828 return osgDB::writeNodeFile(*node, filename);
835 class VisibleSceneInfoVistor : public NodeVisitor, CullStack
838 VisibleSceneInfoVistor()
839 : NodeVisitor(CULL_VISITOR, TRAVERSE_ACTIVE_CHILDREN)
841 setCullingMode(CullSettings::SMALL_FEATURE_CULLING
842 | CullSettings::VIEW_FRUSTUM_CULLING);
843 setComputeNearFarMode(CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
846 VisibleSceneInfoVistor(const VisibleSceneInfoVistor& rhs)
850 META_NodeVisitor("flightgear","VisibleSceneInfoVistor")
852 typedef std::map<const std::string,int> InfoMap;
854 void getNodeInfo(Node* node)
856 const char* typeName = typeid(*node).name();
857 classInfo[typeName]++;
858 const std::string& nodeName = node->getName();
859 if (!nodeName.empty())
860 nodeInfo[nodeName]++;
866 typedef vector<InfoMap::iterator> FreqVector;
867 cout << "class info:\n";
869 for (InfoMap::iterator itr = classInfo.begin(), end = classInfo.end();
872 classes.push_back(itr);
873 sort(classes.begin(), classes.end(), freqComp);
874 for (FreqVector::iterator itr = classes.begin(), end = classes.end();
877 cout << (*itr)->first << " " << (*itr)->second << "\n";
879 cout << "\nnode info:\n";
881 for (InfoMap::iterator itr = nodeInfo.begin(), end = nodeInfo.end();
884 nodes.push_back(itr);
886 sort (nodes.begin(), nodes.end(), freqComp);
887 for (FreqVector::iterator itr = nodes.begin(), end = nodes.end();
890 cout << (*itr)->first << " " << (*itr)->second << "\n";
895 void doTraversal(Camera* camera, Node* root, Viewport* viewport)
897 ref_ptr<RefMatrix> projection
898 = createOrReuseMatrix(camera->getProjectionMatrix());
899 ref_ptr<RefMatrix> mv = createOrReuseMatrix(camera->getViewMatrix());
901 viewport = camera->getViewport();
903 pushViewport(viewport);
904 pushProjectionMatrix(projection.get());
905 pushModelViewMatrix(mv.get(), Transform::ABSOLUTE_RF);
907 popModelViewMatrix();
908 popProjectionMatrix();
914 void apply(Node& node)
923 void apply(Group& node)
933 void apply(Transform& node)
938 ref_ptr<RefMatrix> matrix = createOrReuseMatrix(*getModelViewMatrix());
939 node.computeLocalToWorldMatrix(*matrix,this);
940 pushModelViewMatrix(matrix.get(), node.getReferenceFrame());
943 popModelViewMatrix();
947 void apply(Camera& camera)
949 // Save current cull settings
950 CullSettings saved_cull_settings(*this);
952 // set cull settings from this Camera
953 setCullSettings(camera);
954 // inherit the settings from above
955 inheritCullSettings(saved_cull_settings, camera.getInheritanceMask());
957 // set the cull mask.
958 unsigned int savedTraversalMask = getTraversalMask();
959 bool mustSetCullMask = (camera.getInheritanceMask()
960 & osg::CullSettings::CULL_MASK) == 0;
962 setTraversalMask(camera.getCullMask());
964 osg::RefMatrix* projection = 0;
965 osg::RefMatrix* modelview = 0;
967 if (camera.getReferenceFrame()==osg::Transform::RELATIVE_RF) {
968 if (camera.getTransformOrder()==osg::Camera::POST_MULTIPLY) {
969 projection = createOrReuseMatrix(*getProjectionMatrix()
970 *camera.getProjectionMatrix());
971 modelview = createOrReuseMatrix(*getModelViewMatrix()
972 * camera.getViewMatrix());
974 else { // pre multiply
975 projection = createOrReuseMatrix(camera.getProjectionMatrix()
976 * (*getProjectionMatrix()));
977 modelview = createOrReuseMatrix(camera.getViewMatrix()
978 * (*getModelViewMatrix()));
981 // an absolute reference frame
982 projection = createOrReuseMatrix(camera.getProjectionMatrix());
983 modelview = createOrReuseMatrix(camera.getViewMatrix());
985 if (camera.getViewport())
986 pushViewport(camera.getViewport());
988 pushProjectionMatrix(projection);
989 pushModelViewMatrix(modelview, camera.getReferenceFrame());
993 // restore the previous model view matrix.
994 popModelViewMatrix();
996 // restore the previous model view matrix.
997 popProjectionMatrix();
999 if (camera.getViewport()) popViewport();
1001 // restore the previous traversal mask settings
1002 if (mustSetCullMask)
1003 setTraversalMask(savedTraversalMask);
1005 // restore the previous cull settings
1006 setCullSettings(saved_cull_settings);
1011 static bool freqComp(const InfoMap::iterator& lhs, const InfoMap::iterator& rhs)
1013 return lhs->second > rhs->second;
1019 bool printVisibleSceneInfo(FGRenderer* renderer)
1021 osgViewer::Viewer* viewer = renderer->getViewer();
1022 VisibleSceneInfoVistor vsv;
1024 if (!viewer->getCamera()->getViewport() && viewer->getNumSlaves() > 0) {
1025 const View::Slave& slave = viewer->getSlave(0);
1026 vp = slave._camera->getViewport();
1028 vsv.doTraversal(viewer->getCamera(), viewer->getSceneData(), vp);
1032 // end of renderer.cxx