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/DeletionManager.hxx>
78 #include <simgear/scene/util/SGUpdateVisitor.hxx>
79 #include <simgear/scene/util/RenderConstants.hxx>
80 #include <simgear/scene/util/SGSceneUserData.hxx>
81 #include <simgear/scene/tgdb/GroundLightManager.hxx>
82 #include <simgear/scene/tgdb/pt_lights.hxx>
83 #include <simgear/scene/tgdb/userdata.hxx>
84 #include <simgear/structure/OSGUtils.hxx>
85 #include <simgear/props/props.hxx>
86 #include <simgear/timing/sg_time.hxx>
87 #include <simgear/ephemeris/ephemeris.hxx>
88 #include <simgear/math/sg_random.h>
90 #include <simgear/screen/jpgfactory.hxx>
93 #include <Time/light.hxx>
94 #include <Time/light.hxx>
95 #include <Cockpit/panel.hxx>
97 #include <Model/panelnode.hxx>
98 #include <Model/modelmgr.hxx>
99 #include <Model/acmodel.hxx>
100 #include <Scenery/scenery.hxx>
101 #include <Scenery/redout.hxx>
102 #include <GUI/new_gui.hxx>
103 #include <Instrumentation/HUD/HUD.hxx>
104 #include <Environment/precipitation_mgr.hxx>
105 #include <Environment/environment_mgr.hxx>
107 //#include <Main/main.hxx>
108 #include "viewer.hxx"
109 #include "viewmgr.hxx"
110 #include "splash.hxx"
111 #include "renderer.hxx"
112 #include "CameraGroup.hxx"
113 #include "FGEventHandler.hxx"
118 using namespace simgear;
119 using namespace flightgear;
121 class FGHintUpdateCallback : public osg::StateAttribute::Callback {
123 FGHintUpdateCallback(const char* configNode) :
124 mConfigNode(fgGetNode(configNode, true))
126 virtual void operator()(osg::StateAttribute* stateAttribute,
129 assert(dynamic_cast<osg::Hint*>(stateAttribute));
130 osg::Hint* hint = static_cast<osg::Hint*>(stateAttribute);
132 const char* value = mConfigNode->getStringValue();
134 hint->setMode(GL_DONT_CARE);
135 else if (0 == strcmp(value, "nicest"))
136 hint->setMode(GL_NICEST);
137 else if (0 == strcmp(value, "fastest"))
138 hint->setMode(GL_FASTEST);
140 hint->setMode(GL_DONT_CARE);
143 SGPropertyNode_ptr mConfigNode;
147 class SGPuDrawable : public osg::Drawable {
151 // Dynamic stuff, do not store geometry
152 setUseDisplayList(false);
153 setDataVariance(Object::DYNAMIC);
155 osg::StateSet* stateSet = getOrCreateStateSet();
156 stateSet->setRenderBinDetails(1001, "RenderBin");
157 // speed optimization?
158 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
159 // We can do translucent menus, so why not. :-)
160 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
161 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
162 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
164 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
166 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
167 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
169 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
170 { drawImplementation(*renderInfo.getState()); }
171 void drawImplementation(osg::State& state) const
173 state.setActiveTextureUnit(0);
174 state.setClientActiveTextureUnit(0);
176 state.disableAllVertexArrays();
178 glPushAttrib(GL_ALL_ATTRIB_BITS);
179 glPushClientAttrib(~0u);
187 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
188 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
193 class SGHUDDrawable : public osg::Drawable {
197 // Dynamic stuff, do not store geometry
198 setUseDisplayList(false);
199 setDataVariance(Object::DYNAMIC);
201 osg::StateSet* stateSet = getOrCreateStateSet();
202 stateSet->setRenderBinDetails(1000, "RenderBin");
204 // speed optimization?
205 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
206 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
207 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
208 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
209 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
211 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
213 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
214 { drawImplementation(*renderInfo.getState()); }
215 void drawImplementation(osg::State& state) const
217 state.setActiveTextureUnit(0);
218 state.setClientActiveTextureUnit(0);
219 state.disableAllVertexArrays();
221 glPushAttrib(GL_ALL_ATTRIB_BITS);
222 glPushClientAttrib(~0u);
225 HUD *hud = static_cast<HUD*>(globals->get_subsystem("hud"));
234 virtual osg::Object* cloneType() const { return new SGHUDDrawable; }
235 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDDrawable; }
240 class FGLightSourceUpdateCallback : public osg::NodeCallback {
244 * @param isSun true if the light is the actual sun i.e., for
245 * illuminating the moon.
247 FGLightSourceUpdateCallback(bool isSun = false) : _isSun(isSun) {}
248 FGLightSourceUpdateCallback(const FGLightSourceUpdateCallback& nc,
250 : NodeCallback(nc, op), _isSun(nc._isSun)
252 META_Object(flightgear,FGLightSourceUpdateCallback);
254 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
256 assert(dynamic_cast<osg::LightSource*>(node));
257 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
258 osg::Light* light = lightSource->getLight();
260 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
262 // lighting is down during re-init
267 light->setAmbient(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
268 light->setDiffuse(Vec4(1.0f, 1.0f, 1.0f, 1.0f));
269 light->setSpecular(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
271 light->setAmbient(toOsg(l->scene_ambient()));
272 light->setDiffuse(toOsg(l->scene_diffuse()));
273 light->setSpecular(toOsg(l->scene_specular()));
275 osg::Vec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
276 light->setPosition(position);
284 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
286 FGWireFrameModeUpdateCallback() :
287 mWireframe(fgGetNode("/sim/rendering/wireframe", true))
289 virtual void operator()(osg::StateAttribute* stateAttribute,
292 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
293 osg::PolygonMode* polygonMode;
294 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
296 if (mWireframe->getBoolValue())
297 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
298 osg::PolygonMode::LINE);
300 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
301 osg::PolygonMode::FILL);
304 SGPropertyNode_ptr mWireframe;
307 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
309 FGLightModelUpdateCallback() :
310 mHighlights(fgGetNode("/sim/rendering/specular-highlight", true))
312 virtual void operator()(osg::StateAttribute* stateAttribute,
315 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
316 osg::LightModel* lightModel;
317 lightModel = static_cast<osg::LightModel*>(stateAttribute);
320 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
321 lightModel->setAmbientIntensity(toOsg(l->scene_ambient());
323 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
325 lightModel->setTwoSided(true);
326 lightModel->setLocalViewer(false);
328 if (mHighlights->getBoolValue()) {
329 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
331 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
335 SGPropertyNode_ptr mHighlights;
338 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
340 FGFogEnableUpdateCallback() :
341 mFogEnabled(fgGetNode("/sim/rendering/fog", true))
343 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
345 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
346 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
348 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
352 SGPropertyNode_ptr mFogEnabled;
355 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
357 virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
359 assert(dynamic_cast<SGUpdateVisitor*>(nv));
360 assert(dynamic_cast<osg::Fog*>(sa));
361 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
362 osg::Fog* fog = static_cast<osg::Fog*>(sa);
363 fog->setMode(osg::Fog::EXP2);
364 fog->setColor(toOsg(updateVisitor->getFogColor()));
365 fog->setDensity(updateVisitor->getFogExp2Density());
369 // update callback for the switch node guarding that splash
370 class FGScenerySwitchCallback : public osg::NodeCallback {
372 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
374 assert(dynamic_cast<osg::Switch*>(node));
375 osg::Switch* sw = static_cast<osg::Switch*>(node);
377 bool enabled = scenery_enabled;
378 sw->setValue(0, enabled);
384 static bool scenery_enabled;
387 bool FGScenerySwitchCallback::scenery_enabled = false;
389 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
390 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
392 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
393 static osg::ref_ptr<osg::Group> mDeferredRealRoot = new osg::Group;
395 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
397 #ifdef FG_JPEG_SERVER
398 static void updateRenderer()
400 globals->get_renderer()->update();
404 FGRenderer::FGRenderer() :
406 _ambientFactor( new osg::Uniform( "fg_SunAmbientColor", osg::Vec4f() ) ),
407 _sunDiffuse( new osg::Uniform( "fg_SunDiffuseColor", osg::Vec4f() ) ),
408 _sunSpecular( new osg::Uniform( "fg_SunSpecularColor", osg::Vec4f() ) ),
409 _sunDirection( new osg::Uniform( "fg_SunDirection", osg::Vec3f() ) ),
410 _planes( new osg::Uniform( "fg_Planes", osg::Vec3f() ) ),
411 _fogColor( new osg::Uniform( "fg_FogColor", osg::Vec4f(1.0, 1.0, 1.0, 1.0) ) ),
412 _fogDensity( new osg::Uniform( "fg_FogDensity", 0.0001f ) ),
413 _shadowNumber( new osg::Uniform( "fg_ShadowNumber", (int)4 ) ),
414 _shadowDistances( new osg::Uniform( "fg_ShadowDistances", osg::Vec4f(5.0, 50.0, 500.0, 5000.0 ) ) ),
415 _depthInColor( new osg::Uniform( "fg_DepthInColor", false ) )
417 #ifdef FG_JPEG_SERVER
418 jpgRenderFrame = updateRenderer;
421 // it's not the real root, whatever that means
422 mRoot->setName("fakeRoot");
425 _cascadeFar[0] = 5.f;
426 _cascadeFar[1] = 50.f;
427 _cascadeFar[2] = 500.f;
428 _cascadeFar[3] = 5000.f;
431 FGRenderer::~FGRenderer()
433 #ifdef FG_JPEG_SERVER
434 jpgRenderFrame = NULL;
439 // Initialize various GL/view parameters
440 // XXX This should be called "preinit" or something, as it initializes
441 // critical parts of the scene graph in addition to the splash screen.
443 FGRenderer::splashinit( void ) {
444 osgViewer::Viewer* viewer = getViewer();
445 viewer->setName("osgViewer");
446 mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
447 mRealRoot->setName("realRoot");
449 ref_ptr<Node> splashNode = fgCreateSplashNode();
450 if (_classicalRenderer) {
451 mRealRoot->addChild(splashNode.get());
453 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
454 ii != CameraGroup::getDefault()->camerasEnd();
457 CameraInfo* info = ii->get();
458 Camera* camera = info->getCamera(DISPLAY_CAMERA);
459 if (camera == 0) continue;
461 camera->addChild(splashNode.get());
464 mFrameStamp = viewer->getFrameStamp();
465 // Scene doesn't seem to pass the frame stamp to the update
466 // visitor automatically.
467 mUpdateVisitor->setFrameStamp(mFrameStamp.get());
468 viewer->setUpdateVisitor(mUpdateVisitor.get());
469 fgSetDouble("/sim/startup/splash-alpha", 1.0);
472 class ShadowMapSizeListener : public SGPropertyChangeListener {
474 virtual void valueChanged(SGPropertyNode* node) {
475 globals->get_renderer()->updateShadowMapSize(node->getIntValue());
479 class ShadowEnabledListener : public SGPropertyChangeListener {
481 virtual void valueChanged(SGPropertyNode* node) {
482 globals->get_renderer()->enableShadows(node->getBoolValue());
486 class ShadowNumListener : public SGPropertyChangeListener {
488 virtual void valueChanged(SGPropertyNode* node) {
489 globals->get_renderer()->updateCascadeNumber(node->getIntValue());
493 class ShadowRangeListener : public SGPropertyChangeListener {
495 virtual void valueChanged(SGPropertyNode* node) {
496 globals->get_renderer()->updateCascadeFar(node->getIndex(), node->getFloatValue());
501 FGRenderer::init( void )
504 eventHandler = new FGEventHandler();
506 sgUserDataInit( globals->get_props() );
508 _classicalRenderer = !fgGetBool("/sim/rendering/rembrandt/enabled", false);
509 _shadowMapSize = fgGetInt( "/sim/rendering/shadows/map-size", 4096 );
510 fgAddChangeListener( new ShadowMapSizeListener, "/sim/rendering/shadows/map-size" );
511 fgAddChangeListener( new ShadowEnabledListener, "/sim/rendering/shadows/enabled" );
512 ShadowRangeListener* srl = new ShadowRangeListener;
513 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[0]");
514 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[1]");
515 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[2]");
516 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[3]");
517 fgAddChangeListener(new ShadowNumListener, "/sim/rendering/shadows/num-cascades");
518 _numCascades = fgGetInt("/sim/rendering/shadows/num-cascades", 4);
519 _cascadeFar[0] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[0]", 5.0f);
520 _cascadeFar[1] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[1]", 50.0f);
521 _cascadeFar[2] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[2]", 500.0f);
522 _cascadeFar[3] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[3]", 5000.0f);
523 updateCascadeNumber(_numCascades);
524 updateCascadeFar(0, _cascadeFar[0]);
525 updateCascadeFar(1, _cascadeFar[1]);
526 updateCascadeFar(2, _cascadeFar[2]);
527 updateCascadeFar(3, _cascadeFar[3]);
528 _useColorForDepth = fgGetBool( "/sim/rendering/rembrandt/use-color-for-depth", false );
529 _depthInColor->set( _useColorForDepth );
531 _renderer = fgGetString("/sim/rendering/rembrandt/renderer", "default-pipeline");
532 if (!_classicalRenderer)
533 _pipeline = makeRenderingPipeline(_renderer, 0);
534 _scenery_loaded = fgGetNode("/sim/sceneryloaded", true);
535 _position_finalized = fgGetNode("/sim/position-finalized", true);
537 _panel_hotspots = fgGetNode("/sim/panel-hotspots", true);
538 _virtual_cockpit = fgGetNode("/sim/virtual-cockpit", true);
540 _sim_delta_sec = fgGetNode("/sim/time/delta-sec", true);
542 _xsize = fgGetNode("/sim/startup/xsize", true);
543 _ysize = fgGetNode("/sim/startup/ysize", true);
544 _splash_alpha = fgGetNode("/sim/startup/splash-alpha", true);
546 _skyblend = fgGetNode("/sim/rendering/skyblend", true);
547 _point_sprites = fgGetNode("/sim/rendering/point-sprites", true);
548 _enhanced_lighting = fgGetNode("/sim/rendering/enhanced-lighting", true);
549 _distance_attenuation = fgGetNode("/sim/rendering/distance-attenuation", true);
550 _horizon_effect = fgGetNode("/sim/rendering/horizon-effect", true);
551 _textures = fgGetNode("/sim/rendering/textures", true);
553 _altitude_ft = fgGetNode("/position/altitude-ft", true);
555 _cloud_status = fgGetNode("/environment/clouds/status", true);
556 _visibility_m = fgGetNode("/environment/visibility-m", true);
558 bool use_point_sprites = _point_sprites->getBoolValue();
559 bool enhanced_lighting = _enhanced_lighting->getBoolValue();
560 bool distance_attenuation = _distance_attenuation->getBoolValue();
562 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
563 distance_attenuation );
565 if (const char* tc = fgGetString("/sim/rendering/texture-compression", NULL)) {
566 if (strcmp(tc, "false") == 0 || strcmp(tc, "off") == 0 ||
567 strcmp(tc, "0") == 0 || strcmp(tc, "no") == 0 ||
568 strcmp(tc, "none") == 0) {
569 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::DoNotUseCompression);
570 } else if (strcmp(tc, "arb") == 0) {
571 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseARBCompression);
572 } else if (strcmp(tc, "dxt1") == 0) {
573 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT1Compression);
574 } else if (strcmp(tc, "dxt3") == 0) {
575 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT3Compression);
576 } else if (strcmp(tc, "dxt5") == 0) {
577 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT5Compression);
579 SG_LOG(SG_VIEW, SG_WARN, "Unknown texture compression setting!");
583 // create sky, but can't build until setupView, since we depend
584 // on other subsystems to be inited, eg Ephemeris
587 SGPath texture_path(globals->get_fg_root());
588 texture_path.append("Textures");
589 texture_path.append("Sky");
590 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
591 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
592 _sky->add_cloud_layer(layer);
595 _sky->texture_path( texture_path.str() );
597 if (!_classicalRenderer) {
598 eventHandler->setChangeStatsCameraRenderOrder( true );
599 _sky->set_minimum_sky_visibility( 0.0 ); // A black sky appears for below that
603 void installCullVisitor(Camera* camera)
605 osgViewer::Renderer* renderer
606 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
607 for (int i = 0; i < 2; ++i) {
608 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
610 osg::ref_ptr<osgUtil::CullVisitor::Identifier> identifier;
611 identifier = sceneView->getCullVisitor()->getIdentifier();
612 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
613 sceneView->getCullVisitor()->setIdentifier(identifier.get());
615 identifier = sceneView->getCullVisitorLeft()->getIdentifier();
616 sceneView->setCullVisitorLeft(sceneView->getCullVisitor()->clone());
617 sceneView->getCullVisitorLeft()->setIdentifier(identifier.get());
619 identifier = sceneView->getCullVisitorRight()->getIdentifier();
620 sceneView->setCullVisitorRight(sceneView->getCullVisitor()->clone());
621 sceneView->getCullVisitorRight()->setIdentifier(identifier.get());
627 FGRenderer::buildRenderingPipeline(CameraGroup* cgroup, unsigned flags, Camera* camera,
629 const Matrix& projection,
630 osg::GraphicsContext* gc,
631 bool useMasterSceneData)
633 CameraInfo* info = 0;
634 if (!_classicalRenderer && (flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
635 info = buildDeferredPipeline( cgroup, flags, camera, view, projection, gc );
640 if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
641 _classicalRenderer = true;
642 return buildClassicalPipeline( cgroup, flags, camera, view, projection, useMasterSceneData );
647 FGRenderer::buildClassicalPipeline(CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
648 const osg::Matrix& view,
649 const osg::Matrix& projection,
650 bool useMasterSceneData)
652 CameraInfo* info = new CameraInfo(flags);
653 // The camera group will always update the camera
654 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
655 info->name = "classic";
657 Camera* farCamera = 0;
658 if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0) {
659 farCamera = new Camera;
660 farCamera->setName("farCamera");
661 farCamera->setAllowEventFocus(camera->getAllowEventFocus());
662 farCamera->setGraphicsContext(camera->getGraphicsContext());
663 farCamera->setCullingMode(camera->getCullingMode());
664 farCamera->setInheritanceMask(camera->getInheritanceMask());
665 farCamera->setReferenceFrame(Transform::ABSOLUTE_RF);
666 // Each camera's viewport is written when the window is
667 // resized; if the the viewport isn't copied here, it gets updated
668 // twice and ends up with the wrong value.
669 farCamera->setViewport(simgear::clone(camera->getViewport()));
670 farCamera->setDrawBuffer(camera->getDrawBuffer());
671 farCamera->setReadBuffer(camera->getReadBuffer());
672 farCamera->setRenderTargetImplementation(
673 camera->getRenderTargetImplementation());
674 const Camera::BufferAttachmentMap& bufferMap
675 = camera->getBufferAttachmentMap();
676 if (bufferMap.count(Camera::COLOR_BUFFER) != 0) {
678 Camera::COLOR_BUFFER,
679 bufferMap.find(Camera::COLOR_BUFFER)->second._texture.get());
681 cgroup->getViewer()->addSlave(farCamera, projection, view, useMasterSceneData);
682 installCullVisitor(farCamera);
683 int farSlaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
684 info->addCamera( FAR_CAMERA, farCamera, farSlaveIndex );
685 farCamera->setRenderOrder(Camera::POST_RENDER, farSlaveIndex);
686 camera->setCullMask(camera->getCullMask() & ~simgear::BACKGROUND_BIT);
687 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
689 cgroup->getViewer()->addSlave(camera, projection, view, useMasterSceneData);
690 installCullVisitor(camera);
691 int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
692 info->addCamera( MAIN_CAMERA, camera, slaveIndex );
693 camera->setRenderOrder(Camera::POST_RENDER, slaveIndex);
694 cgroup->addCamera(info);
698 class FGDeferredRenderingCameraCullCallback : public osg::NodeCallback {
700 FGDeferredRenderingCameraCullCallback( const std::string& k, CameraInfo* i, bool nd = false ) : kind( k ), info( i ), needsDuDv(nd) {}
701 virtual void operator()( osg::Node *n, osg::NodeVisitor *nv) {
702 simgear::EffectCullVisitor* cv = dynamic_cast<simgear::EffectCullVisitor*>(nv);
703 osg::Camera* camera = static_cast<osg::Camera*>(n);
705 cv->clearBufferList();
706 for (RenderBufferMap::iterator ii = info->buffers.begin(); ii != info->buffers.end(); ++ii) {
707 cv->addBuffer(ii->first, ii->second.texture);
710 if ( !info->getRenderStageInfo(kind).fullscreen )
711 info->setMatrices( camera );
714 osg::Matrix projInverse;
715 info->projInverse->get( projInverse );
717 osg::Vec4 p0 = osg::Vec4( -1.0, -1.0, 0.0, 1.0 ) * projInverse;
718 info->du->set( osg::Vec4( 1.0, -1.0, 0.0, 1.0 ) * projInverse - p0 );
719 info->dv->set( osg::Vec4( -1.0, 1.0, 0.0, 1.0 ) * projInverse - p0 );
722 cv->traverse( *camera );
724 if ( kind == GEOMETRY_CAMERA ) {
725 // Remove transparent bins. They will be renderer in the additional light stage (side effect)
726 osgUtil::RenderStage* renderStage = cv->getRenderStage();
727 osgUtil::RenderBin::RenderBinList& rbl = renderStage->getRenderBinList();
728 for (osgUtil::RenderBin::RenderBinList::iterator rbi = rbl.begin(); rbi != rbl.end(); ) {
729 if (rbi->second->getSortMode() == osgUtil::RenderBin::SORT_BACK_TO_FRONT) {
735 } else if ( kind == LIGHTING_CAMERA ) {
736 osg::ref_ptr<osg::Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
737 if (mainShadowCamera.valid()) {
738 osg::Switch* grp = mainShadowCamera->getChild(0)->asSwitch();
739 for (int i = 0; i < 4; ++i ) {
740 if (!grp->getValue(i))
743 osg::Camera* cascadeCam = static_cast<osg::Camera*>( grp->getChild(i) );
744 osg::Matrixf shadowMatrix = camera->getInverseViewMatrix() *
745 cascadeCam->getViewMatrix() *
746 cascadeCam->getProjectionMatrix() *
747 osg::Matrix::translate(1.0, 1.0, 1.0) *
748 osg::Matrix::scale(0.5f, 0.5f, 0.5f);
750 info->shadowMatrix[i]->set( shadowMatrix );
762 osg::Texture2D* buildDeferredBuffer(GLint internalFormat, GLenum sourceFormat, GLenum sourceType, GLenum wrapMode, bool shadowComparison = false)
764 osg::Texture2D* tex = new osg::Texture2D;
765 tex->setResizeNonPowerOfTwoHint( false );
766 tex->setInternalFormat( internalFormat );
767 tex->setShadowComparison(shadowComparison);
768 if (shadowComparison) {
769 tex->setShadowTextureMode(osg::Texture2D::LUMINANCE);
770 tex->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
772 tex->setSourceFormat(sourceFormat);
773 tex->setSourceType(sourceType);
774 tex->setFilter( osg::Texture2D::MIN_FILTER, osg::Texture2D::LINEAR );
775 tex->setFilter( osg::Texture2D::MAG_FILTER, osg::Texture2D::LINEAR );
776 tex->setWrap( osg::Texture::WRAP_S, (osg::Texture::WrapMode)wrapMode );
777 tex->setWrap( osg::Texture::WRAP_T, (osg::Texture::WrapMode)wrapMode );
781 void attachBufferToCamera( CameraInfo* info, osg::Camera* camera, osg::Camera::BufferComponent c, const std::string& ck, const std::string& bk )
783 camera->attach( c, info->getBuffer(bk) );
784 info->getRenderStageInfo(ck).buffers.insert( std::make_pair( c, bk ) );
787 void buildAttachments(CameraInfo* info, osg::Camera* camera, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments) {
788 BOOST_FOREACH(ref_ptr<FGRenderingPipeline::Attachment> attachment, attachments) {
789 if (attachment->valid())
790 attachBufferToCamera( info, camera, attachment->component, name, attachment->buffer );
794 osg::Camera* FGRenderer::buildDeferredGeometryCamera( CameraInfo* info, osg::GraphicsContext* gc, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
796 osg::Camera* camera = new osg::Camera;
797 info->addCamera(name, camera );
799 camera->setCullMask( ~simgear::MODELLIGHT_BIT );
800 camera->setName( "GeometryC" );
801 camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
802 camera->setGraphicsContext( gc );
803 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( name, info ) );
804 camera->setClearMask( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
805 camera->setClearColor( osg::Vec4( 0., 0., 0., 0. ) );
806 camera->setClearDepth( 1.0 );
807 camera->setColorMask(true, true, true, true);
808 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
809 camera->setRenderOrder(osg::Camera::NESTED_RENDER, 0);
810 camera->setViewport( new osg::Viewport );
811 buildAttachments(info, camera, name, attachments);
812 camera->setDrawBuffer(GL_FRONT);
813 camera->setReadBuffer(GL_FRONT);
815 osg::StateSet* ss = camera->getOrCreateStateSet();
816 ss->addUniform( _depthInColor );
818 camera->addChild( mDeferredRealRoot.get() );
823 static void setShadowCascadeStateSet( osg::Camera* cam ) {
824 osg::StateSet* ss = cam->getOrCreateStateSet();
825 ss->setAttribute( new osg::PolygonOffset( 1.1f, 5.0f ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
826 ss->setMode( GL_POLYGON_OFFSET_FILL, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
827 ss->setRenderBinDetails( 0, "RenderBin", osg::StateSet::OVERRIDE_RENDERBIN_DETAILS );
828 ss->setAttributeAndModes( new osg::AlphaFunc( osg::AlphaFunc::GREATER, 0.05 ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
829 ss->setAttributeAndModes( new osg::ColorMask( false, false, false, false ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
830 ss->setAttributeAndModes( new osg::CullFace( osg::CullFace::FRONT ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
831 osg::Program* program = new osg::Program;
832 ss->setAttribute( program, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
833 ss->setMode( GL_LIGHTING, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
834 ss->setMode( GL_BLEND, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
835 //ss->setTextureMode( 0, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
836 ss->setTextureMode( 0, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
837 ss->setTextureMode( 1, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
838 ss->setTextureMode( 1, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
839 ss->setTextureMode( 2, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
840 ss->setTextureMode( 2, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
843 static osg::Camera* createShadowCascadeCamera( int no, int cascadeSize ) {
844 osg::Camera* cascadeCam = new osg::Camera;
845 setShadowCascadeStateSet( cascadeCam );
847 std::ostringstream oss;
848 oss << "CascadeCamera" << (no + 1);
849 cascadeCam->setName( oss.str() );
850 cascadeCam->setClearMask(0);
851 cascadeCam->setCullMask( simgear::CASTSHADOW_BIT );
852 cascadeCam->setCullingMode( cascadeCam->getCullingMode() | osg::CullSettings::SMALL_FEATURE_CULLING );
853 cascadeCam->setAllowEventFocus(false);
854 cascadeCam->setReferenceFrame(osg::Transform::ABSOLUTE_RF_INHERIT_VIEWPOINT);
855 cascadeCam->setRenderOrder(osg::Camera::NESTED_RENDER);
856 cascadeCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
857 cascadeCam->setViewport( int( no / 2 ) * cascadeSize, (no & 1) * cascadeSize, cascadeSize, cascadeSize );
861 osg::Camera* FGRenderer::buildDeferredShadowCamera( CameraInfo* info, osg::GraphicsContext* gc, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
863 osg::Camera* mainShadowCamera = new osg::Camera;
864 info->addCamera(name, mainShadowCamera, 0.0f );
866 mainShadowCamera->setName( "ShadowC" );
867 mainShadowCamera->setClearMask( GL_DEPTH_BUFFER_BIT );
868 mainShadowCamera->setClearDepth( 1.0 );
869 mainShadowCamera->setAllowEventFocus(false);
870 mainShadowCamera->setGraphicsContext(gc);
871 mainShadowCamera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
872 buildAttachments(info, mainShadowCamera, name, attachments);
873 mainShadowCamera->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
874 mainShadowCamera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
875 mainShadowCamera->setProjectionMatrix(osg::Matrix::identity());
876 mainShadowCamera->setCullingMode( osg::CullSettings::NO_CULLING );
877 mainShadowCamera->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
878 mainShadowCamera->setDrawBuffer(GL_FRONT);
879 mainShadowCamera->setReadBuffer(GL_FRONT);
880 mainShadowCamera->setRenderOrder(Camera::NESTED_RENDER, 1);
882 osg::Switch* shadowSwitch = new osg::Switch;
883 mainShadowCamera->addChild( shadowSwitch );
885 for (int i = 0; i < 4; ++i ) {
886 osg::Camera* cascadeCam = createShadowCascadeCamera( i, _shadowMapSize/2 );
887 cascadeCam->addChild( mDeferredRealRoot.get() );
888 shadowSwitch->addChild( cascadeCam );
890 if (fgGetBool("/sim/rendering/shadows/enabled", true))
891 shadowSwitch->setAllChildrenOn();
893 shadowSwitch->setAllChildrenOff();
895 return mainShadowCamera;
898 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)
900 osg::Camera* cascade = static_cast<osg::Camera*>( grp->getChild(idx) );
901 osg::Matrixd &viewMatrix = cascade->getViewMatrix();
902 osg::Matrixd &projectionMatrix = cascade->getProjectionMatrix();
904 osg::BoundingSphere bs;
905 bs.expandBy(osg::Vec3(left,bottom,-zNear) * f1);
906 bs.expandBy(osg::Vec3(right,top,-zNear) * f2);
907 bs.expandBy(osg::Vec3(left,bottom,-zNear) * f2);
908 bs.expandBy(osg::Vec3(right,top,-zNear) * f1);
910 osg::Vec4 aim = osg::Vec4(bs.center(), 1.0) * camera->getInverseViewMatrix();
912 projectionMatrix.makeOrtho( -bs.radius(), bs.radius(), -bs.radius(), bs.radius(), 1., 15000.0 );
913 osg::Vec3 position( aim.x(), aim.y(), aim.z() );
914 viewMatrix.makeLookAt( position + (getSunDirection() * 10000.0), position, position );
917 osg::Vec3 FGRenderer::getSunDirection() const
920 _sunDirection->get( val );
924 void FGRenderer::updateShadowCamera(const CameraInfo* info, const osg::Vec3d& position)
926 ref_ptr<Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
927 if (mainShadowCamera.valid()) {
928 ref_ptr<Switch> shadowSwitch = mainShadowCamera->getChild( 0 )->asSwitch();
929 osg::Vec3d up = position,
930 dir = getSunDirection();
933 // cos(100 deg) == -0.17
934 if (up * dir < -0.17 || !fgGetBool("/sim/rendering/shadows/enabled", true)) {
935 shadowSwitch->setAllChildrenOff();
937 double left,right,bottom,top,zNear,zFar;
938 ref_ptr<Camera> camera = info->getCamera(GEOMETRY_CAMERA);
939 camera->getProjectionMatrix().getFrustum(left,right,bottom,top,zNear,zFar);
941 shadowSwitch->setAllChildrenOn();
942 if (_numCascades == 1) {
943 osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(0) );
944 cascadeCam->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
946 for (int no = 0; no < 4; ++no) {
947 osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(no) );
948 cascadeCam->setViewport( int( no / 2 ) * (_shadowMapSize/2), (no & 1) * (_shadowMapSize/2), (_shadowMapSize/2), (_shadowMapSize/2) );
951 updateShadowCascade(info, camera, shadowSwitch, 0, left, right, bottom, top, zNear, 1.0, _cascadeFar[0]/zNear);
952 if (_numCascades > 1) {
953 shadowSwitch->setValue(1, true);
954 updateShadowCascade(info, camera, shadowSwitch, 1, left, right, bottom, top, zNear, _cascadeFar[0]/zNear, _cascadeFar[1]/zNear);
956 shadowSwitch->setValue(1, false);
958 if (_numCascades > 2) {
959 shadowSwitch->setValue(2, true);
960 updateShadowCascade(info, camera, shadowSwitch, 2, left, right, bottom, top, zNear, _cascadeFar[1]/zNear, _cascadeFar[2]/zNear);
962 shadowSwitch->setValue(2, false);
964 if (_numCascades > 3) {
965 shadowSwitch->setValue(3, true);
966 updateShadowCascade(info, camera, shadowSwitch, 3, left, right, bottom, top, zNear, _cascadeFar[2]/zNear, _cascadeFar[3]/zNear);
968 shadowSwitch->setValue(3, false);
971 osg::Matrixd &viewMatrix = mainShadowCamera->getViewMatrix();
973 osg::Vec4 aim = osg::Vec4( 0.0, 0.0, 0.0, 1.0 ) * camera->getInverseViewMatrix();
975 osg::Vec3 position( aim.x(), aim.y(), aim.z() );
976 viewMatrix.makeLookAt( position, position + (getSunDirection() * 10000.0), position );
982 void FGRenderer::updateShadowMapSize(int mapSize)
984 if ( ((~( mapSize-1 )) & mapSize) != mapSize ) {
985 SG_LOG( SG_VIEW, SG_ALERT, "Map size is not a power of two" );
988 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
989 ii != CameraGroup::getDefault()->camerasEnd();
992 CameraInfo* info = ii->get();
993 Camera* camera = info->getCamera(SHADOW_CAMERA);
994 if (camera == 0) continue;
996 Texture2D* tex = info->getBuffer("shadow");
997 if (tex == 0) continue;
999 tex->setTextureSize( mapSize, mapSize );
1000 tex->dirtyTextureObject();
1002 Viewport* vp = camera->getViewport();
1003 vp->width() = mapSize;
1004 vp->height() = mapSize;
1006 osgViewer::Renderer* renderer
1007 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
1008 for (int i = 0; i < 2; ++i) {
1009 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
1010 sceneView->getRenderStage()->setFrameBufferObject(0);
1011 sceneView->getRenderStage()->setCameraRequiresSetUp(true);
1012 if (sceneView->getRenderStageLeft()) {
1013 sceneView->getRenderStageLeft()->setFrameBufferObject(0);
1014 sceneView->getRenderStageLeft()->setCameraRequiresSetUp(true);
1016 if (sceneView->getRenderStageRight()) {
1017 sceneView->getRenderStageRight()->setFrameBufferObject(0);
1018 sceneView->getRenderStageRight()->setCameraRequiresSetUp(true);
1022 int cascadeSize = mapSize / 2;
1023 Group* grp = camera->getChild(0)->asGroup();
1024 for (int i = 0; i < 4; ++i ) {
1025 Camera* cascadeCam = static_cast<Camera*>( grp->getChild(i) );
1026 cascadeCam->setViewport( int( i / 2 ) * cascadeSize, (i & 1) * cascadeSize, cascadeSize, cascadeSize );
1029 _shadowMapSize = mapSize;
1033 void FGRenderer::enableShadows(bool enabled)
1035 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
1036 ii != CameraGroup::getDefault()->camerasEnd();
1039 CameraInfo* info = ii->get();
1040 Camera* camera = info->getCamera(SHADOW_CAMERA);
1041 if (camera == 0) continue;
1043 osg::Switch* shadowSwitch = camera->getChild(0)->asSwitch();
1045 shadowSwitch->setAllChildrenOn();
1047 shadowSwitch->setAllChildrenOff();
1051 void FGRenderer::updateCascadeFar(int index, float far_m)
1053 if (index < 0 || index > 3)
1055 _cascadeFar[index] = far_m;
1056 _shadowDistances->set( osg::Vec4f(_cascadeFar[0], _cascadeFar[1], _cascadeFar[2], _cascadeFar[3]) );
1059 void FGRenderer::updateCascadeNumber(size_t num)
1061 if (num < 1 || num > 4)
1064 _shadowNumber->set( (int)_numCascades );
1067 class DebugPassListener : public SGPropertyChangeListener {
1069 DebugPassListener(osg::Switch* sw, int i) : _switch(sw), _index(i) {}
1070 virtual void valueChanged(SGPropertyNode* node) {
1071 _switch->setValue(_index, node->getBoolValue());
1075 osg::ref_ptr<osg::Switch> _switch;
1080 FGRenderer::buildDeferredLightingCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc, const FGRenderingPipeline::Stage* stage )
1082 osg::Camera* camera = new osg::Camera;
1083 info->addCamera(stage->name, camera );
1085 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( stage->name, info ) );
1086 camera->setAllowEventFocus(false);
1087 camera->setGraphicsContext(gc);
1088 camera->setViewport(new Viewport);
1089 camera->setName(stage->name+"C");
1090 camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1091 camera->setRenderOrder(osg::Camera::NESTED_RENDER, stage->orderNum);
1092 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1093 camera->setViewport( new osg::Viewport );
1094 buildAttachments(info, camera, stage->name, stage->attachments);
1095 camera->setDrawBuffer(GL_FRONT);
1096 camera->setReadBuffer(GL_FRONT);
1097 camera->setClearColor( osg::Vec4( 0.5, 0.5, 0.5, 1. ) );
1098 camera->setClearMask( GL_COLOR_BUFFER_BIT );
1099 osg::StateSet* ss = camera->getOrCreateStateSet();
1100 ss->setAttribute( new osg::Depth(osg::Depth::LESS, 0.0, 1.0, false) );
1101 ss->addUniform( _depthInColor );
1103 osg::Switch* lightingGroup = new osg::Switch;
1105 BOOST_FOREACH( osg::ref_ptr<FGRenderingPipeline::Pass> pass, stage->passes ) {
1106 ref_ptr<Node> node = buildPass(info, pass);
1108 lightingGroup->addChild(node);
1109 if (!pass->debugProperty.empty()) {
1110 lightingGroup->setValue(lightingGroup->getNumChildren()-1, fgGetBool(pass->debugProperty));
1111 fgAddChangeListener(new DebugPassListener(lightingGroup, lightingGroup->getNumChildren()-1), pass->debugProperty);
1116 camera->addChild( lightingGroup );
1122 FGRenderer::buildDeferredPipeline(CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1123 const osg::Matrix& view,
1124 const osg::Matrix& projection,
1125 osg::GraphicsContext* gc)
1127 return buildCameraFromRenderingPipeline(_pipeline, cgroup, flags, camera, view, projection, gc);
1131 FGRenderer::buildDeferredFullscreenCamera( flightgear::CameraInfo* info, const FGRenderingPipeline::Pass* pass )
1133 osg::Camera* camera = new osg::Camera;
1135 camera->setClearMask( 0 );
1136 camera->setAllowEventFocus(false);
1137 camera->setName(pass->name+"C");
1138 camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1139 camera->setRenderOrder(osg::Camera::NESTED_RENDER, pass->orderNum);
1140 camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1141 camera->setViewMatrix(osg::Matrix::identity());
1142 camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1144 osg::StateSet* ss = camera->getOrCreateStateSet();
1145 ss->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1146 ss->addUniform( info->projInverse );
1147 ss->addUniform( info->viewInverse );
1148 ss->addUniform( info->view );
1149 ss->addUniform( info->bufferSize );
1150 ss->addUniform( info->worldPosCart );
1151 ss->addUniform( info->worldPosGeod );
1152 ss->addUniform( info->shadowMatrix[0] );
1153 ss->addUniform( info->shadowMatrix[1] );
1154 ss->addUniform( info->shadowMatrix[2] );
1155 ss->addUniform( info->shadowMatrix[3] );
1156 ss->addUniform( _ambientFactor );
1157 ss->addUniform( _sunDiffuse );
1158 ss->addUniform( _sunSpecular );
1159 ss->addUniform( _sunDirection );
1160 ss->addUniform( _planes );
1161 ss->addUniform( _shadowNumber );
1162 ss->addUniform( _shadowDistances );
1163 ss->addUniform( _fogColor );
1164 ss->addUniform( _fogDensity );
1166 osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1167 g->setUseDisplayList(false);
1168 simgear::EffectGeode* eg = new simgear::EffectGeode;
1169 osg::ref_ptr<SGReaderWriterOptions> opt;
1170 opt = SGReaderWriterOptions::fromPath(globals->get_fg_root());
1171 opt->setPropertyNode(globals->get_props());
1172 simgear::Effect* effect = simgear::makeEffect(pass->effect, true, opt.get());
1174 eg->setEffect( effect );
1177 eg->setName(pass->name+"Quad");
1178 eg->setCullingActive(false);
1180 camera->addChild(eg);
1186 FGRenderer::buildDeferredFullscreenCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc, const FGRenderingPipeline::Stage* stage )
1188 osg::Camera* camera = buildDeferredFullscreenCamera(info, static_cast<const FGRenderingPipeline::Pass*>(stage));
1189 info->addCamera(stage->name, camera, stage->scaleFactor, true);
1191 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback(stage->name, info, stage->needsDuDv) );
1192 camera->setGraphicsContext(gc);
1193 camera->setViewport(new Viewport);
1194 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1195 buildAttachments(info, camera, stage->name, stage->attachments);
1196 camera->setDrawBuffer(GL_FRONT);
1197 camera->setReadBuffer(GL_FRONT);
1198 camera->setClearColor( osg::Vec4( 1., 1., 1., 1. ) );
1199 camera->setClearMask( GL_COLOR_BUFFER_BIT );
1200 camera->setViewMatrix(osg::Matrix::identity());
1201 camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1203 osg::StateSet* ss = camera->getOrCreateStateSet();
1204 if (stage->needsDuDv) {
1205 ss->addUniform( info->du );
1206 ss->addUniform( info->dv );
1213 FGRenderer::buildDeferredDisplayCamera( osg::Camera* camera, flightgear::CameraInfo* info, const FGRenderingPipeline::Stage* stage, osg::GraphicsContext* gc )
1215 camera->setName( "DisplayC" );
1216 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( stage->name, info ) );
1217 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
1218 camera->setAllowEventFocus(false);
1219 osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1220 g->setUseDisplayList(false); //DEBUG
1221 simgear::EffectGeode* eg = new simgear::EffectGeode;
1222 osg::ref_ptr<SGReaderWriterOptions> opt;
1223 opt = SGReaderWriterOptions::fromPath(globals->get_fg_root());
1224 opt->setPropertyNode(globals->get_props());
1225 simgear::Effect* effect = simgear::makeEffect(stage->effect, true, opt.get());
1227 SG_LOG(SG_VIEW, SG_ALERT, stage->effect + " not found");
1230 eg->setEffect(effect);
1231 eg->setCullingActive(false);
1233 camera->setViewMatrix(osg::Matrix::identity());
1234 camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1235 camera->addChild(eg);
1237 osg::StateSet* ss = camera->getOrCreateStateSet();
1238 ss->addUniform( _depthInColor );
1239 ss->addUniform( info->projInverse );
1240 ss->addUniform( info->viewInverse );
1241 ss->addUniform( info->view );
1242 ss->addUniform( info->bufferSize );
1243 ss->addUniform( info->worldPosCart );
1244 ss->addUniform( info->worldPosGeod );
1245 ss->addUniform( info->shadowMatrix[0] );
1246 ss->addUniform( info->shadowMatrix[1] );
1247 ss->addUniform( info->shadowMatrix[2] );
1248 ss->addUniform( info->shadowMatrix[3] );
1249 ss->addUniform( _ambientFactor );
1250 ss->addUniform( _sunDiffuse );
1251 ss->addUniform( _sunSpecular );
1252 ss->addUniform( _sunDirection );
1253 ss->addUniform( _planes );
1254 ss->addUniform( _shadowNumber );
1255 ss->addUniform( _shadowDistances );
1256 ss->addUniform( _fogColor );
1257 ss->addUniform( _fogDensity );
1261 FGRenderer::buildStage(CameraInfo* info,
1262 FGRenderingPipeline::Stage* stage,
1263 CameraGroup* cgroup,
1264 osg::Camera* mainCamera,
1265 const osg::Matrix& view, const osg::Matrix& projection, osg::GraphicsContext* gc)
1267 if (!stage->valid())
1270 ref_ptr<Camera> camera;
1271 bool needOffsets = false;
1272 if (stage->type == "geometry") {
1273 camera = buildDeferredGeometryCamera(info, gc, stage->name, stage->attachments);
1275 } else if (stage->type == "lighting") {
1276 camera = buildDeferredLightingCamera(info, gc, stage);
1278 } else if (stage->type == "shadow")
1279 camera = buildDeferredShadowCamera(info, gc, stage->name, stage->attachments);
1280 else if (stage->type == "fullscreen")
1281 camera = buildDeferredFullscreenCamera(info, gc, stage);
1282 else if (stage->type == "display") {
1283 camera = mainCamera;
1284 buildDeferredDisplayCamera(camera, info, stage, gc);
1286 throw sg_exception("Stage type is not supported");
1289 cgroup->getViewer()->addSlave(camera, projection, view, false);
1291 cgroup->getViewer()->addSlave(camera, false);
1292 installCullVisitor(camera);
1293 int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1294 if (stage->type == "display")
1295 info->addCamera( stage->type, camera, slaveIndex, true );
1296 info->getRenderStageInfo(stage->name).slaveIndex = slaveIndex;
1300 FGRenderer::buildLightingSkyCloudsPass(FGRenderingPipeline::Pass* pass)
1302 Group* group = new Group;
1303 group->setName("skyCloudsGroup");
1304 group->setNodeMask(simgear::BACKGROUND_BIT);
1306 StateSet* ss = group->getOrCreateStateSet();
1307 ss->setAttributeAndModes( new osg::ColorMask( true, true, true, false ), osg::StateAttribute::ON );
1308 group->addChild( _sky->getPreRoot() );
1309 group->addChild( _sky->getCloudRoot() );
1314 FGRenderer::buildLightingLightsPass(CameraInfo* info, FGRenderingPipeline::Pass* pass)
1316 osg::Camera* lightCam = new osg::Camera;
1317 StateSet* ss = lightCam->getOrCreateStateSet();
1318 ss->addUniform( _planes );
1319 ss->addUniform( info->bufferSize );
1320 ss->addUniform( _fogColor );
1321 ss->addUniform( _fogDensity );
1322 lightCam->setName( "LightCamera" );
1323 lightCam->setClearMask(0);
1324 lightCam->setAllowEventFocus(false);
1325 lightCam->setReferenceFrame(osg::Transform::RELATIVE_RF);
1326 lightCam->setRenderOrder(osg::Camera::NESTED_RENDER,pass->orderNum);
1327 lightCam->setViewMatrix(osg::Matrix::identity());
1328 lightCam->setProjectionMatrix(osg::Matrix::identity());
1329 lightCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1330 lightCam->setCullMask( simgear::MODELLIGHT_BIT | simgear::PANEL2D_BIT | simgear::PERMANENTLIGHT_BIT);
1331 lightCam->setInheritanceMask( osg::CullSettings::ALL_VARIABLES & ~osg::CullSettings::CULL_MASK );
1332 lightCam->addChild( mDeferredRealRoot.get() );
1338 FGRenderer::buildPass(CameraInfo* info, FGRenderingPipeline::Pass* pass)
1344 if (pass->type == "sky-clouds")
1345 node = buildLightingSkyCloudsPass(pass);
1346 else if (pass->type == "fullscreen")
1347 node = buildDeferredFullscreenCamera(info, pass);
1348 else if (pass->type == "lights")
1349 node = buildLightingLightsPass(info, pass);
1351 throw sg_exception("Pass type is not supported");
1353 return node.release();
1357 FGRenderer::buildBuffers(FGRenderingPipeline* rpipe, CameraInfo* info)
1359 for (size_t i = 0; i < rpipe->buffers.size(); ++i) {
1360 osg::ref_ptr<FGRenderingPipeline::Buffer> buffer = rpipe->buffers[i];
1361 if (buffer->valid()) {
1362 bool fullscreen = buffer->width == -1 && buffer->height == -1;
1363 info->addBuffer(buffer->name, buildDeferredBuffer( buffer->internalFormat,
1364 buffer->sourceFormat,
1367 buffer->shadowComparison),
1368 fullscreen ? buffer->scaleFactor : 0.0f);
1370 info->getBuffer(buffer->name)->setTextureSize(buffer->width, buffer->height);
1376 CameraInfo* FGRenderer::buildCameraFromRenderingPipeline(FGRenderingPipeline* rpipe, CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1377 const osg::Matrix& view, const osg::Matrix& projection, osg::GraphicsContext* gc)
1379 CameraInfo* info = new CameraInfo(flags);
1380 buildBuffers(rpipe, info);
1382 for (size_t i = 0; i < rpipe->stages.size(); ++i) {
1383 osg::ref_ptr<FGRenderingPipeline::Stage> stage = rpipe->stages[i];
1384 buildStage(info, stage, cgroup, camera, view, projection, gc);
1387 cgroup->addCamera(info);
1393 FGRenderer::setupView( void )
1395 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1396 osg::initNotifyLevel();
1398 // The number of polygon-offset "units" to place between layers. In
1399 // principle, one is supposed to be enough. In practice, I find that
1400 // my hardware/driver requires many more.
1401 osg::PolygonOffset::setUnitsMultiplier(1);
1402 osg::PolygonOffset::setFactorMultiplier(1);
1405 // The sun and moon diameters are scaled down numbers of the
1406 // actual diameters. This was needed to fit both the sun and the
1407 // moon within the distance to the far clip plane.
1408 // Moon diameter: 3,476 kilometers
1409 // Sun diameter: 1,390,000 kilometers
1410 osg::ref_ptr<SGReaderWriterOptions> opt;
1411 opt = SGReaderWriterOptions::fromPath(globals->get_fg_root());
1412 opt->setPropertyNode(globals->get_props());
1413 _sky->build( 80000.0, 80000.0,
1415 *globals->get_ephem(),
1416 fgGetNode("/environment", true),
1420 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1422 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
1424 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
1426 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
1427 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1429 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
1430 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
1431 stateSet->setAttribute(new osg::BlendFunc);
1432 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
1434 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
1436 // this will be set below
1437 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
1439 osg::Material* material = new osg::Material;
1440 stateSet->setAttribute(material);
1442 stateSet->setTextureAttribute(0, new osg::TexEnv);
1443 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
1445 osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
1446 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
1447 stateSet->setAttribute(hint);
1448 hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
1449 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
1450 stateSet->setAttribute(hint);
1451 hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
1452 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
1453 stateSet->setAttribute(hint);
1454 hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
1455 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
1456 stateSet->setAttribute(hint);
1457 hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
1458 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
1459 stateSet->setAttribute(hint);
1461 osg::Group* sceneGroup = new osg::Group;
1462 sceneGroup->setName("rendererScene");
1463 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
1464 sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
1466 //sceneGroup->addChild(thesky->getCloudRoot());
1468 stateSet = sceneGroup->getOrCreateStateSet();
1469 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1471 // need to update the light on every frame
1472 // OSG LightSource objects are rather confusing. OSG only supports
1473 // the 10 lights specified by OpenGL itself; if more than one
1474 // LightSource in the scene graph have the same light number, it's
1475 // indeterminate which values will be used to render geometry that
1476 // has that light number enabled. Also, adding children to a
1477 // LightSource is just a shortcut for setting up a state set that
1478 // has the corresponding OpenGL light enabled: a LightSource will
1479 // affect geometry anywhere in the scene graph that has its light
1480 // number enabled in a state set.
1481 LightSource* lightSource = new LightSource;
1482 lightSource->setName("FGLightSource");
1483 lightSource->getLight()->setDataVariance(Object::DYNAMIC);
1484 // relative because of CameraView being just a clever transform node
1485 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1486 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
1487 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
1488 mRealRoot->addChild(lightSource);
1489 // we need a white diffuse light for the phase of the moon
1490 osg::LightSource* sunLight = new osg::LightSource;
1491 sunLight->setName("sunLightSource");
1492 sunLight->getLight()->setDataVariance(Object::DYNAMIC);
1493 sunLight->getLight()->setLightNum(1);
1494 sunLight->setUpdateCallback(new FGLightSourceUpdateCallback(true));
1495 sunLight->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1496 sunLight->setLocalStateSetModes(osg::StateAttribute::ON);
1498 // Hang a StateSet above the sky subgraph in order to turn off
1500 Group* skyGroup = new Group;
1501 skyGroup->setName("rendererSkyParent");
1502 StateSet* skySS = skyGroup->getOrCreateStateSet();
1503 skySS->setMode(GL_LIGHT0, StateAttribute::OFF);
1504 skyGroup->addChild(_sky->getPreRoot());
1505 sunLight->addChild(skyGroup);
1506 mRoot->addChild(sceneGroup);
1507 if ( _classicalRenderer )
1508 mRoot->addChild(sunLight);
1510 // Clouds are added to the scene graph later
1511 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
1512 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
1513 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
1514 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1516 // enable disable specular highlights.
1517 // is the place where we might plug in an other fragment shader ...
1518 osg::LightModel* lightModel = new osg::LightModel;
1519 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
1520 stateSet->setAttribute(lightModel);
1522 // switch to enable wireframe
1523 osg::PolygonMode* polygonMode = new osg::PolygonMode;
1524 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
1525 stateSet->setAttributeAndModes(polygonMode);
1527 // scene fog handling
1528 osg::Fog* fog = new osg::Fog;
1529 fog->setUpdateCallback(new FGFogUpdateCallback);
1530 stateSet->setAttributeAndModes(fog);
1531 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
1534 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
1537 osg::Geode* geode = new osg::Geode;
1538 geode->addDrawable(new SGPuDrawable);
1539 geode->addDrawable(new SGHUDDrawable);
1540 guiCamera->addChild(geode);
1543 guiCamera->addChild(FGPanelNode::create2DPanelNode());
1546 osg::Switch* sw = new osg::Switch;
1547 sw->setName("scenerySwitch");
1548 sw->setUpdateCallback(new FGScenerySwitchCallback);
1549 sw->addChild(mRoot.get());
1550 mRealRoot->addChild(sw);
1551 // The clouds are attached directly to the scene graph root
1552 // because, in theory, they don't want the same default state set
1553 // as the rest of the scene. This may not be true in practice.
1554 if ( _classicalRenderer ) {
1555 mRealRoot->addChild(_sky->getCloudRoot());
1556 mRealRoot->addChild(FGCreateRedoutNode());
1558 // Attach empty program to the scene root so that shader programs
1559 // don't leak into state sets (effects) that shouldn't have one.
1560 stateSet = mRealRoot->getOrCreateStateSet();
1561 stateSet->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON);
1563 mDeferredRealRoot->addChild( mRealRoot.get() );
1565 DeletionManager::install(mRealRoot.get());
1568 // Update all Visuals (redraws anything graphics related)
1570 FGRenderer::update( ) {
1571 if (!_position_finalized || !_scenery_loaded->getBoolValue())
1573 _splash_alpha->setDoubleValue(1.0);
1576 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1578 if (_splash_alpha->getDoubleValue()>0.0)
1580 // Fade out the splash screen
1581 const double fade_time = 0.5;
1582 const double fade_steps_per_sec = 10;
1583 double delay_time = SGMiscd::min(fade_time/fade_steps_per_sec,
1584 (SGTimeStamp::now() - _splash_time).toSecs());
1585 _splash_time = SGTimeStamp::now();
1586 double sAlpha = _splash_alpha->getDoubleValue();
1587 sAlpha -= SGMiscd::max(0.0,delay_time/fade_time);
1588 FGScenerySwitchCallback::scenery_enabled = (sAlpha<1.0);
1589 _splash_alpha->setDoubleValue((sAlpha < 0) ? 0.0 : sAlpha);
1592 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
1593 if (!_classicalRenderer ) {
1594 _ambientFactor->set( toOsg(l->scene_ambient()) );
1595 _sunDiffuse->set( toOsg(l->scene_diffuse()) );
1596 _sunSpecular->set( toOsg(l->scene_specular()) );
1597 _sunDirection->set( osg::Vec3f(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]) );
1600 // update fog params
1601 double actual_visibility;
1602 if (_cloud_status->getBoolValue()) {
1603 actual_visibility = _sky->get_visibility();
1605 actual_visibility = _visibility_m->getDoubleValue();
1608 // idle_state is now 1000 meaning we've finished all our
1609 // initializations and are running the main loop, so this will
1610 // now work without seg faulting the system.
1612 FGViewer *current__view = globals->get_current_view();
1613 // Force update of center dependent values ...
1614 current__view->set_dirty();
1616 osg::Camera *camera = viewer->getCamera();
1618 bool skyblend = _skyblend->getBoolValue();
1621 if ( _textures->getBoolValue() ) {
1622 SGVec4f clearColor(l->adj_fog_color());
1623 camera->setClearColor(toOsg(clearColor));
1626 SGVec4f clearColor(l->sky_color());
1627 camera->setClearColor(toOsg(clearColor));
1630 // update fog params if visibility has changed
1631 double visibility_meters = _visibility_m->getDoubleValue();
1632 _sky->set_visibility(visibility_meters);
1634 double altitude_m = _altitude_ft->getDoubleValue() * SG_FEET_TO_METER;
1635 _sky->modify_vis( altitude_m, 0.0 /* time factor, now unused */);
1637 // update the sky dome
1640 // The sun and moon distances are scaled down versions
1641 // of the actual distance to get both the moon and the sun
1642 // within the range of the far clip plane.
1643 // Moon distance: 384,467 kilometers
1644 // Sun distance: 150,000,000 kilometers
1646 double sun_horiz_eff, moon_horiz_eff;
1647 if (_horizon_effect->getBoolValue()) {
1649 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
1653 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
1657 sun_horiz_eff = moon_horiz_eff = 1.0;
1661 sstate.pos = current__view->getViewPosition();
1662 sstate.pos_geod = current__view->getPosition();
1663 sstate.ori = current__view->getViewOrientation();
1664 sstate.spin = l->get_sun_rotation();
1665 sstate.gst = globals->get_time_params()->getGst();
1666 sstate.sun_dist = 50000.0 * sun_horiz_eff;
1667 sstate.moon_dist = 40000.0 * moon_horiz_eff;
1668 sstate.sun_angle = l->get_sun_angle();
1671 scolor.sky_color = SGVec3f(l->sky_color().data());
1672 scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
1673 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
1674 scolor.cloud_color = SGVec3f(l->cloud_color().data());
1675 scolor.sun_angle = l->get_sun_angle();
1676 scolor.moon_angle = l->get_moon_angle();
1678 double delta_time_sec = _sim_delta_sec->getDoubleValue();
1679 _sky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
1680 _sky->repaint( scolor, *globals->get_ephem() );
1683 // shadows->setupShadows(
1684 // current__view->getLongitude_deg(),
1685 // current__view->getLatitude_deg(),
1686 // globals->get_time_params()->getGst(),
1687 // globals->get_ephem()->getSunRightAscension(),
1688 // globals->get_ephem()->getSunDeclination(),
1689 // l->get_sun_angle());
1693 // sgEnviro.setLight(l->adj_fog_color());
1694 // sgEnviro.startOfFrame(current__view->get_view_pos(),
1695 // current__view->get_world_up(),
1696 // current__view->getLongitude_deg(),
1697 // current__view->getLatitude_deg(),
1698 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
1702 // sgEnviro.drawLightning();
1704 // double current_view_origin_airspeed_horiz_kt =
1705 // fgGetDouble("/velocities/airspeed-kt", 0.0)
1706 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
1707 // * SGD_DEGREES_TO_RADIANS);
1710 // if( is_internal )
1711 // shadows->endOfFrame();
1713 // need to call the update visitor once
1714 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
1715 mUpdateVisitor->setViewData(current__view->getViewPosition(),
1716 current__view->getViewOrientation());
1717 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
1718 mUpdateVisitor->setLight(direction, l->scene_ambient(),
1719 l->scene_diffuse(), l->scene_specular(),
1721 l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
1722 mUpdateVisitor->setVisibility(actual_visibility);
1723 simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
1724 osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
1725 cullMask |= simgear::GroundLightManager::instance()
1726 ->getLightNodeMask(mUpdateVisitor.get());
1727 if (_panel_hotspots->getBoolValue())
1728 cullMask |= simgear::PICK_BIT;
1729 CameraGroup::getDefault()->setCameraCullMasks(cullMask);
1730 if ( !_classicalRenderer ) {
1731 _fogColor->set( toOsg( l->adj_fog_color() ) );
1732 _fogDensity->set( float( mUpdateVisitor->getFogExp2Density() ) );
1737 FGRenderer::resize( int width, int height )
1739 int curWidth = _xsize->getIntValue(),
1740 curHeight = _ysize->getIntValue();
1741 SG_LOG(SG_VIEW, SG_DEBUG, "FGRenderer::resize: new size " << width << " x " << height);
1742 if ((curHeight != height) || (curWidth != width)) {
1743 // must guard setting these, or PLIB-PUI fails with too many live interfaces
1744 _xsize->setIntValue(width);
1745 _ysize->setIntValue(height);
1749 typedef osgUtil::LineSegmentIntersector::Intersection Intersection;
1750 SGVec2d uvFromIntersection(const Intersection& hit)
1752 // Taken from http://trac.openscenegraph.org/projects/osg/browser/OpenSceneGraph/trunk/examples/osgmovie/osgmovie.cpp
1754 osg::Drawable* drawable = hit.drawable.get();
1755 osg::Geometry* geometry = drawable ? drawable->asGeometry() : 0;
1756 osg::Vec3Array* vertices =
1757 geometry ? dynamic_cast<osg::Vec3Array*>(geometry->getVertexArray()) : 0;
1761 SG_LOG(SG_INPUT, SG_WARN, "Unable to get vertices for intersection.");
1762 return SGVec2d(-9999,-9999);
1765 // get the vertex indices.
1766 const Intersection::IndexList& indices = hit.indexList;
1767 const Intersection::RatioList& ratios = hit.ratioList;
1769 if( indices.size() != 3 || ratios.size() != 3 )
1773 "Intersection has insufficient indices to work with." );
1774 return SGVec2d(-9999,-9999);
1777 unsigned int i1 = indices[0];
1778 unsigned int i2 = indices[1];
1779 unsigned int i3 = indices[2];
1781 float r1 = ratios[0];
1782 float r2 = ratios[1];
1783 float r3 = ratios[2];
1785 osg::Array* texcoords =
1786 (geometry->getNumTexCoordArrays() > 0) ? geometry->getTexCoordArray(0) : 0;
1787 osg::Vec2Array* texcoords_Vec2Array =
1788 dynamic_cast<osg::Vec2Array*>(texcoords);
1790 if( !texcoords_Vec2Array )
1792 SG_LOG(SG_INPUT, SG_WARN, "Unable to get texcoords for intersection.");
1793 return SGVec2d(-9999,-9999);
1796 // we have tex coord array so now we can compute the final tex coord at the
1797 // point of intersection.
1798 osg::Vec2 tc1 = (*texcoords_Vec2Array)[i1];
1799 osg::Vec2 tc2 = (*texcoords_Vec2Array)[i2];
1800 osg::Vec2 tc3 = (*texcoords_Vec2Array)[i3];
1802 return toSG( osg::Vec2d(tc1 * r1 + tc2 * r2 + tc3 * r3) );
1806 FGRenderer::pick(std::vector<SGSceneryPick>& pickList, const osg::Vec2& windowPos)
1808 // wipe out the return ...
1810 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
1811 Intersections intersections;
1813 if (!computeIntersections(CameraGroup::getDefault(), windowPos, intersections))
1815 for (Intersections::iterator hit = intersections.begin(),
1816 e = intersections.end();
1819 const osg::NodePath& np = hit->nodePath;
1820 osg::NodePath::const_reverse_iterator npi;
1822 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
1823 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
1824 if (!ud || (ud->getNumPickCallbacks() == 0))
1827 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
1828 SGPickCallback* pickCallback = ud->getPickCallback(i);
1831 SGSceneryPick sceneryPick;
1832 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
1833 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
1835 if( pickCallback->needsUV() )
1836 sceneryPick.info.uv = uvFromIntersection(*hit);
1838 sceneryPick.callback = pickCallback;
1839 pickList.push_back(sceneryPick);
1840 } // of installed pick callbacks iteration
1841 } // of reverse node path walk
1844 return !pickList.empty();
1848 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
1854 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
1856 eventHandler = eventHandler_;
1860 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
1862 mRealRoot->addChild(camera);
1866 FGRenderer::removeCamera(osg::Camera* camera)
1868 mRealRoot->removeChild(camera);
1872 FGRenderer::setPlanes( double zNear, double zFar )
1874 _planes->set( osg::Vec3f( - zFar, - zFar * zNear, zFar - zNear ) );
1878 fgDumpSceneGraphToFile(const char* filename)
1880 return osgDB::writeNodeFile(*mRealRoot.get(), filename);
1884 fgDumpTerrainBranchToFile(const char* filename)
1886 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
1892 fgDumpNodeToFile(osg::Node* node, const char* filename)
1894 return osgDB::writeNodeFile(*node, filename);
1897 namespace flightgear
1899 using namespace osg;
1901 class VisibleSceneInfoVistor : public NodeVisitor, CullStack
1904 VisibleSceneInfoVistor()
1905 : NodeVisitor(CULL_VISITOR, TRAVERSE_ACTIVE_CHILDREN)
1907 setCullingMode(CullSettings::SMALL_FEATURE_CULLING
1908 | CullSettings::VIEW_FRUSTUM_CULLING);
1909 setComputeNearFarMode(CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1912 VisibleSceneInfoVistor(const VisibleSceneInfoVistor& rhs)
1916 META_NodeVisitor("flightgear","VisibleSceneInfoVistor")
1918 typedef std::map<const std::string,int> InfoMap;
1920 void getNodeInfo(Node* node)
1922 const char* typeName = typeid(*node).name();
1923 classInfo[typeName]++;
1924 const std::string& nodeName = node->getName();
1925 if (!nodeName.empty())
1926 nodeInfo[nodeName]++;
1931 using namespace std;
1932 typedef vector<InfoMap::iterator> FreqVector;
1933 cout << "class info:\n";
1935 for (InfoMap::iterator itr = classInfo.begin(), end = classInfo.end();
1938 classes.push_back(itr);
1939 sort(classes.begin(), classes.end(), freqComp);
1940 for (FreqVector::iterator itr = classes.begin(), end = classes.end();
1943 cout << (*itr)->first << " " << (*itr)->second << "\n";
1945 cout << "\nnode info:\n";
1947 for (InfoMap::iterator itr = nodeInfo.begin(), end = nodeInfo.end();
1950 nodes.push_back(itr);
1952 sort (nodes.begin(), nodes.end(), freqComp);
1953 for (FreqVector::iterator itr = nodes.begin(), end = nodes.end();
1956 cout << (*itr)->first << " " << (*itr)->second << "\n";
1961 void doTraversal(Camera* camera, Node* root, Viewport* viewport)
1963 ref_ptr<RefMatrix> projection
1964 = createOrReuseMatrix(camera->getProjectionMatrix());
1965 ref_ptr<RefMatrix> mv = createOrReuseMatrix(camera->getViewMatrix());
1967 viewport = camera->getViewport();
1969 pushViewport(viewport);
1970 pushProjectionMatrix(projection.get());
1971 pushModelViewMatrix(mv.get(), Transform::ABSOLUTE_RF);
1972 root->accept(*this);
1973 popModelViewMatrix();
1974 popProjectionMatrix();
1980 void apply(Node& node)
1989 void apply(Group& node)
1999 void apply(Transform& node)
2004 ref_ptr<RefMatrix> matrix = createOrReuseMatrix(*getModelViewMatrix());
2005 node.computeLocalToWorldMatrix(*matrix,this);
2006 pushModelViewMatrix(matrix.get(), node.getReferenceFrame());
2009 popModelViewMatrix();
2013 void apply(Camera& camera)
2015 // Save current cull settings
2016 CullSettings saved_cull_settings(*this);
2018 // set cull settings from this Camera
2019 setCullSettings(camera);
2020 // inherit the settings from above
2021 inheritCullSettings(saved_cull_settings, camera.getInheritanceMask());
2023 // set the cull mask.
2024 unsigned int savedTraversalMask = getTraversalMask();
2025 bool mustSetCullMask = (camera.getInheritanceMask()
2026 & osg::CullSettings::CULL_MASK) == 0;
2027 if (mustSetCullMask)
2028 setTraversalMask(camera.getCullMask());
2030 osg::RefMatrix* projection = 0;
2031 osg::RefMatrix* modelview = 0;
2033 if (camera.getReferenceFrame()==osg::Transform::RELATIVE_RF) {
2034 if (camera.getTransformOrder()==osg::Camera::POST_MULTIPLY) {
2035 projection = createOrReuseMatrix(*getProjectionMatrix()
2036 *camera.getProjectionMatrix());
2037 modelview = createOrReuseMatrix(*getModelViewMatrix()
2038 * camera.getViewMatrix());
2040 else { // pre multiply
2041 projection = createOrReuseMatrix(camera.getProjectionMatrix()
2042 * (*getProjectionMatrix()));
2043 modelview = createOrReuseMatrix(camera.getViewMatrix()
2044 * (*getModelViewMatrix()));
2047 // an absolute reference frame
2048 projection = createOrReuseMatrix(camera.getProjectionMatrix());
2049 modelview = createOrReuseMatrix(camera.getViewMatrix());
2051 if (camera.getViewport())
2052 pushViewport(camera.getViewport());
2054 pushProjectionMatrix(projection);
2055 pushModelViewMatrix(modelview, camera.getReferenceFrame());
2059 // restore the previous model view matrix.
2060 popModelViewMatrix();
2062 // restore the previous model view matrix.
2063 popProjectionMatrix();
2065 if (camera.getViewport()) popViewport();
2067 // restore the previous traversal mask settings
2068 if (mustSetCullMask)
2069 setTraversalMask(savedTraversalMask);
2071 // restore the previous cull settings
2072 setCullSettings(saved_cull_settings);
2077 static bool freqComp(const InfoMap::iterator& lhs, const InfoMap::iterator& rhs)
2079 return lhs->second > rhs->second;
2085 bool printVisibleSceneInfo(FGRenderer* renderer)
2087 osgViewer::Viewer* viewer = renderer->getViewer();
2088 VisibleSceneInfoVistor vsv;
2090 if (!viewer->getCamera()->getViewport() && viewer->getNumSlaves() > 0) {
2091 const View::Slave& slave = viewer->getSlave(0);
2092 vp = slave._camera->getViewport();
2094 vsv.doTraversal(viewer->getCamera(), viewer->getSceneData(), vp);
2099 // end of renderer.cxx