1 // renderer.cxx -- top level sim routines
3 // Written by Curtis Olson, started May 1997.
4 // This file contains parts of main.cxx prior to october 2004
6 // Copyright (C) 1997 - 2002 Curtis L. Olson - http://www.flightgear.org/~curt
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 // General Public License for more details.
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
29 #include <simgear/compiler.h>
35 #include <osg/ref_ptr>
36 #include <osg/AlphaFunc>
37 #include <osg/BlendFunc>
39 #include <osg/CullFace>
44 #include <osg/LightModel>
45 #include <osg/LightSource>
46 #include <osg/NodeCallback>
48 #include <osg/PolygonMode>
49 #include <osg/PolygonOffset>
50 #include <osg/ShadeModel>
51 #include <osg/Version>
54 #include <osgUtil/SceneView>
55 #include <osgUtil/UpdateVisitor>
56 #include <osgUtil/IntersectVisitor>
57 #include <osgUtil/LineSegmentIntersector>
59 #include <osg/io_utils>
60 #include <osgDB/WriteFile>
61 #include <osgDB/ReadFile>
64 #include <simgear/math/SGMath.hxx>
65 #include <simgear/screen/extensions.hxx>
66 #include <simgear/scene/material/matlib.hxx>
67 #include <simgear/scene/model/animation.hxx>
68 #include <simgear/scene/model/model.hxx>
69 #include <simgear/scene/model/modellib.hxx>
70 #include <simgear/scene/model/placement.hxx>
71 #include <simgear/scene/util/SGUpdateVisitor.hxx>
72 #include <simgear/scene/util/RenderConstants.hxx>
73 #include <simgear/scene/tgdb/GroundLightManager.hxx>
74 #include <simgear/scene/tgdb/pt_lights.hxx>
75 #include <simgear/props/props.hxx>
76 #include <simgear/timing/sg_time.hxx>
77 #include <simgear/ephemeris/ephemeris.hxx>
78 #include <simgear/math/sg_random.h>
80 #include <simgear/screen/jpgfactory.hxx>
83 #include <simgear/environment/visual_enviro.hxx>
85 #include <Scenery/tileentry.hxx>
86 #include <Time/light.hxx>
87 #include <Time/light.hxx>
88 #include <Aircraft/aircraft.hxx>
89 #include <Cockpit/panel.hxx>
90 #include <Cockpit/cockpit.hxx>
91 #include <Cockpit/hud.hxx>
92 #include <Model/panelnode.hxx>
93 #include <Model/modelmgr.hxx>
94 #include <Model/acmodel.hxx>
95 #include <Scenery/scenery.hxx>
96 #include <Scenery/redout.hxx>
97 #include <Scenery/tilemgr.hxx>
98 #include <GUI/new_gui.hxx>
99 #include <Instrumentation/instrument_mgr.hxx>
100 #include <Instrumentation/HUD/HUD.hxx>
102 #include <Include/general.hxx>
103 #include "splash.hxx"
104 #include "renderer.hxx"
107 // XXX Make this go away when OSG 2.2 is released.
108 #if (FG_OSG_VERSION >= 21004)
109 #define UPDATE_VISITOR_IN_VIEWER 1
112 class SGPuDrawable : public osg::Drawable {
116 // Dynamic stuff, do not store geometry
117 setUseDisplayList(false);
119 osg::StateSet* stateSet = getOrCreateStateSet();
120 stateSet->setRenderBinDetails(1001, "RenderBin");
121 // speed optimization?
122 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
123 // We can do translucent menus, so why not. :-)
124 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
125 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
126 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
128 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
130 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
131 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
133 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
134 { drawImplementation(*renderInfo.getState()); }
135 void drawImplementation(osg::State& state) const
137 if (!fgOSIsMainContext(state.getGraphicsContext()))
140 state.pushStateSet(getStateSet());
142 state.setActiveTextureUnit(0);
143 state.setClientActiveTextureUnit(0);
144 state.disableAllVertexArrays();
146 glPushAttrib(GL_ALL_ATTRIB_BITS);
147 glPushClientAttrib(~0u);
155 state.dirtyAllModes();
156 state.dirtyAllAttributes();
157 state.dirtyAllVertexArrays();
160 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
161 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
166 class SGHUDAndPanelDrawable : public osg::Drawable {
168 SGHUDAndPanelDrawable()
170 // Dynamic stuff, do not store geometry
171 setUseDisplayList(false);
173 osg::StateSet* stateSet = getOrCreateStateSet();
174 stateSet->setRenderBinDetails(1000, "RenderBin");
176 // speed optimization?
177 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
178 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
179 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
180 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
181 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
183 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
185 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
186 { drawImplementation(*renderInfo.getState()); }
187 void drawImplementation(osg::State& state) const
189 // std::cout << state.getGraphicsContext() << std::endl;
190 if (!fgOSIsMainContext(state.getGraphicsContext()))
193 state.pushStateSet(getStateSet());
195 state.setActiveTextureUnit(0);
196 state.setClientActiveTextureUnit(0);
197 state.disableAllVertexArrays();
199 glPushAttrib(GL_ALL_ATTRIB_BITS);
200 glPushClientAttrib(~0u);
202 fgCockpitUpdate(&state);
204 FGInstrumentMgr *instr = static_cast<FGInstrumentMgr*>(globals->get_subsystem("instrumentation"));
205 HUD *hud = static_cast<HUD*>(instr->get_subsystem("hud"));
208 // update the panel subsystem
209 if ( globals->get_current_panel() != NULL )
210 globals->get_current_panel()->update(state);
211 // We don't need a state here - can be safely removed when we can pick
219 state.dirtyAllModes();
220 state.dirtyAllAttributes();
221 state.dirtyAllVertexArrays();
224 virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
225 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
230 class FGLightSourceUpdateCallback : public osg::NodeCallback {
232 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
234 assert(dynamic_cast<osg::LightSource*>(node));
235 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
236 osg::Light* light = lightSource->getLight();
238 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
239 light->setAmbient(l->scene_ambient().osg());
240 light->setDiffuse(l->scene_diffuse().osg());
241 light->setSpecular(l->scene_specular().osg());
242 SGVec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
243 light->setPosition(position.osg());
244 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
245 light->setDirection(direction.osg());
246 light->setSpotExponent(0);
247 light->setSpotCutoff(180);
248 light->setConstantAttenuation(1);
249 light->setLinearAttenuation(0);
250 light->setQuadraticAttenuation(0);
256 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
258 FGWireFrameModeUpdateCallback() :
259 mWireframe(fgGetNode("/sim/rendering/wireframe"))
261 virtual void operator()(osg::StateAttribute* stateAttribute,
264 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
265 osg::PolygonMode* polygonMode;
266 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
268 if (mWireframe->getBoolValue())
269 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
270 osg::PolygonMode::LINE);
272 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
273 osg::PolygonMode::FILL);
276 SGSharedPtr<SGPropertyNode> mWireframe;
279 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
281 FGLightModelUpdateCallback() :
282 mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
284 virtual void operator()(osg::StateAttribute* stateAttribute,
287 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
288 osg::LightModel* lightModel;
289 lightModel = static_cast<osg::LightModel*>(stateAttribute);
292 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
293 lightModel->setAmbientIntensity(l->scene_ambient().osg());
295 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
297 lightModel->setTwoSided(true);
298 lightModel->setLocalViewer(false);
300 if (mHighlights->getBoolValue()) {
301 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
303 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
307 SGSharedPtr<SGPropertyNode> mHighlights;
310 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
312 FGFogEnableUpdateCallback() :
313 mFogEnabled(fgGetNode("/sim/rendering/fog"))
315 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
317 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
318 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
320 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
324 SGSharedPtr<SGPropertyNode> mFogEnabled;
327 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
329 virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
331 assert(dynamic_cast<SGUpdateVisitor*>(nv));
332 assert(dynamic_cast<osg::Fog*>(sa));
333 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
334 osg::Fog* fog = static_cast<osg::Fog*>(sa);
335 fog->setMode(osg::Fog::EXP2);
336 fog->setColor(updateVisitor->getFogColor().osg());
337 fog->setDensity(updateVisitor->getFogExp2Density());
341 // update callback for the switch node guarding that splash
342 class FGScenerySwitchCallback : public osg::NodeCallback {
344 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
346 assert(dynamic_cast<osg::Switch*>(node));
347 osg::Switch* sw = static_cast<osg::Switch*>(node);
349 double t = globals->get_sim_time_sec();
350 bool enabled = 0 < t;
351 sw->setValue(0, enabled);
361 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
362 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
364 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
366 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
368 static osg::ref_ptr<osg::Camera> mBackGroundCamera = new osg::Camera;
370 FGRenderer::FGRenderer()
372 #ifdef FG_JPEG_SERVER
373 jpgRenderFrame = FGRenderer::update;
375 manipulator = new FGManipulator;
378 FGRenderer::~FGRenderer()
380 #ifdef FG_JPEG_SERVER
381 jpgRenderFrame = NULL;
385 // Initialize various GL/view parameters
386 // XXX This should be called "preinit" or something, as it initializes
387 // critical parts of the scene graph in addition to the splash screen.
389 FGRenderer::splashinit( void ) {
390 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
391 mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
392 mRealRoot->addChild(fgCreateSplashNode());
393 mFrameStamp = viewer->getFrameStamp();
394 // Scene doesn't seem to pass the frame stamp to the update
395 // visitor automatically.
396 mUpdateVisitor->setFrameStamp(mFrameStamp.get());
397 #ifdef UPDATE_VISITOR_IN_VIEWER
398 viewer->setUpdateVisitor(mUpdateVisitor.get());
400 osgViewer::Scene* scene = viewer->getScene();
401 scene->setUpdateVisitor(mUpdateVisitor.get());
406 FGRenderer::init( void ) {
407 // The viewer can call this before the graphics context is current
408 // in the main thread; indeed, in a multithreaded setup it might
409 // never be current in the main thread.
411 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
412 osg::initNotifyLevel();
414 // The number of polygon-offset "units" to place between layers. In
415 // principle, one is supposed to be enough. In practice, I find that
416 // my hardware/driver requires many more.
417 osg::PolygonOffset::setUnitsMultiplier(1);
418 osg::PolygonOffset::setFactorMultiplier(1);
420 // Go full screen if requested ...
421 if ( fgGetBool("/sim/startup/fullscreen") )
424 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
425 (!fgGetBool("/sim/rendering/shading"))) {
426 // if fastest fog requested, or if flat shading force fastest
427 glHint ( GL_FOG_HINT, GL_FASTEST );
428 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
429 glHint ( GL_FOG_HINT, GL_DONT_CARE );
432 glHint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
433 glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
434 glHint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
437 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
439 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
441 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
443 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
444 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
446 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
447 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
448 stateSet->setAttribute(new osg::BlendFunc);
449 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
451 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
453 // this will be set below
454 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
456 osg::Material* material = new osg::Material;
457 stateSet->setAttribute(material);
459 stateSet->setTextureAttribute(0, new osg::TexEnv);
460 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
463 // stateSet->setAttribute(new osg::CullFace(osg::CullFace::BACK));
464 // stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::ON);
466 // this is the topmost scenegraph node for osg
467 mBackGroundCamera->addChild(thesky->getPreRoot());
468 mBackGroundCamera->setClearMask(0);
470 GLbitfield inheritanceMask = osg::CullSettings::ALL_VARIABLES;
471 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
472 inheritanceMask &= ~osg::CullSettings::NEAR_FAR_RATIO;
473 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
474 mBackGroundCamera->setInheritanceMask(inheritanceMask);
475 mBackGroundCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
476 mBackGroundCamera->setCullingMode(osg::CullSettings::NO_CULLING);
477 mBackGroundCamera->setRenderOrder(osg::Camera::NESTED_RENDER);
479 stateSet = mBackGroundCamera->getOrCreateStateSet();
480 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
482 osg::Group* sceneGroup = new osg::Group;
483 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
484 sceneGroup->addChild(thesky->getCloudRoot());
486 stateSet = sceneGroup->getOrCreateStateSet();
487 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
488 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
490 // need to update the light on every frame
491 osg::LightSource* lightSource = new osg::LightSource;
492 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
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 mRoot->addChild(lightSource);
498 lightSource->addChild(mBackGroundCamera.get());
499 lightSource->addChild(sceneGroup);
502 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
503 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
504 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
505 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
506 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
508 // enable disable specular highlights.
509 // is the place where we might plug in an other fragment shader ...
510 osg::LightModel* lightModel = new osg::LightModel;
511 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
512 stateSet->setAttribute(lightModel);
514 // switch to enable wireframe
515 osg::PolygonMode* polygonMode = new osg::PolygonMode;
516 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
517 stateSet->setAttributeAndModes(polygonMode);
519 // scene fog handling
520 osg::Fog* fog = new osg::Fog;
521 fog->setUpdateCallback(new FGFogUpdateCallback);
522 stateSet->setAttributeAndModes(fog);
523 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
526 osg::Camera* guiCamera = new osg::Camera;
527 guiCamera->setRenderOrder(osg::Camera::POST_RENDER, 100);
528 guiCamera->setClearMask(0);
529 inheritanceMask = osg::CullSettings::ALL_VARIABLES;
530 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
531 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
532 guiCamera->setInheritanceMask(inheritanceMask);
533 guiCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
534 guiCamera->setCullingMode(osg::CullSettings::NO_CULLING);
535 osg::Geode* geode = new osg::Geode;
536 geode->addDrawable(new SGPuDrawable);
537 geode->addDrawable(new SGHUDAndPanelDrawable);
538 guiCamera->addChild(geode);
540 osg::Switch* sw = new osg::Switch;
541 sw->setUpdateCallback(new FGScenerySwitchCallback);
542 sw->addChild(mRoot.get());
544 mRealRoot->addChild(sw);
545 mRealRoot->addChild(FGCreateRedoutNode());
546 mRealRoot->addChild(guiCamera);
550 // Update all Visuals (redraws anything graphics related)
552 FGRenderer::update( bool refresh_camera_settings ) {
553 bool scenery_loaded = fgGetBool("sim/sceneryloaded")
554 || fgGetBool("sim/sceneryloaded-override");
555 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
556 if ( idle_state < 1000 || !scenery_loaded ) {
557 fgSetDouble("/sim/startup/splash-alpha", 1.0);
559 // Keep resetting sim time while the sim is initializing
560 // the splash screen is now in the scenegraph
561 globals->set_sim_time_sec( 0.0 );
565 // Fade out the splash screen over the first three seconds.
566 double sAlpha = SGMiscd::max(0, (2.5 - globals->get_sim_time_sec()) / 2.5);
567 fgSetDouble("/sim/startup/splash-alpha", sAlpha);
569 bool skyblend = fgGetBool("/sim/rendering/skyblend");
570 bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
571 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
572 bool distance_attenuation
573 = fgGetBool("/sim/rendering/distance-attenuation");
575 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
576 distance_attenuation );
578 static const SGPropertyNode *groundlevel_nearplane
579 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
581 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
584 double actual_visibility;
585 if (fgGetBool("/environment/clouds/status")) {
586 actual_visibility = thesky->get_visibility();
588 actual_visibility = fgGetDouble("/environment/visibility-m");
591 // idle_state is now 1000 meaning we've finished all our
592 // initializations and are running the main loop, so this will
593 // now work without seg faulting the system.
595 FGViewer *current__view = globals->get_current_view();
596 // Force update of center dependent values ...
597 current__view->set_dirty();
599 if ( refresh_camera_settings ) {
601 resize( fgGetInt("/sim/startup/xsize"),
602 fgGetInt("/sim/startup/ysize") );
604 SGVec3d position = current__view->getViewPosition();
605 SGQuatd attitude = current__view->getViewOrientation();
606 SGVec3d osgPosition = attitude.transform(-position);
608 FGManipulator *manipulator = globals->get_renderer()->getManipulator();
609 manipulator->setPosition(position.osg());
610 manipulator->setAttitude(attitude.osg());
612 osg::Camera *camera = viewer->getCamera();
616 if ( fgGetBool("/sim/rendering/textures") ) {
617 SGVec4f clearColor(l->adj_fog_color());
618 camera->setClearColor(clearColor.osg());
621 SGVec4f clearColor(l->sky_color());
622 camera->setClearColor(clearColor.osg());
625 // update fog params if visibility has changed
626 double visibility_meters = fgGetDouble("/environment/visibility-m");
627 thesky->set_visibility(visibility_meters);
629 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
630 ( global_multi_loop * fgGetInt("/sim/speed-up") )
631 / (double)fgGetInt("/sim/model-hz") );
633 // update the sky dome
636 // The sun and moon distances are scaled down versions
637 // of the actual distance to get both the moon and the sun
638 // within the range of the far clip plane.
639 // Moon distance: 384,467 kilometers
640 // Sun distance: 150,000,000 kilometers
642 double sun_horiz_eff, moon_horiz_eff;
643 if (fgGetBool("/sim/rendering/horizon-effect")) {
644 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
645 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
647 sun_horiz_eff = moon_horiz_eff = 1.0;
650 static SGSkyState sstate;
652 sstate.view_pos = toVec3f(current__view->get_view_pos());
653 sstate.zero_elev = toVec3f(current__view->get_zero_elev());
654 sstate.view_up = current__view->get_world_up();
655 sstate.lon = current__view->getLongitude_deg()
656 * SGD_DEGREES_TO_RADIANS;
657 sstate.lat = current__view->getLatitude_deg()
658 * SGD_DEGREES_TO_RADIANS;
659 sstate.alt = current__view->getAltitudeASL_ft()
661 sstate.spin = l->get_sun_rotation();
662 sstate.gst = globals->get_time_params()->getGst();
663 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
664 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
665 sstate.sun_dist = 50000.0 * sun_horiz_eff;
666 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
667 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
668 sstate.moon_dist = 40000.0 * moon_horiz_eff;
669 sstate.sun_angle = l->get_sun_angle();
673 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
674 << l->sky_color()[0] << " "
675 << l->sky_color()[1] << " "
676 << l->sky_color()[2] << " "
677 << l->sky_color()[3] );
678 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
679 << l->fog_color()[0] << " "
680 << l->fog_color()[1] << " "
681 << l->fog_color()[2] << " "
682 << l->fog_color()[3] );
683 SG_LOG( SG_GENERAL, SG_BULK,
684 " sun_angle = " << l->sun_angle
685 << " moon_angle = " << l->moon_angle );
688 static SGSkyColor scolor;
690 scolor.sky_color = SGVec3f(l->sky_color().data());
691 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
692 scolor.cloud_color = SGVec3f(l->cloud_color().data());
693 scolor.sun_angle = l->get_sun_angle();
694 scolor.moon_angle = l->get_moon_angle();
695 scolor.nplanets = globals->get_ephem()->getNumPlanets();
696 scolor.nstars = globals->get_ephem()->getNumStars();
697 scolor.planet_data = globals->get_ephem()->getPlanets();
698 scolor.star_data = globals->get_ephem()->getStars();
700 thesky->reposition( sstate, delta_time_sec );
701 thesky->repaint( scolor );
704 SG_LOG( SG_GENERAL, SG_BULK,
705 "thesky->reposition( view_pos = " << view_pos[0] << " "
706 << view_pos[1] << " " << view_pos[2] );
707 SG_LOG( SG_GENERAL, SG_BULK,
708 " zero_elev = " << zero_elev[0] << " "
709 << zero_elev[1] << " " << zero_elev[2]
710 << " lon = " << cur_fdm_state->get_Longitude()
711 << " lat = " << cur_fdm_state->get_Latitude() );
712 SG_LOG( SG_GENERAL, SG_BULK,
713 " sun_rot = " << l->get_sun_rotation
714 << " gst = " << SGTime::cur_time_params->getGst() );
715 SG_LOG( SG_GENERAL, SG_BULK,
716 " sun ra = " << globals->get_ephem()->getSunRightAscension()
717 << " sun dec = " << globals->get_ephem()->getSunDeclination()
718 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
719 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
723 // shadows->setupShadows(
724 // current__view->getLongitude_deg(),
725 // current__view->getLatitude_deg(),
726 // globals->get_time_params()->getGst(),
727 // globals->get_ephem()->getSunRightAscension(),
728 // globals->get_ephem()->getSunDeclination(),
729 // l->get_sun_angle());
733 // sgEnviro.setLight(l->adj_fog_color());
735 // texture parameters
736 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
738 double agl = current__view->getAltitudeASL_ft()*SG_FEET_TO_METER
739 - current__view->getSGLocation()->get_cur_elev_m();
741 float scene_nearplane, scene_farplane;
743 scene_nearplane = 10.0f;
744 scene_farplane = 120000.0f;
746 scene_nearplane = groundlevel_nearplane->getDoubleValue();
747 scene_farplane = 120000.0f;
749 setNearFar( scene_nearplane, scene_farplane );
751 // sgEnviro.startOfFrame(current__view->get_view_pos(),
752 // current__view->get_world_up(),
753 // current__view->getLongitude_deg(),
754 // current__view->getLatitude_deg(),
755 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
759 // sgEnviro.drawLightning();
761 // double current_view_origin_airspeed_horiz_kt =
762 // fgGetDouble("/velocities/airspeed-kt", 0.0)
763 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
764 // * SGD_DEGREES_TO_RADIANS);
765 // TODO:find the real view speed, not the AC one
766 // sgEnviro.drawPrecipitation(
767 // fgGetDouble("/environment/metar/rain-norm", 0.0),
768 // fgGetDouble("/environment/metar/snow-norm", 0.0),
769 // fgGetDouble("/environment/metar/hail-norm", 0.0),
770 // current__view->getPitch_deg() + current__view->getPitchOffset_deg(),
771 // current__view->getRoll_deg() + current__view->getRollOffset_deg(),
772 // - current__view->getHeadingOffset_deg(),
773 // current_view_origin_airspeed_horiz_kt
778 // shadows->endOfFrame();
780 // need to call the update visitor once
781 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
782 mUpdateVisitor->setViewData(current__view->getViewPosition(),
783 current__view->getViewOrientation());
784 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
785 mUpdateVisitor->setLight(direction, l->scene_ambient(),
786 l->scene_diffuse(), l->scene_specular(),
788 l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
789 mUpdateVisitor->setVisibility(actual_visibility);
790 simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
791 bool hotspots = fgGetBool("/sim/panel-hotspots");
792 osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
793 cullMask |= simgear::GroundLightManager::instance()
794 ->getLightNodeMask(mUpdateVisitor.get());
796 cullMask |= simgear::PICK_BIT;
797 camera->setCullMask(cullMask);
798 for (int i = 0; i < viewer->getNumSlaves(); ++i)
799 viewer->getSlave(i)._camera->setCullMask(cullMask);
804 // options.cxx needs to see this for toggle_panel()
805 // Handle new window size or exposure
807 FGRenderer::resize( int width, int height ) {
810 if ( (!fgGetBool("/sim/virtual-cockpit"))
811 && fgPanelVisible() && idle_state == 1000 ) {
812 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
813 globals->get_current_panel()->getYOffset()) / 768.0);
818 static int lastwidth = 0;
819 static int lastheight = 0;
820 if (width != lastwidth)
821 fgSetInt("/sim/startup/xsize", lastwidth = width);
822 if (height != lastheight)
823 fgSetInt("/sim/startup/ysize", lastheight = height);
825 guiInitMouse(width, height);
828 FGViewMgr *viewmgr = globals->get_viewmgr();
830 for ( int i = 0; i < viewmgr->size(); ++i ) {
831 viewmgr->get_view(i)->
832 set_aspect_ratio((float)view_h / (float)width);
835 setFOV( viewmgr->get_current_view()->get_h_fov(),
836 viewmgr->get_current_view()->get_v_fov() );
841 // we need some static storage space for these values. However, we
842 // can't store it in a renderer class object because the functions
843 // that manipulate these are static. They are static so they can
844 // interface to the display callback system. There's probably a
845 // better way, there has to be a better way, but I'm not seeing it
847 static float fov_width = 55.0;
848 static float fov_height = 42.0;
849 static float fov_near = 1.0;
850 static float fov_far = 1000.0;
853 /** FlightGear code should use this routine to set the FOV rather than
854 * calling the ssg routine directly
856 void FGRenderer::setFOV( float w, float h ) {
859 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
860 viewer->getCamera()->setProjectionMatrixAsPerspective(fov_height, 4.0/3.0,
865 /** FlightGear code should use this routine to set the Near/Far clip
866 * planes rather than calling the ssg routine directly
868 void FGRenderer::setNearFar( float n, float f ) {
869 // OSGFIXME: we have currently too much z-buffer fights
873 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
874 viewer->getCamera()->setProjectionMatrixAsPerspective(fov_height, 4.0/3.0,
879 FGRenderer::pick( unsigned x, unsigned y,
880 std::vector<SGSceneryPick>& pickList,
881 const osgGA::GUIEventAdapter* ea )
883 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
884 // wipe out the return ...
888 // just compute intersections in the viewers method ...
889 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
890 Intersections intersections;
891 viewer->computeIntersections(ea->getX(), ea->getY(), intersections);
893 Intersections::iterator hit;
894 for (hit = intersections.begin(); hit != intersections.end(); ++hit) {
895 const osg::NodePath& np = hit->nodePath;
896 osg::NodePath::const_reverse_iterator npi;
897 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
898 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
901 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
902 SGPickCallback* pickCallback = ud->getPickCallback(i);
905 SGSceneryPick sceneryPick;
906 sceneryPick.info.local = SGVec3d(hit->getLocalIntersectPoint());
907 sceneryPick.info.wgs84 = SGVec3d(hit->getWorldIntersectPoint());
908 sceneryPick.callback = pickCallback;
909 pickList.push_back(sceneryPick);
913 return !pickList.empty();
914 } else { // we can get called early ...
920 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
922 mRealRoot->addChild(camera);
926 fgDumpSceneGraphToFile(const char* filename)
928 return osgDB::writeNodeFile(*mRealRoot.get(), filename);
932 fgDumpTerrainBranchToFile(const char* filename)
934 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
940 fgDumpNodeToFile(osg::Node* node, const char* filename)
942 return osgDB::writeNodeFile(*node, filename);
944 // end of renderer.cxx