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/math/SGMath.hxx>
68 #include <simgear/scene/material/matlib.hxx>
69 #include <simgear/scene/material/EffectCullVisitor.hxx>
70 #include <simgear/scene/material/Effect.hxx>
71 #include <simgear/scene/material/EffectGeode.hxx>
72 #include <simgear/scene/model/animation.hxx>
73 #include <simgear/scene/model/placement.hxx>
74 #include <simgear/scene/sky/sky.hxx>
75 #include <simgear/scene/util/SGUpdateVisitor.hxx>
76 #include <simgear/scene/util/RenderConstants.hxx>
77 #include <simgear/scene/util/SGSceneUserData.hxx>
78 #include <simgear/scene/tgdb/GroundLightManager.hxx>
79 #include <simgear/scene/tgdb/pt_lights.hxx>
80 #include <simgear/structure/OSGUtils.hxx>
81 #include <simgear/props/props.hxx>
82 #include <simgear/timing/sg_time.hxx>
83 #include <simgear/ephemeris/ephemeris.hxx>
84 #include <simgear/math/sg_random.h>
86 #include <simgear/screen/jpgfactory.hxx>
89 #include <Time/light.hxx>
90 #include <Time/light.hxx>
91 #include <Cockpit/panel.hxx>
93 #include <Model/panelnode.hxx>
94 #include <Model/modelmgr.hxx>
95 #include <Model/acmodel.hxx>
96 #include <Scenery/scenery.hxx>
97 #include <Scenery/redout.hxx>
98 #include <GUI/new_gui.hxx>
99 #include <Instrumentation/HUD/HUD.hxx>
100 #include <Environment/precipitation_mgr.hxx>
101 #include <Environment/environment_mgr.hxx>
103 #include "splash.hxx"
104 #include "renderer.hxx"
106 #include "CameraGroup.hxx"
107 #include "FGEventHandler.hxx"
108 #include <Main/viewer.hxx>
109 #include <Main/viewmgr.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 ) )
419 #ifdef FG_JPEG_SERVER
420 jpgRenderFrame = updateRenderer;
422 eventHandler = new FGEventHandler;
425 FGRenderer::~FGRenderer()
427 #ifdef FG_JPEG_SERVER
428 jpgRenderFrame = NULL;
433 // Initialize various GL/view parameters
434 // XXX This should be called "preinit" or something, as it initializes
435 // critical parts of the scene graph in addition to the splash screen.
437 FGRenderer::splashinit( void ) {
438 osgViewer::Viewer* viewer = getViewer();
439 mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
440 mRealRoot->addChild(fgCreateSplashNode());
441 mFrameStamp = viewer->getFrameStamp();
442 // Scene doesn't seem to pass the frame stamp to the update
443 // visitor automatically.
444 mUpdateVisitor->setFrameStamp(mFrameStamp.get());
445 viewer->setUpdateVisitor(mUpdateVisitor.get());
446 fgSetDouble("/sim/startup/splash-alpha", 1.0);
449 class ShadowMapSizeListener : public SGPropertyChangeListener {
451 virtual void valueChanged(SGPropertyNode* node) {
452 globals->get_renderer()->updateShadowMapSize(node->getIntValue());
457 FGRenderer::init( void )
459 _classicalRenderer = !fgGetBool("/sim/rendering/rembrandt", false);
460 _shadowMapSize = fgGetInt( "/sim/rendering/shadows/map-size", 4096 );
461 fgAddChangeListener( new ShadowMapSizeListener, "/sim/rendering/shadows/map-size" );
462 _scenery_loaded = fgGetNode("/sim/sceneryloaded", true);
463 _scenery_override = fgGetNode("/sim/sceneryloaded-override", true);
464 _panel_hotspots = fgGetNode("/sim/panel-hotspots", true);
465 _virtual_cockpit = fgGetNode("/sim/virtual-cockpit", true);
467 _sim_delta_sec = fgGetNode("/sim/time/delta-sec", true);
469 _xsize = fgGetNode("/sim/startup/xsize", true);
470 _ysize = fgGetNode("/sim/startup/ysize", true);
471 _splash_alpha = fgGetNode("/sim/startup/splash-alpha", true);
473 _skyblend = fgGetNode("/sim/rendering/skyblend", true);
474 _point_sprites = fgGetNode("/sim/rendering/point-sprites", true);
475 _enhanced_lighting = fgGetNode("/sim/rendering/enhanced-lighting", true);
476 _distance_attenuation = fgGetNode("/sim/rendering/distance-attenuation", true);
477 _horizon_effect = fgGetNode("/sim/rendering/horizon-effect", true);
478 _textures = fgGetNode("/sim/rendering/textures", true);
480 _altitude_ft = fgGetNode("/position/altitude-ft", true);
482 _cloud_status = fgGetNode("/environment/clouds/status", true);
483 _visibility_m = fgGetNode("/environment/visibility-m", true);
485 bool use_point_sprites = _point_sprites->getBoolValue();
486 bool enhanced_lighting = _enhanced_lighting->getBoolValue();
487 bool distance_attenuation = _distance_attenuation->getBoolValue();
489 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
490 distance_attenuation );
492 if (const char* tc = fgGetString("/sim/rendering/texture-compression", NULL)) {
493 if (strcmp(tc, "false") == 0 || strcmp(tc, "off") == 0 ||
494 strcmp(tc, "0") == 0 || strcmp(tc, "no") == 0 ||
495 strcmp(tc, "none") == 0) {
496 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::DoNotUseCompression);
497 } else if (strcmp(tc, "arb") == 0) {
498 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseARBCompression);
499 } else if (strcmp(tc, "dxt1") == 0) {
500 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT1Compression);
501 } else if (strcmp(tc, "dxt3") == 0) {
502 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT3Compression);
503 } else if (strcmp(tc, "dxt5") == 0) {
504 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT5Compression);
506 SG_LOG(SG_VIEW, SG_WARN, "Unknown texture compression setting!");
510 // create sky, but can't build until setupView, since we depend
511 // on other subsystems to be inited, eg Ephemeris
514 SGPath texture_path(globals->get_fg_root());
515 texture_path.append("Textures");
516 texture_path.append("Sky");
517 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
518 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
519 _sky->add_cloud_layer(layer);
522 _sky->texture_path( texture_path.str() );
525 void installCullVisitor(Camera* camera)
527 osgViewer::Renderer* renderer
528 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
529 for (int i = 0; i < 2; ++i) {
530 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
531 #if SG_OSG_VERSION_LESS_THAN(3,0,0)
532 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
534 osg::ref_ptr<osgUtil::CullVisitor::Identifier> identifier;
535 identifier = sceneView->getCullVisitor()->getIdentifier();
536 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
537 sceneView->getCullVisitor()->setIdentifier(identifier.get());
539 identifier = sceneView->getCullVisitorLeft()->getIdentifier();
540 sceneView->setCullVisitorLeft(sceneView->getCullVisitor()->clone());
541 sceneView->getCullVisitorLeft()->setIdentifier(identifier.get());
543 identifier = sceneView->getCullVisitorRight()->getIdentifier();
544 sceneView->setCullVisitorRight(sceneView->getCullVisitor()->clone());
545 sceneView->getCullVisitorRight()->setIdentifier(identifier.get());
550 flightgear::CameraInfo*
551 FGRenderer::buildRenderingPipeline(flightgear::CameraGroup* cgroup, unsigned flags, Camera* camera,
553 const Matrix& projection,
554 osg::GraphicsContext* gc,
555 bool useMasterSceneData)
557 flightgear::CameraInfo* info = 0;
558 if (!_classicalRenderer && (flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
559 info = buildDeferredPipeline( cgroup, flags, camera, view, projection, gc );
564 if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
565 _classicalRenderer = true;
566 return buildClassicalPipeline( cgroup, flags, camera, view, projection, useMasterSceneData );
570 flightgear::CameraInfo*
571 FGRenderer::buildClassicalPipeline(flightgear::CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
572 const osg::Matrix& view,
573 const osg::Matrix& projection,
574 bool useMasterSceneData)
576 CameraInfo* info = new CameraInfo(flags);
577 // The camera group will always update the camera
578 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
580 Camera* farCamera = 0;
581 if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0) {
582 farCamera = new Camera;
583 farCamera->setAllowEventFocus(camera->getAllowEventFocus());
584 farCamera->setGraphicsContext(camera->getGraphicsContext());
585 farCamera->setCullingMode(camera->getCullingMode());
586 farCamera->setInheritanceMask(camera->getInheritanceMask());
587 farCamera->setReferenceFrame(Transform::ABSOLUTE_RF);
588 // Each camera's viewport is written when the window is
589 // resized; if the the viewport isn't copied here, it gets updated
590 // twice and ends up with the wrong value.
591 farCamera->setViewport(simgear::clone(camera->getViewport()));
592 farCamera->setDrawBuffer(camera->getDrawBuffer());
593 farCamera->setReadBuffer(camera->getReadBuffer());
594 farCamera->setRenderTargetImplementation(
595 camera->getRenderTargetImplementation());
596 const Camera::BufferAttachmentMap& bufferMap
597 = camera->getBufferAttachmentMap();
598 if (bufferMap.count(Camera::COLOR_BUFFER) != 0) {
600 Camera::COLOR_BUFFER,
601 bufferMap.find(Camera::COLOR_BUFFER)->second._texture.get());
603 cgroup->getViewer()->addSlave(farCamera, projection, view, useMasterSceneData);
604 installCullVisitor(farCamera);
605 int farSlaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
606 info->addCamera( FAR_CAMERA, farCamera, farSlaveIndex );
607 farCamera->setRenderOrder(Camera::POST_RENDER, farSlaveIndex);
608 camera->setCullMask(camera->getCullMask() & ~simgear::BACKGROUND_BIT);
609 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
611 cgroup->getViewer()->addSlave(camera, projection, view, useMasterSceneData);
612 installCullVisitor(camera);
613 int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
614 info->addCamera( MAIN_CAMERA, camera, slaveIndex );
615 camera->setRenderOrder(Camera::POST_RENDER, slaveIndex);
616 cgroup->addCamera(info);
620 class FGDeferredRenderingCameraCullCallback : public osg::NodeCallback {
622 FGDeferredRenderingCameraCullCallback( flightgear::CameraKind k, CameraInfo* i ) : kind( k ), info( i ) {}
623 virtual void operator()( osg::Node *n, osg::NodeVisitor *nv) {
624 simgear::EffectCullVisitor* cv = dynamic_cast<simgear::EffectCullVisitor*>(nv);
625 osg::Camera* camera = static_cast<osg::Camera*>(n);
627 cv->clearBufferList();
628 cv->addBuffer(simgear::Effect::DEPTH_BUFFER, info->getBuffer( flightgear::RenderBufferInfo::DEPTH_BUFFER ) );
629 cv->addBuffer(simgear::Effect::NORMAL_BUFFER, info->getBuffer( flightgear::RenderBufferInfo::NORMAL_BUFFER ) );
630 cv->addBuffer(simgear::Effect::DIFFUSE_BUFFER, info->getBuffer( flightgear::RenderBufferInfo::DIFFUSE_BUFFER ) );
631 cv->addBuffer(simgear::Effect::SPEC_EMIS_BUFFER, info->getBuffer( flightgear::RenderBufferInfo::SPEC_EMIS_BUFFER ) );
632 cv->addBuffer(simgear::Effect::LIGHTING_BUFFER, info->getBuffer( flightgear::RenderBufferInfo::LIGHTING_BUFFER ) );
633 cv->addBuffer(simgear::Effect::SHADOW_BUFFER, info->getBuffer( flightgear::RenderBufferInfo::SHADOW_BUFFER ) );
634 // cv->addBuffer(simgear::Effect::AO_BUFFER, info->gBuffer->aoBuffer[2]);
636 if ( !info->getRenderStageInfo(kind).fullscreen )
637 info->setMatrices( camera );
639 cv->traverse( *camera );
641 if ( kind == flightgear::GEOMETRY_CAMERA ) {
642 // Save transparent bins to render later
643 osgUtil::RenderStage* renderStage = cv->getRenderStage();
644 osgUtil::RenderBin::RenderBinList& rbl = renderStage->getRenderBinList();
645 for (osgUtil::RenderBin::RenderBinList::iterator rbi = rbl.begin(); rbi != rbl.end(); ) {
646 if (rbi->second->getSortMode() == osgUtil::RenderBin::SORT_BACK_TO_FRONT) {
647 info->savedTransparentBins.insert( std::make_pair( rbi->first, rbi->second ) );
653 } else if ( kind == flightgear::LIGHTING_CAMERA ) {
654 osg::ref_ptr<osg::Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
655 if (mainShadowCamera.valid()) {
656 osg::Group* grp = mainShadowCamera->getChild(0)->asGroup();
657 for (int i = 0; i < 4; ++i ) {
658 osg::TexGen* shadowTexGen = info->shadowTexGen[i];
659 shadowTexGen->setMode(osg::TexGen::EYE_LINEAR);
661 osg::Camera* cascadeCam = static_cast<osg::Camera*>( grp->getChild(i) );
662 // compute the matrix which takes a vertex from view coords into tex coords
663 shadowTexGen->setPlanesFromMatrix( cascadeCam->getProjectionMatrix() *
664 osg::Matrix::translate(1.0,1.0,1.0) *
665 osg::Matrix::scale(0.5f,0.5f,0.5f) );
667 osg::RefMatrix * refMatrix = new osg::RefMatrix( cascadeCam->getInverseViewMatrix() * *cv->getModelViewMatrix() );
669 cv->getRenderStage()->getPositionalStateContainer()->addPositionedTextureAttribute( i+1, refMatrix, shadowTexGen );
672 // Render saved transparent render bins
673 osgUtil::RenderStage* renderStage = cv->getRenderStage();
674 osgUtil::RenderBin::RenderBinList& rbl = renderStage->getRenderBinList();
675 for (osgUtil::RenderBin::RenderBinList::iterator rbi = info->savedTransparentBins.begin(); rbi != info->savedTransparentBins.end(); ++rbi ){
676 rbl.insert( std::make_pair( rbi->first + 10000, rbi->second ) );
678 info->savedTransparentBins.clear();
683 flightgear::CameraKind kind;
687 osg::Texture2D* buildDeferredBuffer(GLint internalFormat, GLenum sourceFormat, GLenum sourceType, osg::Texture::WrapMode wrapMode, bool shadowComparison = false)
689 osg::Texture2D* tex = new osg::Texture2D;
690 tex->setResizeNonPowerOfTwoHint( false );
691 tex->setInternalFormat( internalFormat );
692 tex->setShadowComparison(shadowComparison);
693 if (shadowComparison) {
694 tex->setShadowTextureMode(osg::Texture2D::LUMINANCE);
695 tex->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
697 tex->setSourceFormat(sourceFormat);
698 tex->setSourceType(sourceType);
699 tex->setFilter( osg::Texture2D::MIN_FILTER, osg::Texture2D::LINEAR );
700 tex->setFilter( osg::Texture2D::MAG_FILTER, osg::Texture2D::LINEAR );
701 tex->setWrap( osg::Texture::WRAP_S, wrapMode );
702 tex->setWrap( osg::Texture::WRAP_T, wrapMode );
706 void buildDeferredBuffers( flightgear::CameraInfo* info, int shadowMapSize, bool normal16 )
708 info->addBuffer(flightgear::RenderBufferInfo::DEPTH_BUFFER, buildDeferredBuffer( GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_FLOAT, osg::Texture::CLAMP_TO_BORDER) );
710 info->addBuffer(flightgear::RenderBufferInfo::NORMAL_BUFFER, buildDeferredBuffer( 0x822C /*GL_RG16*/, 0x8227 /*GL_RG*/, GL_UNSIGNED_SHORT, osg::Texture::CLAMP_TO_BORDER) );
712 info->addBuffer(flightgear::RenderBufferInfo::NORMAL_BUFFER, buildDeferredBuffer( GL_RGBA8, GL_RGBA, GL_UNSIGNED_SHORT, osg::Texture::CLAMP_TO_BORDER) );
714 info->addBuffer(flightgear::RenderBufferInfo::DIFFUSE_BUFFER, buildDeferredBuffer( GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, osg::Texture::CLAMP_TO_BORDER) );
715 info->addBuffer(flightgear::RenderBufferInfo::SPEC_EMIS_BUFFER, buildDeferredBuffer( GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, osg::Texture::CLAMP_TO_BORDER) );
716 info->addBuffer(flightgear::RenderBufferInfo::LIGHTING_BUFFER, buildDeferredBuffer( GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, osg::Texture::CLAMP_TO_BORDER) );
717 info->addBuffer(flightgear::RenderBufferInfo::SHADOW_BUFFER, buildDeferredBuffer( GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_FLOAT, osg::Texture::CLAMP_TO_BORDER, true), 0.0f );
718 info->getBuffer(RenderBufferInfo::SHADOW_BUFFER)->setTextureSize(shadowMapSize,shadowMapSize);
721 void attachBufferToCamera( flightgear::CameraInfo* info, osg::Camera* camera, osg::Camera::BufferComponent c, flightgear::CameraKind ck, flightgear::RenderBufferInfo::Kind bk )
723 camera->attach( c, info->getBuffer(bk) );
724 info->getRenderStageInfo(ck).buffers.insert( std::make_pair( c, bk ) );
727 osg::Camera* FGRenderer::buildDeferredGeometryCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc )
729 osg::Camera* camera = new osg::Camera;
730 info->addCamera(flightgear::GEOMETRY_CAMERA, camera );
732 camera->setCullMask( ~simgear::MODELLIGHT_BIT );
733 camera->setName( "GeometryCamera" );
734 camera->setGraphicsContext( gc );
735 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( flightgear::GEOMETRY_CAMERA, info ) );
736 camera->setClearMask( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
737 camera->setClearColor( osg::Vec4( 0., 0., 0., 0. ) );
738 camera->setClearDepth( 1.0 );
739 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
740 camera->setViewport( new osg::Viewport );
741 attachBufferToCamera( info, camera, osg::Camera::DEPTH_BUFFER, flightgear::GEOMETRY_CAMERA, flightgear::RenderBufferInfo::DEPTH_BUFFER );
742 attachBufferToCamera( info, camera, osg::Camera::COLOR_BUFFER0, flightgear::GEOMETRY_CAMERA, flightgear::RenderBufferInfo::NORMAL_BUFFER );
743 attachBufferToCamera( info, camera, osg::Camera::COLOR_BUFFER1, flightgear::GEOMETRY_CAMERA, flightgear::RenderBufferInfo::DIFFUSE_BUFFER );
744 attachBufferToCamera( info, camera, osg::Camera::COLOR_BUFFER2, flightgear::GEOMETRY_CAMERA, flightgear::RenderBufferInfo::SPEC_EMIS_BUFFER );
745 camera->setDrawBuffer(GL_FRONT);
746 camera->setReadBuffer(GL_FRONT);
748 camera->addChild( mDeferredRealRoot.get() );
753 static void setShadowCascadeStateSet( osg::Camera* cam ) {
754 osg::StateSet* ss = cam->getOrCreateStateSet();
755 ss->setAttribute( new osg::PolygonOffset( 1.1f, 5.0f ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
756 ss->setMode( GL_POLYGON_OFFSET_FILL, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
757 ss->setRenderBinDetails( 0, "RenderBin", osg::StateSet::OVERRIDE_RENDERBIN_DETAILS );
758 ss->setAttributeAndModes( new osg::AlphaFunc( osg::AlphaFunc::GREATER, 0.05 ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
759 ss->setAttributeAndModes( new osg::ColorMask( false, false, false, false ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
760 ss->setAttributeAndModes( new osg::CullFace( osg::CullFace::FRONT ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
761 osg::Program* program = new osg::Program;
762 ss->setAttribute( program, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
763 ss->setMode( GL_LIGHTING, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
764 ss->setMode( GL_BLEND, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
765 //ss->setTextureMode( 0, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
766 ss->setTextureMode( 0, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
767 ss->setTextureMode( 1, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
768 ss->setTextureMode( 1, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
769 ss->setTextureMode( 2, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
770 ss->setTextureMode( 2, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
773 static osg::Camera* createShadowCascadeCamera( int no, int cascadeSize ) {
774 osg::Camera* cascadeCam = new osg::Camera;
775 setShadowCascadeStateSet( cascadeCam );
777 std::ostringstream oss;
778 oss << "CascadeCamera" << (no + 1);
779 cascadeCam->setName( oss.str() );
780 cascadeCam->setClearMask(0);
781 cascadeCam->setCullMask(~( simgear::MODELLIGHT_BIT /* | simgear::NO_SHADOW_BIT */ ) );
782 cascadeCam->setCullingMode( cascadeCam->getCullingMode() & ~osg::CullSettings::SMALL_FEATURE_CULLING );
783 cascadeCam->setAllowEventFocus(false);
784 cascadeCam->setReferenceFrame(osg::Transform::ABSOLUTE_RF_INHERIT_VIEWPOINT);
785 cascadeCam->setRenderOrder(osg::Camera::NESTED_RENDER);
786 cascadeCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
787 cascadeCam->setViewport( int( no / 2 ) * cascadeSize, (no & 1) * cascadeSize, cascadeSize, cascadeSize );
791 osg::Camera* FGRenderer::buildDeferredShadowCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc )
793 osg::Camera* mainShadowCamera = new osg::Camera;
794 info->addCamera(flightgear::SHADOW_CAMERA, mainShadowCamera, 0.0f );
796 mainShadowCamera->setName( "ShadowCamera" );
797 mainShadowCamera->setClearMask( GL_DEPTH_BUFFER_BIT );
798 mainShadowCamera->setClearDepth( 1.0 );
799 mainShadowCamera->setAllowEventFocus(false);
800 mainShadowCamera->setGraphicsContext(gc);
801 mainShadowCamera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
802 attachBufferToCamera( info, mainShadowCamera, osg::Camera::DEPTH_BUFFER, flightgear::SHADOW_CAMERA, flightgear::RenderBufferInfo::SHADOW_BUFFER );
803 mainShadowCamera->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
804 mainShadowCamera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
805 mainShadowCamera->setProjectionMatrix(osg::Matrix::identity());
806 mainShadowCamera->setCullingMode( osg::CullSettings::NO_CULLING );
807 mainShadowCamera->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
808 mainShadowCamera->setDrawBuffer(GL_FRONT);
809 mainShadowCamera->setReadBuffer(GL_FRONT);
811 osg::Switch* shadowSwitch = new osg::Switch;
812 mainShadowCamera->addChild( shadowSwitch );
814 for (int i = 0; i < 4; ++i ) {
815 osg::Camera* cascadeCam = createShadowCascadeCamera( i, _shadowMapSize/2 );
816 cascadeCam->addChild( mDeferredRealRoot.get() );
817 shadowSwitch->addChild( cascadeCam );
818 info->shadowTexGen[i] = new osg::TexGen;
820 shadowSwitch->setAllChildrenOn();
822 return mainShadowCamera;
825 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)
827 osg::Camera* cascade = static_cast<osg::Camera*>( grp->getChild(idx) );
828 osg::Matrixd &viewMatrix = cascade->getViewMatrix();
829 osg::Matrixd &projectionMatrix = cascade->getProjectionMatrix();
831 osg::BoundingSphere bs;
832 bs.expandBy(osg::Vec3(left,bottom,-zNear) * f1);
833 bs.expandBy(osg::Vec3(right,top,-zNear) * f2);
834 bs.expandBy(osg::Vec3(left,bottom,-zNear) * f2);
835 bs.expandBy(osg::Vec3(right,top,-zNear) * f1);
837 osg::Vec4 aim = osg::Vec4(bs.center(), 1.0) * camera->getInverseViewMatrix();
839 projectionMatrix.makeOrtho( -bs.radius(), bs.radius(), -bs.radius(), bs.radius(), 1., 15000.0 );
840 osg::Vec3 position( aim.x(), aim.y(), aim.z() );
841 viewMatrix.makeLookAt( position + (getSunDirection() * 10000.0), position, position );
844 osg::Vec3 FGRenderer::getSunDirection() const
847 _sunDirection->get( val );
851 void FGRenderer::updateShadowCamera(const flightgear::CameraInfo* info, const osg::Vec3d& position)
853 ref_ptr<Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
854 if (mainShadowCamera.valid()) {
855 ref_ptr<Switch> shadowSwitch = mainShadowCamera->getChild( 0 )->asSwitch();
856 osg::Vec3d up = position,
857 dir = getSunDirection();
860 // cos(100 deg) == -0.17
861 if (up * dir < -0.17 ) {
862 shadowSwitch->setAllChildrenOff();
864 double left,right,bottom,top,zNear,zFar;
865 ref_ptr<Camera> camera = info->getCamera(GEOMETRY_CAMERA);
866 camera->getProjectionMatrix().getFrustum(left,right,bottom,top,zNear,zFar);
868 shadowSwitch->setAllChildrenOn();
869 osg::Group* grp = mainShadowCamera->getChild(0)->asGroup();
870 updateShadowCascade(info, camera, grp, 0, left, right, bottom, top, zNear, 1.0, 5.0/zNear);
871 updateShadowCascade(info, camera, grp, 1, left, right, bottom, top, zNear, 5.0/zNear,50.0/zNear);
872 updateShadowCascade(info, camera, grp, 2, left, right, bottom, top, zNear, 50.0/zNear,512.0/zNear);
873 updateShadowCascade(info, camera, grp, 3, left, right, bottom, top, zNear, 512.0/zNear,5000.0/zNear);
875 osg::Matrixd &viewMatrix = mainShadowCamera->getViewMatrix();
877 osg::Vec4 aim = osg::Vec4( 0.0, 0.0, 0.0, 1.0 ) * camera->getInverseViewMatrix();
879 osg::Vec3 position( aim.x(), aim.y(), aim.z() );
880 viewMatrix.makeLookAt( position, position + (getSunDirection() * 10000.0), position );
886 void FGRenderer::updateShadowMapSize(int mapSize)
888 if ( ((~( mapSize-1 )) & mapSize) != mapSize ) {
889 SG_LOG( SG_VIEW, SG_ALERT, "Map size is not a power of two" );
892 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
893 ii != CameraGroup::getDefault()->camerasEnd();
896 CameraInfo* info = ii->get();
897 Camera* camera = info->getCamera(SHADOW_CAMERA);
898 if (camera == 0) continue;
900 Texture2D* tex = info->getBuffer(RenderBufferInfo::SHADOW_BUFFER);
901 if (tex == 0) continue;
903 tex->setTextureSize( mapSize, mapSize );
904 tex->dirtyTextureObject();
906 Viewport* vp = camera->getViewport();
907 vp->width() = mapSize;
908 vp->height() = mapSize;
910 osgViewer::Renderer* renderer
911 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
912 for (int i = 0; i < 2; ++i) {
913 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
914 sceneView->getRenderStage()->setFrameBufferObject(0);
915 sceneView->getRenderStage()->setCameraRequiresSetUp(true);
916 if (sceneView->getRenderStageLeft()) {
917 sceneView->getRenderStageLeft()->setFrameBufferObject(0);
918 sceneView->getRenderStageLeft()->setCameraRequiresSetUp(true);
920 if (sceneView->getRenderStageRight()) {
921 sceneView->getRenderStageRight()->setFrameBufferObject(0);
922 sceneView->getRenderStageRight()->setCameraRequiresSetUp(true);
926 int cascadeSize = mapSize / 2;
927 Group* grp = camera->getChild(0)->asGroup();
928 for (int i = 0; i < 4; ++i ) {
929 Camera* cascadeCam = static_cast<Camera*>( grp->getChild(i) );
930 cascadeCam->setViewport( int( i / 2 ) * cascadeSize, (i & 1) * cascadeSize, cascadeSize, cascadeSize );
933 _shadowMapSize = mapSize;
937 #define STRINGIFY(x) #x
938 #define TOSTRING(x) STRINGIFY(x)
940 const char *ambient_vert_src = ""
941 "#line " TOSTRING(__LINE__) " 1\n"
943 " gl_Position = gl_Vertex;\n"
944 " gl_TexCoord[0] = gl_MultiTexCoord0;\n"
947 const char *ambient_frag_src = ""
948 "#line " TOSTRING(__LINE__) " 1\n"
949 "uniform sampler2D color_tex;\n"
950 // "uniform sampler2D ao_tex;\n"
951 "uniform sampler2D normal_tex;\n"
952 "uniform sampler2D spec_emis_tex;\n"
953 "uniform vec4 fg_SunAmbientColor;\n"
955 " vec2 coords = gl_TexCoord[0].xy;\n"
956 " float initialized = texture2D( spec_emis_tex, coords ).a;\n"
957 " if ( initialized < 0.1 )\n"
959 " vec3 tcolor = texture2D( color_tex, coords ).rgb;\n"
960 // " float ao = texture2D( ao_tex, coords ).r;\n"
961 // " gl_FragColor = vec4(tcolor*fg_SunAmbientColor.rgb*ao, 1.0);\n"
962 " gl_FragColor = vec4(tcolor*fg_SunAmbientColor.rgb, 1.0);\n"
965 const char *sunlight_vert_src = ""
966 "#line " TOSTRING(__LINE__) " 1\n"
967 // "uniform mat4 fg_ViewMatrixInverse;\n"
968 "uniform mat4 fg_ProjectionMatrixInverse;\n"
969 "varying vec3 ray;\n"
971 " gl_Position = gl_Vertex;\n"
972 " gl_TexCoord[0] = gl_MultiTexCoord0;\n"
973 // " ray = (fg_ViewMatrixInverse * vec4((fg_ProjectionMatrixInverse * gl_Vertex).xyz, 0.0)).xyz;\n"
974 " ray = (fg_ProjectionMatrixInverse * gl_Vertex).xyz;\n"
977 const char *sunlight_frag_src = ""
981 "#line " TOSTRING(__LINE__) " 1\n"
982 "uniform mat4 fg_ViewMatrix;\n"
983 "uniform sampler2D depth_tex;\n"
984 "uniform sampler2D normal_tex;\n"
985 "uniform sampler2D color_tex;\n"
986 "uniform sampler2D spec_emis_tex;\n"
987 "uniform sampler2DShadow shadow_tex;\n"
988 "uniform vec4 fg_SunDiffuseColor;\n"
989 "uniform vec4 fg_SunSpecularColor;\n"
990 "uniform vec3 fg_SunDirection;\n"
991 "uniform vec3 fg_Planes;\n"
992 "varying vec3 ray;\n"
993 "vec4 DynamicShadow( in vec4 ecPosition, out vec4 tint )\n"
996 " vec2 shift = vec2( 0.0 );\n"
998 " if (ecPosition.z > -5.0) {\n"
1000 " tint = vec4(0.0,1.0,0.0,1.0);\n"
1001 " } else if (ecPosition.z > -50.0) {\n"
1003 " shift = vec2( 0.0, 0.5 );\n"
1004 " tint = vec4(0.0,0.0,1.0,1.0);\n"
1005 " } else if (ecPosition.z > -512.0) {\n"
1007 " shift = vec2( 0.5, 0.0 );\n"
1008 " tint = vec4(1.0,1.0,0.0,1.0);\n"
1009 " } else if (ecPosition.z > -10000.0) {\n"
1010 " shift = vec2( 0.5, 0.5 );\n"
1011 " tint = vec4(1.0,0.0,0.0,1.0);\n"
1013 " return vec4(1.1,1.1,0.0,1.0);\n" // outside, clamp to border
1015 " coords.s = dot( ecPosition, gl_EyePlaneS[index] );\n"
1016 " coords.t = dot( ecPosition, gl_EyePlaneT[index] );\n"
1017 " coords.p = dot( ecPosition, gl_EyePlaneR[index] );\n"
1018 " coords.q = dot( ecPosition, gl_EyePlaneQ[index] );\n"
1019 " coords.st *= .5;\n"
1020 " coords.st += shift;\n"
1024 " vec2 coords = gl_TexCoord[0].xy;\n"
1025 " vec4 spec_emis = texture2D( spec_emis_tex, coords );\n"
1026 " if ( spec_emis.a < 0.1 )\n"
1029 " normal.xy = texture2D( normal_tex, coords ).rg * 2.0 - vec2(1.0,1.0);\n"
1030 " normal.z = sqrt( 1.0 - dot( normal.xy, normal.xy ) );\n"
1031 " float len = length(normal);\n"
1033 " vec3 viewDir = normalize(ray);\n"
1034 " float depth = texture2D( depth_tex, coords ).r;\n"
1036 " pos.z = - fg_Planes.y / (fg_Planes.x + depth * fg_Planes.z);\n"
1037 " pos.xy = viewDir.xy / viewDir.z * pos.z;\n"
1041 " float shadow = 1.0;\n"
1043 " float shadow = shadow2DProj( shadow_tex, DynamicShadow( vec4( pos, 1.0 ), tint ) ).r;\n"
1045 " float kernel[9] = float[]( 36/256.0, 24/256.0, 6/256.0,\n"
1046 " 24/256.0, 16/256.0, 4/256.0,\n"
1047 " 6/256.0, 4/256.0, 1/256.0 );\n"
1048 " float shadow = 0;\n"
1049 " for( int x = -2; x <= 2; ++x )\n"
1050 " for( int y = -2; y <= 2; ++y )\n"
1051 " shadow += kernel[abs(x)*3 + abs(y)] * shadow2DProj( shadow_tex, DynamicShadow( vec4(pos + vec3(0.05 * x, 0.05 * y, 0), 1.0), tint ) ).r;\n"
1053 " vec3 lightDir = (fg_ViewMatrix * vec4( fg_SunDirection, 0.0 )).xyz;\n"
1054 " lightDir = normalize( lightDir );\n"
1055 " vec3 color = texture2D( color_tex, coords ).rgb;\n"
1056 " vec3 Idiff = clamp( dot( lightDir, normal ), 0.0, 1.0 ) * color * fg_SunDiffuseColor.rgb;\n"
1057 " vec3 halfDir = lightDir - viewDir;\n"
1058 " len = length( halfDir );\n"
1059 " vec3 Ispec = vec3(0.0);\n"
1060 " vec3 Iemis = spec_emis.z * color;\n"
1061 " if (len > 0.0001) {\n"
1062 " halfDir /= len;\n"
1063 " Ispec = pow( clamp( dot( halfDir, normal ), 0.0, 1.0 ), spec_emis.y * 255.0 ) * spec_emis.x * fg_SunSpecularColor.rgb;\n"
1065 " gl_FragColor = vec4(mix(vec3(0.0), Idiff + Ispec, shadow) + Iemis, 1.0);\n"
1066 // " gl_FragColor = mix(tint, vec4(mix(vec3(0.0), Idiff + Ispec, shadow) + Iemis, 1.0), 0.92);\n"
1069 const char *fog_vert_src = ""
1070 "#line " TOSTRING(__LINE__) " 1\n"
1071 "uniform mat4 fg_ProjectionMatrixInverse;\n"
1072 "varying vec3 ray;\n"
1074 " gl_Position = gl_Vertex;\n"
1075 " gl_TexCoord[0] = gl_MultiTexCoord0;\n"
1076 " ray = (fg_ProjectionMatrixInverse * gl_Vertex).xyz;\n"
1079 const char *fog_frag_src = ""
1080 "#line " TOSTRING(__LINE__) " 1\n"
1081 "uniform sampler2D depth_tex;\n"
1082 "uniform sampler2D normal_tex;\n"
1083 "uniform sampler2D color_tex;\n"
1084 "uniform sampler2D spec_emis_tex;\n"
1085 "uniform vec4 fg_FogColor;\n"
1086 "uniform float fg_FogDensity;\n"
1087 "uniform vec3 fg_Planes;\n"
1088 "varying vec3 ray;\n"
1090 " vec2 coords = gl_TexCoord[0].xy;\n"
1091 " float initialized = texture2D( spec_emis_tex, coords ).a;\n"
1092 " if ( initialized < 0.1 )\n"
1095 " normal.xy = texture2D( normal_tex, coords ).rg * 2.0 - vec2(1.0,1.0);\n"
1096 " normal.z = sqrt( 1.0 - dot( normal.xy, normal.xy ) );\n"
1097 " float len = length(normal);\n"
1099 " vec3 viewDir = normalize(ray);\n"
1100 " float depth = texture2D( depth_tex, coords ).r;\n"
1102 " pos.z = - fg_Planes.y / (fg_Planes.x + depth * fg_Planes.z);\n"
1103 " pos.xy = viewDir.xy / viewDir.z * pos.z;\n"
1105 " float fogFactor = 0.0;\n"
1106 " const float LOG2 = 1.442695;\n"
1107 " fogFactor = exp2(-fg_FogDensity * fg_FogDensity * pos.z * pos.z * LOG2);\n"
1108 " fogFactor = clamp(fogFactor, 0.0, 1.0);\n"
1110 " gl_FragColor = vec4(fg_FogColor.rgb, 1.0 - fogFactor);\n"
1113 osg::Camera* FGRenderer::buildDeferredLightingCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc )
1115 osg::Camera* camera = new osg::Camera;
1116 info->addCamera(flightgear::LIGHTING_CAMERA, camera );
1118 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( flightgear::LIGHTING_CAMERA, info ) );
1119 camera->setAllowEventFocus(false);
1120 camera->setGraphicsContext(gc);
1121 camera->setViewport(new Viewport);
1122 camera->setName("LightingCamera");
1123 camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1124 camera->setRenderOrder(osg::Camera::POST_RENDER, 50);
1125 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1126 camera->setViewport( new osg::Viewport );
1127 attachBufferToCamera( info, camera, osg::Camera::DEPTH_BUFFER, flightgear::LIGHTING_CAMERA, flightgear::RenderBufferInfo::DEPTH_BUFFER );
1128 attachBufferToCamera( info, camera, osg::Camera::COLOR_BUFFER, flightgear::LIGHTING_CAMERA, flightgear::RenderBufferInfo::LIGHTING_BUFFER );
1129 camera->setDrawBuffer(GL_FRONT);
1130 camera->setReadBuffer(GL_FRONT);
1131 camera->setClearColor( osg::Vec4( 0., 0., 0., 1. ) );
1132 camera->setClearMask( GL_COLOR_BUFFER_BIT );
1133 osg::StateSet* ss = camera->getOrCreateStateSet();
1134 ss->setAttribute( new osg::Depth(osg::Depth::LESS, 0.0, 1.0, false) );
1136 osg::Group* lightingGroup = new osg::Group;
1138 osg::Camera* quadCam1 = new osg::Camera;
1139 quadCam1->setName( "QuadCamera1" );
1140 quadCam1->setClearMask(0);
1141 quadCam1->setAllowEventFocus(false);
1142 quadCam1->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1143 quadCam1->setRenderOrder(osg::Camera::NESTED_RENDER);
1144 quadCam1->setViewMatrix(osg::Matrix::identity());
1145 quadCam1->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1146 quadCam1->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1147 ss = quadCam1->getOrCreateStateSet();
1148 ss->addUniform( _ambientFactor );
1149 ss->addUniform( info->projInverse );
1150 ss->addUniform( info->viewInverse );
1151 ss->addUniform( info->view );
1152 ss->addUniform( _sunDiffuse );
1153 ss->addUniform( _sunSpecular );
1154 ss->addUniform( _sunDirection );
1155 ss->addUniform( _planes );
1157 osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1158 g->setUseDisplayList(false);
1159 simgear::EffectGeode* eg = new simgear::EffectGeode;
1160 simgear::Effect* effect = simgear::makeEffect("Effects/ambient", true);
1162 eg->setEffect( effect );
1164 SG_LOG( SG_VIEW, SG_ALERT, "=> Using default, builtin, Effects/ambient" );
1165 ss = eg->getOrCreateStateSet();
1166 ss->setMode( GL_LIGHTING, osg::StateAttribute::OFF );
1167 ss->setMode( GL_DEPTH_TEST, osg::StateAttribute::OFF );
1168 ss->setTextureAttributeAndModes( 0, info->getBuffer( flightgear::RenderBufferInfo::DEPTH_BUFFER ) );
1169 ss->setTextureAttributeAndModes( 1, info->getBuffer( flightgear::RenderBufferInfo::NORMAL_BUFFER ) );
1170 ss->setTextureAttributeAndModes( 2, info->getBuffer( flightgear::RenderBufferInfo::DIFFUSE_BUFFER ) );
1171 ss->setTextureAttributeAndModes( 3, info->getBuffer( flightgear::RenderBufferInfo::SPEC_EMIS_BUFFER ) );
1172 //ss->setTextureAttributeAndModes( 4, info->gBuffer->aoBuffer[2] );
1173 ss->addUniform( new osg::Uniform( "depth_tex", 0 ) );
1174 ss->addUniform( new osg::Uniform( "normal_tex", 1 ) );
1175 ss->addUniform( new osg::Uniform( "color_tex", 2 ) );
1176 ss->addUniform( new osg::Uniform( "spec_emis_tex", 3 ) );
1177 //ss->addUniform( new osg::Uniform( "ao_tex", 4 ) );
1178 ss->setRenderBinDetails( 0, "RenderBin" );
1179 osg::Program* program = new osg::Program;
1180 program->addShader( new osg::Shader( osg::Shader::VERTEX, ambient_vert_src ) );
1181 program->addShader( new osg::Shader( osg::Shader::FRAGMENT, ambient_frag_src ) );
1182 ss->setAttributeAndModes( program );
1185 g->setName( "AmbientQuad" );
1186 eg->setName("AmbientQuad");
1187 eg->setCullingActive(false);
1189 quadCam1->addChild( eg );
1191 g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1192 g->setUseDisplayList(false);
1193 g->setName( "SunlightQuad" );
1194 eg = new simgear::EffectGeode;
1195 effect = simgear::makeEffect("Effects/sunlight", true);
1197 eg->setEffect( effect );
1199 SG_LOG( SG_VIEW, SG_ALERT, "=> Using default, builtin, Effects/sunlight" );
1200 ss = eg->getOrCreateStateSet();
1201 ss->setMode( GL_LIGHTING, osg::StateAttribute::OFF );
1202 ss->setMode( GL_DEPTH_TEST, osg::StateAttribute::OFF );
1203 ss->setAttributeAndModes( new osg::BlendFunc( osg::BlendFunc::ONE, osg::BlendFunc::ONE ) );
1204 ss->setTextureAttribute( 0, info->getBuffer( flightgear::RenderBufferInfo::DEPTH_BUFFER ) );
1205 ss->setTextureAttribute( 1, info->getBuffer( flightgear::RenderBufferInfo::NORMAL_BUFFER ) );
1206 ss->setTextureAttribute( 2, info->getBuffer( flightgear::RenderBufferInfo::DIFFUSE_BUFFER ) );
1207 ss->setTextureAttribute( 3, info->getBuffer( flightgear::RenderBufferInfo::SPEC_EMIS_BUFFER ) );
1208 ss->setTextureAttribute( 4, info->getBuffer( flightgear::RenderBufferInfo::SHADOW_BUFFER ) );
1209 ss->addUniform( new osg::Uniform( "depth_tex", 0 ) );
1210 ss->addUniform( new osg::Uniform( "normal_tex", 1 ) );
1211 ss->addUniform( new osg::Uniform( "color_tex", 2 ) );
1212 ss->addUniform( new osg::Uniform( "spec_emis_tex", 3 ) );
1213 ss->addUniform( new osg::Uniform( "shadow_tex", 4 ) );
1214 ss->setRenderBinDetails( 1, "RenderBin" );
1215 osg::Program* program = new osg::Program;
1216 program->addShader( new osg::Shader( osg::Shader::VERTEX, sunlight_vert_src ) );
1217 program->addShader( new osg::Shader( osg::Shader::FRAGMENT, sunlight_frag_src ) );
1218 ss->setAttributeAndModes( program );
1220 eg->setName("SunlightQuad");
1221 eg->setCullingActive(false);
1223 quadCam1->addChild( eg );
1225 osg::Camera* lightCam = new osg::Camera;
1226 ss = lightCam->getOrCreateStateSet();
1227 ss->addUniform( _planes );
1228 ss->addUniform( info->bufferSize );
1229 lightCam->setName( "LightCamera" );
1230 lightCam->setClearMask(0);
1231 lightCam->setAllowEventFocus(false);
1232 lightCam->setReferenceFrame(osg::Transform::RELATIVE_RF);
1233 lightCam->setRenderOrder(osg::Camera::NESTED_RENDER,1);
1234 lightCam->setViewMatrix(osg::Matrix::identity());
1235 lightCam->setProjectionMatrix(osg::Matrix::identity());
1236 lightCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1237 lightCam->setCullMask( simgear::MODELLIGHT_BIT );
1238 lightCam->setInheritanceMask( osg::CullSettings::ALL_VARIABLES & ~osg::CullSettings::CULL_MASK );
1239 lightCam->addChild( mDeferredRealRoot.get() );
1242 osg::Camera* quadCam2 = new osg::Camera;
1243 quadCam2->setName( "QuadCamera1" );
1244 quadCam2->setClearMask(0);
1245 quadCam2->setAllowEventFocus(false);
1246 quadCam2->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1247 quadCam2->setRenderOrder(osg::Camera::NESTED_RENDER,2);
1248 quadCam2->setViewMatrix(osg::Matrix::identity());
1249 quadCam2->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1250 quadCam2->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1251 ss = quadCam2->getOrCreateStateSet();
1252 ss->addUniform( _ambientFactor );
1253 ss->addUniform( info->projInverse );
1254 ss->addUniform( info->viewInverse );
1255 ss->addUniform( info->view );
1256 ss->addUniform( _sunDiffuse );
1257 ss->addUniform( _sunSpecular );
1258 ss->addUniform( _sunDirection );
1259 ss->addUniform( _fogColor );
1260 ss->addUniform( _fogDensity );
1261 ss->addUniform( _planes );
1263 g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1264 g->setUseDisplayList(false);
1265 g->setName( "FogQuad" );
1266 eg = new simgear::EffectGeode;
1267 effect = simgear::makeEffect("Effects/fog", true);
1269 eg->setEffect( effect );
1271 SG_LOG( SG_VIEW, SG_ALERT, "=> Using default, builtin, Effects/fog" );
1272 ss = eg->getOrCreateStateSet();
1273 ss->setMode( GL_LIGHTING, osg::StateAttribute::OFF );
1274 ss->setMode( GL_DEPTH_TEST, osg::StateAttribute::OFF );
1275 ss->setAttributeAndModes( new osg::BlendFunc( osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA ) );
1276 ss->setTextureAttributeAndModes( 0, info->getBuffer( flightgear::RenderBufferInfo::DEPTH_BUFFER ) );
1277 ss->setTextureAttributeAndModes( 1, info->getBuffer( flightgear::RenderBufferInfo::NORMAL_BUFFER ) );
1278 ss->setTextureAttributeAndModes( 2, info->getBuffer( flightgear::RenderBufferInfo::DIFFUSE_BUFFER ) );
1279 ss->setTextureAttributeAndModes( 3, info->getBuffer( flightgear::RenderBufferInfo::SPEC_EMIS_BUFFER ) );
1280 ss->addUniform( new osg::Uniform( "depth_tex", 0 ) );
1281 ss->addUniform( new osg::Uniform( "normal_tex", 1 ) );
1282 ss->addUniform( new osg::Uniform( "color_tex", 2 ) );
1283 ss->addUniform( new osg::Uniform( "spec_emis_tex", 3 ) );
1284 ss->setRenderBinDetails( 10000, "RenderBin" );
1285 osg::Program* program = new osg::Program;
1286 program->addShader( new osg::Shader( osg::Shader::VERTEX, fog_vert_src ) );
1287 program->addShader( new osg::Shader( osg::Shader::FRAGMENT, fog_frag_src ) );
1288 ss->setAttributeAndModes( program );
1290 eg->setName("FogQuad");
1291 eg->setCullingActive(false);
1293 quadCam2->addChild( eg );
1295 lightingGroup->addChild( _sky->getPreRoot() );
1296 lightingGroup->addChild( _sky->getCloudRoot() );
1297 lightingGroup->addChild( quadCam1 );
1298 lightingGroup->addChild( lightCam );
1299 lightingGroup->addChild( quadCam2 );
1301 camera->addChild( lightingGroup );
1306 flightgear::CameraInfo*
1307 FGRenderer::buildDeferredPipeline(flightgear::CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1308 const osg::Matrix& view,
1309 const osg::Matrix& projection,
1310 osg::GraphicsContext* gc)
1312 CameraInfo* info = new CameraInfo(flags);
1313 buildDeferredBuffers( info, _shadowMapSize, !fgGetBool("/sim/rendering/no-16bit-buffer", false ) );
1315 osg::Camera* geometryCamera = buildDeferredGeometryCamera( info, gc );
1316 cgroup->getViewer()->addSlave(geometryCamera, false);
1317 installCullVisitor(geometryCamera);
1318 int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1319 info->getRenderStageInfo(GEOMETRY_CAMERA).slaveIndex = slaveIndex;
1321 Camera* shadowCamera = buildDeferredShadowCamera( info, gc );
1322 cgroup->getViewer()->addSlave(shadowCamera, false);
1323 installCullVisitor(shadowCamera);
1324 slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1325 info->getRenderStageInfo(SHADOW_CAMERA).slaveIndex = slaveIndex;
1327 osg::Camera* lightingCamera = buildDeferredLightingCamera( info, gc );
1328 cgroup->getViewer()->addSlave(lightingCamera, false);
1329 installCullVisitor(lightingCamera);
1330 slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1331 info->getRenderStageInfo(LIGHTING_CAMERA).slaveIndex = slaveIndex;
1333 camera->setName( "DisplayCamera" );
1334 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( flightgear::DISPLAY_CAMERA, info ) );
1335 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
1336 camera->setAllowEventFocus(false);
1337 osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1338 g->setUseDisplayList(false); //DEBUG
1339 simgear::EffectGeode* eg = new simgear::EffectGeode;
1340 simgear::Effect* effect = simgear::makeEffect("Effects/display", true);
1342 SG_LOG(SG_VIEW, SG_ALERT, "Effects/display not found");
1345 eg->setEffect(effect);
1346 eg->setCullingActive(false);
1348 camera->setViewMatrix(osg::Matrix::identity());
1349 camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1350 camera->addChild(eg);
1352 cgroup->getViewer()->addSlave(camera, false);
1353 installCullVisitor(camera);
1354 slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1355 info->addCamera( DISPLAY_CAMERA, camera, slaveIndex, true );
1356 camera->setRenderOrder(Camera::POST_RENDER, 99+slaveIndex); //FIXME
1357 cgroup->addCamera(info);
1363 FGRenderer::setupView( void )
1365 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1366 osg::initNotifyLevel();
1368 // The number of polygon-offset "units" to place between layers. In
1369 // principle, one is supposed to be enough. In practice, I find that
1370 // my hardware/driver requires many more.
1371 osg::PolygonOffset::setUnitsMultiplier(1);
1372 osg::PolygonOffset::setFactorMultiplier(1);
1374 // Go full screen if requested ...
1375 if ( fgGetBool("/sim/startup/fullscreen") )
1379 // The sun and moon diameters are scaled down numbers of the
1380 // actual diameters. This was needed to fit both the sun and the
1381 // moon within the distance to the far clip plane.
1382 // Moon diameter: 3,476 kilometers
1383 // Sun diameter: 1,390,000 kilometers
1384 _sky->build( 80000.0, 80000.0,
1386 *globals->get_ephem(),
1387 fgGetNode("/environment", true));
1390 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1392 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
1394 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
1396 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
1397 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1399 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
1400 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
1401 stateSet->setAttribute(new osg::BlendFunc);
1402 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
1404 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
1406 // this will be set below
1407 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
1409 osg::Material* material = new osg::Material;
1410 stateSet->setAttribute(material);
1412 stateSet->setTextureAttribute(0, new osg::TexEnv);
1413 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
1415 osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
1416 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
1417 stateSet->setAttribute(hint);
1418 hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
1419 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
1420 stateSet->setAttribute(hint);
1421 hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
1422 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
1423 stateSet->setAttribute(hint);
1424 hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
1425 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
1426 stateSet->setAttribute(hint);
1427 hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
1428 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
1429 stateSet->setAttribute(hint);
1431 osg::Group* sceneGroup = new osg::Group;
1432 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
1433 sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
1435 //sceneGroup->addChild(thesky->getCloudRoot());
1437 stateSet = sceneGroup->getOrCreateStateSet();
1438 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1440 // need to update the light on every frame
1441 // OSG LightSource objects are rather confusing. OSG only supports
1442 // the 10 lights specified by OpenGL itself; if more than one
1443 // LightSource in the scene graph have the same light number, it's
1444 // indeterminate which values will be used to render geometry that
1445 // has that light number enabled. Also, adding children to a
1446 // LightSource is just a shortcut for setting up a state set that
1447 // has the corresponding OpenGL light enabled: a LightSource will
1448 // affect geometry anywhere in the scene graph that has its light
1449 // number enabled in a state set.
1450 LightSource* lightSource = new LightSource;
1451 lightSource->getLight()->setDataVariance(Object::DYNAMIC);
1452 // relative because of CameraView being just a clever transform node
1453 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1454 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
1455 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
1456 mRealRoot->addChild(lightSource);
1457 // we need a white diffuse light for the phase of the moon
1458 osg::LightSource* sunLight = new osg::LightSource;
1459 sunLight->getLight()->setDataVariance(Object::DYNAMIC);
1460 sunLight->getLight()->setLightNum(1);
1461 sunLight->setUpdateCallback(new FGLightSourceUpdateCallback(true));
1462 sunLight->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1463 sunLight->setLocalStateSetModes(osg::StateAttribute::ON);
1465 // Hang a StateSet above the sky subgraph in order to turn off
1467 Group* skyGroup = new Group;
1468 StateSet* skySS = skyGroup->getOrCreateStateSet();
1469 skySS->setMode(GL_LIGHT0, StateAttribute::OFF);
1470 skyGroup->addChild(_sky->getPreRoot());
1471 sunLight->addChild(skyGroup);
1472 mRoot->addChild(sceneGroup);
1473 mRoot->addChild(sunLight);
1475 // Clouds are added to the scene graph later
1476 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
1477 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
1478 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
1479 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1481 // enable disable specular highlights.
1482 // is the place where we might plug in an other fragment shader ...
1483 osg::LightModel* lightModel = new osg::LightModel;
1484 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
1485 stateSet->setAttribute(lightModel);
1487 // switch to enable wireframe
1488 osg::PolygonMode* polygonMode = new osg::PolygonMode;
1489 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
1490 stateSet->setAttributeAndModes(polygonMode);
1492 // scene fog handling
1493 osg::Fog* fog = new osg::Fog;
1494 fog->setUpdateCallback(new FGFogUpdateCallback);
1495 stateSet->setAttributeAndModes(fog);
1496 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
1499 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
1502 osg::Geode* geode = new osg::Geode;
1503 geode->addDrawable(new SGPuDrawable);
1504 geode->addDrawable(new SGHUDDrawable);
1505 guiCamera->addChild(geode);
1507 panelSwitch = new osg::Switch;
1508 osg::StateSet* stateSet = panelSwitch->getOrCreateStateSet();
1509 stateSet->setRenderBinDetails(1000, "RenderBin");
1511 // speed optimization?
1512 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
1513 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
1514 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
1515 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
1516 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1519 panelSwitch->setUpdateCallback(new FGPanelSwitchCallback);
1522 guiCamera->addChild(panelSwitch.get());
1525 osg::Switch* sw = new osg::Switch;
1526 sw->setUpdateCallback(new FGScenerySwitchCallback);
1527 sw->addChild(mRoot.get());
1528 mRealRoot->addChild(sw);
1529 // The clouds are attached directly to the scene graph root
1530 // because, in theory, they don't want the same default state set
1531 // as the rest of the scene. This may not be true in practice.
1532 if ( _classicalRenderer ) {
1533 mRealRoot->addChild(_sky->getCloudRoot());
1534 mRealRoot->addChild(FGCreateRedoutNode());
1536 // Attach empty program to the scene root so that shader programs
1537 // don't leak into state sets (effects) that shouldn't have one.
1538 stateSet = mRealRoot->getOrCreateStateSet();
1539 stateSet->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON);
1541 mDeferredRealRoot->addChild( mRealRoot.get() );
1544 void FGRenderer::panelChanged()
1550 osg::Node* n = FGPanelNode::createNode(globals->get_current_panel());
1551 if (panelSwitch->getNumChildren()) {
1552 panelSwitch->setChild(0, n);
1554 panelSwitch->addChild(n);
1558 // Update all Visuals (redraws anything graphics related)
1560 FGRenderer::update( ) {
1561 if (!(_scenery_loaded->getBoolValue() ||
1562 _scenery_override->getBoolValue()))
1564 _splash_alpha->setDoubleValue(1.0);
1567 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1569 if (_splash_alpha->getDoubleValue()>0.0)
1571 // Fade out the splash screen
1572 const double fade_time = 0.8;
1573 const double fade_steps_per_sec = 20;
1574 double delay_time = SGMiscd::min(fade_time/fade_steps_per_sec,
1575 (SGTimeStamp::now() - _splash_time).toSecs());
1576 _splash_time = SGTimeStamp::now();
1577 double sAlpha = _splash_alpha->getDoubleValue();
1578 sAlpha -= SGMiscd::max(0.0,delay_time/fade_time);
1579 FGScenerySwitchCallback::scenery_enabled = (sAlpha<1.0);
1580 _splash_alpha->setDoubleValue((sAlpha < 0) ? 0.0 : sAlpha);
1583 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
1584 if (!_classicalRenderer ) {
1585 _ambientFactor->set( toOsg(l->scene_ambient()) );
1586 _sunDiffuse->set( toOsg(l->scene_diffuse()) );
1587 _sunSpecular->set( toOsg(l->scene_specular()) );
1588 _sunDirection->set( osg::Vec3f(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]) );
1591 // update fog params
1592 double actual_visibility;
1593 if (_cloud_status->getBoolValue()) {
1594 actual_visibility = _sky->get_visibility();
1596 actual_visibility = _visibility_m->getDoubleValue();
1599 // idle_state is now 1000 meaning we've finished all our
1600 // initializations and are running the main loop, so this will
1601 // now work without seg faulting the system.
1603 FGViewer *current__view = globals->get_current_view();
1604 // Force update of center dependent values ...
1605 current__view->set_dirty();
1607 osg::Camera *camera = viewer->getCamera();
1609 bool skyblend = _skyblend->getBoolValue();
1612 if ( _textures->getBoolValue() ) {
1613 SGVec4f clearColor(l->adj_fog_color());
1614 camera->setClearColor(toOsg(clearColor));
1617 SGVec4f clearColor(l->sky_color());
1618 camera->setClearColor(toOsg(clearColor));
1621 // update fog params if visibility has changed
1622 double visibility_meters = _visibility_m->getDoubleValue();
1623 _sky->set_visibility(visibility_meters);
1625 double altitude_m = _altitude_ft->getDoubleValue() * SG_FEET_TO_METER;
1626 _sky->modify_vis( altitude_m, 0.0 /* time factor, now unused */);
1628 // update the sky dome
1631 // The sun and moon distances are scaled down versions
1632 // of the actual distance to get both the moon and the sun
1633 // within the range of the far clip plane.
1634 // Moon distance: 384,467 kilometers
1635 // Sun distance: 150,000,000 kilometers
1637 double sun_horiz_eff, moon_horiz_eff;
1638 if (_horizon_effect->getBoolValue()) {
1640 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
1644 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
1648 sun_horiz_eff = moon_horiz_eff = 1.0;
1652 sstate.pos = current__view->getViewPosition();
1653 sstate.pos_geod = current__view->getPosition();
1654 sstate.ori = current__view->getViewOrientation();
1655 sstate.spin = l->get_sun_rotation();
1656 sstate.gst = globals->get_time_params()->getGst();
1657 sstate.sun_dist = 50000.0 * sun_horiz_eff;
1658 sstate.moon_dist = 40000.0 * moon_horiz_eff;
1659 sstate.sun_angle = l->get_sun_angle();
1662 scolor.sky_color = SGVec3f(l->sky_color().data());
1663 scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
1664 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
1665 scolor.cloud_color = SGVec3f(l->cloud_color().data());
1666 scolor.sun_angle = l->get_sun_angle();
1667 scolor.moon_angle = l->get_moon_angle();
1669 double delta_time_sec = _sim_delta_sec->getDoubleValue();
1670 _sky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
1671 _sky->repaint( scolor, *globals->get_ephem() );
1674 // shadows->setupShadows(
1675 // current__view->getLongitude_deg(),
1676 // current__view->getLatitude_deg(),
1677 // globals->get_time_params()->getGst(),
1678 // globals->get_ephem()->getSunRightAscension(),
1679 // globals->get_ephem()->getSunDeclination(),
1680 // l->get_sun_angle());
1684 // sgEnviro.setLight(l->adj_fog_color());
1685 // sgEnviro.startOfFrame(current__view->get_view_pos(),
1686 // current__view->get_world_up(),
1687 // current__view->getLongitude_deg(),
1688 // current__view->getLatitude_deg(),
1689 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
1693 // sgEnviro.drawLightning();
1695 // double current_view_origin_airspeed_horiz_kt =
1696 // fgGetDouble("/velocities/airspeed-kt", 0.0)
1697 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
1698 // * SGD_DEGREES_TO_RADIANS);
1701 // if( is_internal )
1702 // shadows->endOfFrame();
1704 // need to call the update visitor once
1705 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
1706 mUpdateVisitor->setViewData(current__view->getViewPosition(),
1707 current__view->getViewOrientation());
1708 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
1709 mUpdateVisitor->setLight(direction, l->scene_ambient(),
1710 l->scene_diffuse(), l->scene_specular(),
1712 l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
1713 mUpdateVisitor->setVisibility(actual_visibility);
1714 simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
1715 osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
1716 cullMask |= simgear::GroundLightManager::instance()
1717 ->getLightNodeMask(mUpdateVisitor.get());
1718 if (_panel_hotspots->getBoolValue())
1719 cullMask |= simgear::PICK_BIT;
1720 CameraGroup::getDefault()->setCameraCullMasks(cullMask);
1721 if ( !_classicalRenderer ) {
1722 _fogColor->set( toOsg( l->adj_fog_color() ) );
1723 _fogDensity->set( float( mUpdateVisitor->getFogExp2Density() ) );
1728 FGRenderer::resize( int width, int height )
1730 int curWidth = _xsize->getIntValue(),
1731 curHeight = _ysize->getIntValue();
1732 SG_LOG(SG_VIEW, SG_DEBUG, "FGRenderer::resize: new size " << width << " x " << height);
1733 if ((curHeight != height) || (curWidth != width)) {
1734 // must guard setting these, or PLIB-PUI fails with too many live interfaces
1735 _xsize->setIntValue(width);
1736 _ysize->setIntValue(height);
1741 FGRenderer::pick(std::vector<SGSceneryPick>& pickList,
1742 const osgGA::GUIEventAdapter* ea)
1744 // wipe out the return ...
1746 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
1747 Intersections intersections;
1749 if (!computeIntersections(CameraGroup::getDefault(), ea, intersections))
1751 for (Intersections::iterator hit = intersections.begin(),
1752 e = intersections.end();
1755 const osg::NodePath& np = hit->nodePath;
1756 osg::NodePath::const_reverse_iterator npi;
1757 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
1758 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
1761 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
1762 SGPickCallback* pickCallback = ud->getPickCallback(i);
1765 SGSceneryPick sceneryPick;
1766 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
1767 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
1768 sceneryPick.callback = pickCallback;
1769 pickList.push_back(sceneryPick);
1773 return !pickList.empty();
1777 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
1783 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
1785 eventHandler = eventHandler_;
1789 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
1791 mRealRoot->addChild(camera);
1795 FGRenderer::setPlanes( double zNear, double zFar )
1797 _planes->set( osg::Vec3f( - zFar, - zFar * zNear, zFar - zNear ) );
1801 fgDumpSceneGraphToFile(const char* filename)
1803 return osgDB::writeNodeFile(*mRealRoot.get(), filename);
1807 fgDumpTerrainBranchToFile(const char* filename)
1809 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
1815 fgDumpNodeToFile(osg::Node* node, const char* filename)
1817 return osgDB::writeNodeFile(*node, filename);
1820 namespace flightgear
1822 using namespace osg;
1824 class VisibleSceneInfoVistor : public NodeVisitor, CullStack
1827 VisibleSceneInfoVistor()
1828 : NodeVisitor(CULL_VISITOR, TRAVERSE_ACTIVE_CHILDREN)
1830 setCullingMode(CullSettings::SMALL_FEATURE_CULLING
1831 | CullSettings::VIEW_FRUSTUM_CULLING);
1832 setComputeNearFarMode(CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1835 VisibleSceneInfoVistor(const VisibleSceneInfoVistor& rhs)
1839 META_NodeVisitor("flightgear","VisibleSceneInfoVistor")
1841 typedef std::map<const std::string,int> InfoMap;
1843 void getNodeInfo(Node* node)
1845 const char* typeName = typeid(*node).name();
1846 classInfo[typeName]++;
1847 const std::string& nodeName = node->getName();
1848 if (!nodeName.empty())
1849 nodeInfo[nodeName]++;
1854 using namespace std;
1855 typedef vector<InfoMap::iterator> FreqVector;
1856 cout << "class info:\n";
1858 for (InfoMap::iterator itr = classInfo.begin(), end = classInfo.end();
1861 classes.push_back(itr);
1862 sort(classes.begin(), classes.end(), freqComp);
1863 for (FreqVector::iterator itr = classes.begin(), end = classes.end();
1866 cout << (*itr)->first << " " << (*itr)->second << "\n";
1868 cout << "\nnode info:\n";
1870 for (InfoMap::iterator itr = nodeInfo.begin(), end = nodeInfo.end();
1873 nodes.push_back(itr);
1875 sort (nodes.begin(), nodes.end(), freqComp);
1876 for (FreqVector::iterator itr = nodes.begin(), end = nodes.end();
1879 cout << (*itr)->first << " " << (*itr)->second << "\n";
1884 void doTraversal(Camera* camera, Node* root, Viewport* viewport)
1886 ref_ptr<RefMatrix> projection
1887 = createOrReuseMatrix(camera->getProjectionMatrix());
1888 ref_ptr<RefMatrix> mv = createOrReuseMatrix(camera->getViewMatrix());
1890 viewport = camera->getViewport();
1892 pushViewport(viewport);
1893 pushProjectionMatrix(projection.get());
1894 pushModelViewMatrix(mv.get(), Transform::ABSOLUTE_RF);
1895 root->accept(*this);
1896 popModelViewMatrix();
1897 popProjectionMatrix();
1903 void apply(Node& node)
1912 void apply(Group& node)
1922 void apply(Transform& node)
1927 ref_ptr<RefMatrix> matrix = createOrReuseMatrix(*getModelViewMatrix());
1928 node.computeLocalToWorldMatrix(*matrix,this);
1929 pushModelViewMatrix(matrix.get(), node.getReferenceFrame());
1932 popModelViewMatrix();
1936 void apply(Camera& camera)
1938 // Save current cull settings
1939 CullSettings saved_cull_settings(*this);
1941 // set cull settings from this Camera
1942 setCullSettings(camera);
1943 // inherit the settings from above
1944 inheritCullSettings(saved_cull_settings, camera.getInheritanceMask());
1946 // set the cull mask.
1947 unsigned int savedTraversalMask = getTraversalMask();
1948 bool mustSetCullMask = (camera.getInheritanceMask()
1949 & osg::CullSettings::CULL_MASK) == 0;
1950 if (mustSetCullMask)
1951 setTraversalMask(camera.getCullMask());
1953 osg::RefMatrix* projection = 0;
1954 osg::RefMatrix* modelview = 0;
1956 if (camera.getReferenceFrame()==osg::Transform::RELATIVE_RF) {
1957 if (camera.getTransformOrder()==osg::Camera::POST_MULTIPLY) {
1958 projection = createOrReuseMatrix(*getProjectionMatrix()
1959 *camera.getProjectionMatrix());
1960 modelview = createOrReuseMatrix(*getModelViewMatrix()
1961 * camera.getViewMatrix());
1963 else { // pre multiply
1964 projection = createOrReuseMatrix(camera.getProjectionMatrix()
1965 * (*getProjectionMatrix()));
1966 modelview = createOrReuseMatrix(camera.getViewMatrix()
1967 * (*getModelViewMatrix()));
1970 // an absolute reference frame
1971 projection = createOrReuseMatrix(camera.getProjectionMatrix());
1972 modelview = createOrReuseMatrix(camera.getViewMatrix());
1974 if (camera.getViewport())
1975 pushViewport(camera.getViewport());
1977 pushProjectionMatrix(projection);
1978 pushModelViewMatrix(modelview, camera.getReferenceFrame());
1982 // restore the previous model view matrix.
1983 popModelViewMatrix();
1985 // restore the previous model view matrix.
1986 popProjectionMatrix();
1988 if (camera.getViewport()) popViewport();
1990 // restore the previous traversal mask settings
1991 if (mustSetCullMask)
1992 setTraversalMask(savedTraversalMask);
1994 // restore the previous cull settings
1995 setCullSettings(saved_cull_settings);
2000 static bool freqComp(const InfoMap::iterator& lhs, const InfoMap::iterator& rhs)
2002 return lhs->second > rhs->second;
2008 bool printVisibleSceneInfo(FGRenderer* renderer)
2010 osgViewer::Viewer* viewer = renderer->getViewer();
2011 VisibleSceneInfoVistor vsv;
2013 if (!viewer->getCamera()->getViewport() && viewer->getNumSlaves() > 0) {
2014 const View::Slave& slave = viewer->getSlave(0);
2015 vp = slave._camera->getViewport();
2017 vsv.doTraversal(viewer->getCamera(), viewer->getSceneData(), vp);
2022 // end of renderer.cxx