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>
65 #include <osgViewer/Renderer>
67 #include <simgear/scene/material/matlib.hxx>
68 #include <simgear/scene/material/EffectCullVisitor.hxx>
69 #include <simgear/scene/material/Effect.hxx>
70 #include <simgear/scene/material/EffectGeode.hxx>
71 #include <simgear/scene/model/animation.hxx>
72 #include <simgear/scene/model/placement.hxx>
73 #include <simgear/scene/sky/sky.hxx>
74 #include <simgear/scene/util/SGUpdateVisitor.hxx>
75 #include <simgear/scene/util/RenderConstants.hxx>
76 #include <simgear/scene/util/SGSceneUserData.hxx>
77 #include <simgear/scene/tgdb/GroundLightManager.hxx>
78 #include <simgear/scene/tgdb/pt_lights.hxx>
79 #include <simgear/structure/OSGUtils.hxx>
80 #include <simgear/props/props.hxx>
81 #include <simgear/timing/sg_time.hxx>
82 #include <simgear/ephemeris/ephemeris.hxx>
83 #include <simgear/math/sg_random.h>
85 #include <simgear/screen/jpgfactory.hxx>
88 #include <Time/light.hxx>
89 #include <Time/light.hxx>
90 #include <Cockpit/panel.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 <GUI/new_gui.hxx>
98 #include <Instrumentation/HUD/HUD.hxx>
99 #include <Environment/precipitation_mgr.hxx>
100 #include <Environment/environment_mgr.hxx>
102 //#include <Main/main.hxx>
103 #include "viewer.hxx"
104 #include "viewmgr.hxx"
105 #include "splash.hxx"
106 #include "renderingpipeline.hxx"
107 #include "renderer.hxx"
108 #include "CameraGroup.hxx"
109 #include "FGEventHandler.hxx"
112 using namespace simgear;
113 using namespace flightgear;
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 SGPropertyNode_ptr mConfigNode;
141 class SGPuDrawable : public osg::Drawable {
145 // Dynamic stuff, do not store geometry
146 setUseDisplayList(false);
147 setDataVariance(Object::DYNAMIC);
149 osg::StateSet* stateSet = getOrCreateStateSet();
150 stateSet->setRenderBinDetails(1001, "RenderBin");
151 // speed optimization?
152 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
153 // We can do translucent menus, so why not. :-)
154 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
155 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
156 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
158 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
160 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
161 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
163 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
164 { drawImplementation(*renderInfo.getState()); }
165 void drawImplementation(osg::State& state) const
167 state.setActiveTextureUnit(0);
168 state.setClientActiveTextureUnit(0);
170 state.disableAllVertexArrays();
172 glPushAttrib(GL_ALL_ATTRIB_BITS);
173 glPushClientAttrib(~0u);
181 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
182 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
187 class SGHUDDrawable : public osg::Drawable {
191 // Dynamic stuff, do not store geometry
192 setUseDisplayList(false);
193 setDataVariance(Object::DYNAMIC);
195 osg::StateSet* stateSet = getOrCreateStateSet();
196 stateSet->setRenderBinDetails(1000, "RenderBin");
198 // speed optimization?
199 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
200 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
201 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
202 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
203 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
205 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
207 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
208 { drawImplementation(*renderInfo.getState()); }
209 void drawImplementation(osg::State& state) const
211 state.setActiveTextureUnit(0);
212 state.setClientActiveTextureUnit(0);
213 state.disableAllVertexArrays();
215 glPushAttrib(GL_ALL_ATTRIB_BITS);
216 glPushClientAttrib(~0u);
218 HUD *hud = static_cast<HUD*>(globals->get_subsystem("hud"));
225 virtual osg::Object* cloneType() const { return new SGHUDDrawable; }
226 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDDrawable; }
231 class FGLightSourceUpdateCallback : public osg::NodeCallback {
235 * @param isSun true if the light is the actual sun i.e., for
236 * illuminating the moon.
238 FGLightSourceUpdateCallback(bool isSun = false) : _isSun(isSun) {}
239 FGLightSourceUpdateCallback(const FGLightSourceUpdateCallback& nc,
241 : NodeCallback(nc, op), _isSun(nc._isSun)
243 META_Object(flightgear,FGLightSourceUpdateCallback);
245 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
247 assert(dynamic_cast<osg::LightSource*>(node));
248 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
249 osg::Light* light = lightSource->getLight();
251 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
253 light->setAmbient(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
254 light->setDiffuse(Vec4(1.0f, 1.0f, 1.0f, 1.0f));
255 light->setSpecular(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
257 light->setAmbient(toOsg(l->scene_ambient()));
258 light->setDiffuse(toOsg(l->scene_diffuse()));
259 light->setSpecular(toOsg(l->scene_specular()));
261 osg::Vec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
262 light->setPosition(position);
270 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
272 FGWireFrameModeUpdateCallback() :
273 mWireframe(fgGetNode("/sim/rendering/wireframe", true))
275 virtual void operator()(osg::StateAttribute* stateAttribute,
278 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
279 osg::PolygonMode* polygonMode;
280 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
282 if (mWireframe->getBoolValue())
283 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
284 osg::PolygonMode::LINE);
286 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
287 osg::PolygonMode::FILL);
290 SGPropertyNode_ptr mWireframe;
293 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
295 FGLightModelUpdateCallback() :
296 mHighlights(fgGetNode("/sim/rendering/specular-highlight", true))
298 virtual void operator()(osg::StateAttribute* stateAttribute,
301 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
302 osg::LightModel* lightModel;
303 lightModel = static_cast<osg::LightModel*>(stateAttribute);
306 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
307 lightModel->setAmbientIntensity(toOsg(l->scene_ambient());
309 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
311 lightModel->setTwoSided(true);
312 lightModel->setLocalViewer(false);
314 if (mHighlights->getBoolValue()) {
315 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
317 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
321 SGPropertyNode_ptr mHighlights;
324 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
326 FGFogEnableUpdateCallback() :
327 mFogEnabled(fgGetNode("/sim/rendering/fog", true))
329 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
331 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
332 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
334 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
338 SGPropertyNode_ptr mFogEnabled;
341 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
343 virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
345 assert(dynamic_cast<SGUpdateVisitor*>(nv));
346 assert(dynamic_cast<osg::Fog*>(sa));
347 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
348 osg::Fog* fog = static_cast<osg::Fog*>(sa);
349 fog->setMode(osg::Fog::EXP2);
350 fog->setColor(toOsg(updateVisitor->getFogColor()));
351 fog->setDensity(updateVisitor->getFogExp2Density());
355 // update callback for the switch node guarding that splash
356 class FGScenerySwitchCallback : public osg::NodeCallback {
358 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
360 assert(dynamic_cast<osg::Switch*>(node));
361 osg::Switch* sw = static_cast<osg::Switch*>(node);
363 bool enabled = scenery_enabled;
364 sw->setValue(0, enabled);
370 static bool scenery_enabled;
373 bool FGScenerySwitchCallback::scenery_enabled = false;
375 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
376 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
378 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
379 static osg::ref_ptr<osg::Group> mDeferredRealRoot = new osg::Group;
381 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
383 static osg::ref_ptr<osg::Switch> panelSwitch;
386 // update callback for the switch node controlling the 2D panel
387 class FGPanelSwitchCallback : public osg::NodeCallback {
389 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
391 assert(dynamic_cast<osg::Switch*>(node));
392 osg::Switch* sw = static_cast<osg::Switch*>(node);
394 bool enabled = fgPanelVisible();
395 sw->setValue(0, enabled);
402 #ifdef FG_JPEG_SERVER
403 static void updateRenderer()
405 globals->get_renderer()->update();
409 FGRenderer::FGRenderer() :
411 _ambientFactor( new osg::Uniform( "fg_SunAmbientColor", osg::Vec4f() ) ),
412 _sunDiffuse( new osg::Uniform( "fg_SunDiffuseColor", osg::Vec4f() ) ),
413 _sunSpecular( new osg::Uniform( "fg_SunSpecularColor", osg::Vec4f() ) ),
414 _sunDirection( new osg::Uniform( "fg_SunDirection", osg::Vec3f() ) ),
415 _planes( new osg::Uniform( "fg_Planes", osg::Vec3f() ) ),
416 _fogColor( new osg::Uniform( "fg_FogColor", osg::Vec4f(1.0, 1.0, 1.0, 1.0) ) ),
417 _fogDensity( new osg::Uniform( "fg_FogDensity", 0.0001f ) ),
418 _shadowNumber( new osg::Uniform( "fg_ShadowNumber", (int)4 ) ),
419 _shadowDistances( new osg::Uniform( "fg_ShadowDistances", osg::Vec4f(5.0, 50.0, 500.0, 5000.0 ) ) ),
420 _depthInColor( new osg::Uniform( "fg_DepthInColor", false ) )
422 #ifdef FG_JPEG_SERVER
423 jpgRenderFrame = updateRenderer;
425 eventHandler = new FGEventHandler;
428 _cascadeFar[0] = 5.f;
429 _cascadeFar[1] = 50.f;
430 _cascadeFar[2] = 500.f;
431 _cascadeFar[3] = 5000.f;
434 FGRenderer::~FGRenderer()
436 #ifdef FG_JPEG_SERVER
437 jpgRenderFrame = NULL;
442 // Initialize various GL/view parameters
443 // XXX This should be called "preinit" or something, as it initializes
444 // critical parts of the scene graph in addition to the splash screen.
446 FGRenderer::splashinit( void ) {
447 osgViewer::Viewer* viewer = getViewer();
448 mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
449 ref_ptr<Node> splashNode = fgCreateSplashNode();
450 if (_classicalRenderer) {
451 mRealRoot->addChild(splashNode.get());
453 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
454 ii != CameraGroup::getDefault()->camerasEnd();
457 CameraInfo* info = ii->get();
458 Camera* camera = info->getCamera(DISPLAY_CAMERA);
459 if (camera == 0) continue;
461 camera->addChild(splashNode.get());
464 mFrameStamp = viewer->getFrameStamp();
465 // Scene doesn't seem to pass the frame stamp to the update
466 // visitor automatically.
467 mUpdateVisitor->setFrameStamp(mFrameStamp.get());
468 viewer->setUpdateVisitor(mUpdateVisitor.get());
469 fgSetDouble("/sim/startup/splash-alpha", 1.0);
472 class ShadowMapSizeListener : public SGPropertyChangeListener {
474 virtual void valueChanged(SGPropertyNode* node) {
475 globals->get_renderer()->updateShadowMapSize(node->getIntValue());
479 class ShadowEnabledListener : public SGPropertyChangeListener {
481 virtual void valueChanged(SGPropertyNode* node) {
482 globals->get_renderer()->enableShadows(node->getBoolValue());
486 class ShadowNumListener : public SGPropertyChangeListener {
488 virtual void valueChanged(SGPropertyNode* node) {
489 globals->get_renderer()->updateCascadeNumber(node->getIntValue());
493 class ShadowRangeListener : public SGPropertyChangeListener {
495 virtual void valueChanged(SGPropertyNode* node) {
496 globals->get_renderer()->updateCascadeFar(node->getIndex(), node->getFloatValue());
501 FGRenderer::init( void )
503 _classicalRenderer = !fgGetBool("/sim/rendering/rembrandt", false);
504 _shadowMapSize = fgGetInt( "/sim/rendering/shadows/map-size", 4096 );
505 fgAddChangeListener( new ShadowMapSizeListener, "/sim/rendering/shadows/map-size" );
506 fgAddChangeListener( new ShadowEnabledListener, "/sim/rendering/shadows/enabled" );
507 ShadowRangeListener* srl = new ShadowRangeListener;
508 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[0]");
509 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[1]");
510 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[2]");
511 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[3]");
512 fgAddChangeListener(new ShadowNumListener, "/sim/rendering/shadows/num-cascades");
513 _numCascades = fgGetInt("/sim/rendering/shadows/num-cascades", 4);
514 _cascadeFar[0] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[0]", 5.0f);
515 _cascadeFar[1] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[1]", 50.0f);
516 _cascadeFar[2] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[2]", 500.0f);
517 _cascadeFar[3] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[3]", 5000.0f);
518 updateCascadeNumber(_numCascades);
519 updateCascadeFar(0, _cascadeFar[0]);
520 updateCascadeFar(1, _cascadeFar[1]);
521 updateCascadeFar(2, _cascadeFar[2]);
522 updateCascadeFar(3, _cascadeFar[3]);
523 _useColorForDepth = fgGetBool( "/sim/rendering/use-color-for-depth", false );
524 _depthInColor->set( _useColorForDepth );
526 _renderer = fgGetString("/sim/rendering/renderer", "");
527 if (!_classicalRenderer && !_renderer.empty())
528 _pipeline = makeRenderingPipeline(_renderer, 0);
529 _scenery_loaded = fgGetNode("/sim/sceneryloaded", true);
530 _scenery_override = fgGetNode("/sim/sceneryloaded-override", true);
531 _panel_hotspots = fgGetNode("/sim/panel-hotspots", true);
532 _virtual_cockpit = fgGetNode("/sim/virtual-cockpit", true);
534 _sim_delta_sec = fgGetNode("/sim/time/delta-sec", true);
536 _xsize = fgGetNode("/sim/startup/xsize", true);
537 _ysize = fgGetNode("/sim/startup/ysize", true);
538 _splash_alpha = fgGetNode("/sim/startup/splash-alpha", true);
540 _skyblend = fgGetNode("/sim/rendering/skyblend", true);
541 _point_sprites = fgGetNode("/sim/rendering/point-sprites", true);
542 _enhanced_lighting = fgGetNode("/sim/rendering/enhanced-lighting", true);
543 _distance_attenuation = fgGetNode("/sim/rendering/distance-attenuation", true);
544 _horizon_effect = fgGetNode("/sim/rendering/horizon-effect", true);
545 _textures = fgGetNode("/sim/rendering/textures", true);
547 _altitude_ft = fgGetNode("/position/altitude-ft", true);
549 _cloud_status = fgGetNode("/environment/clouds/status", true);
550 _visibility_m = fgGetNode("/environment/visibility-m", true);
552 bool use_point_sprites = _point_sprites->getBoolValue();
553 bool enhanced_lighting = _enhanced_lighting->getBoolValue();
554 bool distance_attenuation = _distance_attenuation->getBoolValue();
556 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
557 distance_attenuation );
559 if (const char* tc = fgGetString("/sim/rendering/texture-compression", NULL)) {
560 if (strcmp(tc, "false") == 0 || strcmp(tc, "off") == 0 ||
561 strcmp(tc, "0") == 0 || strcmp(tc, "no") == 0 ||
562 strcmp(tc, "none") == 0) {
563 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::DoNotUseCompression);
564 } else if (strcmp(tc, "arb") == 0) {
565 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseARBCompression);
566 } else if (strcmp(tc, "dxt1") == 0) {
567 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT1Compression);
568 } else if (strcmp(tc, "dxt3") == 0) {
569 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT3Compression);
570 } else if (strcmp(tc, "dxt5") == 0) {
571 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT5Compression);
573 SG_LOG(SG_VIEW, SG_WARN, "Unknown texture compression setting!");
577 // create sky, but can't build until setupView, since we depend
578 // on other subsystems to be inited, eg Ephemeris
581 SGPath texture_path(globals->get_fg_root());
582 texture_path.append("Textures");
583 texture_path.append("Sky");
584 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
585 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
586 _sky->add_cloud_layer(layer);
589 _sky->texture_path( texture_path.str() );
591 if (!_classicalRenderer) {
592 eventHandler->setChangeStatsCameraRenderOrder( true );
596 void installCullVisitor(Camera* camera)
598 osgViewer::Renderer* renderer
599 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
600 for (int i = 0; i < 2; ++i) {
601 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
602 #if SG_OSG_VERSION_LESS_THAN(3,0,0)
603 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
605 osg::ref_ptr<osgUtil::CullVisitor::Identifier> identifier;
606 identifier = sceneView->getCullVisitor()->getIdentifier();
607 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
608 sceneView->getCullVisitor()->setIdentifier(identifier.get());
610 identifier = sceneView->getCullVisitorLeft()->getIdentifier();
611 sceneView->setCullVisitorLeft(sceneView->getCullVisitor()->clone());
612 sceneView->getCullVisitorLeft()->setIdentifier(identifier.get());
614 identifier = sceneView->getCullVisitorRight()->getIdentifier();
615 sceneView->setCullVisitorRight(sceneView->getCullVisitor()->clone());
616 sceneView->getCullVisitorRight()->setIdentifier(identifier.get());
621 flightgear::CameraInfo*
622 FGRenderer::buildRenderingPipeline(flightgear::CameraGroup* cgroup, unsigned flags, Camera* camera,
624 const Matrix& projection,
625 osg::GraphicsContext* gc,
626 bool useMasterSceneData)
628 flightgear::CameraInfo* info = 0;
629 if (!_classicalRenderer && (flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
630 info = buildDeferredPipeline( cgroup, flags, camera, view, projection, gc );
635 if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
636 _classicalRenderer = true;
637 return buildClassicalPipeline( cgroup, flags, camera, view, projection, useMasterSceneData );
641 flightgear::CameraInfo*
642 FGRenderer::buildClassicalPipeline(flightgear::CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
643 const osg::Matrix& view,
644 const osg::Matrix& projection,
645 bool useMasterSceneData)
647 CameraInfo* info = new CameraInfo(flags);
648 // The camera group will always update the camera
649 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
651 Camera* farCamera = 0;
652 if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0) {
653 farCamera = new Camera;
654 farCamera->setAllowEventFocus(camera->getAllowEventFocus());
655 farCamera->setGraphicsContext(camera->getGraphicsContext());
656 farCamera->setCullingMode(camera->getCullingMode());
657 farCamera->setInheritanceMask(camera->getInheritanceMask());
658 farCamera->setReferenceFrame(Transform::ABSOLUTE_RF);
659 // Each camera's viewport is written when the window is
660 // resized; if the the viewport isn't copied here, it gets updated
661 // twice and ends up with the wrong value.
662 farCamera->setViewport(simgear::clone(camera->getViewport()));
663 farCamera->setDrawBuffer(camera->getDrawBuffer());
664 farCamera->setReadBuffer(camera->getReadBuffer());
665 farCamera->setRenderTargetImplementation(
666 camera->getRenderTargetImplementation());
667 const Camera::BufferAttachmentMap& bufferMap
668 = camera->getBufferAttachmentMap();
669 if (bufferMap.count(Camera::COLOR_BUFFER) != 0) {
671 Camera::COLOR_BUFFER,
672 bufferMap.find(Camera::COLOR_BUFFER)->second._texture.get());
674 cgroup->getViewer()->addSlave(farCamera, projection, view, useMasterSceneData);
675 installCullVisitor(farCamera);
676 int farSlaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
677 info->addCamera( FAR_CAMERA, farCamera, farSlaveIndex );
678 farCamera->setRenderOrder(Camera::POST_RENDER, farSlaveIndex);
679 camera->setCullMask(camera->getCullMask() & ~simgear::BACKGROUND_BIT);
680 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
682 cgroup->getViewer()->addSlave(camera, projection, view, useMasterSceneData);
683 installCullVisitor(camera);
684 int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
685 info->addCamera( MAIN_CAMERA, camera, slaveIndex );
686 camera->setRenderOrder(Camera::POST_RENDER, slaveIndex);
687 cgroup->addCamera(info);
691 class FGDeferredRenderingCameraCullCallback : public osg::NodeCallback {
693 FGDeferredRenderingCameraCullCallback( const std::string& k, CameraInfo* i ) : kind( k ), info( i ) {}
694 virtual void operator()( osg::Node *n, osg::NodeVisitor *nv) {
695 simgear::EffectCullVisitor* cv = dynamic_cast<simgear::EffectCullVisitor*>(nv);
696 osg::Camera* camera = static_cast<osg::Camera*>(n);
698 cv->clearBufferList();
699 cv->addBuffer("depth", info->getBuffer( "depth" ) );
700 cv->addBuffer("normal", info->getBuffer( "normal" ) );
701 cv->addBuffer("diffuse", info->getBuffer( "diffuse" ) );
702 cv->addBuffer("spec-emis", info->getBuffer( "spec-emis" ) );
703 cv->addBuffer("lighting", info->getBuffer( "lighting" ) );
704 cv->addBuffer("shadow", info->getBuffer( "shadow" ) );
705 // cv->addBuffer(simgear::Effect::AO_BUFFER, info->gBuffer->aoBuffer[2]);
707 if ( !info->getRenderStageInfo(kind).fullscreen )
708 info->setMatrices( camera );
710 cv->traverse( *camera );
712 if ( kind == flightgear::GEOMETRY_CAMERA ) {
713 // Save transparent bins to render later
714 osgUtil::RenderStage* renderStage = cv->getRenderStage();
715 osgUtil::RenderBin::RenderBinList& rbl = renderStage->getRenderBinList();
716 for (osgUtil::RenderBin::RenderBinList::iterator rbi = rbl.begin(); rbi != rbl.end(); ) {
717 if (rbi->second->getSortMode() == osgUtil::RenderBin::SORT_BACK_TO_FRONT) {
718 info->savedTransparentBins.insert( std::make_pair( rbi->first, rbi->second ) );
724 } else if ( kind == flightgear::LIGHTING_CAMERA ) {
725 osg::ref_ptr<osg::Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
726 if (mainShadowCamera.valid()) {
727 osg::Switch* grp = mainShadowCamera->getChild(0)->asSwitch();
728 for (int i = 0; i < 4; ++i ) {
729 if (!grp->getValue(i))
731 osg::TexGen* shadowTexGen = info->shadowTexGen[i];
732 shadowTexGen->setMode(osg::TexGen::EYE_LINEAR);
734 osg::Camera* cascadeCam = static_cast<osg::Camera*>( grp->getChild(i) );
735 // compute the matrix which takes a vertex from view coords into tex coords
736 shadowTexGen->setPlanesFromMatrix( cascadeCam->getProjectionMatrix() *
737 osg::Matrix::translate(1.0,1.0,1.0) *
738 osg::Matrix::scale(0.5f,0.5f,0.5f) );
740 osg::RefMatrix * refMatrix = new osg::RefMatrix( cascadeCam->getInverseViewMatrix() * *cv->getModelViewMatrix() );
742 cv->getRenderStage()->getPositionalStateContainer()->addPositionedTextureAttribute( i+1, refMatrix, shadowTexGen );
745 // Render saved transparent render bins
746 osgUtil::RenderStage* renderStage = cv->getRenderStage();
747 osgUtil::RenderBin::RenderBinList& rbl = renderStage->getRenderBinList();
748 for (osgUtil::RenderBin::RenderBinList::iterator rbi = info->savedTransparentBins.begin(); rbi != info->savedTransparentBins.end(); ++rbi ){
749 rbl.insert( std::make_pair( rbi->first + 10000, rbi->second ) );
751 info->savedTransparentBins.clear();
760 osg::Texture2D* buildDeferredBuffer(GLint internalFormat, GLenum sourceFormat, GLenum sourceType, osg::Texture::WrapMode wrapMode, bool shadowComparison = false)
762 osg::Texture2D* tex = new osg::Texture2D;
763 tex->setResizeNonPowerOfTwoHint( false );
764 tex->setInternalFormat( internalFormat );
765 tex->setShadowComparison(shadowComparison);
766 if (shadowComparison) {
767 tex->setShadowTextureMode(osg::Texture2D::LUMINANCE);
768 tex->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
770 tex->setSourceFormat(sourceFormat);
771 tex->setSourceType(sourceType);
772 tex->setFilter( osg::Texture2D::MIN_FILTER, osg::Texture2D::LINEAR );
773 tex->setFilter( osg::Texture2D::MAG_FILTER, osg::Texture2D::LINEAR );
774 tex->setWrap( osg::Texture::WRAP_S, wrapMode );
775 tex->setWrap( osg::Texture::WRAP_T, wrapMode );
779 void buildDeferredBuffers( flightgear::CameraInfo* info, int shadowMapSize, bool useColorForDepth )
781 if (useColorForDepth) {
782 info->addBuffer("real-depth", buildDeferredBuffer( GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_FLOAT, osg::Texture::CLAMP_TO_BORDER) );
783 info->addBuffer("depth", buildDeferredBuffer( GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, osg::Texture::CLAMP_TO_BORDER) );
786 info->addBuffer("depth", buildDeferredBuffer( GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_FLOAT, osg::Texture::CLAMP_TO_BORDER) );
788 info->addBuffer("normal", buildDeferredBuffer( GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, osg::Texture::CLAMP_TO_BORDER) );
789 info->addBuffer("diffuse", buildDeferredBuffer( GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, osg::Texture::CLAMP_TO_BORDER) );
790 info->addBuffer("spec-emis", buildDeferredBuffer( GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, osg::Texture::CLAMP_TO_BORDER) );
791 info->addBuffer("lighting", buildDeferredBuffer( GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, osg::Texture::CLAMP_TO_BORDER) );
792 info->addBuffer("shadow", buildDeferredBuffer( GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_FLOAT, osg::Texture::CLAMP_TO_BORDER, true), 0.0f );
793 info->getBuffer("shadow")->setTextureSize(shadowMapSize,shadowMapSize);
796 void attachBufferToCamera( flightgear::CameraInfo* info, osg::Camera* camera, osg::Camera::BufferComponent c, const std::string& ck, const std::string& bk )
798 camera->attach( c, info->getBuffer(bk) );
799 info->getRenderStageInfo(ck).buffers.insert( std::make_pair( c, bk ) );
802 osg::Camera* FGRenderer::buildDeferredGeometryCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc )
804 osg::Camera* camera = new osg::Camera;
805 info->addCamera(flightgear::GEOMETRY_CAMERA, camera );
807 camera->setCullMask( ~simgear::MODELLIGHT_BIT );
808 camera->setName( "GeometryC" );
809 camera->setGraphicsContext( gc );
810 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( flightgear::GEOMETRY_CAMERA, info ) );
811 camera->setClearMask( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
812 camera->setClearColor( osg::Vec4( 0., 0., 0., 0. ) );
813 camera->setClearDepth( 1.0 );
814 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
815 camera->setViewport( new osg::Viewport );
816 attachBufferToCamera( info, camera, osg::Camera::COLOR_BUFFER0, flightgear::GEOMETRY_CAMERA, "normal" );
817 attachBufferToCamera( info, camera, osg::Camera::COLOR_BUFFER1, flightgear::GEOMETRY_CAMERA, "diffuse" );
818 attachBufferToCamera( info, camera, osg::Camera::COLOR_BUFFER2, flightgear::GEOMETRY_CAMERA, "spec-emis" );
819 if (_useColorForDepth) {
820 attachBufferToCamera( info, camera, osg::Camera::DEPTH_BUFFER, flightgear::GEOMETRY_CAMERA, "real-depth" );
821 attachBufferToCamera( info, camera, osg::Camera::COLOR_BUFFER3, flightgear::GEOMETRY_CAMERA, "depth" );
823 attachBufferToCamera( info, camera, osg::Camera::DEPTH_BUFFER, flightgear::GEOMETRY_CAMERA, "depth" );
825 camera->setDrawBuffer(GL_FRONT);
826 camera->setReadBuffer(GL_FRONT);
828 osg::StateSet* ss = camera->getOrCreateStateSet();
829 ss->addUniform( _depthInColor );
831 camera->addChild( mDeferredRealRoot.get() );
836 static void setShadowCascadeStateSet( osg::Camera* cam ) {
837 osg::StateSet* ss = cam->getOrCreateStateSet();
838 ss->setAttribute( new osg::PolygonOffset( 1.1f, 5.0f ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
839 ss->setMode( GL_POLYGON_OFFSET_FILL, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
840 ss->setRenderBinDetails( 0, "RenderBin", osg::StateSet::OVERRIDE_RENDERBIN_DETAILS );
841 ss->setAttributeAndModes( new osg::AlphaFunc( osg::AlphaFunc::GREATER, 0.05 ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
842 ss->setAttributeAndModes( new osg::ColorMask( false, false, false, false ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
843 ss->setAttributeAndModes( new osg::CullFace( osg::CullFace::FRONT ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
844 osg::Program* program = new osg::Program;
845 ss->setAttribute( program, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
846 ss->setMode( GL_LIGHTING, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
847 ss->setMode( GL_BLEND, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
848 //ss->setTextureMode( 0, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
849 ss->setTextureMode( 0, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
850 ss->setTextureMode( 1, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
851 ss->setTextureMode( 1, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
852 ss->setTextureMode( 2, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
853 ss->setTextureMode( 2, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
856 static osg::Camera* createShadowCascadeCamera( int no, int cascadeSize ) {
857 osg::Camera* cascadeCam = new osg::Camera;
858 setShadowCascadeStateSet( cascadeCam );
860 std::ostringstream oss;
861 oss << "CascadeCamera" << (no + 1);
862 cascadeCam->setName( oss.str() );
863 cascadeCam->setClearMask(0);
864 cascadeCam->setCullMask(~( simgear::MODELLIGHT_BIT /* | simgear::NO_SHADOW_BIT */ ) );
865 cascadeCam->setCullingMode( cascadeCam->getCullingMode() & ~osg::CullSettings::SMALL_FEATURE_CULLING );
866 cascadeCam->setAllowEventFocus(false);
867 cascadeCam->setReferenceFrame(osg::Transform::ABSOLUTE_RF_INHERIT_VIEWPOINT);
868 cascadeCam->setRenderOrder(osg::Camera::NESTED_RENDER);
869 cascadeCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
870 cascadeCam->setViewport( int( no / 2 ) * cascadeSize, (no & 1) * cascadeSize, cascadeSize, cascadeSize );
874 osg::Camera* FGRenderer::buildDeferredShadowCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc )
876 osg::Camera* mainShadowCamera = new osg::Camera;
877 info->addCamera(flightgear::SHADOW_CAMERA, mainShadowCamera, 0.0f );
879 mainShadowCamera->setName( "ShadowC" );
880 mainShadowCamera->setClearMask( GL_DEPTH_BUFFER_BIT );
881 mainShadowCamera->setClearDepth( 1.0 );
882 mainShadowCamera->setAllowEventFocus(false);
883 mainShadowCamera->setGraphicsContext(gc);
884 mainShadowCamera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
885 attachBufferToCamera( info, mainShadowCamera, osg::Camera::DEPTH_BUFFER, flightgear::SHADOW_CAMERA, "shadow" );
886 mainShadowCamera->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
887 mainShadowCamera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
888 mainShadowCamera->setProjectionMatrix(osg::Matrix::identity());
889 mainShadowCamera->setCullingMode( osg::CullSettings::NO_CULLING );
890 mainShadowCamera->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
891 mainShadowCamera->setDrawBuffer(GL_FRONT);
892 mainShadowCamera->setReadBuffer(GL_FRONT);
894 osg::Switch* shadowSwitch = new osg::Switch;
895 mainShadowCamera->addChild( shadowSwitch );
897 for (int i = 0; i < 4; ++i ) {
898 osg::Camera* cascadeCam = createShadowCascadeCamera( i, _shadowMapSize/2 );
899 cascadeCam->addChild( mDeferredRealRoot.get() );
900 shadowSwitch->addChild( cascadeCam );
901 info->shadowTexGen[i] = new osg::TexGen;
903 if (fgGetBool("/sim/rendering/shadows/enabled", true))
904 shadowSwitch->setAllChildrenOn();
906 shadowSwitch->setAllChildrenOff();
908 return mainShadowCamera;
911 void FGRenderer::updateShadowCascade(const CameraInfo* info, osg::Camera* camera, osg::Group* grp, int idx, double left, double right, double bottom, double top, double zNear, double f1, double f2)
913 osg::Camera* cascade = static_cast<osg::Camera*>( grp->getChild(idx) );
914 osg::Matrixd &viewMatrix = cascade->getViewMatrix();
915 osg::Matrixd &projectionMatrix = cascade->getProjectionMatrix();
917 osg::BoundingSphere bs;
918 bs.expandBy(osg::Vec3(left,bottom,-zNear) * f1);
919 bs.expandBy(osg::Vec3(right,top,-zNear) * f2);
920 bs.expandBy(osg::Vec3(left,bottom,-zNear) * f2);
921 bs.expandBy(osg::Vec3(right,top,-zNear) * f1);
923 osg::Vec4 aim = osg::Vec4(bs.center(), 1.0) * camera->getInverseViewMatrix();
925 projectionMatrix.makeOrtho( -bs.radius(), bs.radius(), -bs.radius(), bs.radius(), 1., 15000.0 );
926 osg::Vec3 position( aim.x(), aim.y(), aim.z() );
927 viewMatrix.makeLookAt( position + (getSunDirection() * 10000.0), position, position );
930 osg::Vec3 FGRenderer::getSunDirection() const
933 _sunDirection->get( val );
937 void FGRenderer::updateShadowCamera(const flightgear::CameraInfo* info, const osg::Vec3d& position)
939 ref_ptr<Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
940 if (mainShadowCamera.valid()) {
941 ref_ptr<Switch> shadowSwitch = mainShadowCamera->getChild( 0 )->asSwitch();
942 osg::Vec3d up = position,
943 dir = getSunDirection();
946 // cos(100 deg) == -0.17
947 if (up * dir < -0.17 || !fgGetBool("/sim/rendering/shadows/enabled", true)) {
948 shadowSwitch->setAllChildrenOff();
950 double left,right,bottom,top,zNear,zFar;
951 ref_ptr<Camera> camera = info->getCamera(GEOMETRY_CAMERA);
952 camera->getProjectionMatrix().getFrustum(left,right,bottom,top,zNear,zFar);
954 shadowSwitch->setAllChildrenOn();
955 if (_numCascades == 1) {
956 osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(0) );
957 cascadeCam->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
959 for (int no = 0; no < 4; ++no) {
960 osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(no) );
961 cascadeCam->setViewport( int( no / 2 ) * (_shadowMapSize/2), (no & 1) * (_shadowMapSize/2), (_shadowMapSize/2), (_shadowMapSize/2) );
964 updateShadowCascade(info, camera, shadowSwitch, 0, left, right, bottom, top, zNear, 1.0, _cascadeFar[0]/zNear);
965 if (_numCascades > 1) {
966 shadowSwitch->setValue(1, true);
967 updateShadowCascade(info, camera, shadowSwitch, 1, left, right, bottom, top, zNear, _cascadeFar[0]/zNear, _cascadeFar[1]/zNear);
969 shadowSwitch->setValue(1, false);
971 if (_numCascades > 2) {
972 shadowSwitch->setValue(2, true);
973 updateShadowCascade(info, camera, shadowSwitch, 2, left, right, bottom, top, zNear, _cascadeFar[1]/zNear, _cascadeFar[2]/zNear);
975 shadowSwitch->setValue(2, false);
977 if (_numCascades > 3) {
978 shadowSwitch->setValue(3, true);
979 updateShadowCascade(info, camera, shadowSwitch, 3, left, right, bottom, top, zNear, _cascadeFar[2]/zNear, _cascadeFar[3]/zNear);
981 shadowSwitch->setValue(3, false);
984 osg::Matrixd &viewMatrix = mainShadowCamera->getViewMatrix();
986 osg::Vec4 aim = osg::Vec4( 0.0, 0.0, 0.0, 1.0 ) * camera->getInverseViewMatrix();
988 osg::Vec3 position( aim.x(), aim.y(), aim.z() );
989 viewMatrix.makeLookAt( position, position + (getSunDirection() * 10000.0), position );
995 void FGRenderer::updateShadowMapSize(int mapSize)
997 if ( ((~( mapSize-1 )) & mapSize) != mapSize ) {
998 SG_LOG( SG_VIEW, SG_ALERT, "Map size is not a power of two" );
1001 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
1002 ii != CameraGroup::getDefault()->camerasEnd();
1005 CameraInfo* info = ii->get();
1006 Camera* camera = info->getCamera(SHADOW_CAMERA);
1007 if (camera == 0) continue;
1009 Texture2D* tex = info->getBuffer("shadow");
1010 if (tex == 0) continue;
1012 tex->setTextureSize( mapSize, mapSize );
1013 tex->dirtyTextureObject();
1015 Viewport* vp = camera->getViewport();
1016 vp->width() = mapSize;
1017 vp->height() = mapSize;
1019 osgViewer::Renderer* renderer
1020 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
1021 for (int i = 0; i < 2; ++i) {
1022 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
1023 sceneView->getRenderStage()->setFrameBufferObject(0);
1024 sceneView->getRenderStage()->setCameraRequiresSetUp(true);
1025 if (sceneView->getRenderStageLeft()) {
1026 sceneView->getRenderStageLeft()->setFrameBufferObject(0);
1027 sceneView->getRenderStageLeft()->setCameraRequiresSetUp(true);
1029 if (sceneView->getRenderStageRight()) {
1030 sceneView->getRenderStageRight()->setFrameBufferObject(0);
1031 sceneView->getRenderStageRight()->setCameraRequiresSetUp(true);
1035 int cascadeSize = mapSize / 2;
1036 Group* grp = camera->getChild(0)->asGroup();
1037 for (int i = 0; i < 4; ++i ) {
1038 Camera* cascadeCam = static_cast<Camera*>( grp->getChild(i) );
1039 cascadeCam->setViewport( int( i / 2 ) * cascadeSize, (i & 1) * cascadeSize, cascadeSize, cascadeSize );
1042 _shadowMapSize = mapSize;
1046 void FGRenderer::enableShadows(bool enabled)
1048 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
1049 ii != CameraGroup::getDefault()->camerasEnd();
1052 CameraInfo* info = ii->get();
1053 Camera* camera = info->getCamera(SHADOW_CAMERA);
1054 if (camera == 0) continue;
1056 osg::Switch* shadowSwitch = camera->getChild(0)->asSwitch();
1058 shadowSwitch->setAllChildrenOn();
1060 shadowSwitch->setAllChildrenOff();
1064 void FGRenderer::updateCascadeFar(int index, float far_m)
1066 if (index < 0 || index > 3)
1068 _cascadeFar[index] = far_m;
1069 _shadowDistances->set( osg::Vec4f(_cascadeFar[0], _cascadeFar[1], _cascadeFar[2], _cascadeFar[3]) );
1072 void FGRenderer::updateCascadeNumber(size_t num)
1074 if (num < 1 || num > 4)
1077 _shadowNumber->set( (int)_numCascades );
1080 osg::Camera* FGRenderer::buildDeferredLightingCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc )
1082 osg::Camera* camera = new osg::Camera;
1083 info->addCamera(flightgear::LIGHTING_CAMERA, camera );
1085 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( flightgear::LIGHTING_CAMERA, info ) );
1086 camera->setAllowEventFocus(false);
1087 camera->setGraphicsContext(gc);
1088 camera->setViewport(new Viewport);
1089 camera->setName("LightingC");
1090 camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1091 camera->setRenderOrder(osg::Camera::POST_RENDER, 50);
1092 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1093 camera->setViewport( new osg::Viewport );
1094 attachBufferToCamera( info, camera, osg::Camera::COLOR_BUFFER, flightgear::LIGHTING_CAMERA, "lighting" );
1095 if (_useColorForDepth) {
1096 attachBufferToCamera( info, camera, osg::Camera::DEPTH_BUFFER, flightgear::GEOMETRY_CAMERA, "real-depth" );
1098 attachBufferToCamera( info, camera, osg::Camera::DEPTH_BUFFER, flightgear::GEOMETRY_CAMERA, "depth" );
1100 camera->setDrawBuffer(GL_FRONT);
1101 camera->setReadBuffer(GL_FRONT);
1102 camera->setClearColor( osg::Vec4( 0., 0., 0., 1. ) );
1103 camera->setClearMask( GL_COLOR_BUFFER_BIT );
1104 osg::StateSet* ss = camera->getOrCreateStateSet();
1105 ss->setAttribute( new osg::Depth(osg::Depth::LESS, 0.0, 1.0, false) );
1106 ss->addUniform( _depthInColor );
1108 osg::Group* lightingGroup = new osg::Group;
1110 osg::Camera* quadCam1 = new osg::Camera;
1111 quadCam1->setName( "QuadCamera1" );
1112 quadCam1->setClearMask(0);
1113 quadCam1->setAllowEventFocus(false);
1114 quadCam1->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1115 quadCam1->setRenderOrder(osg::Camera::NESTED_RENDER);
1116 quadCam1->setViewMatrix(osg::Matrix::identity());
1117 quadCam1->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1118 quadCam1->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1119 ss = quadCam1->getOrCreateStateSet();
1120 ss->addUniform( _ambientFactor );
1121 ss->addUniform( info->projInverse );
1122 ss->addUniform( info->viewInverse );
1123 ss->addUniform( info->view );
1124 ss->addUniform( _sunDiffuse );
1125 ss->addUniform( _sunSpecular );
1126 ss->addUniform( _sunDirection );
1127 ss->addUniform( _planes );
1128 ss->addUniform( _shadowNumber );
1129 ss->addUniform( _shadowDistances );
1131 osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1132 g->setUseDisplayList(false);
1133 simgear::EffectGeode* eg = new simgear::EffectGeode;
1134 simgear::Effect* effect = simgear::makeEffect("Effects/ambient", true);
1136 SG_LOG(SG_VIEW, SG_ALERT, "Effects/ambient not found");
1139 eg->setEffect( effect );
1140 g->setName( "AmbientQuad" );
1141 eg->setName("AmbientQuad");
1142 eg->setCullingActive(false);
1144 quadCam1->addChild( eg );
1146 g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1147 g->setUseDisplayList(false);
1148 g->setName( "SunlightQuad" );
1149 eg = new simgear::EffectGeode;
1150 effect = simgear::makeEffect("Effects/sunlight", true);
1152 SG_LOG(SG_VIEW, SG_ALERT, "Effects/sunlight not found");
1155 eg->setEffect( effect );
1156 eg->setName("SunlightQuad");
1157 eg->setCullingActive(false);
1159 quadCam1->addChild( eg );
1161 osg::Camera* lightCam = new osg::Camera;
1162 ss = lightCam->getOrCreateStateSet();
1163 ss->addUniform( _planes );
1164 ss->addUniform( info->bufferSize );
1165 lightCam->setName( "LightCamera" );
1166 lightCam->setClearMask(0);
1167 lightCam->setAllowEventFocus(false);
1168 lightCam->setReferenceFrame(osg::Transform::RELATIVE_RF);
1169 lightCam->setRenderOrder(osg::Camera::NESTED_RENDER,1);
1170 lightCam->setViewMatrix(osg::Matrix::identity());
1171 lightCam->setProjectionMatrix(osg::Matrix::identity());
1172 lightCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1173 lightCam->setCullMask( simgear::MODELLIGHT_BIT );
1174 lightCam->setInheritanceMask( osg::CullSettings::ALL_VARIABLES & ~osg::CullSettings::CULL_MASK );
1175 lightCam->addChild( mDeferredRealRoot.get() );
1178 osg::Camera* quadCam2 = new osg::Camera;
1179 quadCam2->setName( "QuadCamera1" );
1180 quadCam2->setClearMask(0);
1181 quadCam2->setAllowEventFocus(false);
1182 quadCam2->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1183 quadCam2->setRenderOrder(osg::Camera::NESTED_RENDER,2);
1184 quadCam2->setViewMatrix(osg::Matrix::identity());
1185 quadCam2->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1186 quadCam2->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1187 ss = quadCam2->getOrCreateStateSet();
1188 ss->addUniform( _ambientFactor );
1189 ss->addUniform( info->projInverse );
1190 ss->addUniform( info->viewInverse );
1191 ss->addUniform( info->view );
1192 ss->addUniform( _sunDiffuse );
1193 ss->addUniform( _sunSpecular );
1194 ss->addUniform( _sunDirection );
1195 ss->addUniform( _fogColor );
1196 ss->addUniform( _fogDensity );
1197 ss->addUniform( _planes );
1199 g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1200 g->setUseDisplayList(false);
1201 g->setName( "FogQuad" );
1202 eg = new simgear::EffectGeode;
1203 effect = simgear::makeEffect("Effects/fog", true);
1205 SG_LOG(SG_VIEW, SG_ALERT, "Effects/fog not found");
1208 eg->setEffect( effect );
1209 eg->setName("FogQuad");
1210 eg->setCullingActive(false);
1212 quadCam2->addChild( eg );
1214 lightingGroup->addChild( _sky->getPreRoot() );
1215 lightingGroup->addChild( _sky->getCloudRoot() );
1216 lightingGroup->addChild( quadCam1 );
1217 lightingGroup->addChild( lightCam );
1218 lightingGroup->addChild( quadCam2 );
1220 camera->addChild( lightingGroup );
1225 flightgear::CameraInfo*
1226 FGRenderer::buildDeferredPipeline(flightgear::CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1227 const osg::Matrix& view,
1228 const osg::Matrix& projection,
1229 osg::GraphicsContext* gc)
1231 if (_renderer.empty() || !_pipeline.valid())
1232 return buildDefaultDeferredPipeline(cgroup, flags, camera, view, projection, gc);
1233 return _pipeline->buildCamera(cgroup, flags, camera, view, projection, gc);
1236 flightgear::CameraInfo*
1237 FGRenderer::buildDefaultDeferredPipeline(flightgear::CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1238 const osg::Matrix& view,
1239 const osg::Matrix& projection,
1240 osg::GraphicsContext* gc)
1242 CameraInfo* info = new CameraInfo(flags);
1243 buildDeferredBuffers(info, _shadowMapSize, _useColorForDepth);
1245 osg::Camera* geometryCamera = buildDeferredGeometryCamera( info, gc );
1246 cgroup->getViewer()->addSlave(geometryCamera, false);
1247 installCullVisitor(geometryCamera);
1248 int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1249 info->getRenderStageInfo(GEOMETRY_CAMERA).slaveIndex = slaveIndex;
1251 Camera* shadowCamera = buildDeferredShadowCamera( info, gc );
1252 cgroup->getViewer()->addSlave(shadowCamera, false);
1253 installCullVisitor(shadowCamera);
1254 slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1255 info->getRenderStageInfo(SHADOW_CAMERA).slaveIndex = slaveIndex;
1257 osg::Camera* lightingCamera = buildDeferredLightingCamera( info, gc );
1258 cgroup->getViewer()->addSlave(lightingCamera, false);
1259 installCullVisitor(lightingCamera);
1260 slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1261 info->getRenderStageInfo(LIGHTING_CAMERA).slaveIndex = slaveIndex;
1263 camera->setName( "DisplayC" );
1264 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( flightgear::DISPLAY_CAMERA, info ) );
1265 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
1266 camera->setAllowEventFocus(false);
1267 osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1268 g->setUseDisplayList(false); //DEBUG
1269 simgear::EffectGeode* eg = new simgear::EffectGeode;
1270 simgear::Effect* effect = simgear::makeEffect("Effects/display", true);
1272 SG_LOG(SG_VIEW, SG_ALERT, "Effects/display not found");
1275 eg->setEffect(effect);
1276 eg->setCullingActive(false);
1278 camera->setViewMatrix(osg::Matrix::identity());
1279 camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1280 camera->addChild(eg);
1282 osg::StateSet* ss = camera->getOrCreateStateSet();
1283 ss->addUniform( _depthInColor );
1285 cgroup->getViewer()->addSlave(camera, false);
1286 installCullVisitor(camera);
1287 slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1288 info->addCamera( DISPLAY_CAMERA, camera, slaveIndex, true );
1289 camera->setRenderOrder(Camera::POST_RENDER, 99+slaveIndex); //FIXME
1290 cgroup->addCamera(info);
1296 FGRenderer::setupView( void )
1298 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1299 osg::initNotifyLevel();
1301 // The number of polygon-offset "units" to place between layers. In
1302 // principle, one is supposed to be enough. In practice, I find that
1303 // my hardware/driver requires many more.
1304 osg::PolygonOffset::setUnitsMultiplier(1);
1305 osg::PolygonOffset::setFactorMultiplier(1);
1307 // Go full screen if requested ...
1308 if ( fgGetBool("/sim/startup/fullscreen") )
1312 // The sun and moon diameters are scaled down numbers of the
1313 // actual diameters. This was needed to fit both the sun and the
1314 // moon within the distance to the far clip plane.
1315 // Moon diameter: 3,476 kilometers
1316 // Sun diameter: 1,390,000 kilometers
1317 _sky->build( 80000.0, 80000.0,
1319 *globals->get_ephem(),
1320 fgGetNode("/environment", true));
1323 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1325 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
1327 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
1329 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
1330 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1332 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
1333 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
1334 stateSet->setAttribute(new osg::BlendFunc);
1335 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
1337 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
1339 // this will be set below
1340 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
1342 osg::Material* material = new osg::Material;
1343 stateSet->setAttribute(material);
1345 stateSet->setTextureAttribute(0, new osg::TexEnv);
1346 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
1348 osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
1349 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
1350 stateSet->setAttribute(hint);
1351 hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
1352 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
1353 stateSet->setAttribute(hint);
1354 hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
1355 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
1356 stateSet->setAttribute(hint);
1357 hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
1358 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
1359 stateSet->setAttribute(hint);
1360 hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
1361 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
1362 stateSet->setAttribute(hint);
1364 osg::Group* sceneGroup = new osg::Group;
1365 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
1366 sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
1368 //sceneGroup->addChild(thesky->getCloudRoot());
1370 stateSet = sceneGroup->getOrCreateStateSet();
1371 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1373 // need to update the light on every frame
1374 // OSG LightSource objects are rather confusing. OSG only supports
1375 // the 10 lights specified by OpenGL itself; if more than one
1376 // LightSource in the scene graph have the same light number, it's
1377 // indeterminate which values will be used to render geometry that
1378 // has that light number enabled. Also, adding children to a
1379 // LightSource is just a shortcut for setting up a state set that
1380 // has the corresponding OpenGL light enabled: a LightSource will
1381 // affect geometry anywhere in the scene graph that has its light
1382 // number enabled in a state set.
1383 LightSource* lightSource = new LightSource;
1384 lightSource->getLight()->setDataVariance(Object::DYNAMIC);
1385 // relative because of CameraView being just a clever transform node
1386 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1387 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
1388 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
1389 mRealRoot->addChild(lightSource);
1390 // we need a white diffuse light for the phase of the moon
1391 osg::LightSource* sunLight = new osg::LightSource;
1392 sunLight->getLight()->setDataVariance(Object::DYNAMIC);
1393 sunLight->getLight()->setLightNum(1);
1394 sunLight->setUpdateCallback(new FGLightSourceUpdateCallback(true));
1395 sunLight->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1396 sunLight->setLocalStateSetModes(osg::StateAttribute::ON);
1398 // Hang a StateSet above the sky subgraph in order to turn off
1400 Group* skyGroup = new Group;
1401 StateSet* skySS = skyGroup->getOrCreateStateSet();
1402 skySS->setMode(GL_LIGHT0, StateAttribute::OFF);
1403 skyGroup->addChild(_sky->getPreRoot());
1404 sunLight->addChild(skyGroup);
1405 mRoot->addChild(sceneGroup);
1406 if ( _classicalRenderer )
1407 mRoot->addChild(sunLight);
1409 // Clouds are added to the scene graph later
1410 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
1411 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
1412 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
1413 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1415 // enable disable specular highlights.
1416 // is the place where we might plug in an other fragment shader ...
1417 osg::LightModel* lightModel = new osg::LightModel;
1418 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
1419 stateSet->setAttribute(lightModel);
1421 // switch to enable wireframe
1422 osg::PolygonMode* polygonMode = new osg::PolygonMode;
1423 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
1424 stateSet->setAttributeAndModes(polygonMode);
1426 // scene fog handling
1427 osg::Fog* fog = new osg::Fog;
1428 fog->setUpdateCallback(new FGFogUpdateCallback);
1429 stateSet->setAttributeAndModes(fog);
1430 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
1433 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
1436 osg::Geode* geode = new osg::Geode;
1437 geode->addDrawable(new SGPuDrawable);
1438 geode->addDrawable(new SGHUDDrawable);
1439 guiCamera->addChild(geode);
1441 panelSwitch = new osg::Switch;
1442 osg::StateSet* stateSet = panelSwitch->getOrCreateStateSet();
1443 stateSet->setRenderBinDetails(1000, "RenderBin");
1445 // speed optimization?
1446 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
1447 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
1448 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
1449 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
1450 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1453 panelSwitch->setUpdateCallback(new FGPanelSwitchCallback);
1456 guiCamera->addChild(panelSwitch.get());
1459 osg::Switch* sw = new osg::Switch;
1460 sw->setUpdateCallback(new FGScenerySwitchCallback);
1461 sw->addChild(mRoot.get());
1462 mRealRoot->addChild(sw);
1463 // The clouds are attached directly to the scene graph root
1464 // because, in theory, they don't want the same default state set
1465 // as the rest of the scene. This may not be true in practice.
1466 if ( _classicalRenderer ) {
1467 mRealRoot->addChild(_sky->getCloudRoot());
1468 mRealRoot->addChild(FGCreateRedoutNode());
1470 // Attach empty program to the scene root so that shader programs
1471 // don't leak into state sets (effects) that shouldn't have one.
1472 stateSet = mRealRoot->getOrCreateStateSet();
1473 stateSet->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON);
1475 mDeferredRealRoot->addChild( mRealRoot.get() );
1478 void FGRenderer::panelChanged()
1484 osg::Node* n = FGPanelNode::createNode(globals->get_current_panel());
1485 if (panelSwitch->getNumChildren()) {
1486 panelSwitch->setChild(0, n);
1488 panelSwitch->addChild(n);
1492 // Update all Visuals (redraws anything graphics related)
1494 FGRenderer::update( ) {
1495 if (!(_scenery_loaded->getBoolValue() ||
1496 _scenery_override->getBoolValue()))
1498 _splash_alpha->setDoubleValue(1.0);
1501 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1503 if (_splash_alpha->getDoubleValue()>0.0)
1505 // Fade out the splash screen
1506 const double fade_time = 0.5;
1507 const double fade_steps_per_sec = 10;
1508 double delay_time = SGMiscd::min(fade_time/fade_steps_per_sec,
1509 (SGTimeStamp::now() - _splash_time).toSecs());
1510 _splash_time = SGTimeStamp::now();
1511 double sAlpha = _splash_alpha->getDoubleValue();
1512 sAlpha -= SGMiscd::max(0.0,delay_time/fade_time);
1513 FGScenerySwitchCallback::scenery_enabled = (sAlpha<1.0);
1514 _splash_alpha->setDoubleValue((sAlpha < 0) ? 0.0 : sAlpha);
1517 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
1518 if (!_classicalRenderer ) {
1519 _ambientFactor->set( toOsg(l->scene_ambient()) );
1520 _sunDiffuse->set( toOsg(l->scene_diffuse()) );
1521 _sunSpecular->set( toOsg(l->scene_specular()) );
1522 _sunDirection->set( osg::Vec3f(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]) );
1525 // update fog params
1526 double actual_visibility;
1527 if (_cloud_status->getBoolValue()) {
1528 actual_visibility = _sky->get_visibility();
1530 actual_visibility = _visibility_m->getDoubleValue();
1533 // idle_state is now 1000 meaning we've finished all our
1534 // initializations and are running the main loop, so this will
1535 // now work without seg faulting the system.
1537 FGViewer *current__view = globals->get_current_view();
1538 // Force update of center dependent values ...
1539 current__view->set_dirty();
1541 osg::Camera *camera = viewer->getCamera();
1543 bool skyblend = _skyblend->getBoolValue();
1546 if ( _textures->getBoolValue() ) {
1547 SGVec4f clearColor(l->adj_fog_color());
1548 camera->setClearColor(toOsg(clearColor));
1551 SGVec4f clearColor(l->sky_color());
1552 camera->setClearColor(toOsg(clearColor));
1555 // update fog params if visibility has changed
1556 double visibility_meters = _visibility_m->getDoubleValue();
1557 _sky->set_visibility(visibility_meters);
1559 double altitude_m = _altitude_ft->getDoubleValue() * SG_FEET_TO_METER;
1560 _sky->modify_vis( altitude_m, 0.0 /* time factor, now unused */);
1562 // update the sky dome
1565 // The sun and moon distances are scaled down versions
1566 // of the actual distance to get both the moon and the sun
1567 // within the range of the far clip plane.
1568 // Moon distance: 384,467 kilometers
1569 // Sun distance: 150,000,000 kilometers
1571 double sun_horiz_eff, moon_horiz_eff;
1572 if (_horizon_effect->getBoolValue()) {
1574 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
1578 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
1582 sun_horiz_eff = moon_horiz_eff = 1.0;
1586 sstate.pos = current__view->getViewPosition();
1587 sstate.pos_geod = current__view->getPosition();
1588 sstate.ori = current__view->getViewOrientation();
1589 sstate.spin = l->get_sun_rotation();
1590 sstate.gst = globals->get_time_params()->getGst();
1591 sstate.sun_dist = 50000.0 * sun_horiz_eff;
1592 sstate.moon_dist = 40000.0 * moon_horiz_eff;
1593 sstate.sun_angle = l->get_sun_angle();
1596 scolor.sky_color = SGVec3f(l->sky_color().data());
1597 scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
1598 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
1599 scolor.cloud_color = SGVec3f(l->cloud_color().data());
1600 scolor.sun_angle = l->get_sun_angle();
1601 scolor.moon_angle = l->get_moon_angle();
1603 double delta_time_sec = _sim_delta_sec->getDoubleValue();
1604 _sky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
1605 _sky->repaint( scolor, *globals->get_ephem() );
1608 // shadows->setupShadows(
1609 // current__view->getLongitude_deg(),
1610 // current__view->getLatitude_deg(),
1611 // globals->get_time_params()->getGst(),
1612 // globals->get_ephem()->getSunRightAscension(),
1613 // globals->get_ephem()->getSunDeclination(),
1614 // l->get_sun_angle());
1618 // sgEnviro.setLight(l->adj_fog_color());
1619 // sgEnviro.startOfFrame(current__view->get_view_pos(),
1620 // current__view->get_world_up(),
1621 // current__view->getLongitude_deg(),
1622 // current__view->getLatitude_deg(),
1623 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
1627 // sgEnviro.drawLightning();
1629 // double current_view_origin_airspeed_horiz_kt =
1630 // fgGetDouble("/velocities/airspeed-kt", 0.0)
1631 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
1632 // * SGD_DEGREES_TO_RADIANS);
1635 // if( is_internal )
1636 // shadows->endOfFrame();
1638 // need to call the update visitor once
1639 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
1640 mUpdateVisitor->setViewData(current__view->getViewPosition(),
1641 current__view->getViewOrientation());
1642 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
1643 mUpdateVisitor->setLight(direction, l->scene_ambient(),
1644 l->scene_diffuse(), l->scene_specular(),
1646 l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
1647 mUpdateVisitor->setVisibility(actual_visibility);
1648 simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
1649 osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
1650 cullMask |= simgear::GroundLightManager::instance()
1651 ->getLightNodeMask(mUpdateVisitor.get());
1652 if (_panel_hotspots->getBoolValue())
1653 cullMask |= simgear::PICK_BIT;
1654 CameraGroup::getDefault()->setCameraCullMasks(cullMask);
1655 if ( !_classicalRenderer ) {
1656 _fogColor->set( toOsg( l->adj_fog_color() ) );
1657 _fogDensity->set( float( mUpdateVisitor->getFogExp2Density() ) );
1662 FGRenderer::resize( int width, int height )
1664 int curWidth = _xsize->getIntValue(),
1665 curHeight = _ysize->getIntValue();
1666 SG_LOG(SG_VIEW, SG_DEBUG, "FGRenderer::resize: new size " << width << " x " << height);
1667 if ((curHeight != height) || (curWidth != width)) {
1668 // must guard setting these, or PLIB-PUI fails with too many live interfaces
1669 _xsize->setIntValue(width);
1670 _ysize->setIntValue(height);
1675 FGRenderer::pick(std::vector<SGSceneryPick>& pickList,
1676 const osgGA::GUIEventAdapter* ea)
1678 // wipe out the return ...
1680 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
1681 Intersections intersections;
1683 if (!computeIntersections(CameraGroup::getDefault(), ea, intersections))
1685 for (Intersections::iterator hit = intersections.begin(),
1686 e = intersections.end();
1689 const osg::NodePath& np = hit->nodePath;
1690 osg::NodePath::const_reverse_iterator npi;
1691 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
1692 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
1695 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
1696 SGPickCallback* pickCallback = ud->getPickCallback(i);
1699 SGSceneryPick sceneryPick;
1700 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
1701 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
1702 sceneryPick.callback = pickCallback;
1703 pickList.push_back(sceneryPick);
1707 return !pickList.empty();
1711 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
1717 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
1719 eventHandler = eventHandler_;
1723 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
1725 mRealRoot->addChild(camera);
1729 FGRenderer::removeCamera(osg::Camera* camera)
1731 mRealRoot->removeChild(camera);
1735 FGRenderer::setPlanes( double zNear, double zFar )
1737 _planes->set( osg::Vec3f( - zFar, - zFar * zNear, zFar - zNear ) );
1741 fgDumpSceneGraphToFile(const char* filename)
1743 return osgDB::writeNodeFile(*mRealRoot.get(), filename);
1747 fgDumpTerrainBranchToFile(const char* filename)
1749 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
1755 fgDumpNodeToFile(osg::Node* node, const char* filename)
1757 return osgDB::writeNodeFile(*node, filename);
1760 namespace flightgear
1762 using namespace osg;
1764 class VisibleSceneInfoVistor : public NodeVisitor, CullStack
1767 VisibleSceneInfoVistor()
1768 : NodeVisitor(CULL_VISITOR, TRAVERSE_ACTIVE_CHILDREN)
1770 setCullingMode(CullSettings::SMALL_FEATURE_CULLING
1771 | CullSettings::VIEW_FRUSTUM_CULLING);
1772 setComputeNearFarMode(CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1775 VisibleSceneInfoVistor(const VisibleSceneInfoVistor& rhs)
1779 META_NodeVisitor("flightgear","VisibleSceneInfoVistor")
1781 typedef std::map<const std::string,int> InfoMap;
1783 void getNodeInfo(Node* node)
1785 const char* typeName = typeid(*node).name();
1786 classInfo[typeName]++;
1787 const std::string& nodeName = node->getName();
1788 if (!nodeName.empty())
1789 nodeInfo[nodeName]++;
1794 using namespace std;
1795 typedef vector<InfoMap::iterator> FreqVector;
1796 cout << "class info:\n";
1798 for (InfoMap::iterator itr = classInfo.begin(), end = classInfo.end();
1801 classes.push_back(itr);
1802 sort(classes.begin(), classes.end(), freqComp);
1803 for (FreqVector::iterator itr = classes.begin(), end = classes.end();
1806 cout << (*itr)->first << " " << (*itr)->second << "\n";
1808 cout << "\nnode info:\n";
1810 for (InfoMap::iterator itr = nodeInfo.begin(), end = nodeInfo.end();
1813 nodes.push_back(itr);
1815 sort (nodes.begin(), nodes.end(), freqComp);
1816 for (FreqVector::iterator itr = nodes.begin(), end = nodes.end();
1819 cout << (*itr)->first << " " << (*itr)->second << "\n";
1824 void doTraversal(Camera* camera, Node* root, Viewport* viewport)
1826 ref_ptr<RefMatrix> projection
1827 = createOrReuseMatrix(camera->getProjectionMatrix());
1828 ref_ptr<RefMatrix> mv = createOrReuseMatrix(camera->getViewMatrix());
1830 viewport = camera->getViewport();
1832 pushViewport(viewport);
1833 pushProjectionMatrix(projection.get());
1834 pushModelViewMatrix(mv.get(), Transform::ABSOLUTE_RF);
1835 root->accept(*this);
1836 popModelViewMatrix();
1837 popProjectionMatrix();
1843 void apply(Node& node)
1852 void apply(Group& node)
1862 void apply(Transform& node)
1867 ref_ptr<RefMatrix> matrix = createOrReuseMatrix(*getModelViewMatrix());
1868 node.computeLocalToWorldMatrix(*matrix,this);
1869 pushModelViewMatrix(matrix.get(), node.getReferenceFrame());
1872 popModelViewMatrix();
1876 void apply(Camera& camera)
1878 // Save current cull settings
1879 CullSettings saved_cull_settings(*this);
1881 // set cull settings from this Camera
1882 setCullSettings(camera);
1883 // inherit the settings from above
1884 inheritCullSettings(saved_cull_settings, camera.getInheritanceMask());
1886 // set the cull mask.
1887 unsigned int savedTraversalMask = getTraversalMask();
1888 bool mustSetCullMask = (camera.getInheritanceMask()
1889 & osg::CullSettings::CULL_MASK) == 0;
1890 if (mustSetCullMask)
1891 setTraversalMask(camera.getCullMask());
1893 osg::RefMatrix* projection = 0;
1894 osg::RefMatrix* modelview = 0;
1896 if (camera.getReferenceFrame()==osg::Transform::RELATIVE_RF) {
1897 if (camera.getTransformOrder()==osg::Camera::POST_MULTIPLY) {
1898 projection = createOrReuseMatrix(*getProjectionMatrix()
1899 *camera.getProjectionMatrix());
1900 modelview = createOrReuseMatrix(*getModelViewMatrix()
1901 * camera.getViewMatrix());
1903 else { // pre multiply
1904 projection = createOrReuseMatrix(camera.getProjectionMatrix()
1905 * (*getProjectionMatrix()));
1906 modelview = createOrReuseMatrix(camera.getViewMatrix()
1907 * (*getModelViewMatrix()));
1910 // an absolute reference frame
1911 projection = createOrReuseMatrix(camera.getProjectionMatrix());
1912 modelview = createOrReuseMatrix(camera.getViewMatrix());
1914 if (camera.getViewport())
1915 pushViewport(camera.getViewport());
1917 pushProjectionMatrix(projection);
1918 pushModelViewMatrix(modelview, camera.getReferenceFrame());
1922 // restore the previous model view matrix.
1923 popModelViewMatrix();
1925 // restore the previous model view matrix.
1926 popProjectionMatrix();
1928 if (camera.getViewport()) popViewport();
1930 // restore the previous traversal mask settings
1931 if (mustSetCullMask)
1932 setTraversalMask(savedTraversalMask);
1934 // restore the previous cull settings
1935 setCullSettings(saved_cull_settings);
1940 static bool freqComp(const InfoMap::iterator& lhs, const InfoMap::iterator& rhs)
1942 return lhs->second > rhs->second;
1948 bool printVisibleSceneInfo(FGRenderer* renderer)
1950 osgViewer::Viewer* viewer = renderer->getViewer();
1951 VisibleSceneInfoVistor vsv;
1953 if (!viewer->getCamera()->getViewport() && viewer->getNumSlaves() > 0) {
1954 const View::Slave& slave = viewer->getSlave(0);
1955 vp = slave._camera->getViewport();
1957 vsv.doTraversal(viewer->getCamera(), viewer->getSceneData(), vp);
1962 // end of renderer.cxx