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>
102 #include <Environment/precipitation_mgr.hxx>
104 #include <Include/general.hxx>
105 #include "splash.hxx"
106 #include "renderer.hxx"
108 #include "ViewPartitionNode.hxx"
110 // XXX Make this go away when OSG 2.2 is released.
111 #if (FG_OSG_VERSION >= 21004)
112 #define UPDATE_VISITOR_IN_VIEWER 1
115 class FGHintUpdateCallback : public osg::StateAttribute::Callback {
117 FGHintUpdateCallback(const char* configNode) :
118 mConfigNode(fgGetNode(configNode, true))
120 virtual void operator()(osg::StateAttribute* stateAttribute,
123 assert(dynamic_cast<osg::Hint*>(stateAttribute));
124 osg::Hint* hint = static_cast<osg::Hint*>(stateAttribute);
126 const char* value = mConfigNode->getStringValue();
128 hint->setMode(GL_DONT_CARE);
129 else if (0 == strcmp(value, "nicest"))
130 hint->setMode(GL_NICEST);
131 else if (0 == strcmp(value, "fastest"))
132 hint->setMode(GL_FASTEST);
134 hint->setMode(GL_DONT_CARE);
137 SGSharedPtr<SGPropertyNode> mConfigNode;
141 class SGPuDrawable : public osg::Drawable {
145 // Dynamic stuff, do not store geometry
146 setUseDisplayList(false);
148 osg::StateSet* stateSet = getOrCreateStateSet();
149 stateSet->setRenderBinDetails(1001, "RenderBin");
150 // speed optimization?
151 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
152 // We can do translucent menus, so why not. :-)
153 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
154 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
155 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
157 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
159 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
160 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
162 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
163 { drawImplementation(*renderInfo.getState()); }
164 void drawImplementation(osg::State& state) const
166 if (!fgOSIsMainContext(state.getGraphicsContext()))
169 state.pushStateSet(getStateSet());
171 state.setActiveTextureUnit(0);
172 state.setClientActiveTextureUnit(0);
173 state.disableAllVertexArrays();
175 glPushAttrib(GL_ALL_ATTRIB_BITS);
176 glPushClientAttrib(~0u);
184 state.dirtyAllModes();
185 state.dirtyAllAttributes();
186 state.dirtyAllVertexArrays();
189 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
190 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
195 class SGHUDAndPanelDrawable : public osg::Drawable {
197 SGHUDAndPanelDrawable()
199 // Dynamic stuff, do not store geometry
200 setUseDisplayList(false);
202 osg::StateSet* stateSet = getOrCreateStateSet();
203 stateSet->setRenderBinDetails(1000, "RenderBin");
205 // speed optimization?
206 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
207 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
208 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
209 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
210 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
212 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
214 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
215 { drawImplementation(*renderInfo.getState()); }
216 void drawImplementation(osg::State& state) const
218 // std::cout << state.getGraphicsContext() << std::endl;
219 if (!fgOSIsMainContext(state.getGraphicsContext()))
222 state.pushStateSet(getStateSet());
224 state.setActiveTextureUnit(0);
225 state.setClientActiveTextureUnit(0);
226 state.disableAllVertexArrays();
228 glPushAttrib(GL_ALL_ATTRIB_BITS);
229 glPushClientAttrib(~0u);
231 fgCockpitUpdate(&state);
233 FGInstrumentMgr *instr = static_cast<FGInstrumentMgr*>(globals->get_subsystem("instrumentation"));
234 HUD *hud = static_cast<HUD*>(instr->get_subsystem("hud"));
237 // update the panel subsystem
238 if ( globals->get_current_panel() != NULL )
239 globals->get_current_panel()->update(state);
240 // We don't need a state here - can be safely removed when we can pick
248 state.dirtyAllModes();
249 state.dirtyAllAttributes();
250 state.dirtyAllVertexArrays();
253 virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
254 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
259 class FGLightSourceUpdateCallback : public osg::NodeCallback {
261 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
263 assert(dynamic_cast<osg::LightSource*>(node));
264 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
265 osg::Light* light = lightSource->getLight();
267 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
268 light->setAmbient(l->scene_ambient().osg());
269 light->setDiffuse(l->scene_diffuse().osg());
270 light->setSpecular(l->scene_specular().osg());
271 SGVec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
272 light->setPosition(position.osg());
273 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
274 light->setDirection(direction.osg());
275 light->setSpotExponent(0);
276 light->setSpotCutoff(180);
277 light->setConstantAttenuation(1);
278 light->setLinearAttenuation(0);
279 light->setQuadraticAttenuation(0);
285 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
287 FGWireFrameModeUpdateCallback() :
288 mWireframe(fgGetNode("/sim/rendering/wireframe"))
290 virtual void operator()(osg::StateAttribute* stateAttribute,
293 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
294 osg::PolygonMode* polygonMode;
295 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
297 if (mWireframe->getBoolValue())
298 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
299 osg::PolygonMode::LINE);
301 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
302 osg::PolygonMode::FILL);
305 SGSharedPtr<SGPropertyNode> mWireframe;
308 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
310 FGLightModelUpdateCallback() :
311 mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
313 virtual void operator()(osg::StateAttribute* stateAttribute,
316 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
317 osg::LightModel* lightModel;
318 lightModel = static_cast<osg::LightModel*>(stateAttribute);
321 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
322 lightModel->setAmbientIntensity(l->scene_ambient().osg());
324 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
326 lightModel->setTwoSided(true);
327 lightModel->setLocalViewer(false);
329 if (mHighlights->getBoolValue()) {
330 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
332 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
336 SGSharedPtr<SGPropertyNode> mHighlights;
339 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
341 FGFogEnableUpdateCallback() :
342 mFogEnabled(fgGetNode("/sim/rendering/fog"))
344 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
346 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
347 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
349 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
353 SGSharedPtr<SGPropertyNode> mFogEnabled;
356 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
358 virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
360 assert(dynamic_cast<SGUpdateVisitor*>(nv));
361 assert(dynamic_cast<osg::Fog*>(sa));
362 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
363 osg::Fog* fog = static_cast<osg::Fog*>(sa);
364 fog->setMode(osg::Fog::EXP2);
365 fog->setColor(updateVisitor->getFogColor().osg());
366 fog->setDensity(updateVisitor->getFogExp2Density());
370 // update callback for the switch node guarding that splash
371 class FGScenerySwitchCallback : public osg::NodeCallback {
373 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
375 assert(dynamic_cast<osg::Switch*>(node));
376 osg::Switch* sw = static_cast<osg::Switch*>(node);
378 double t = globals->get_sim_time_sec();
379 bool enabled = 0 < t;
380 sw->setValue(0, enabled);
390 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
391 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
393 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
395 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
397 static osg::ref_ptr<ViewPartitionNode> viewPartition = new ViewPartitionNode;
399 FGRenderer::FGRenderer()
401 #ifdef FG_JPEG_SERVER
402 jpgRenderFrame = FGRenderer::update;
404 manipulator = new FGManipulator;
407 FGRenderer::~FGRenderer()
409 #ifdef FG_JPEG_SERVER
410 jpgRenderFrame = NULL;
414 // Initialize various GL/view parameters
415 // XXX This should be called "preinit" or something, as it initializes
416 // critical parts of the scene graph in addition to the splash screen.
418 FGRenderer::splashinit( void ) {
419 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
420 mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
421 mRealRoot->addChild(fgCreateSplashNode());
422 mFrameStamp = viewer->getFrameStamp();
423 // Scene doesn't seem to pass the frame stamp to the update
424 // visitor automatically.
425 mUpdateVisitor->setFrameStamp(mFrameStamp.get());
426 #ifdef UPDATE_VISITOR_IN_VIEWER
427 viewer->setUpdateVisitor(mUpdateVisitor.get());
429 osgViewer::Scene* scene = viewer->getScene();
430 scene->setUpdateVisitor(mUpdateVisitor.get());
435 FGRenderer::init( void ) {
436 // The viewer can call this before the graphics context is current
437 // in the main thread; indeed, in a multithreaded setup it might
438 // never be current in the main thread.
440 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
441 osg::initNotifyLevel();
443 // The number of polygon-offset "units" to place between layers. In
444 // principle, one is supposed to be enough. In practice, I find that
445 // my hardware/driver requires many more.
446 osg::PolygonOffset::setUnitsMultiplier(1);
447 osg::PolygonOffset::setFactorMultiplier(1);
449 // Go full screen if requested ...
450 if ( fgGetBool("/sim/startup/fullscreen") )
454 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
456 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
458 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
460 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
461 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
463 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
464 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
465 stateSet->setAttribute(new osg::BlendFunc);
466 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
468 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
470 // this will be set below
471 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
473 osg::Material* material = new osg::Material;
474 stateSet->setAttribute(material);
476 stateSet->setTextureAttribute(0, new osg::TexEnv);
477 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
479 osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
480 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
481 stateSet->setAttribute(hint);
482 hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
483 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
484 stateSet->setAttribute(hint);
485 hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
486 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
487 stateSet->setAttribute(hint);
488 hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
489 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
490 stateSet->setAttribute(hint);
491 hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
492 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
493 stateSet->setAttribute(hint);
495 osg::Group* sceneGroup = new osg::Group;
496 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
497 sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
499 //sceneGroup->addChild(thesky->getCloudRoot());
501 stateSet = sceneGroup->getOrCreateStateSet();
502 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
503 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
505 // need to update the light on every frame
506 osg::LightSource* lightSource = new osg::LightSource;
507 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
508 // relative because of CameraView being just a clever transform node
509 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
510 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
512 lightSource->addChild(sceneGroup);
513 lightSource->addChild(thesky->getPreRoot());
514 mRoot->addChild(lightSource);
516 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
517 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
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 = new osg::Camera;
541 guiCamera->setRenderOrder(osg::Camera::POST_RENDER, 100);
542 guiCamera->setClearMask(0);
543 GLbitfield inheritanceMask = osg::CullSettings::ALL_VARIABLES;
544 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
545 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
546 guiCamera->setInheritanceMask(inheritanceMask);
547 guiCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
548 guiCamera->setCullingMode(osg::CullSettings::NO_CULLING);
549 osg::Geode* geode = new osg::Geode;
550 geode->addDrawable(new SGPuDrawable);
551 geode->addDrawable(new SGHUDAndPanelDrawable);
552 guiCamera->addChild(geode);
554 osg::Switch* sw = new osg::Switch;
555 sw->setUpdateCallback(new FGScenerySwitchCallback);
556 sw->addChild(mRoot.get());
557 viewPartition->addChild(sw);
558 viewPartition->addChild(thesky->getCloudRoot());
560 mRealRoot->addChild(viewPartition.get());
561 mRealRoot->addChild(FGCreateRedoutNode());
562 mRealRoot->addChild(guiCamera);
566 // Update all Visuals (redraws anything graphics related)
568 FGRenderer::update( bool refresh_camera_settings ) {
569 bool scenery_loaded = fgGetBool("sim/sceneryloaded")
570 || fgGetBool("sim/sceneryloaded-override");
571 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
572 if ( idle_state < 1000 || !scenery_loaded ) {
573 fgSetDouble("/sim/startup/splash-alpha", 1.0);
575 // Keep resetting sim time while the sim is initializing
576 // the splash screen is now in the scenegraph
577 globals->set_sim_time_sec( 0.0 );
581 // Fade out the splash screen over the first three seconds.
582 double sAlpha = SGMiscd::max(0, (2.5 - globals->get_sim_time_sec()) / 2.5);
583 fgSetDouble("/sim/startup/splash-alpha", sAlpha);
585 bool skyblend = fgGetBool("/sim/rendering/skyblend");
586 bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
587 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
588 bool distance_attenuation
589 = fgGetBool("/sim/rendering/distance-attenuation");
591 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
592 distance_attenuation );
594 static const SGPropertyNode *groundlevel_nearplane
595 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
597 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
600 double actual_visibility;
601 if (fgGetBool("/environment/clouds/status")) {
602 actual_visibility = thesky->get_visibility();
604 actual_visibility = fgGetDouble("/environment/visibility-m");
607 // idle_state is now 1000 meaning we've finished all our
608 // initializations and are running the main loop, so this will
609 // now work without seg faulting the system.
611 FGViewer *current__view = globals->get_current_view();
612 // Force update of center dependent values ...
613 current__view->set_dirty();
615 if ( refresh_camera_settings ) {
617 resize( fgGetInt("/sim/startup/xsize"),
618 fgGetInt("/sim/startup/ysize") );
620 SGVec3d position = current__view->getViewPosition();
621 SGQuatd attitude = current__view->getViewOrientation();
622 SGVec3d osgPosition = attitude.transform(-position);
624 FGManipulator *manipulator = globals->get_renderer()->getManipulator();
625 manipulator->setPosition(position.osg());
626 manipulator->setAttitude(attitude.osg());
628 osg::Camera *camera = viewer->getCamera();
632 if ( fgGetBool("/sim/rendering/textures") ) {
633 SGVec4f clearColor(l->adj_fog_color());
634 camera->setClearColor(clearColor.osg());
637 SGVec4f clearColor(l->sky_color());
638 camera->setClearColor(clearColor.osg());
641 // update fog params if visibility has changed
642 double visibility_meters = fgGetDouble("/environment/visibility-m");
643 thesky->set_visibility(visibility_meters);
645 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
646 ( global_multi_loop * fgGetInt("/sim/speed-up") )
647 / (double)fgGetInt("/sim/model-hz") );
649 // update the sky dome
652 // The sun and moon distances are scaled down versions
653 // of the actual distance to get both the moon and the sun
654 // within the range of the far clip plane.
655 // Moon distance: 384,467 kilometers
656 // Sun distance: 150,000,000 kilometers
658 double sun_horiz_eff, moon_horiz_eff;
659 if (fgGetBool("/sim/rendering/horizon-effect")) {
660 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
661 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
663 sun_horiz_eff = moon_horiz_eff = 1.0;
666 static SGSkyState sstate;
668 sstate.view_pos = toVec3f(current__view->get_view_pos());
669 sstate.zero_elev = toVec3f(current__view->get_zero_elev());
670 sstate.view_up = current__view->get_world_up();
671 sstate.lon = current__view->getLongitude_deg()
672 * SGD_DEGREES_TO_RADIANS;
673 sstate.lat = current__view->getLatitude_deg()
674 * SGD_DEGREES_TO_RADIANS;
675 sstate.alt = current__view->getAltitudeASL_ft()
677 sstate.spin = l->get_sun_rotation();
678 sstate.gst = globals->get_time_params()->getGst();
679 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
680 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
681 sstate.sun_dist = 50000.0 * sun_horiz_eff;
682 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
683 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
684 sstate.moon_dist = 40000.0 * moon_horiz_eff;
685 sstate.sun_angle = l->get_sun_angle();
689 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
690 << l->sky_color()[0] << " "
691 << l->sky_color()[1] << " "
692 << l->sky_color()[2] << " "
693 << l->sky_color()[3] );
694 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
695 << l->fog_color()[0] << " "
696 << l->fog_color()[1] << " "
697 << l->fog_color()[2] << " "
698 << l->fog_color()[3] );
699 SG_LOG( SG_GENERAL, SG_BULK,
700 " sun_angle = " << l->sun_angle
701 << " moon_angle = " << l->moon_angle );
704 static SGSkyColor scolor;
706 scolor.sky_color = SGVec3f(l->sky_color().data());
707 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
708 scolor.cloud_color = SGVec3f(l->cloud_color().data());
709 scolor.sun_angle = l->get_sun_angle();
710 scolor.moon_angle = l->get_moon_angle();
711 scolor.nplanets = globals->get_ephem()->getNumPlanets();
712 scolor.nstars = globals->get_ephem()->getNumStars();
713 scolor.planet_data = globals->get_ephem()->getPlanets();
714 scolor.star_data = globals->get_ephem()->getStars();
716 thesky->reposition( sstate, delta_time_sec );
717 thesky->repaint( scolor );
720 SG_LOG( SG_GENERAL, SG_BULK,
721 "thesky->reposition( view_pos = " << view_pos[0] << " "
722 << view_pos[1] << " " << view_pos[2] );
723 SG_LOG( SG_GENERAL, SG_BULK,
724 " zero_elev = " << zero_elev[0] << " "
725 << zero_elev[1] << " " << zero_elev[2]
726 << " lon = " << cur_fdm_state->get_Longitude()
727 << " lat = " << cur_fdm_state->get_Latitude() );
728 SG_LOG( SG_GENERAL, SG_BULK,
729 " sun_rot = " << l->get_sun_rotation
730 << " gst = " << SGTime::cur_time_params->getGst() );
731 SG_LOG( SG_GENERAL, SG_BULK,
732 " sun ra = " << globals->get_ephem()->getSunRightAscension()
733 << " sun dec = " << globals->get_ephem()->getSunDeclination()
734 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
735 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
739 // shadows->setupShadows(
740 // current__view->getLongitude_deg(),
741 // current__view->getLatitude_deg(),
742 // globals->get_time_params()->getGst(),
743 // globals->get_ephem()->getSunRightAscension(),
744 // globals->get_ephem()->getSunDeclination(),
745 // l->get_sun_angle());
749 // sgEnviro.setLight(l->adj_fog_color());
751 double agl = current__view->getAltitudeASL_ft()*SG_FEET_TO_METER
752 - current__view->getSGLocation()->get_cur_elev_m();
754 float scene_nearplane, scene_farplane;
755 // XXX Given that the own airplane model is part of the scene
756 // graph, should this business be ripped out? The near plane is
757 // ignored by setCameraParameters.
759 scene_nearplane = 10.0f;
760 scene_farplane = 120000.0f;
762 scene_nearplane = groundlevel_nearplane->getDoubleValue();
763 scene_farplane = 120000.0f;
765 setCameraParameters(current__view->get_v_fov(),
766 current__view->get_aspect_ratio(),
767 scene_nearplane, scene_farplane);
769 // sgEnviro.startOfFrame(current__view->get_view_pos(),
770 // current__view->get_world_up(),
771 // current__view->getLongitude_deg(),
772 // current__view->getLatitude_deg(),
773 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
777 // sgEnviro.drawLightning();
779 // double current_view_origin_airspeed_horiz_kt =
780 // fgGetDouble("/velocities/airspeed-kt", 0.0)
781 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
782 // * SGD_DEGREES_TO_RADIANS);
786 // shadows->endOfFrame();
788 // need to call the update visitor once
789 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
790 mUpdateVisitor->setViewData(current__view->getViewPosition(),
791 current__view->getViewOrientation());
792 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
793 mUpdateVisitor->setLight(direction, l->scene_ambient(),
794 l->scene_diffuse(), l->scene_specular(),
796 l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
797 mUpdateVisitor->setVisibility(actual_visibility);
798 viewPartition->setVisibility(actual_visibility);
799 simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
800 bool hotspots = fgGetBool("/sim/panel-hotspots");
801 osg::Node::NodeMask cullMask = (~simgear::LIGHTS_BITS & ~simgear::PICK_BIT
802 & ~simgear::BACKGROUND_BIT);
803 cullMask |= simgear::GroundLightManager::instance()
804 ->getLightNodeMask(mUpdateVisitor.get());
806 cullMask |= simgear::PICK_BIT;
807 camera->setCullMask(cullMask);
809 for (int i = 0; i < viewer->getNumSlaves(); ++i)
810 viewer->getSlave(i)._camera->setCullMask(cullMask);
815 // options.cxx needs to see this for toggle_panel()
816 // Handle new window size or exposure
818 FGRenderer::resize( int width, int height ) {
821 if ( (!fgGetBool("/sim/virtual-cockpit"))
822 && fgPanelVisible() && idle_state == 1000 ) {
823 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
824 globals->get_current_panel()->getYOffset()) / 768.0);
829 static int lastwidth = 0;
830 static int lastheight = 0;
831 if (width != lastwidth)
832 fgSetInt("/sim/startup/xsize", lastwidth = width);
833 if (height != lastheight)
834 fgSetInt("/sim/startup/ysize", lastheight = height);
836 guiInitMouse(width, height);
839 FGViewMgr *viewmgr = globals->get_viewmgr();
841 for ( int i = 0; i < viewmgr->size(); ++i ) {
842 viewmgr->get_view(i)->
843 set_aspect_ratio((float)view_h / (float)width);
848 void FGRenderer::setCameraParameters(float vfov, float aspectRatio,
849 float zNear, float zFar)
852 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
853 viewer->getCamera()->setProjectionMatrixAsPerspective(vfov,
859 FGRenderer::pick( unsigned x, unsigned y,
860 std::vector<SGSceneryPick>& pickList,
861 const osgGA::GUIEventAdapter* ea )
863 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
864 // wipe out the return ...
868 // just compute intersections in the viewers method ...
869 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
870 Intersections intersections;
871 viewer->computeIntersections(ea->getX(), ea->getY(), intersections);
873 Intersections::iterator hit;
874 for (hit = intersections.begin(); hit != intersections.end(); ++hit) {
875 const osg::NodePath& np = hit->nodePath;
876 osg::NodePath::const_reverse_iterator npi;
877 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
878 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
881 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
882 SGPickCallback* pickCallback = ud->getPickCallback(i);
885 SGSceneryPick sceneryPick;
886 sceneryPick.info.local = SGVec3d(hit->getLocalIntersectPoint());
887 sceneryPick.info.wgs84 = SGVec3d(hit->getWorldIntersectPoint());
888 sceneryPick.callback = pickCallback;
889 pickList.push_back(sceneryPick);
893 return !pickList.empty();
894 } else { // we can get called early ...
900 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
902 mRealRoot->addChild(camera);
906 fgDumpSceneGraphToFile(const char* filename)
908 return osgDB::writeNodeFile(*mRealRoot.get(), filename);
912 fgDumpTerrainBranchToFile(const char* filename)
914 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
920 fgDumpNodeToFile(osg::Node* node, const char* filename)
922 return osgDB::writeNodeFile(*node, filename);
924 // end of renderer.cxx