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>
45 #include <osg/LightModel>
46 #include <osg/LightSource>
47 #include <osg/NodeCallback>
49 #include <osg/PolygonMode>
50 #include <osg/PolygonOffset>
51 #include <osg/ShadeModel>
52 #include <osg/Version>
55 #include <osgUtil/SceneView>
56 #include <osgUtil/UpdateVisitor>
57 #include <osgUtil/IntersectVisitor>
58 #include <osgUtil/LineSegmentIntersector>
60 #include <osg/io_utils>
61 #include <osgDB/WriteFile>
62 #include <osgDB/ReadFile>
65 #include <simgear/math/SGMath.hxx>
66 #include <simgear/screen/extensions.hxx>
67 #include <simgear/scene/material/matlib.hxx>
68 #include <simgear/scene/model/animation.hxx>
69 #include <simgear/scene/model/model.hxx>
70 #include <simgear/scene/model/modellib.hxx>
71 #include <simgear/scene/model/placement.hxx>
72 #include <simgear/scene/util/SGUpdateVisitor.hxx>
73 #include <simgear/scene/util/RenderConstants.hxx>
74 #include <simgear/scene/tgdb/GroundLightManager.hxx>
75 #include <simgear/scene/tgdb/pt_lights.hxx>
76 #include <simgear/props/props.hxx>
77 #include <simgear/timing/sg_time.hxx>
78 #include <simgear/ephemeris/ephemeris.hxx>
79 #include <simgear/math/sg_random.h>
81 #include <simgear/screen/jpgfactory.hxx>
84 #include <simgear/environment/visual_enviro.hxx>
86 #include <Scenery/tileentry.hxx>
87 #include <Time/light.hxx>
88 #include <Time/light.hxx>
89 #include <Aircraft/aircraft.hxx>
90 #include <Cockpit/panel.hxx>
91 #include <Cockpit/cockpit.hxx>
92 #include <Cockpit/hud.hxx>
93 #include <Model/panelnode.hxx>
94 #include <Model/modelmgr.hxx>
95 #include <Model/acmodel.hxx>
96 #include <Scenery/scenery.hxx>
97 #include <Scenery/redout.hxx>
98 #include <Scenery/tilemgr.hxx>
99 #include <GUI/new_gui.hxx>
100 #include <Instrumentation/instrument_mgr.hxx>
101 #include <Instrumentation/HUD/HUD.hxx>
103 #include <Include/general.hxx>
104 #include "splash.hxx"
105 #include "renderer.hxx"
107 #include "ViewPartitionNode.hxx"
109 // XXX Make this go away when OSG 2.2 is released.
110 #if (FG_OSG_VERSION >= 21004)
111 #define UPDATE_VISITOR_IN_VIEWER 1
114 class FGHintUpdateCallback : public osg::StateAttribute::Callback {
116 FGHintUpdateCallback(const char* configNode) :
117 mConfigNode(fgGetNode(configNode, true))
119 virtual void operator()(osg::StateAttribute* stateAttribute,
122 assert(dynamic_cast<osg::Hint*>(stateAttribute));
123 osg::Hint* hint = static_cast<osg::Hint*>(stateAttribute);
125 const char* value = mConfigNode->getStringValue();
127 hint->setMode(GL_DONT_CARE);
128 else if (0 == strcmp(value, "nicest"))
129 hint->setMode(GL_NICEST);
130 else if (0 == strcmp(value, "fastest"))
131 hint->setMode(GL_FASTEST);
133 hint->setMode(GL_DONT_CARE);
136 SGSharedPtr<SGPropertyNode> mConfigNode;
140 class SGPuDrawable : public osg::Drawable {
144 // Dynamic stuff, do not store geometry
145 setUseDisplayList(false);
147 osg::StateSet* stateSet = getOrCreateStateSet();
148 stateSet->setRenderBinDetails(1001, "RenderBin");
149 // speed optimization?
150 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
151 // We can do translucent menus, so why not. :-)
152 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
153 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
154 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
156 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
158 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
159 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
161 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
162 { drawImplementation(*renderInfo.getState()); }
163 void drawImplementation(osg::State& state) const
165 if (!fgOSIsMainContext(state.getGraphicsContext()))
168 state.pushStateSet(getStateSet());
170 state.setActiveTextureUnit(0);
171 state.setClientActiveTextureUnit(0);
172 state.disableAllVertexArrays();
174 glPushAttrib(GL_ALL_ATTRIB_BITS);
175 glPushClientAttrib(~0u);
183 state.dirtyAllModes();
184 state.dirtyAllAttributes();
185 state.dirtyAllVertexArrays();
188 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
189 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
194 class SGHUDAndPanelDrawable : public osg::Drawable {
196 SGHUDAndPanelDrawable()
198 // Dynamic stuff, do not store geometry
199 setUseDisplayList(false);
201 osg::StateSet* stateSet = getOrCreateStateSet();
202 stateSet->setRenderBinDetails(1000, "RenderBin");
204 // speed optimization?
205 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
206 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
207 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
208 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
209 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
211 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
213 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
214 { drawImplementation(*renderInfo.getState()); }
215 void drawImplementation(osg::State& state) const
217 // std::cout << state.getGraphicsContext() << std::endl;
218 if (!fgOSIsMainContext(state.getGraphicsContext()))
221 state.pushStateSet(getStateSet());
223 state.setActiveTextureUnit(0);
224 state.setClientActiveTextureUnit(0);
225 state.disableAllVertexArrays();
227 glPushAttrib(GL_ALL_ATTRIB_BITS);
228 glPushClientAttrib(~0u);
230 fgCockpitUpdate(&state);
232 FGInstrumentMgr *instr = static_cast<FGInstrumentMgr*>(globals->get_subsystem("instrumentation"));
233 HUD *hud = static_cast<HUD*>(instr->get_subsystem("hud"));
236 // update the panel subsystem
237 if ( globals->get_current_panel() != NULL )
238 globals->get_current_panel()->update(state);
239 // We don't need a state here - can be safely removed when we can pick
247 state.dirtyAllModes();
248 state.dirtyAllAttributes();
249 state.dirtyAllVertexArrays();
252 virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
253 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
258 class FGLightSourceUpdateCallback : public osg::NodeCallback {
260 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
262 assert(dynamic_cast<osg::LightSource*>(node));
263 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
264 osg::Light* light = lightSource->getLight();
266 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
267 light->setAmbient(l->scene_ambient().osg());
268 light->setDiffuse(l->scene_diffuse().osg());
269 light->setSpecular(l->scene_specular().osg());
270 SGVec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
271 light->setPosition(position.osg());
272 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
273 light->setDirection(direction.osg());
274 light->setSpotExponent(0);
275 light->setSpotCutoff(180);
276 light->setConstantAttenuation(1);
277 light->setLinearAttenuation(0);
278 light->setQuadraticAttenuation(0);
284 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
286 FGWireFrameModeUpdateCallback() :
287 mWireframe(fgGetNode("/sim/rendering/wireframe"))
289 virtual void operator()(osg::StateAttribute* stateAttribute,
292 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
293 osg::PolygonMode* polygonMode;
294 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
296 if (mWireframe->getBoolValue())
297 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
298 osg::PolygonMode::LINE);
300 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
301 osg::PolygonMode::FILL);
304 SGSharedPtr<SGPropertyNode> mWireframe;
307 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
309 FGLightModelUpdateCallback() :
310 mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
312 virtual void operator()(osg::StateAttribute* stateAttribute,
315 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
316 osg::LightModel* lightModel;
317 lightModel = static_cast<osg::LightModel*>(stateAttribute);
320 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
321 lightModel->setAmbientIntensity(l->scene_ambient().osg());
323 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
325 lightModel->setTwoSided(true);
326 lightModel->setLocalViewer(false);
328 if (mHighlights->getBoolValue()) {
329 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
331 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
335 SGSharedPtr<SGPropertyNode> mHighlights;
338 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
340 FGFogEnableUpdateCallback() :
341 mFogEnabled(fgGetNode("/sim/rendering/fog"))
343 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
345 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
346 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
348 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
352 SGSharedPtr<SGPropertyNode> mFogEnabled;
355 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
357 virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
359 assert(dynamic_cast<SGUpdateVisitor*>(nv));
360 assert(dynamic_cast<osg::Fog*>(sa));
361 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
362 osg::Fog* fog = static_cast<osg::Fog*>(sa);
363 fog->setMode(osg::Fog::EXP2);
364 fog->setColor(updateVisitor->getFogColor().osg());
365 fog->setDensity(updateVisitor->getFogExp2Density());
369 // update callback for the switch node guarding that splash
370 class FGScenerySwitchCallback : public osg::NodeCallback {
372 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
374 assert(dynamic_cast<osg::Switch*>(node));
375 osg::Switch* sw = static_cast<osg::Switch*>(node);
377 double t = globals->get_sim_time_sec();
378 bool enabled = 0 < t;
379 sw->setValue(0, enabled);
389 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
390 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
392 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
394 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
396 static osg::ref_ptr<ViewPartitionNode> viewPartition = new ViewPartitionNode;
398 FGRenderer::FGRenderer()
400 #ifdef FG_JPEG_SERVER
401 jpgRenderFrame = FGRenderer::update;
403 manipulator = new FGManipulator;
406 FGRenderer::~FGRenderer()
408 #ifdef FG_JPEG_SERVER
409 jpgRenderFrame = NULL;
413 // Initialize various GL/view parameters
414 // XXX This should be called "preinit" or something, as it initializes
415 // critical parts of the scene graph in addition to the splash screen.
417 FGRenderer::splashinit( void ) {
418 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
419 mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
420 mRealRoot->addChild(fgCreateSplashNode());
421 mFrameStamp = viewer->getFrameStamp();
422 // Scene doesn't seem to pass the frame stamp to the update
423 // visitor automatically.
424 mUpdateVisitor->setFrameStamp(mFrameStamp.get());
425 #ifdef UPDATE_VISITOR_IN_VIEWER
426 viewer->setUpdateVisitor(mUpdateVisitor.get());
428 osgViewer::Scene* scene = viewer->getScene();
429 scene->setUpdateVisitor(mUpdateVisitor.get());
434 FGRenderer::init( void ) {
435 // The viewer can call this before the graphics context is current
436 // in the main thread; indeed, in a multithreaded setup it might
437 // never be current in the main thread.
439 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
440 osg::initNotifyLevel();
442 // The number of polygon-offset "units" to place between layers. In
443 // principle, one is supposed to be enough. In practice, I find that
444 // my hardware/driver requires many more.
445 osg::PolygonOffset::setUnitsMultiplier(1);
446 osg::PolygonOffset::setFactorMultiplier(1);
448 // Go full screen if requested ...
449 if ( fgGetBool("/sim/startup/fullscreen") )
453 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
455 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
457 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
459 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
460 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
462 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
463 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
464 stateSet->setAttribute(new osg::BlendFunc);
465 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
467 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
469 // this will be set below
470 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
472 osg::Material* material = new osg::Material;
473 stateSet->setAttribute(material);
475 stateSet->setTextureAttribute(0, new osg::TexEnv);
476 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
478 osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
479 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
480 stateSet->setAttribute(hint);
481 hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
482 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
483 stateSet->setAttribute(hint);
484 hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
485 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
486 stateSet->setAttribute(hint);
487 hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
488 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
489 stateSet->setAttribute(hint);
490 hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
491 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
492 stateSet->setAttribute(hint);
494 osg::Group* sceneGroup = new osg::Group;
495 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
496 sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
498 //sceneGroup->addChild(thesky->getCloudRoot());
500 stateSet = sceneGroup->getOrCreateStateSet();
501 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
502 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
504 // need to update the light on every frame
505 osg::LightSource* lightSource = new osg::LightSource;
506 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
507 // relative because of CameraView being just a clever transform node
508 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
509 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
511 lightSource->addChild(sceneGroup);
512 lightSource->addChild(thesky->getPreRoot());
513 mRoot->addChild(lightSource);
515 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
516 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
517 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
518 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
519 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
521 // enable disable specular highlights.
522 // is the place where we might plug in an other fragment shader ...
523 osg::LightModel* lightModel = new osg::LightModel;
524 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
525 stateSet->setAttribute(lightModel);
527 // switch to enable wireframe
528 osg::PolygonMode* polygonMode = new osg::PolygonMode;
529 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
530 stateSet->setAttributeAndModes(polygonMode);
532 // scene fog handling
533 osg::Fog* fog = new osg::Fog;
534 fog->setUpdateCallback(new FGFogUpdateCallback);
535 stateSet->setAttributeAndModes(fog);
536 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
539 osg::Camera* guiCamera = new osg::Camera;
540 guiCamera->setRenderOrder(osg::Camera::POST_RENDER, 100);
541 guiCamera->setClearMask(0);
542 GLbitfield inheritanceMask = osg::CullSettings::ALL_VARIABLES;
543 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
544 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
545 guiCamera->setInheritanceMask(inheritanceMask);
546 guiCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
547 guiCamera->setCullingMode(osg::CullSettings::NO_CULLING);
548 osg::Geode* geode = new osg::Geode;
549 geode->addDrawable(new SGPuDrawable);
550 geode->addDrawable(new SGHUDAndPanelDrawable);
551 guiCamera->addChild(geode);
553 osg::Switch* sw = new osg::Switch;
554 sw->setUpdateCallback(new FGScenerySwitchCallback);
555 sw->addChild(mRoot.get());
556 viewPartition->addChild(sw);
557 viewPartition->addChild(thesky->getCloudRoot());
559 mRealRoot->addChild(viewPartition.get());
560 mRealRoot->addChild(FGCreateRedoutNode());
561 mRealRoot->addChild(guiCamera);
565 // Update all Visuals (redraws anything graphics related)
567 FGRenderer::update( bool refresh_camera_settings ) {
568 bool scenery_loaded = fgGetBool("sim/sceneryloaded")
569 || fgGetBool("sim/sceneryloaded-override");
570 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
571 if ( idle_state < 1000 || !scenery_loaded ) {
572 fgSetDouble("/sim/startup/splash-alpha", 1.0);
574 // Keep resetting sim time while the sim is initializing
575 // the splash screen is now in the scenegraph
576 globals->set_sim_time_sec( 0.0 );
580 // Fade out the splash screen over the first three seconds.
581 double sAlpha = SGMiscd::max(0, (2.5 - globals->get_sim_time_sec()) / 2.5);
582 fgSetDouble("/sim/startup/splash-alpha", sAlpha);
584 bool skyblend = fgGetBool("/sim/rendering/skyblend");
585 bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
586 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
587 bool distance_attenuation
588 = fgGetBool("/sim/rendering/distance-attenuation");
590 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
591 distance_attenuation );
593 static const SGPropertyNode *groundlevel_nearplane
594 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
596 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
599 double actual_visibility;
600 if (fgGetBool("/environment/clouds/status")) {
601 actual_visibility = thesky->get_visibility();
603 actual_visibility = fgGetDouble("/environment/visibility-m");
606 // idle_state is now 1000 meaning we've finished all our
607 // initializations and are running the main loop, so this will
608 // now work without seg faulting the system.
610 FGViewer *current__view = globals->get_current_view();
611 // Force update of center dependent values ...
612 current__view->set_dirty();
614 if ( refresh_camera_settings ) {
616 resize( fgGetInt("/sim/startup/xsize"),
617 fgGetInt("/sim/startup/ysize") );
619 SGVec3d position = current__view->getViewPosition();
620 SGQuatd attitude = current__view->getViewOrientation();
621 SGVec3d osgPosition = attitude.transform(-position);
623 FGManipulator *manipulator = globals->get_renderer()->getManipulator();
624 manipulator->setPosition(position.osg());
625 manipulator->setAttitude(attitude.osg());
627 osg::Camera *camera = viewer->getCamera();
631 if ( fgGetBool("/sim/rendering/textures") ) {
632 SGVec4f clearColor(l->adj_fog_color());
633 camera->setClearColor(clearColor.osg());
636 SGVec4f clearColor(l->sky_color());
637 camera->setClearColor(clearColor.osg());
640 // update fog params if visibility has changed
641 double visibility_meters = fgGetDouble("/environment/visibility-m");
642 thesky->set_visibility(visibility_meters);
644 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
645 ( global_multi_loop * fgGetInt("/sim/speed-up") )
646 / (double)fgGetInt("/sim/model-hz") );
648 // update the sky dome
651 // The sun and moon distances are scaled down versions
652 // of the actual distance to get both the moon and the sun
653 // within the range of the far clip plane.
654 // Moon distance: 384,467 kilometers
655 // Sun distance: 150,000,000 kilometers
657 double sun_horiz_eff, moon_horiz_eff;
658 if (fgGetBool("/sim/rendering/horizon-effect")) {
659 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
660 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
662 sun_horiz_eff = moon_horiz_eff = 1.0;
665 static SGSkyState sstate;
667 sstate.view_pos = toVec3f(current__view->get_view_pos());
668 sstate.zero_elev = toVec3f(current__view->get_zero_elev());
669 sstate.view_up = current__view->get_world_up();
670 sstate.lon = current__view->getLongitude_deg()
671 * SGD_DEGREES_TO_RADIANS;
672 sstate.lat = current__view->getLatitude_deg()
673 * SGD_DEGREES_TO_RADIANS;
674 sstate.alt = current__view->getAltitudeASL_ft()
676 sstate.spin = l->get_sun_rotation();
677 sstate.gst = globals->get_time_params()->getGst();
678 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
679 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
680 sstate.sun_dist = 50000.0 * sun_horiz_eff;
681 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
682 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
683 sstate.moon_dist = 40000.0 * moon_horiz_eff;
684 sstate.sun_angle = l->get_sun_angle();
688 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
689 << l->sky_color()[0] << " "
690 << l->sky_color()[1] << " "
691 << l->sky_color()[2] << " "
692 << l->sky_color()[3] );
693 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
694 << l->fog_color()[0] << " "
695 << l->fog_color()[1] << " "
696 << l->fog_color()[2] << " "
697 << l->fog_color()[3] );
698 SG_LOG( SG_GENERAL, SG_BULK,
699 " sun_angle = " << l->sun_angle
700 << " moon_angle = " << l->moon_angle );
703 static SGSkyColor scolor;
705 scolor.sky_color = SGVec3f(l->sky_color().data());
706 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
707 scolor.cloud_color = SGVec3f(l->cloud_color().data());
708 scolor.sun_angle = l->get_sun_angle();
709 scolor.moon_angle = l->get_moon_angle();
710 scolor.nplanets = globals->get_ephem()->getNumPlanets();
711 scolor.nstars = globals->get_ephem()->getNumStars();
712 scolor.planet_data = globals->get_ephem()->getPlanets();
713 scolor.star_data = globals->get_ephem()->getStars();
715 thesky->reposition( sstate, delta_time_sec );
716 thesky->repaint( scolor );
719 SG_LOG( SG_GENERAL, SG_BULK,
720 "thesky->reposition( view_pos = " << view_pos[0] << " "
721 << view_pos[1] << " " << view_pos[2] );
722 SG_LOG( SG_GENERAL, SG_BULK,
723 " zero_elev = " << zero_elev[0] << " "
724 << zero_elev[1] << " " << zero_elev[2]
725 << " lon = " << cur_fdm_state->get_Longitude()
726 << " lat = " << cur_fdm_state->get_Latitude() );
727 SG_LOG( SG_GENERAL, SG_BULK,
728 " sun_rot = " << l->get_sun_rotation
729 << " gst = " << SGTime::cur_time_params->getGst() );
730 SG_LOG( SG_GENERAL, SG_BULK,
731 " sun ra = " << globals->get_ephem()->getSunRightAscension()
732 << " sun dec = " << globals->get_ephem()->getSunDeclination()
733 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
734 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
738 // shadows->setupShadows(
739 // current__view->getLongitude_deg(),
740 // current__view->getLatitude_deg(),
741 // globals->get_time_params()->getGst(),
742 // globals->get_ephem()->getSunRightAscension(),
743 // globals->get_ephem()->getSunDeclination(),
744 // l->get_sun_angle());
748 // sgEnviro.setLight(l->adj_fog_color());
750 double agl = current__view->getAltitudeASL_ft()*SG_FEET_TO_METER
751 - current__view->getSGLocation()->get_cur_elev_m();
753 float scene_nearplane, scene_farplane;
754 // XXX Given that the own airplane model is part of the scene
755 // graph, should this business be ripped out? The near plane is
756 // ignored by setCameraParameters.
758 scene_nearplane = 10.0f;
759 scene_farplane = 120000.0f;
761 scene_nearplane = groundlevel_nearplane->getDoubleValue();
762 scene_farplane = 120000.0f;
764 setCameraParameters(current__view->get_v_fov(),
765 current__view->get_aspect_ratio(),
766 scene_nearplane, scene_farplane);
768 // sgEnviro.startOfFrame(current__view->get_view_pos(),
769 // current__view->get_world_up(),
770 // current__view->getLongitude_deg(),
771 // current__view->getLatitude_deg(),
772 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
776 // sgEnviro.drawLightning();
778 // double current_view_origin_airspeed_horiz_kt =
779 // fgGetDouble("/velocities/airspeed-kt", 0.0)
780 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
781 // * SGD_DEGREES_TO_RADIANS);
782 // TODO:find the real view speed, not the AC one
783 // sgEnviro.drawPrecipitation(
784 // fgGetDouble("/environment/metar/rain-norm", 0.0),
785 // fgGetDouble("/environment/metar/snow-norm", 0.0),
786 // fgGetDouble("/environment/metar/hail-norm", 0.0),
787 // current__view->getPitch_deg() + current__view->getPitchOffset_deg(),
788 // current__view->getRoll_deg() + current__view->getRollOffset_deg(),
789 // - current__view->getHeadingOffset_deg(),
790 // current_view_origin_airspeed_horiz_kt
795 // shadows->endOfFrame();
797 // need to call the update visitor once
798 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
799 mUpdateVisitor->setViewData(current__view->getViewPosition(),
800 current__view->getViewOrientation());
801 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
802 mUpdateVisitor->setLight(direction, l->scene_ambient(),
803 l->scene_diffuse(), l->scene_specular(),
805 l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
806 mUpdateVisitor->setVisibility(actual_visibility);
807 viewPartition->setVisibility(actual_visibility);
808 simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
809 bool hotspots = fgGetBool("/sim/panel-hotspots");
810 osg::Node::NodeMask cullMask = (~simgear::LIGHTS_BITS & ~simgear::PICK_BIT
811 & ~simgear::BACKGROUND_BIT);
812 cullMask |= simgear::GroundLightManager::instance()
813 ->getLightNodeMask(mUpdateVisitor.get());
815 cullMask |= simgear::PICK_BIT;
816 camera->setCullMask(cullMask);
818 for (int i = 0; i < viewer->getNumSlaves(); ++i)
819 viewer->getSlave(i)._camera->setCullMask(cullMask);
824 // options.cxx needs to see this for toggle_panel()
825 // Handle new window size or exposure
827 FGRenderer::resize( int width, int height ) {
830 if ( (!fgGetBool("/sim/virtual-cockpit"))
831 && fgPanelVisible() && idle_state == 1000 ) {
832 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
833 globals->get_current_panel()->getYOffset()) / 768.0);
838 static int lastwidth = 0;
839 static int lastheight = 0;
840 if (width != lastwidth)
841 fgSetInt("/sim/startup/xsize", lastwidth = width);
842 if (height != lastheight)
843 fgSetInt("/sim/startup/ysize", lastheight = height);
845 guiInitMouse(width, height);
848 FGViewMgr *viewmgr = globals->get_viewmgr();
850 for ( int i = 0; i < viewmgr->size(); ++i ) {
851 viewmgr->get_view(i)->
852 set_aspect_ratio((float)view_h / (float)width);
857 void FGRenderer::setCameraParameters(float vfov, float aspectRatio,
858 float near, float far)
861 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
862 viewer->getCamera()->setProjectionMatrixAsPerspective(vfov,
868 FGRenderer::pick( unsigned x, unsigned y,
869 std::vector<SGSceneryPick>& pickList,
870 const osgGA::GUIEventAdapter* ea )
872 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
873 // wipe out the return ...
877 // just compute intersections in the viewers method ...
878 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
879 Intersections intersections;
880 viewer->computeIntersections(ea->getX(), ea->getY(), intersections);
882 Intersections::iterator hit;
883 for (hit = intersections.begin(); hit != intersections.end(); ++hit) {
884 const osg::NodePath& np = hit->nodePath;
885 osg::NodePath::const_reverse_iterator npi;
886 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
887 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
890 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
891 SGPickCallback* pickCallback = ud->getPickCallback(i);
894 SGSceneryPick sceneryPick;
895 sceneryPick.info.local = SGVec3d(hit->getLocalIntersectPoint());
896 sceneryPick.info.wgs84 = SGVec3d(hit->getWorldIntersectPoint());
897 sceneryPick.callback = pickCallback;
898 pickList.push_back(sceneryPick);
902 return !pickList.empty();
903 } else { // we can get called early ...
909 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
911 mRealRoot->addChild(camera);
915 fgDumpSceneGraphToFile(const char* filename)
917 return osgDB::writeNodeFile(*mRealRoot.get(), filename);
921 fgDumpTerrainBranchToFile(const char* filename)
923 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
929 fgDumpNodeToFile(osg::Node* node, const char* filename)
931 return osgDB::writeNodeFile(*node, filename);
933 // end of renderer.cxx