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 <boost/foreach.hpp>
40 #include <osg/ref_ptr>
41 #include <osg/AlphaFunc>
42 #include <osg/BlendFunc>
44 #include <osg/CullFace>
45 #include <osg/CullStack>
51 #include <osg/LightModel>
52 #include <osg/LightSource>
53 #include <osg/Material>
55 #include <osg/NodeCallback>
57 #include <osg/PolygonMode>
58 #include <osg/PolygonOffset>
59 #include <osg/Program>
60 #include <osg/Version>
63 #include <osgUtil/LineSegmentIntersector>
65 #include <osg/io_utils>
66 #include <osgDB/WriteFile>
67 #include <osgViewer/Renderer>
69 #include <simgear/scene/material/matlib.hxx>
70 #include <simgear/scene/material/EffectCullVisitor.hxx>
71 #include <simgear/scene/material/Effect.hxx>
72 #include <simgear/scene/material/EffectGeode.hxx>
73 #include <simgear/scene/material/EffectBuilder.hxx>
74 #include <simgear/scene/model/animation.hxx>
75 #include <simgear/scene/model/placement.hxx>
76 #include <simgear/scene/sky/sky.hxx>
77 #include <simgear/scene/util/SGUpdateVisitor.hxx>
78 #include <simgear/scene/util/RenderConstants.hxx>
79 #include <simgear/scene/util/SGSceneUserData.hxx>
80 #include <simgear/scene/tgdb/GroundLightManager.hxx>
81 #include <simgear/scene/tgdb/pt_lights.hxx>
82 #include <simgear/structure/OSGUtils.hxx>
83 #include <simgear/props/props.hxx>
84 #include <simgear/timing/sg_time.hxx>
85 #include <simgear/ephemeris/ephemeris.hxx>
86 #include <simgear/math/sg_random.h>
88 #include <simgear/screen/jpgfactory.hxx>
91 #include <Time/light.hxx>
92 #include <Time/light.hxx>
93 #include <Cockpit/panel.hxx>
95 #include <Model/panelnode.hxx>
96 #include <Model/modelmgr.hxx>
97 #include <Model/acmodel.hxx>
98 #include <Scenery/scenery.hxx>
99 #include <Scenery/redout.hxx>
100 #include <GUI/new_gui.hxx>
101 #include <Instrumentation/HUD/HUD.hxx>
102 #include <Environment/precipitation_mgr.hxx>
103 #include <Environment/environment_mgr.hxx>
105 //#include <Main/main.hxx>
106 #include "viewer.hxx"
107 #include "viewmgr.hxx"
108 #include "splash.hxx"
109 #include "renderer.hxx"
110 #include "CameraGroup.hxx"
111 #include "FGEventHandler.hxx"
114 using namespace simgear;
115 using namespace flightgear;
117 class FGHintUpdateCallback : public osg::StateAttribute::Callback {
119 FGHintUpdateCallback(const char* configNode) :
120 mConfigNode(fgGetNode(configNode, true))
122 virtual void operator()(osg::StateAttribute* stateAttribute,
125 assert(dynamic_cast<osg::Hint*>(stateAttribute));
126 osg::Hint* hint = static_cast<osg::Hint*>(stateAttribute);
128 const char* value = mConfigNode->getStringValue();
130 hint->setMode(GL_DONT_CARE);
131 else if (0 == strcmp(value, "nicest"))
132 hint->setMode(GL_NICEST);
133 else if (0 == strcmp(value, "fastest"))
134 hint->setMode(GL_FASTEST);
136 hint->setMode(GL_DONT_CARE);
139 SGPropertyNode_ptr mConfigNode;
143 class SGPuDrawable : public osg::Drawable {
147 // Dynamic stuff, do not store geometry
148 setUseDisplayList(false);
149 setDataVariance(Object::DYNAMIC);
151 osg::StateSet* stateSet = getOrCreateStateSet();
152 stateSet->setRenderBinDetails(1001, "RenderBin");
153 // speed optimization?
154 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
155 // We can do translucent menus, so why not. :-)
156 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
157 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
158 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
160 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
162 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
163 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
165 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
166 { drawImplementation(*renderInfo.getState()); }
167 void drawImplementation(osg::State& state) const
169 state.setActiveTextureUnit(0);
170 state.setClientActiveTextureUnit(0);
172 state.disableAllVertexArrays();
174 glPushAttrib(GL_ALL_ATTRIB_BITS);
175 glPushClientAttrib(~0u);
183 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
184 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
189 class SGHUDDrawable : public osg::Drawable {
193 // Dynamic stuff, do not store geometry
194 setUseDisplayList(false);
195 setDataVariance(Object::DYNAMIC);
197 osg::StateSet* stateSet = getOrCreateStateSet();
198 stateSet->setRenderBinDetails(1000, "RenderBin");
200 // speed optimization?
201 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
202 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
203 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
204 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
205 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
207 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
209 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
210 { drawImplementation(*renderInfo.getState()); }
211 void drawImplementation(osg::State& state) const
213 state.setActiveTextureUnit(0);
214 state.setClientActiveTextureUnit(0);
215 state.disableAllVertexArrays();
217 glPushAttrib(GL_ALL_ATTRIB_BITS);
218 glPushClientAttrib(~0u);
220 HUD *hud = static_cast<HUD*>(globals->get_subsystem("hud"));
227 virtual osg::Object* cloneType() const { return new SGHUDDrawable; }
228 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDDrawable; }
233 class FGLightSourceUpdateCallback : public osg::NodeCallback {
237 * @param isSun true if the light is the actual sun i.e., for
238 * illuminating the moon.
240 FGLightSourceUpdateCallback(bool isSun = false) : _isSun(isSun) {}
241 FGLightSourceUpdateCallback(const FGLightSourceUpdateCallback& nc,
243 : NodeCallback(nc, op), _isSun(nc._isSun)
245 META_Object(flightgear,FGLightSourceUpdateCallback);
247 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
249 assert(dynamic_cast<osg::LightSource*>(node));
250 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
251 osg::Light* light = lightSource->getLight();
253 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
255 light->setAmbient(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
256 light->setDiffuse(Vec4(1.0f, 1.0f, 1.0f, 1.0f));
257 light->setSpecular(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
259 light->setAmbient(toOsg(l->scene_ambient()));
260 light->setDiffuse(toOsg(l->scene_diffuse()));
261 light->setSpecular(toOsg(l->scene_specular()));
263 osg::Vec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
264 light->setPosition(position);
272 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
274 FGWireFrameModeUpdateCallback() :
275 mWireframe(fgGetNode("/sim/rendering/wireframe", true))
277 virtual void operator()(osg::StateAttribute* stateAttribute,
280 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
281 osg::PolygonMode* polygonMode;
282 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
284 if (mWireframe->getBoolValue())
285 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
286 osg::PolygonMode::LINE);
288 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
289 osg::PolygonMode::FILL);
292 SGPropertyNode_ptr mWireframe;
295 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
297 FGLightModelUpdateCallback() :
298 mHighlights(fgGetNode("/sim/rendering/specular-highlight", true))
300 virtual void operator()(osg::StateAttribute* stateAttribute,
303 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
304 osg::LightModel* lightModel;
305 lightModel = static_cast<osg::LightModel*>(stateAttribute);
308 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
309 lightModel->setAmbientIntensity(toOsg(l->scene_ambient());
311 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
313 lightModel->setTwoSided(true);
314 lightModel->setLocalViewer(false);
316 if (mHighlights->getBoolValue()) {
317 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
319 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
323 SGPropertyNode_ptr mHighlights;
326 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
328 FGFogEnableUpdateCallback() :
329 mFogEnabled(fgGetNode("/sim/rendering/fog", true))
331 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
333 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
334 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
336 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
340 SGPropertyNode_ptr mFogEnabled;
343 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
345 virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
347 assert(dynamic_cast<SGUpdateVisitor*>(nv));
348 assert(dynamic_cast<osg::Fog*>(sa));
349 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
350 osg::Fog* fog = static_cast<osg::Fog*>(sa);
351 fog->setMode(osg::Fog::EXP2);
352 fog->setColor(toOsg(updateVisitor->getFogColor()));
353 fog->setDensity(updateVisitor->getFogExp2Density());
357 // update callback for the switch node guarding that splash
358 class FGScenerySwitchCallback : public osg::NodeCallback {
360 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
362 assert(dynamic_cast<osg::Switch*>(node));
363 osg::Switch* sw = static_cast<osg::Switch*>(node);
365 bool enabled = scenery_enabled;
366 sw->setValue(0, enabled);
372 static bool scenery_enabled;
375 bool FGScenerySwitchCallback::scenery_enabled = false;
377 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
378 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
380 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
381 static osg::ref_ptr<osg::Group> mDeferredRealRoot = new osg::Group;
383 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
385 static osg::ref_ptr<osg::Switch> panelSwitch;
388 // update callback for the switch node controlling the 2D panel
389 class FGPanelSwitchCallback : public osg::NodeCallback {
391 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
393 assert(dynamic_cast<osg::Switch*>(node));
394 osg::Switch* sw = static_cast<osg::Switch*>(node);
396 bool enabled = fgPanelVisible();
397 sw->setValue(0, enabled);
404 #ifdef FG_JPEG_SERVER
405 static void updateRenderer()
407 globals->get_renderer()->update();
411 FGRenderer::FGRenderer() :
413 _ambientFactor( new osg::Uniform( "fg_SunAmbientColor", osg::Vec4f() ) ),
414 _sunDiffuse( new osg::Uniform( "fg_SunDiffuseColor", osg::Vec4f() ) ),
415 _sunSpecular( new osg::Uniform( "fg_SunSpecularColor", osg::Vec4f() ) ),
416 _sunDirection( new osg::Uniform( "fg_SunDirection", osg::Vec3f() ) ),
417 _planes( new osg::Uniform( "fg_Planes", osg::Vec3f() ) ),
418 _fogColor( new osg::Uniform( "fg_FogColor", osg::Vec4f(1.0, 1.0, 1.0, 1.0) ) ),
419 _fogDensity( new osg::Uniform( "fg_FogDensity", 0.0001f ) ),
420 _shadowNumber( new osg::Uniform( "fg_ShadowNumber", (int)4 ) ),
421 _shadowDistances( new osg::Uniform( "fg_ShadowDistances", osg::Vec4f(5.0, 50.0, 500.0, 5000.0 ) ) ),
422 _depthInColor( new osg::Uniform( "fg_DepthInColor", false ) )
424 #ifdef FG_JPEG_SERVER
425 jpgRenderFrame = updateRenderer;
427 eventHandler = new FGEventHandler;
430 _cascadeFar[0] = 5.f;
431 _cascadeFar[1] = 50.f;
432 _cascadeFar[2] = 500.f;
433 _cascadeFar[3] = 5000.f;
436 FGRenderer::~FGRenderer()
438 #ifdef FG_JPEG_SERVER
439 jpgRenderFrame = NULL;
444 // Initialize various GL/view parameters
445 // XXX This should be called "preinit" or something, as it initializes
446 // critical parts of the scene graph in addition to the splash screen.
448 FGRenderer::splashinit( void ) {
449 osgViewer::Viewer* viewer = getViewer();
450 mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
451 ref_ptr<Node> splashNode = fgCreateSplashNode();
452 if (_classicalRenderer) {
453 mRealRoot->addChild(splashNode.get());
455 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
456 ii != CameraGroup::getDefault()->camerasEnd();
459 CameraInfo* info = ii->get();
460 Camera* camera = info->getCamera(DISPLAY_CAMERA);
461 if (camera == 0) continue;
463 camera->addChild(splashNode.get());
466 mFrameStamp = viewer->getFrameStamp();
467 // Scene doesn't seem to pass the frame stamp to the update
468 // visitor automatically.
469 mUpdateVisitor->setFrameStamp(mFrameStamp.get());
470 viewer->setUpdateVisitor(mUpdateVisitor.get());
471 fgSetDouble("/sim/startup/splash-alpha", 1.0);
474 class ShadowMapSizeListener : public SGPropertyChangeListener {
476 virtual void valueChanged(SGPropertyNode* node) {
477 globals->get_renderer()->updateShadowMapSize(node->getIntValue());
481 class ShadowEnabledListener : public SGPropertyChangeListener {
483 virtual void valueChanged(SGPropertyNode* node) {
484 globals->get_renderer()->enableShadows(node->getBoolValue());
488 class ShadowNumListener : public SGPropertyChangeListener {
490 virtual void valueChanged(SGPropertyNode* node) {
491 globals->get_renderer()->updateCascadeNumber(node->getIntValue());
495 class ShadowRangeListener : public SGPropertyChangeListener {
497 virtual void valueChanged(SGPropertyNode* node) {
498 globals->get_renderer()->updateCascadeFar(node->getIndex(), node->getFloatValue());
503 FGRenderer::init( void )
505 _classicalRenderer = !fgGetBool("/sim/rendering/rembrandt/enabled", false);
506 _shadowMapSize = fgGetInt( "/sim/rendering/shadows/map-size", 4096 );
507 fgAddChangeListener( new ShadowMapSizeListener, "/sim/rendering/shadows/map-size" );
508 fgAddChangeListener( new ShadowEnabledListener, "/sim/rendering/shadows/enabled" );
509 ShadowRangeListener* srl = new ShadowRangeListener;
510 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[0]");
511 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[1]");
512 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[2]");
513 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[3]");
514 fgAddChangeListener(new ShadowNumListener, "/sim/rendering/shadows/num-cascades");
515 _numCascades = fgGetInt("/sim/rendering/shadows/num-cascades", 4);
516 _cascadeFar[0] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[0]", 5.0f);
517 _cascadeFar[1] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[1]", 50.0f);
518 _cascadeFar[2] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[2]", 500.0f);
519 _cascadeFar[3] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[3]", 5000.0f);
520 updateCascadeNumber(_numCascades);
521 updateCascadeFar(0, _cascadeFar[0]);
522 updateCascadeFar(1, _cascadeFar[1]);
523 updateCascadeFar(2, _cascadeFar[2]);
524 updateCascadeFar(3, _cascadeFar[3]);
525 _useColorForDepth = fgGetBool( "/sim/rendering/rembrandt/use-color-for-depth", false );
526 _depthInColor->set( _useColorForDepth );
528 _renderer = fgGetString("/sim/rendering/rembrandt/renderer", "");
529 if (!_classicalRenderer && !_renderer.empty())
530 _pipeline = makeRenderingPipeline(_renderer, 0);
531 _scenery_loaded = fgGetNode("/sim/sceneryloaded", true);
532 _scenery_override = fgGetNode("/sim/sceneryloaded-override", true);
533 _panel_hotspots = fgGetNode("/sim/panel-hotspots", true);
534 _virtual_cockpit = fgGetNode("/sim/virtual-cockpit", true);
536 _sim_delta_sec = fgGetNode("/sim/time/delta-sec", true);
538 _xsize = fgGetNode("/sim/startup/xsize", true);
539 _ysize = fgGetNode("/sim/startup/ysize", true);
540 _splash_alpha = fgGetNode("/sim/startup/splash-alpha", true);
542 _skyblend = fgGetNode("/sim/rendering/skyblend", true);
543 _point_sprites = fgGetNode("/sim/rendering/point-sprites", true);
544 _enhanced_lighting = fgGetNode("/sim/rendering/enhanced-lighting", true);
545 _distance_attenuation = fgGetNode("/sim/rendering/distance-attenuation", true);
546 _horizon_effect = fgGetNode("/sim/rendering/horizon-effect", true);
547 _textures = fgGetNode("/sim/rendering/textures", true);
549 _altitude_ft = fgGetNode("/position/altitude-ft", true);
551 _cloud_status = fgGetNode("/environment/clouds/status", true);
552 _visibility_m = fgGetNode("/environment/visibility-m", true);
554 bool use_point_sprites = _point_sprites->getBoolValue();
555 bool enhanced_lighting = _enhanced_lighting->getBoolValue();
556 bool distance_attenuation = _distance_attenuation->getBoolValue();
558 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
559 distance_attenuation );
561 if (const char* tc = fgGetString("/sim/rendering/texture-compression", NULL)) {
562 if (strcmp(tc, "false") == 0 || strcmp(tc, "off") == 0 ||
563 strcmp(tc, "0") == 0 || strcmp(tc, "no") == 0 ||
564 strcmp(tc, "none") == 0) {
565 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::DoNotUseCompression);
566 } else if (strcmp(tc, "arb") == 0) {
567 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseARBCompression);
568 } else if (strcmp(tc, "dxt1") == 0) {
569 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT1Compression);
570 } else if (strcmp(tc, "dxt3") == 0) {
571 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT3Compression);
572 } else if (strcmp(tc, "dxt5") == 0) {
573 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT5Compression);
575 SG_LOG(SG_VIEW, SG_WARN, "Unknown texture compression setting!");
579 // create sky, but can't build until setupView, since we depend
580 // on other subsystems to be inited, eg Ephemeris
583 SGPath texture_path(globals->get_fg_root());
584 texture_path.append("Textures");
585 texture_path.append("Sky");
586 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
587 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
588 _sky->add_cloud_layer(layer);
591 _sky->texture_path( texture_path.str() );
593 if (!_classicalRenderer) {
594 eventHandler->setChangeStatsCameraRenderOrder( true );
598 void installCullVisitor(Camera* camera)
600 osgViewer::Renderer* renderer
601 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
602 for (int i = 0; i < 2; ++i) {
603 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
604 #if SG_OSG_VERSION_LESS_THAN(3,0,0)
605 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
607 osg::ref_ptr<osgUtil::CullVisitor::Identifier> identifier;
608 identifier = sceneView->getCullVisitor()->getIdentifier();
609 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
610 sceneView->getCullVisitor()->setIdentifier(identifier.get());
612 identifier = sceneView->getCullVisitorLeft()->getIdentifier();
613 sceneView->setCullVisitorLeft(sceneView->getCullVisitor()->clone());
614 sceneView->getCullVisitorLeft()->setIdentifier(identifier.get());
616 identifier = sceneView->getCullVisitorRight()->getIdentifier();
617 sceneView->setCullVisitorRight(sceneView->getCullVisitor()->clone());
618 sceneView->getCullVisitorRight()->setIdentifier(identifier.get());
624 FGRenderer::buildRenderingPipeline(CameraGroup* cgroup, unsigned flags, Camera* camera,
626 const Matrix& projection,
627 osg::GraphicsContext* gc,
628 bool useMasterSceneData)
630 CameraInfo* info = 0;
631 if (!_classicalRenderer && (flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
632 info = buildDeferredPipeline( cgroup, flags, camera, view, projection, gc );
637 if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
638 _classicalRenderer = true;
639 return buildClassicalPipeline( cgroup, flags, camera, view, projection, useMasterSceneData );
644 FGRenderer::buildClassicalPipeline(CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
645 const osg::Matrix& view,
646 const osg::Matrix& projection,
647 bool useMasterSceneData)
649 CameraInfo* info = new CameraInfo(flags);
650 // The camera group will always update the camera
651 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
653 Camera* farCamera = 0;
654 if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0) {
655 farCamera = new Camera;
656 farCamera->setAllowEventFocus(camera->getAllowEventFocus());
657 farCamera->setGraphicsContext(camera->getGraphicsContext());
658 farCamera->setCullingMode(camera->getCullingMode());
659 farCamera->setInheritanceMask(camera->getInheritanceMask());
660 farCamera->setReferenceFrame(Transform::ABSOLUTE_RF);
661 // Each camera's viewport is written when the window is
662 // resized; if the the viewport isn't copied here, it gets updated
663 // twice and ends up with the wrong value.
664 farCamera->setViewport(simgear::clone(camera->getViewport()));
665 farCamera->setDrawBuffer(camera->getDrawBuffer());
666 farCamera->setReadBuffer(camera->getReadBuffer());
667 farCamera->setRenderTargetImplementation(
668 camera->getRenderTargetImplementation());
669 const Camera::BufferAttachmentMap& bufferMap
670 = camera->getBufferAttachmentMap();
671 if (bufferMap.count(Camera::COLOR_BUFFER) != 0) {
673 Camera::COLOR_BUFFER,
674 bufferMap.find(Camera::COLOR_BUFFER)->second._texture.get());
676 cgroup->getViewer()->addSlave(farCamera, projection, view, useMasterSceneData);
677 installCullVisitor(farCamera);
678 int farSlaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
679 info->addCamera( FAR_CAMERA, farCamera, farSlaveIndex );
680 farCamera->setRenderOrder(Camera::POST_RENDER, farSlaveIndex);
681 camera->setCullMask(camera->getCullMask() & ~simgear::BACKGROUND_BIT);
682 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
684 cgroup->getViewer()->addSlave(camera, projection, view, useMasterSceneData);
685 installCullVisitor(camera);
686 int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
687 info->addCamera( MAIN_CAMERA, camera, slaveIndex );
688 camera->setRenderOrder(Camera::POST_RENDER, slaveIndex);
689 cgroup->addCamera(info);
693 class FGDeferredRenderingCameraCullCallback : public osg::NodeCallback {
695 FGDeferredRenderingCameraCullCallback( const std::string& k, CameraInfo* i ) : kind( k ), info( i ) {}
696 virtual void operator()( osg::Node *n, osg::NodeVisitor *nv) {
697 simgear::EffectCullVisitor* cv = dynamic_cast<simgear::EffectCullVisitor*>(nv);
698 osg::Camera* camera = static_cast<osg::Camera*>(n);
700 cv->clearBufferList();
701 for (RenderBufferMap::iterator ii = info->buffers.begin(); ii != info->buffers.end(); ++ii) {
702 cv->addBuffer(ii->first, ii->second.texture);
705 if ( !info->getRenderStageInfo(kind).fullscreen )
706 info->setMatrices( camera );
708 cv->traverse( *camera );
710 if ( kind == GEOMETRY_CAMERA ) {
711 // Save transparent bins to render later
712 osgUtil::RenderStage* renderStage = cv->getRenderStage();
713 osgUtil::RenderBin::RenderBinList& rbl = renderStage->getRenderBinList();
714 for (osgUtil::RenderBin::RenderBinList::iterator rbi = rbl.begin(); rbi != rbl.end(); ) {
715 if (rbi->second->getSortMode() == osgUtil::RenderBin::SORT_BACK_TO_FRONT) {
716 info->savedTransparentBins.insert( std::make_pair( rbi->first, rbi->second ) );
722 } else if ( kind == LIGHTING_CAMERA ) {
723 osg::ref_ptr<osg::Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
724 if (mainShadowCamera.valid()) {
725 osg::Switch* grp = mainShadowCamera->getChild(0)->asSwitch();
726 for (int i = 0; i < 4; ++i ) {
727 if (!grp->getValue(i))
729 osg::TexGen* shadowTexGen = info->shadowTexGen[i];
730 shadowTexGen->setMode(osg::TexGen::EYE_LINEAR);
732 osg::Camera* cascadeCam = static_cast<osg::Camera*>( grp->getChild(i) );
733 // compute the matrix which takes a vertex from view coords into tex coords
734 shadowTexGen->setPlanesFromMatrix( cascadeCam->getProjectionMatrix() *
735 osg::Matrix::translate(1.0,1.0,1.0) *
736 osg::Matrix::scale(0.5f,0.5f,0.5f) );
738 osg::RefMatrix * refMatrix = new osg::RefMatrix( cascadeCam->getInverseViewMatrix() * *cv->getModelViewMatrix() );
740 cv->getRenderStage()->getPositionalStateContainer()->addPositionedTextureAttribute( i+1, refMatrix, shadowTexGen );
743 // Render saved transparent render bins
744 osgUtil::RenderStage* renderStage = cv->getRenderStage();
745 osgUtil::RenderBin::RenderBinList& rbl = renderStage->getRenderBinList();
746 for (osgUtil::RenderBin::RenderBinList::iterator rbi = info->savedTransparentBins.begin(); rbi != info->savedTransparentBins.end(); ++rbi ){
747 rbl.insert( std::make_pair( rbi->first + 10000, rbi->second ) );
749 info->savedTransparentBins.clear();
758 osg::Texture2D* buildDeferredBuffer(GLint internalFormat, GLenum sourceFormat, GLenum sourceType, GLenum wrapMode, bool shadowComparison = false)
760 osg::Texture2D* tex = new osg::Texture2D;
761 tex->setResizeNonPowerOfTwoHint( false );
762 tex->setInternalFormat( internalFormat );
763 tex->setShadowComparison(shadowComparison);
764 if (shadowComparison) {
765 tex->setShadowTextureMode(osg::Texture2D::LUMINANCE);
766 tex->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
768 tex->setSourceFormat(sourceFormat);
769 tex->setSourceType(sourceType);
770 tex->setFilter( osg::Texture2D::MIN_FILTER, osg::Texture2D::LINEAR );
771 tex->setFilter( osg::Texture2D::MAG_FILTER, osg::Texture2D::LINEAR );
772 tex->setWrap( osg::Texture::WRAP_S, (osg::Texture::WrapMode)wrapMode );
773 tex->setWrap( osg::Texture::WRAP_T, (osg::Texture::WrapMode)wrapMode );
777 void buildDefaultDeferredBuffers( CameraInfo* info, int shadowMapSize, bool useColorForDepth )
779 if (useColorForDepth) {
780 info->addBuffer("real-depth", buildDeferredBuffer( GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_FLOAT, osg::Texture::CLAMP_TO_BORDER) );
781 info->addBuffer("depth", buildDeferredBuffer( GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, osg::Texture::CLAMP_TO_BORDER) );
784 info->addBuffer("depth", buildDeferredBuffer( GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_FLOAT, osg::Texture::CLAMP_TO_BORDER) );
786 info->addBuffer("normal", buildDeferredBuffer( GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, osg::Texture::CLAMP_TO_BORDER) );
787 info->addBuffer("diffuse", buildDeferredBuffer( GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, osg::Texture::CLAMP_TO_BORDER) );
788 info->addBuffer("spec-emis", buildDeferredBuffer( GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, osg::Texture::CLAMP_TO_BORDER) );
789 info->addBuffer("lighting", buildDeferredBuffer( GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, osg::Texture::CLAMP_TO_BORDER) );
790 info->addBuffer("shadow", buildDeferredBuffer( GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_FLOAT, osg::Texture::CLAMP_TO_BORDER, true), 0.0f );
791 info->getBuffer("shadow")->setTextureSize(shadowMapSize,shadowMapSize);
794 void attachBufferToCamera( CameraInfo* info, osg::Camera* camera, osg::Camera::BufferComponent c, const std::string& ck, const std::string& bk )
796 camera->attach( c, info->getBuffer(bk) );
797 info->getRenderStageInfo(ck).buffers.insert( std::make_pair( c, bk ) );
800 osg::Camera* FGRenderer::buildDefaultDeferredGeometryCamera( CameraInfo* info, osg::GraphicsContext* gc )
802 std::vector<ref_ptr<FGRenderingPipeline::Attachment> > attachments;
803 if (_useColorForDepth) {
804 attachments.push_back(new FGRenderingPipeline::Attachment(osg::Camera::DEPTH_BUFFER, "real-depth") );
805 attachments.push_back(new FGRenderingPipeline::Attachment(osg::Camera::COLOR_BUFFER3, "depth") );
807 attachments.push_back(new FGRenderingPipeline::Attachment(osg::Camera::DEPTH_BUFFER, "depth") );
809 attachments.push_back(new FGRenderingPipeline::Attachment(osg::Camera::COLOR_BUFFER0, "normal") );
810 attachments.push_back(new FGRenderingPipeline::Attachment(osg::Camera::COLOR_BUFFER1, "diffuse") );
811 attachments.push_back(new FGRenderingPipeline::Attachment(osg::Camera::COLOR_BUFFER2, "spec-emis") );
812 return buildDeferredGeometryCamera(info, gc, GEOMETRY_CAMERA, attachments);
815 osg::Camera* FGRenderer::buildDeferredGeometryCamera( CameraInfo* info, osg::GraphicsContext* gc, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
817 osg::Camera* camera = new osg::Camera;
818 info->addCamera(name, camera );
820 camera->setCullMask( ~simgear::MODELLIGHT_BIT );
821 camera->setName( "GeometryC" );
822 camera->setGraphicsContext( gc );
823 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( name, info ) );
824 camera->setClearMask( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
825 camera->setClearColor( osg::Vec4( 0., 0., 0., 0. ) );
826 camera->setClearDepth( 1.0 );
827 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
828 camera->setViewport( new osg::Viewport );
829 BOOST_FOREACH(ref_ptr<FGRenderingPipeline::Attachment> attachment, attachments) {
830 attachBufferToCamera( info, camera, attachment->component, name, attachment->buffer );
832 camera->setDrawBuffer(GL_FRONT);
833 camera->setReadBuffer(GL_FRONT);
835 osg::StateSet* ss = camera->getOrCreateStateSet();
836 ss->addUniform( _depthInColor );
838 camera->addChild( mDeferredRealRoot.get() );
843 static void setShadowCascadeStateSet( osg::Camera* cam ) {
844 osg::StateSet* ss = cam->getOrCreateStateSet();
845 ss->setAttribute( new osg::PolygonOffset( 1.1f, 5.0f ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
846 ss->setMode( GL_POLYGON_OFFSET_FILL, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
847 ss->setRenderBinDetails( 0, "RenderBin", osg::StateSet::OVERRIDE_RENDERBIN_DETAILS );
848 ss->setAttributeAndModes( new osg::AlphaFunc( osg::AlphaFunc::GREATER, 0.05 ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
849 ss->setAttributeAndModes( new osg::ColorMask( false, false, false, false ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
850 ss->setAttributeAndModes( new osg::CullFace( osg::CullFace::FRONT ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
851 osg::Program* program = new osg::Program;
852 ss->setAttribute( program, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
853 ss->setMode( GL_LIGHTING, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
854 ss->setMode( GL_BLEND, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
855 //ss->setTextureMode( 0, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
856 ss->setTextureMode( 0, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
857 ss->setTextureMode( 1, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
858 ss->setTextureMode( 1, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
859 ss->setTextureMode( 2, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
860 ss->setTextureMode( 2, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
863 static osg::Camera* createShadowCascadeCamera( int no, int cascadeSize ) {
864 osg::Camera* cascadeCam = new osg::Camera;
865 setShadowCascadeStateSet( cascadeCam );
867 std::ostringstream oss;
868 oss << "CascadeCamera" << (no + 1);
869 cascadeCam->setName( oss.str() );
870 cascadeCam->setClearMask(0);
871 cascadeCam->setCullMask(~( simgear::MODELLIGHT_BIT /* | simgear::NO_SHADOW_BIT */ ) );
872 cascadeCam->setCullingMode( cascadeCam->getCullingMode() & ~osg::CullSettings::SMALL_FEATURE_CULLING );
873 cascadeCam->setAllowEventFocus(false);
874 cascadeCam->setReferenceFrame(osg::Transform::ABSOLUTE_RF_INHERIT_VIEWPOINT);
875 cascadeCam->setRenderOrder(osg::Camera::NESTED_RENDER);
876 cascadeCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
877 cascadeCam->setViewport( int( no / 2 ) * cascadeSize, (no & 1) * cascadeSize, cascadeSize, cascadeSize );
881 osg::Camera* FGRenderer::buildDefaultDeferredShadowCamera( CameraInfo* info, osg::GraphicsContext* gc )
883 std::vector<ref_ptr<FGRenderingPipeline::Attachment> > attachments;
884 attachments.push_back(new FGRenderingPipeline::Attachment(osg::Camera::DEPTH_BUFFER, "shadow") );
885 return buildDeferredShadowCamera(info, gc, SHADOW_CAMERA, attachments);
888 osg::Camera* FGRenderer::buildDeferredShadowCamera( CameraInfo* info, osg::GraphicsContext* gc, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
890 osg::Camera* mainShadowCamera = new osg::Camera;
891 info->addCamera(name, mainShadowCamera, 0.0f );
893 mainShadowCamera->setName( "ShadowC" );
894 mainShadowCamera->setClearMask( GL_DEPTH_BUFFER_BIT );
895 mainShadowCamera->setClearDepth( 1.0 );
896 mainShadowCamera->setAllowEventFocus(false);
897 mainShadowCamera->setGraphicsContext(gc);
898 mainShadowCamera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
899 BOOST_FOREACH(ref_ptr<FGRenderingPipeline::Attachment> attachment, attachments) {
900 attachBufferToCamera( info, mainShadowCamera, attachment->component, name, attachment->buffer );
902 mainShadowCamera->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
903 mainShadowCamera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
904 mainShadowCamera->setProjectionMatrix(osg::Matrix::identity());
905 mainShadowCamera->setCullingMode( osg::CullSettings::NO_CULLING );
906 mainShadowCamera->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
907 mainShadowCamera->setDrawBuffer(GL_FRONT);
908 mainShadowCamera->setReadBuffer(GL_FRONT);
910 osg::Switch* shadowSwitch = new osg::Switch;
911 mainShadowCamera->addChild( shadowSwitch );
913 for (int i = 0; i < 4; ++i ) {
914 osg::Camera* cascadeCam = createShadowCascadeCamera( i, _shadowMapSize/2 );
915 cascadeCam->addChild( mDeferredRealRoot.get() );
916 shadowSwitch->addChild( cascadeCam );
917 info->shadowTexGen[i] = new osg::TexGen;
919 if (fgGetBool("/sim/rendering/shadows/enabled", true))
920 shadowSwitch->setAllChildrenOn();
922 shadowSwitch->setAllChildrenOff();
924 return mainShadowCamera;
927 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)
929 osg::Camera* cascade = static_cast<osg::Camera*>( grp->getChild(idx) );
930 osg::Matrixd &viewMatrix = cascade->getViewMatrix();
931 osg::Matrixd &projectionMatrix = cascade->getProjectionMatrix();
933 osg::BoundingSphere bs;
934 bs.expandBy(osg::Vec3(left,bottom,-zNear) * f1);
935 bs.expandBy(osg::Vec3(right,top,-zNear) * f2);
936 bs.expandBy(osg::Vec3(left,bottom,-zNear) * f2);
937 bs.expandBy(osg::Vec3(right,top,-zNear) * f1);
939 osg::Vec4 aim = osg::Vec4(bs.center(), 1.0) * camera->getInverseViewMatrix();
941 projectionMatrix.makeOrtho( -bs.radius(), bs.radius(), -bs.radius(), bs.radius(), 1., 15000.0 );
942 osg::Vec3 position( aim.x(), aim.y(), aim.z() );
943 viewMatrix.makeLookAt( position + (getSunDirection() * 10000.0), position, position );
946 osg::Vec3 FGRenderer::getSunDirection() const
949 _sunDirection->get( val );
953 void FGRenderer::updateShadowCamera(const CameraInfo* info, const osg::Vec3d& position)
955 ref_ptr<Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
956 if (mainShadowCamera.valid()) {
957 ref_ptr<Switch> shadowSwitch = mainShadowCamera->getChild( 0 )->asSwitch();
958 osg::Vec3d up = position,
959 dir = getSunDirection();
962 // cos(100 deg) == -0.17
963 if (up * dir < -0.17 || !fgGetBool("/sim/rendering/shadows/enabled", true)) {
964 shadowSwitch->setAllChildrenOff();
966 double left,right,bottom,top,zNear,zFar;
967 ref_ptr<Camera> camera = info->getCamera(GEOMETRY_CAMERA);
968 camera->getProjectionMatrix().getFrustum(left,right,bottom,top,zNear,zFar);
970 shadowSwitch->setAllChildrenOn();
971 if (_numCascades == 1) {
972 osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(0) );
973 cascadeCam->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
975 for (int no = 0; no < 4; ++no) {
976 osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(no) );
977 cascadeCam->setViewport( int( no / 2 ) * (_shadowMapSize/2), (no & 1) * (_shadowMapSize/2), (_shadowMapSize/2), (_shadowMapSize/2) );
980 updateShadowCascade(info, camera, shadowSwitch, 0, left, right, bottom, top, zNear, 1.0, _cascadeFar[0]/zNear);
981 if (_numCascades > 1) {
982 shadowSwitch->setValue(1, true);
983 updateShadowCascade(info, camera, shadowSwitch, 1, left, right, bottom, top, zNear, _cascadeFar[0]/zNear, _cascadeFar[1]/zNear);
985 shadowSwitch->setValue(1, false);
987 if (_numCascades > 2) {
988 shadowSwitch->setValue(2, true);
989 updateShadowCascade(info, camera, shadowSwitch, 2, left, right, bottom, top, zNear, _cascadeFar[1]/zNear, _cascadeFar[2]/zNear);
991 shadowSwitch->setValue(2, false);
993 if (_numCascades > 3) {
994 shadowSwitch->setValue(3, true);
995 updateShadowCascade(info, camera, shadowSwitch, 3, left, right, bottom, top, zNear, _cascadeFar[2]/zNear, _cascadeFar[3]/zNear);
997 shadowSwitch->setValue(3, false);
1000 osg::Matrixd &viewMatrix = mainShadowCamera->getViewMatrix();
1002 osg::Vec4 aim = osg::Vec4( 0.0, 0.0, 0.0, 1.0 ) * camera->getInverseViewMatrix();
1004 osg::Vec3 position( aim.x(), aim.y(), aim.z() );
1005 viewMatrix.makeLookAt( position, position + (getSunDirection() * 10000.0), position );
1011 void FGRenderer::updateShadowMapSize(int mapSize)
1013 if ( ((~( mapSize-1 )) & mapSize) != mapSize ) {
1014 SG_LOG( SG_VIEW, SG_ALERT, "Map size is not a power of two" );
1017 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
1018 ii != CameraGroup::getDefault()->camerasEnd();
1021 CameraInfo* info = ii->get();
1022 Camera* camera = info->getCamera(SHADOW_CAMERA);
1023 if (camera == 0) continue;
1025 Texture2D* tex = info->getBuffer("shadow");
1026 if (tex == 0) continue;
1028 tex->setTextureSize( mapSize, mapSize );
1029 tex->dirtyTextureObject();
1031 Viewport* vp = camera->getViewport();
1032 vp->width() = mapSize;
1033 vp->height() = mapSize;
1035 osgViewer::Renderer* renderer
1036 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
1037 for (int i = 0; i < 2; ++i) {
1038 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
1039 sceneView->getRenderStage()->setFrameBufferObject(0);
1040 sceneView->getRenderStage()->setCameraRequiresSetUp(true);
1041 if (sceneView->getRenderStageLeft()) {
1042 sceneView->getRenderStageLeft()->setFrameBufferObject(0);
1043 sceneView->getRenderStageLeft()->setCameraRequiresSetUp(true);
1045 if (sceneView->getRenderStageRight()) {
1046 sceneView->getRenderStageRight()->setFrameBufferObject(0);
1047 sceneView->getRenderStageRight()->setCameraRequiresSetUp(true);
1051 int cascadeSize = mapSize / 2;
1052 Group* grp = camera->getChild(0)->asGroup();
1053 for (int i = 0; i < 4; ++i ) {
1054 Camera* cascadeCam = static_cast<Camera*>( grp->getChild(i) );
1055 cascadeCam->setViewport( int( i / 2 ) * cascadeSize, (i & 1) * cascadeSize, cascadeSize, cascadeSize );
1058 _shadowMapSize = mapSize;
1062 void FGRenderer::enableShadows(bool enabled)
1064 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
1065 ii != CameraGroup::getDefault()->camerasEnd();
1068 CameraInfo* info = ii->get();
1069 Camera* camera = info->getCamera(SHADOW_CAMERA);
1070 if (camera == 0) continue;
1072 osg::Switch* shadowSwitch = camera->getChild(0)->asSwitch();
1074 shadowSwitch->setAllChildrenOn();
1076 shadowSwitch->setAllChildrenOff();
1080 void FGRenderer::updateCascadeFar(int index, float far_m)
1082 if (index < 0 || index > 3)
1084 _cascadeFar[index] = far_m;
1085 _shadowDistances->set( osg::Vec4f(_cascadeFar[0], _cascadeFar[1], _cascadeFar[2], _cascadeFar[3]) );
1088 void FGRenderer::updateCascadeNumber(size_t num)
1090 if (num < 1 || num > 4)
1093 _shadowNumber->set( (int)_numCascades );
1096 osg::Camera* FGRenderer::buildDefaultDeferredLightingCamera( CameraInfo* info, osg::GraphicsContext* gc )
1098 std::vector<ref_ptr<FGRenderingPipeline::Attachment> > attachments;
1099 if (_useColorForDepth) {
1100 attachments.push_back(new FGRenderingPipeline::Attachment(osg::Camera::DEPTH_BUFFER, "real-depth") );
1102 attachments.push_back(new FGRenderingPipeline::Attachment(osg::Camera::DEPTH_BUFFER, "depth") );
1104 attachments.push_back(new FGRenderingPipeline::Attachment(osg::Camera::COLOR_BUFFER0, "lighting") );
1105 return buildDeferredLightingCamera( info, gc, LIGHTING_CAMERA, attachments );
1108 osg::Camera* FGRenderer::buildDeferredLightingCamera( CameraInfo* info, osg::GraphicsContext* gc, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
1110 osg::Camera* camera = new osg::Camera;
1111 info->addCamera(name, camera );
1113 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( name, info ) );
1114 camera->setAllowEventFocus(false);
1115 camera->setGraphicsContext(gc);
1116 camera->setViewport(new Viewport);
1117 camera->setName("LightingC");
1118 camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1119 camera->setRenderOrder(osg::Camera::POST_RENDER, 50);
1120 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1121 camera->setViewport( new osg::Viewport );
1122 BOOST_FOREACH(ref_ptr<FGRenderingPipeline::Attachment> attachment, attachments) {
1123 attachBufferToCamera( info, camera, attachment->component, name, attachment->buffer );
1125 camera->setDrawBuffer(GL_FRONT);
1126 camera->setReadBuffer(GL_FRONT);
1127 camera->setClearColor( osg::Vec4( 0., 0., 0., 1. ) );
1128 camera->setClearMask( GL_COLOR_BUFFER_BIT );
1129 osg::StateSet* ss = camera->getOrCreateStateSet();
1130 ss->setAttribute( new osg::Depth(osg::Depth::LESS, 0.0, 1.0, false) );
1131 ss->addUniform( _depthInColor );
1133 osg::Group* lightingGroup = new osg::Group;
1135 osg::Camera* quadCam1 = new osg::Camera;
1136 quadCam1->setName( "QuadCamera1" );
1137 quadCam1->setClearMask(0);
1138 quadCam1->setAllowEventFocus(false);
1139 quadCam1->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1140 quadCam1->setRenderOrder(osg::Camera::NESTED_RENDER);
1141 quadCam1->setViewMatrix(osg::Matrix::identity());
1142 quadCam1->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1143 quadCam1->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1144 ss = quadCam1->getOrCreateStateSet();
1145 ss->addUniform( _ambientFactor );
1146 ss->addUniform( info->projInverse );
1147 ss->addUniform( info->viewInverse );
1148 ss->addUniform( info->view );
1149 ss->addUniform( _sunDiffuse );
1150 ss->addUniform( _sunSpecular );
1151 ss->addUniform( _sunDirection );
1152 ss->addUniform( _planes );
1153 ss->addUniform( _shadowNumber );
1154 ss->addUniform( _shadowDistances );
1156 osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1157 g->setUseDisplayList(false);
1158 simgear::EffectGeode* eg = new simgear::EffectGeode;
1159 simgear::Effect* effect = simgear::makeEffect("Effects/ambient", true);
1161 SG_LOG(SG_VIEW, SG_ALERT, "Effects/ambient not found");
1164 eg->setEffect( effect );
1165 g->setName( "AmbientQuad" );
1166 eg->setName("AmbientQuad");
1167 eg->setCullingActive(false);
1169 quadCam1->addChild( eg );
1171 g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1172 g->setUseDisplayList(false);
1173 g->setName( "SunlightQuad" );
1174 eg = new simgear::EffectGeode;
1175 effect = simgear::makeEffect("Effects/sunlight", true);
1177 SG_LOG(SG_VIEW, SG_ALERT, "Effects/sunlight not found");
1180 eg->setEffect( effect );
1181 eg->setName("SunlightQuad");
1182 eg->setCullingActive(false);
1184 quadCam1->addChild( eg );
1186 osg::Camera* lightCam = new osg::Camera;
1187 ss = lightCam->getOrCreateStateSet();
1188 ss->addUniform( _planes );
1189 ss->addUniform( info->bufferSize );
1190 lightCam->setName( "LightCamera" );
1191 lightCam->setClearMask(0);
1192 lightCam->setAllowEventFocus(false);
1193 lightCam->setReferenceFrame(osg::Transform::RELATIVE_RF);
1194 lightCam->setRenderOrder(osg::Camera::NESTED_RENDER,1);
1195 lightCam->setViewMatrix(osg::Matrix::identity());
1196 lightCam->setProjectionMatrix(osg::Matrix::identity());
1197 lightCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1198 lightCam->setCullMask( simgear::MODELLIGHT_BIT );
1199 lightCam->setInheritanceMask( osg::CullSettings::ALL_VARIABLES & ~osg::CullSettings::CULL_MASK );
1200 lightCam->addChild( mDeferredRealRoot.get() );
1203 osg::Camera* quadCam2 = new osg::Camera;
1204 quadCam2->setName( "QuadCamera1" );
1205 quadCam2->setClearMask(0);
1206 quadCam2->setAllowEventFocus(false);
1207 quadCam2->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1208 quadCam2->setRenderOrder(osg::Camera::NESTED_RENDER,2);
1209 quadCam2->setViewMatrix(osg::Matrix::identity());
1210 quadCam2->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1211 quadCam2->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1212 ss = quadCam2->getOrCreateStateSet();
1213 ss->addUniform( _ambientFactor );
1214 ss->addUniform( info->projInverse );
1215 ss->addUniform( info->viewInverse );
1216 ss->addUniform( info->view );
1217 ss->addUniform( _sunDiffuse );
1218 ss->addUniform( _sunSpecular );
1219 ss->addUniform( _sunDirection );
1220 ss->addUniform( _fogColor );
1221 ss->addUniform( _fogDensity );
1222 ss->addUniform( _planes );
1224 g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1225 g->setUseDisplayList(false);
1226 g->setName( "FogQuad" );
1227 eg = new simgear::EffectGeode;
1228 effect = simgear::makeEffect("Effects/fog", true);
1230 SG_LOG(SG_VIEW, SG_ALERT, "Effects/fog not found");
1233 eg->setEffect( effect );
1234 eg->setName("FogQuad");
1235 eg->setCullingActive(false);
1237 quadCam2->addChild( eg );
1239 lightingGroup->addChild( _sky->getPreRoot() );
1240 lightingGroup->addChild( _sky->getCloudRoot() );
1241 lightingGroup->addChild( quadCam1 );
1242 lightingGroup->addChild( lightCam );
1243 lightingGroup->addChild( quadCam2 );
1245 camera->addChild( lightingGroup );
1250 namespace flightgear {
1251 CameraInfo* buildCameraFromRenderingPipeline(FGRenderingPipeline* rpipe, CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1252 const osg::Matrix& view, const osg::Matrix& projection, osg::GraphicsContext* gc);
1256 FGRenderer::buildDeferredPipeline(CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1257 const osg::Matrix& view,
1258 const osg::Matrix& projection,
1259 osg::GraphicsContext* gc)
1261 if (_renderer.empty() || !_pipeline.valid())
1262 return buildDefaultDeferredPipeline(cgroup, flags, camera, view, projection, gc);
1263 return buildCameraFromRenderingPipeline(_pipeline, cgroup, flags, camera, view, projection, gc);
1267 FGRenderer::buildDeferredFullscreenCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc, const FGRenderingPipeline::Stage* stage )
1269 osg::Camera* camera = new osg::Camera;
1270 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback(stage->name, info) );
1271 camera->setAllowEventFocus(false);
1272 camera->setGraphicsContext(gc);
1273 camera->setViewport(new Viewport);
1274 camera->setName(stage->name+"C");
1275 camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1276 camera->setRenderOrder(osg::Camera::POST_RENDER, stage->orderNum);
1277 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1278 BOOST_FOREACH(ref_ptr<FGRenderingPipeline::Attachment> attachment, stage->attachments) {
1279 attachBufferToCamera( info, camera, attachment->component, stage->name, attachment->buffer );
1281 camera->setDrawBuffer(GL_FRONT);
1282 camera->setReadBuffer(GL_FRONT);
1283 camera->setClearColor( osg::Vec4( 1., 1., 1., 1. ) );
1284 camera->setClearMask( GL_COLOR_BUFFER_BIT );
1285 camera->setViewMatrix(osg::Matrix::identity());
1286 camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1288 osg::StateSet* ss = camera->getOrCreateStateSet();
1289 ss->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1291 osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1292 g->setUseDisplayList(false);
1293 simgear::EffectGeode* eg = new simgear::EffectGeode;
1294 simgear::Effect* effect = simgear::makeEffect(stage->effect, true);
1296 eg->setEffect( effect );
1299 eg->setName(stage->name+"Quad");
1300 eg->setCullingActive(false);
1307 FGRenderer::buildDeferredDisplayCamera( osg::Camera* camera, flightgear::CameraInfo* info, const std::string& name, osg::GraphicsContext* gc )
1309 camera->setName( "DisplayC" );
1310 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( name, info ) );
1311 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
1312 camera->setAllowEventFocus(false);
1313 osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1314 g->setUseDisplayList(false); //DEBUG
1315 simgear::EffectGeode* eg = new simgear::EffectGeode;
1316 simgear::Effect* effect = simgear::makeEffect("Effects/display", true);
1318 SG_LOG(SG_VIEW, SG_ALERT, "Effects/display not found");
1321 eg->setEffect(effect);
1322 eg->setCullingActive(false);
1324 camera->setViewMatrix(osg::Matrix::identity());
1325 camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1326 camera->addChild(eg);
1328 osg::StateSet* ss = camera->getOrCreateStateSet();
1329 ss->addUniform( _depthInColor );
1333 FGRenderer::buildDefaultDeferredPipeline(CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1334 const osg::Matrix& view,
1335 const osg::Matrix& projection,
1336 osg::GraphicsContext* gc)
1338 CameraInfo* info = new CameraInfo(flags);
1339 buildDefaultDeferredBuffers(info, _shadowMapSize, _useColorForDepth);
1341 osg::Camera* geometryCamera = buildDefaultDeferredGeometryCamera( info, gc );
1342 cgroup->getViewer()->addSlave(geometryCamera, false);
1343 installCullVisitor(geometryCamera);
1344 int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1345 info->getRenderStageInfo(GEOMETRY_CAMERA).slaveIndex = slaveIndex;
1347 Camera* shadowCamera = buildDefaultDeferredShadowCamera( info, gc );
1348 cgroup->getViewer()->addSlave(shadowCamera, false);
1349 installCullVisitor(shadowCamera);
1350 slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1351 info->getRenderStageInfo(SHADOW_CAMERA).slaveIndex = slaveIndex;
1353 osg::Camera* lightingCamera = buildDefaultDeferredLightingCamera( info, gc );
1354 cgroup->getViewer()->addSlave(lightingCamera, false);
1355 installCullVisitor(lightingCamera);
1356 slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1357 info->getRenderStageInfo(LIGHTING_CAMERA).slaveIndex = slaveIndex;
1359 buildDeferredDisplayCamera( camera, info, DISPLAY_CAMERA, gc );
1361 cgroup->getViewer()->addSlave(camera, false);
1362 installCullVisitor(camera);
1363 slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1364 info->addCamera( DISPLAY_CAMERA, camera, slaveIndex, true );
1365 camera->setRenderOrder(Camera::POST_RENDER, 99+slaveIndex); //FIXME
1366 cgroup->addCamera(info);
1370 void FGRenderer::buildStage(FGRenderingPipeline* rpipe, CameraInfo* info,
1371 FGRenderingPipeline::Stage* stage,
1372 CameraGroup* cgroup,
1373 osg::Camera* mainCamera,
1374 const osg::Matrix& view,
1375 const osg::Matrix& projection,
1376 osg::GraphicsContext* gc)
1378 ref_ptr<Camera> camera;
1379 if (stage->type == "geometry")
1380 camera = buildDeferredGeometryCamera(info, gc, stage->name, stage->attachments);
1381 else if (stage->type == "lighting")
1382 camera = buildDeferredLightingCamera(info, gc, stage->name, stage->attachments);
1383 else if (stage->type == "shadow")
1384 camera = buildDeferredShadowCamera(info, gc, stage->name, stage->attachments);
1385 else if (stage->type == "fullscreen")
1386 camera = buildDeferredFullscreenCamera(info, gc, stage);
1387 else if (stage->type == "display") {
1388 camera = mainCamera;
1389 buildDeferredDisplayCamera(camera, info, stage->name, gc);
1391 throw sg_exception("Stage type is not supported");
1393 cgroup->getViewer()->addSlave(camera, false);
1394 installCullVisitor(camera);
1395 int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1396 if (stage->type == "display")
1397 info->addCamera( stage->type, camera, slaveIndex, true );
1398 info->getRenderStageInfo(stage->name).slaveIndex = slaveIndex;
1401 void FGRenderer::buildBuffers(FGRenderingPipeline* rpipe, CameraInfo* info)
1403 for (size_t i = 0; i < rpipe->buffers.size(); ++i) {
1404 osg::ref_ptr<FGRenderingPipeline::Buffer> buffer = rpipe->buffers[i];
1405 bool fullscreen = buffer->width == -1 && buffer->height == -1;
1406 info->addBuffer(buffer->name, buildDeferredBuffer( buffer->internalFormat,
1407 buffer->sourceFormat,
1410 buffer->shadowComparison),
1411 fullscreen ? buffer->scaleFactor : 0.0f);
1413 info->getBuffer(buffer->name)->setTextureSize(buffer->width, buffer->height);
1418 CameraInfo* FGRenderer::buildCameraFromRenderingPipeline(FGRenderingPipeline* rpipe, CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1419 const osg::Matrix& view, const osg::Matrix& projection, osg::GraphicsContext* gc)
1421 CameraInfo* info = new CameraInfo(flags);
1422 buildBuffers(rpipe, info);
1424 for (size_t i = 0; i < rpipe->stages.size(); ++i) {
1425 osg::ref_ptr<FGRenderingPipeline::Stage> stage = rpipe->stages[i];
1426 buildStage(rpipe, info, stage, cgroup, camera, view, projection, gc);
1429 int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1430 camera->setRenderOrder(Camera::POST_RENDER, 99+slaveIndex); //FIXME
1431 cgroup->addCamera(info);
1437 FGRenderer::setupView( void )
1439 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1440 osg::initNotifyLevel();
1442 // The number of polygon-offset "units" to place between layers. In
1443 // principle, one is supposed to be enough. In practice, I find that
1444 // my hardware/driver requires many more.
1445 osg::PolygonOffset::setUnitsMultiplier(1);
1446 osg::PolygonOffset::setFactorMultiplier(1);
1448 // Go full screen if requested ...
1449 if ( fgGetBool("/sim/startup/fullscreen") )
1453 // The sun and moon diameters are scaled down numbers of the
1454 // actual diameters. This was needed to fit both the sun and the
1455 // moon within the distance to the far clip plane.
1456 // Moon diameter: 3,476 kilometers
1457 // Sun diameter: 1,390,000 kilometers
1458 _sky->build( 80000.0, 80000.0,
1460 *globals->get_ephem(),
1461 fgGetNode("/environment", true));
1464 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1466 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
1468 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
1470 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
1471 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1473 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
1474 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
1475 stateSet->setAttribute(new osg::BlendFunc);
1476 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
1478 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
1480 // this will be set below
1481 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
1483 osg::Material* material = new osg::Material;
1484 stateSet->setAttribute(material);
1486 stateSet->setTextureAttribute(0, new osg::TexEnv);
1487 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
1489 osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
1490 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
1491 stateSet->setAttribute(hint);
1492 hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
1493 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
1494 stateSet->setAttribute(hint);
1495 hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
1496 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
1497 stateSet->setAttribute(hint);
1498 hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
1499 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
1500 stateSet->setAttribute(hint);
1501 hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
1502 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
1503 stateSet->setAttribute(hint);
1505 osg::Group* sceneGroup = new osg::Group;
1506 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
1507 sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
1509 //sceneGroup->addChild(thesky->getCloudRoot());
1511 stateSet = sceneGroup->getOrCreateStateSet();
1512 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1514 // need to update the light on every frame
1515 // OSG LightSource objects are rather confusing. OSG only supports
1516 // the 10 lights specified by OpenGL itself; if more than one
1517 // LightSource in the scene graph have the same light number, it's
1518 // indeterminate which values will be used to render geometry that
1519 // has that light number enabled. Also, adding children to a
1520 // LightSource is just a shortcut for setting up a state set that
1521 // has the corresponding OpenGL light enabled: a LightSource will
1522 // affect geometry anywhere in the scene graph that has its light
1523 // number enabled in a state set.
1524 LightSource* lightSource = new LightSource;
1525 lightSource->getLight()->setDataVariance(Object::DYNAMIC);
1526 // relative because of CameraView being just a clever transform node
1527 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1528 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
1529 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
1530 mRealRoot->addChild(lightSource);
1531 // we need a white diffuse light for the phase of the moon
1532 osg::LightSource* sunLight = new osg::LightSource;
1533 sunLight->getLight()->setDataVariance(Object::DYNAMIC);
1534 sunLight->getLight()->setLightNum(1);
1535 sunLight->setUpdateCallback(new FGLightSourceUpdateCallback(true));
1536 sunLight->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1537 sunLight->setLocalStateSetModes(osg::StateAttribute::ON);
1539 // Hang a StateSet above the sky subgraph in order to turn off
1541 Group* skyGroup = new Group;
1542 StateSet* skySS = skyGroup->getOrCreateStateSet();
1543 skySS->setMode(GL_LIGHT0, StateAttribute::OFF);
1544 skyGroup->addChild(_sky->getPreRoot());
1545 sunLight->addChild(skyGroup);
1546 mRoot->addChild(sceneGroup);
1547 if ( _classicalRenderer )
1548 mRoot->addChild(sunLight);
1550 // Clouds are added to the scene graph later
1551 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
1552 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
1553 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
1554 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1556 // enable disable specular highlights.
1557 // is the place where we might plug in an other fragment shader ...
1558 osg::LightModel* lightModel = new osg::LightModel;
1559 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
1560 stateSet->setAttribute(lightModel);
1562 // switch to enable wireframe
1563 osg::PolygonMode* polygonMode = new osg::PolygonMode;
1564 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
1565 stateSet->setAttributeAndModes(polygonMode);
1567 // scene fog handling
1568 osg::Fog* fog = new osg::Fog;
1569 fog->setUpdateCallback(new FGFogUpdateCallback);
1570 stateSet->setAttributeAndModes(fog);
1571 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
1574 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
1577 osg::Geode* geode = new osg::Geode;
1578 geode->addDrawable(new SGPuDrawable);
1579 geode->addDrawable(new SGHUDDrawable);
1580 guiCamera->addChild(geode);
1582 panelSwitch = new osg::Switch;
1583 osg::StateSet* stateSet = panelSwitch->getOrCreateStateSet();
1584 stateSet->setRenderBinDetails(1000, "RenderBin");
1586 // speed optimization?
1587 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
1588 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
1589 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
1590 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
1591 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1594 panelSwitch->setUpdateCallback(new FGPanelSwitchCallback);
1597 guiCamera->addChild(panelSwitch.get());
1600 osg::Switch* sw = new osg::Switch;
1601 sw->setUpdateCallback(new FGScenerySwitchCallback);
1602 sw->addChild(mRoot.get());
1603 mRealRoot->addChild(sw);
1604 // The clouds are attached directly to the scene graph root
1605 // because, in theory, they don't want the same default state set
1606 // as the rest of the scene. This may not be true in practice.
1607 if ( _classicalRenderer ) {
1608 mRealRoot->addChild(_sky->getCloudRoot());
1609 mRealRoot->addChild(FGCreateRedoutNode());
1611 // Attach empty program to the scene root so that shader programs
1612 // don't leak into state sets (effects) that shouldn't have one.
1613 stateSet = mRealRoot->getOrCreateStateSet();
1614 stateSet->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON);
1616 mDeferredRealRoot->addChild( mRealRoot.get() );
1619 void FGRenderer::panelChanged()
1625 osg::Node* n = FGPanelNode::createNode(globals->get_current_panel());
1626 if (panelSwitch->getNumChildren()) {
1627 panelSwitch->setChild(0, n);
1629 panelSwitch->addChild(n);
1633 // Update all Visuals (redraws anything graphics related)
1635 FGRenderer::update( ) {
1636 if (!(_scenery_loaded->getBoolValue() ||
1637 _scenery_override->getBoolValue()))
1639 _splash_alpha->setDoubleValue(1.0);
1642 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1644 if (_splash_alpha->getDoubleValue()>0.0)
1646 // Fade out the splash screen
1647 const double fade_time = 0.5;
1648 const double fade_steps_per_sec = 10;
1649 double delay_time = SGMiscd::min(fade_time/fade_steps_per_sec,
1650 (SGTimeStamp::now() - _splash_time).toSecs());
1651 _splash_time = SGTimeStamp::now();
1652 double sAlpha = _splash_alpha->getDoubleValue();
1653 sAlpha -= SGMiscd::max(0.0,delay_time/fade_time);
1654 FGScenerySwitchCallback::scenery_enabled = (sAlpha<1.0);
1655 _splash_alpha->setDoubleValue((sAlpha < 0) ? 0.0 : sAlpha);
1658 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
1659 if (!_classicalRenderer ) {
1660 _ambientFactor->set( toOsg(l->scene_ambient()) );
1661 _sunDiffuse->set( toOsg(l->scene_diffuse()) );
1662 _sunSpecular->set( toOsg(l->scene_specular()) );
1663 _sunDirection->set( osg::Vec3f(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]) );
1666 // update fog params
1667 double actual_visibility;
1668 if (_cloud_status->getBoolValue()) {
1669 actual_visibility = _sky->get_visibility();
1671 actual_visibility = _visibility_m->getDoubleValue();
1674 // idle_state is now 1000 meaning we've finished all our
1675 // initializations and are running the main loop, so this will
1676 // now work without seg faulting the system.
1678 FGViewer *current__view = globals->get_current_view();
1679 // Force update of center dependent values ...
1680 current__view->set_dirty();
1682 osg::Camera *camera = viewer->getCamera();
1684 bool skyblend = _skyblend->getBoolValue();
1687 if ( _textures->getBoolValue() ) {
1688 SGVec4f clearColor(l->adj_fog_color());
1689 camera->setClearColor(toOsg(clearColor));
1692 SGVec4f clearColor(l->sky_color());
1693 camera->setClearColor(toOsg(clearColor));
1696 // update fog params if visibility has changed
1697 double visibility_meters = _visibility_m->getDoubleValue();
1698 _sky->set_visibility(visibility_meters);
1700 double altitude_m = _altitude_ft->getDoubleValue() * SG_FEET_TO_METER;
1701 _sky->modify_vis( altitude_m, 0.0 /* time factor, now unused */);
1703 // update the sky dome
1706 // The sun and moon distances are scaled down versions
1707 // of the actual distance to get both the moon and the sun
1708 // within the range of the far clip plane.
1709 // Moon distance: 384,467 kilometers
1710 // Sun distance: 150,000,000 kilometers
1712 double sun_horiz_eff, moon_horiz_eff;
1713 if (_horizon_effect->getBoolValue()) {
1715 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
1719 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
1723 sun_horiz_eff = moon_horiz_eff = 1.0;
1727 sstate.pos = current__view->getViewPosition();
1728 sstate.pos_geod = current__view->getPosition();
1729 sstate.ori = current__view->getViewOrientation();
1730 sstate.spin = l->get_sun_rotation();
1731 sstate.gst = globals->get_time_params()->getGst();
1732 sstate.sun_dist = 50000.0 * sun_horiz_eff;
1733 sstate.moon_dist = 40000.0 * moon_horiz_eff;
1734 sstate.sun_angle = l->get_sun_angle();
1737 scolor.sky_color = SGVec3f(l->sky_color().data());
1738 scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
1739 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
1740 scolor.cloud_color = SGVec3f(l->cloud_color().data());
1741 scolor.sun_angle = l->get_sun_angle();
1742 scolor.moon_angle = l->get_moon_angle();
1744 double delta_time_sec = _sim_delta_sec->getDoubleValue();
1745 _sky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
1746 _sky->repaint( scolor, *globals->get_ephem() );
1749 // shadows->setupShadows(
1750 // current__view->getLongitude_deg(),
1751 // current__view->getLatitude_deg(),
1752 // globals->get_time_params()->getGst(),
1753 // globals->get_ephem()->getSunRightAscension(),
1754 // globals->get_ephem()->getSunDeclination(),
1755 // l->get_sun_angle());
1759 // sgEnviro.setLight(l->adj_fog_color());
1760 // sgEnviro.startOfFrame(current__view->get_view_pos(),
1761 // current__view->get_world_up(),
1762 // current__view->getLongitude_deg(),
1763 // current__view->getLatitude_deg(),
1764 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
1768 // sgEnviro.drawLightning();
1770 // double current_view_origin_airspeed_horiz_kt =
1771 // fgGetDouble("/velocities/airspeed-kt", 0.0)
1772 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
1773 // * SGD_DEGREES_TO_RADIANS);
1776 // if( is_internal )
1777 // shadows->endOfFrame();
1779 // need to call the update visitor once
1780 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
1781 mUpdateVisitor->setViewData(current__view->getViewPosition(),
1782 current__view->getViewOrientation());
1783 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
1784 mUpdateVisitor->setLight(direction, l->scene_ambient(),
1785 l->scene_diffuse(), l->scene_specular(),
1787 l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
1788 mUpdateVisitor->setVisibility(actual_visibility);
1789 simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
1790 osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
1791 cullMask |= simgear::GroundLightManager::instance()
1792 ->getLightNodeMask(mUpdateVisitor.get());
1793 if (_panel_hotspots->getBoolValue())
1794 cullMask |= simgear::PICK_BIT;
1795 CameraGroup::getDefault()->setCameraCullMasks(cullMask);
1796 if ( !_classicalRenderer ) {
1797 _fogColor->set( toOsg( l->adj_fog_color() ) );
1798 _fogDensity->set( float( mUpdateVisitor->getFogExp2Density() ) );
1803 FGRenderer::resize( int width, int height )
1805 int curWidth = _xsize->getIntValue(),
1806 curHeight = _ysize->getIntValue();
1807 SG_LOG(SG_VIEW, SG_DEBUG, "FGRenderer::resize: new size " << width << " x " << height);
1808 if ((curHeight != height) || (curWidth != width)) {
1809 // must guard setting these, or PLIB-PUI fails with too many live interfaces
1810 _xsize->setIntValue(width);
1811 _ysize->setIntValue(height);
1816 FGRenderer::pick(std::vector<SGSceneryPick>& pickList,
1817 const osgGA::GUIEventAdapter* ea)
1819 // wipe out the return ...
1821 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
1822 Intersections intersections;
1824 if (!computeIntersections(CameraGroup::getDefault(), ea, intersections))
1826 for (Intersections::iterator hit = intersections.begin(),
1827 e = intersections.end();
1830 const osg::NodePath& np = hit->nodePath;
1831 osg::NodePath::const_reverse_iterator npi;
1832 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
1833 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
1836 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
1837 SGPickCallback* pickCallback = ud->getPickCallback(i);
1840 SGSceneryPick sceneryPick;
1841 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
1842 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
1843 sceneryPick.callback = pickCallback;
1844 pickList.push_back(sceneryPick);
1848 return !pickList.empty();
1852 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
1858 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
1860 eventHandler = eventHandler_;
1864 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
1866 mRealRoot->addChild(camera);
1870 FGRenderer::removeCamera(osg::Camera* camera)
1872 mRealRoot->removeChild(camera);
1876 FGRenderer::setPlanes( double zNear, double zFar )
1878 _planes->set( osg::Vec3f( - zFar, - zFar * zNear, zFar - zNear ) );
1882 fgDumpSceneGraphToFile(const char* filename)
1884 return osgDB::writeNodeFile(*mRealRoot.get(), filename);
1888 fgDumpTerrainBranchToFile(const char* filename)
1890 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
1896 fgDumpNodeToFile(osg::Node* node, const char* filename)
1898 return osgDB::writeNodeFile(*node, filename);
1901 namespace flightgear
1903 using namespace osg;
1905 class VisibleSceneInfoVistor : public NodeVisitor, CullStack
1908 VisibleSceneInfoVistor()
1909 : NodeVisitor(CULL_VISITOR, TRAVERSE_ACTIVE_CHILDREN)
1911 setCullingMode(CullSettings::SMALL_FEATURE_CULLING
1912 | CullSettings::VIEW_FRUSTUM_CULLING);
1913 setComputeNearFarMode(CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1916 VisibleSceneInfoVistor(const VisibleSceneInfoVistor& rhs)
1920 META_NodeVisitor("flightgear","VisibleSceneInfoVistor")
1922 typedef std::map<const std::string,int> InfoMap;
1924 void getNodeInfo(Node* node)
1926 const char* typeName = typeid(*node).name();
1927 classInfo[typeName]++;
1928 const std::string& nodeName = node->getName();
1929 if (!nodeName.empty())
1930 nodeInfo[nodeName]++;
1935 using namespace std;
1936 typedef vector<InfoMap::iterator> FreqVector;
1937 cout << "class info:\n";
1939 for (InfoMap::iterator itr = classInfo.begin(), end = classInfo.end();
1942 classes.push_back(itr);
1943 sort(classes.begin(), classes.end(), freqComp);
1944 for (FreqVector::iterator itr = classes.begin(), end = classes.end();
1947 cout << (*itr)->first << " " << (*itr)->second << "\n";
1949 cout << "\nnode info:\n";
1951 for (InfoMap::iterator itr = nodeInfo.begin(), end = nodeInfo.end();
1954 nodes.push_back(itr);
1956 sort (nodes.begin(), nodes.end(), freqComp);
1957 for (FreqVector::iterator itr = nodes.begin(), end = nodes.end();
1960 cout << (*itr)->first << " " << (*itr)->second << "\n";
1965 void doTraversal(Camera* camera, Node* root, Viewport* viewport)
1967 ref_ptr<RefMatrix> projection
1968 = createOrReuseMatrix(camera->getProjectionMatrix());
1969 ref_ptr<RefMatrix> mv = createOrReuseMatrix(camera->getViewMatrix());
1971 viewport = camera->getViewport();
1973 pushViewport(viewport);
1974 pushProjectionMatrix(projection.get());
1975 pushModelViewMatrix(mv.get(), Transform::ABSOLUTE_RF);
1976 root->accept(*this);
1977 popModelViewMatrix();
1978 popProjectionMatrix();
1984 void apply(Node& node)
1993 void apply(Group& node)
2003 void apply(Transform& node)
2008 ref_ptr<RefMatrix> matrix = createOrReuseMatrix(*getModelViewMatrix());
2009 node.computeLocalToWorldMatrix(*matrix,this);
2010 pushModelViewMatrix(matrix.get(), node.getReferenceFrame());
2013 popModelViewMatrix();
2017 void apply(Camera& camera)
2019 // Save current cull settings
2020 CullSettings saved_cull_settings(*this);
2022 // set cull settings from this Camera
2023 setCullSettings(camera);
2024 // inherit the settings from above
2025 inheritCullSettings(saved_cull_settings, camera.getInheritanceMask());
2027 // set the cull mask.
2028 unsigned int savedTraversalMask = getTraversalMask();
2029 bool mustSetCullMask = (camera.getInheritanceMask()
2030 & osg::CullSettings::CULL_MASK) == 0;
2031 if (mustSetCullMask)
2032 setTraversalMask(camera.getCullMask());
2034 osg::RefMatrix* projection = 0;
2035 osg::RefMatrix* modelview = 0;
2037 if (camera.getReferenceFrame()==osg::Transform::RELATIVE_RF) {
2038 if (camera.getTransformOrder()==osg::Camera::POST_MULTIPLY) {
2039 projection = createOrReuseMatrix(*getProjectionMatrix()
2040 *camera.getProjectionMatrix());
2041 modelview = createOrReuseMatrix(*getModelViewMatrix()
2042 * camera.getViewMatrix());
2044 else { // pre multiply
2045 projection = createOrReuseMatrix(camera.getProjectionMatrix()
2046 * (*getProjectionMatrix()));
2047 modelview = createOrReuseMatrix(camera.getViewMatrix()
2048 * (*getModelViewMatrix()));
2051 // an absolute reference frame
2052 projection = createOrReuseMatrix(camera.getProjectionMatrix());
2053 modelview = createOrReuseMatrix(camera.getViewMatrix());
2055 if (camera.getViewport())
2056 pushViewport(camera.getViewport());
2058 pushProjectionMatrix(projection);
2059 pushModelViewMatrix(modelview, camera.getReferenceFrame());
2063 // restore the previous model view matrix.
2064 popModelViewMatrix();
2066 // restore the previous model view matrix.
2067 popProjectionMatrix();
2069 if (camera.getViewport()) popViewport();
2071 // restore the previous traversal mask settings
2072 if (mustSetCullMask)
2073 setTraversalMask(savedTraversalMask);
2075 // restore the previous cull settings
2076 setCullSettings(saved_cull_settings);
2081 static bool freqComp(const InfoMap::iterator& lhs, const InfoMap::iterator& rhs)
2083 return lhs->second > rhs->second;
2089 bool printVisibleSceneInfo(FGRenderer* renderer)
2091 osgViewer::Viewer* viewer = renderer->getViewer();
2092 VisibleSceneInfoVistor vsv;
2094 if (!viewer->getCamera()->getViewport() && viewer->getNumSlaves() > 0) {
2095 const View::Slave& slave = viewer->getSlave(0);
2096 vp = slave._camera->getViewport();
2098 vsv.doTraversal(viewer->getCamera(), viewer->getSceneData(), vp);
2103 // end of renderer.cxx