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);
224 HUD *hud = static_cast<HUD*>(globals->get_subsystem("hud"));
231 virtual osg::Object* cloneType() const { return new SGHUDDrawable; }
232 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDDrawable; }
237 class FGLightSourceUpdateCallback : public osg::NodeCallback {
241 * @param isSun true if the light is the actual sun i.e., for
242 * illuminating the moon.
244 FGLightSourceUpdateCallback(bool isSun = false) : _isSun(isSun) {}
245 FGLightSourceUpdateCallback(const FGLightSourceUpdateCallback& nc,
247 : NodeCallback(nc, op), _isSun(nc._isSun)
249 META_Object(flightgear,FGLightSourceUpdateCallback);
251 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
253 assert(dynamic_cast<osg::LightSource*>(node));
254 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
255 osg::Light* light = lightSource->getLight();
257 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
259 light->setAmbient(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
260 light->setDiffuse(Vec4(1.0f, 1.0f, 1.0f, 1.0f));
261 light->setSpecular(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
263 light->setAmbient(toOsg(l->scene_ambient()));
264 light->setDiffuse(toOsg(l->scene_diffuse()));
265 light->setSpecular(toOsg(l->scene_specular()));
267 osg::Vec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
268 light->setPosition(position);
276 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
278 FGWireFrameModeUpdateCallback() :
279 mWireframe(fgGetNode("/sim/rendering/wireframe", true))
281 virtual void operator()(osg::StateAttribute* stateAttribute,
284 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
285 osg::PolygonMode* polygonMode;
286 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
288 if (mWireframe->getBoolValue())
289 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
290 osg::PolygonMode::LINE);
292 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
293 osg::PolygonMode::FILL);
296 SGPropertyNode_ptr mWireframe;
299 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
301 FGLightModelUpdateCallback() :
302 mHighlights(fgGetNode("/sim/rendering/specular-highlight", true))
304 virtual void operator()(osg::StateAttribute* stateAttribute,
307 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
308 osg::LightModel* lightModel;
309 lightModel = static_cast<osg::LightModel*>(stateAttribute);
312 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
313 lightModel->setAmbientIntensity(toOsg(l->scene_ambient());
315 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
317 lightModel->setTwoSided(true);
318 lightModel->setLocalViewer(false);
320 if (mHighlights->getBoolValue()) {
321 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
323 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
327 SGPropertyNode_ptr mHighlights;
330 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
332 FGFogEnableUpdateCallback() :
333 mFogEnabled(fgGetNode("/sim/rendering/fog", true))
335 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
337 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
338 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
340 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
344 SGPropertyNode_ptr mFogEnabled;
347 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
349 virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
351 assert(dynamic_cast<SGUpdateVisitor*>(nv));
352 assert(dynamic_cast<osg::Fog*>(sa));
353 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
354 osg::Fog* fog = static_cast<osg::Fog*>(sa);
355 fog->setMode(osg::Fog::EXP2);
356 fog->setColor(toOsg(updateVisitor->getFogColor()));
357 fog->setDensity(updateVisitor->getFogExp2Density());
361 // update callback for the switch node guarding that splash
362 class FGScenerySwitchCallback : public osg::NodeCallback {
364 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
366 assert(dynamic_cast<osg::Switch*>(node));
367 osg::Switch* sw = static_cast<osg::Switch*>(node);
369 bool enabled = scenery_enabled;
370 sw->setValue(0, enabled);
376 static bool scenery_enabled;
379 bool FGScenerySwitchCallback::scenery_enabled = false;
381 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
382 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
384 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
385 static osg::ref_ptr<osg::Group> mDeferredRealRoot = new osg::Group;
387 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
389 #ifdef FG_JPEG_SERVER
390 static void updateRenderer()
392 globals->get_renderer()->update();
396 FGRenderer::FGRenderer() :
398 _ambientFactor( new osg::Uniform( "fg_SunAmbientColor", osg::Vec4f() ) ),
399 _sunDiffuse( new osg::Uniform( "fg_SunDiffuseColor", osg::Vec4f() ) ),
400 _sunSpecular( new osg::Uniform( "fg_SunSpecularColor", osg::Vec4f() ) ),
401 _sunDirection( new osg::Uniform( "fg_SunDirection", osg::Vec3f() ) ),
402 _planes( new osg::Uniform( "fg_Planes", osg::Vec3f() ) ),
403 _fogColor( new osg::Uniform( "fg_FogColor", osg::Vec4f(1.0, 1.0, 1.0, 1.0) ) ),
404 _fogDensity( new osg::Uniform( "fg_FogDensity", 0.0001f ) ),
405 _shadowNumber( new osg::Uniform( "fg_ShadowNumber", (int)4 ) ),
406 _shadowDistances( new osg::Uniform( "fg_ShadowDistances", osg::Vec4f(5.0, 50.0, 500.0, 5000.0 ) ) ),
407 _depthInColor( new osg::Uniform( "fg_DepthInColor", false ) )
409 #ifdef FG_JPEG_SERVER
410 jpgRenderFrame = updateRenderer;
412 eventHandler = new FGEventHandler;
415 _cascadeFar[0] = 5.f;
416 _cascadeFar[1] = 50.f;
417 _cascadeFar[2] = 500.f;
418 _cascadeFar[3] = 5000.f;
421 FGRenderer::~FGRenderer()
423 #ifdef FG_JPEG_SERVER
424 jpgRenderFrame = NULL;
429 // Initialize various GL/view parameters
430 // XXX This should be called "preinit" or something, as it initializes
431 // critical parts of the scene graph in addition to the splash screen.
433 FGRenderer::splashinit( void ) {
434 osgViewer::Viewer* viewer = getViewer();
435 mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
436 ref_ptr<Node> splashNode = fgCreateSplashNode();
437 if (_classicalRenderer) {
438 mRealRoot->addChild(splashNode.get());
440 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
441 ii != CameraGroup::getDefault()->camerasEnd();
444 CameraInfo* info = ii->get();
445 Camera* camera = info->getCamera(DISPLAY_CAMERA);
446 if (camera == 0) continue;
448 camera->addChild(splashNode.get());
451 mFrameStamp = viewer->getFrameStamp();
452 // Scene doesn't seem to pass the frame stamp to the update
453 // visitor automatically.
454 mUpdateVisitor->setFrameStamp(mFrameStamp.get());
455 viewer->setUpdateVisitor(mUpdateVisitor.get());
456 fgSetDouble("/sim/startup/splash-alpha", 1.0);
459 class ShadowMapSizeListener : public SGPropertyChangeListener {
461 virtual void valueChanged(SGPropertyNode* node) {
462 globals->get_renderer()->updateShadowMapSize(node->getIntValue());
466 class ShadowEnabledListener : public SGPropertyChangeListener {
468 virtual void valueChanged(SGPropertyNode* node) {
469 globals->get_renderer()->enableShadows(node->getBoolValue());
473 class ShadowNumListener : public SGPropertyChangeListener {
475 virtual void valueChanged(SGPropertyNode* node) {
476 globals->get_renderer()->updateCascadeNumber(node->getIntValue());
480 class ShadowRangeListener : public SGPropertyChangeListener {
482 virtual void valueChanged(SGPropertyNode* node) {
483 globals->get_renderer()->updateCascadeFar(node->getIndex(), node->getFloatValue());
488 FGRenderer::init( void )
490 sgUserDataInit( globals->get_props() );
492 _classicalRenderer = !fgGetBool("/sim/rendering/rembrandt/enabled", false);
493 _shadowMapSize = fgGetInt( "/sim/rendering/shadows/map-size", 4096 );
494 fgAddChangeListener( new ShadowMapSizeListener, "/sim/rendering/shadows/map-size" );
495 fgAddChangeListener( new ShadowEnabledListener, "/sim/rendering/shadows/enabled" );
496 ShadowRangeListener* srl = new ShadowRangeListener;
497 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[0]");
498 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[1]");
499 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[2]");
500 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[3]");
501 fgAddChangeListener(new ShadowNumListener, "/sim/rendering/shadows/num-cascades");
502 _numCascades = fgGetInt("/sim/rendering/shadows/num-cascades", 4);
503 _cascadeFar[0] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[0]", 5.0f);
504 _cascadeFar[1] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[1]", 50.0f);
505 _cascadeFar[2] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[2]", 500.0f);
506 _cascadeFar[3] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[3]", 5000.0f);
507 updateCascadeNumber(_numCascades);
508 updateCascadeFar(0, _cascadeFar[0]);
509 updateCascadeFar(1, _cascadeFar[1]);
510 updateCascadeFar(2, _cascadeFar[2]);
511 updateCascadeFar(3, _cascadeFar[3]);
512 _useColorForDepth = fgGetBool( "/sim/rendering/rembrandt/use-color-for-depth", false );
513 _depthInColor->set( _useColorForDepth );
515 _renderer = fgGetString("/sim/rendering/rembrandt/renderer", "default-pipeline");
516 if (!_classicalRenderer)
517 _pipeline = makeRenderingPipeline(_renderer, 0);
518 _scenery_loaded = fgGetNode("/sim/sceneryloaded", true);
519 _panel_hotspots = fgGetNode("/sim/panel-hotspots", true);
520 _virtual_cockpit = fgGetNode("/sim/virtual-cockpit", true);
522 _sim_delta_sec = fgGetNode("/sim/time/delta-sec", true);
524 _xsize = fgGetNode("/sim/startup/xsize", true);
525 _ysize = fgGetNode("/sim/startup/ysize", true);
526 _splash_alpha = fgGetNode("/sim/startup/splash-alpha", true);
528 _skyblend = fgGetNode("/sim/rendering/skyblend", true);
529 _point_sprites = fgGetNode("/sim/rendering/point-sprites", true);
530 _enhanced_lighting = fgGetNode("/sim/rendering/enhanced-lighting", true);
531 _distance_attenuation = fgGetNode("/sim/rendering/distance-attenuation", true);
532 _horizon_effect = fgGetNode("/sim/rendering/horizon-effect", true);
533 _textures = fgGetNode("/sim/rendering/textures", true);
535 _altitude_ft = fgGetNode("/position/altitude-ft", true);
537 _cloud_status = fgGetNode("/environment/clouds/status", true);
538 _visibility_m = fgGetNode("/environment/visibility-m", true);
540 bool use_point_sprites = _point_sprites->getBoolValue();
541 bool enhanced_lighting = _enhanced_lighting->getBoolValue();
542 bool distance_attenuation = _distance_attenuation->getBoolValue();
544 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
545 distance_attenuation );
547 if (const char* tc = fgGetString("/sim/rendering/texture-compression", NULL)) {
548 if (strcmp(tc, "false") == 0 || strcmp(tc, "off") == 0 ||
549 strcmp(tc, "0") == 0 || strcmp(tc, "no") == 0 ||
550 strcmp(tc, "none") == 0) {
551 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::DoNotUseCompression);
552 } else if (strcmp(tc, "arb") == 0) {
553 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseARBCompression);
554 } else if (strcmp(tc, "dxt1") == 0) {
555 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT1Compression);
556 } else if (strcmp(tc, "dxt3") == 0) {
557 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT3Compression);
558 } else if (strcmp(tc, "dxt5") == 0) {
559 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT5Compression);
561 SG_LOG(SG_VIEW, SG_WARN, "Unknown texture compression setting!");
565 // create sky, but can't build until setupView, since we depend
566 // on other subsystems to be inited, eg Ephemeris
569 SGPath texture_path(globals->get_fg_root());
570 texture_path.append("Textures");
571 texture_path.append("Sky");
572 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
573 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
574 _sky->add_cloud_layer(layer);
577 _sky->texture_path( texture_path.str() );
579 if (!_classicalRenderer) {
580 eventHandler->setChangeStatsCameraRenderOrder( true );
581 _sky->set_minimum_sky_visibility( 0.0 ); // A black sky appears for below that
585 void installCullVisitor(Camera* camera)
587 osgViewer::Renderer* renderer
588 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
589 for (int i = 0; i < 2; ++i) {
590 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
591 #if SG_OSG_VERSION_LESS_THAN(3,0,0)
592 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
594 osg::ref_ptr<osgUtil::CullVisitor::Identifier> identifier;
595 identifier = sceneView->getCullVisitor()->getIdentifier();
596 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
597 sceneView->getCullVisitor()->setIdentifier(identifier.get());
599 identifier = sceneView->getCullVisitorLeft()->getIdentifier();
600 sceneView->setCullVisitorLeft(sceneView->getCullVisitor()->clone());
601 sceneView->getCullVisitorLeft()->setIdentifier(identifier.get());
603 identifier = sceneView->getCullVisitorRight()->getIdentifier();
604 sceneView->setCullVisitorRight(sceneView->getCullVisitor()->clone());
605 sceneView->getCullVisitorRight()->setIdentifier(identifier.get());
611 FGRenderer::buildRenderingPipeline(CameraGroup* cgroup, unsigned flags, Camera* camera,
613 const Matrix& projection,
614 osg::GraphicsContext* gc,
615 bool useMasterSceneData)
617 CameraInfo* info = 0;
618 if (!_classicalRenderer && (flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
619 info = buildDeferredPipeline( cgroup, flags, camera, view, projection, gc );
624 if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
625 _classicalRenderer = true;
626 return buildClassicalPipeline( cgroup, flags, camera, view, projection, useMasterSceneData );
631 FGRenderer::buildClassicalPipeline(CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
632 const osg::Matrix& view,
633 const osg::Matrix& projection,
634 bool useMasterSceneData)
636 CameraInfo* info = new CameraInfo(flags);
637 // The camera group will always update the camera
638 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
640 Camera* farCamera = 0;
641 if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0) {
642 farCamera = new Camera;
643 farCamera->setAllowEventFocus(camera->getAllowEventFocus());
644 farCamera->setGraphicsContext(camera->getGraphicsContext());
645 farCamera->setCullingMode(camera->getCullingMode());
646 farCamera->setInheritanceMask(camera->getInheritanceMask());
647 farCamera->setReferenceFrame(Transform::ABSOLUTE_RF);
648 // Each camera's viewport is written when the window is
649 // resized; if the the viewport isn't copied here, it gets updated
650 // twice and ends up with the wrong value.
651 farCamera->setViewport(simgear::clone(camera->getViewport()));
652 farCamera->setDrawBuffer(camera->getDrawBuffer());
653 farCamera->setReadBuffer(camera->getReadBuffer());
654 farCamera->setRenderTargetImplementation(
655 camera->getRenderTargetImplementation());
656 const Camera::BufferAttachmentMap& bufferMap
657 = camera->getBufferAttachmentMap();
658 if (bufferMap.count(Camera::COLOR_BUFFER) != 0) {
660 Camera::COLOR_BUFFER,
661 bufferMap.find(Camera::COLOR_BUFFER)->second._texture.get());
663 cgroup->getViewer()->addSlave(farCamera, projection, view, useMasterSceneData);
664 installCullVisitor(farCamera);
665 int farSlaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
666 info->addCamera( FAR_CAMERA, farCamera, farSlaveIndex );
667 farCamera->setRenderOrder(Camera::POST_RENDER, farSlaveIndex);
668 camera->setCullMask(camera->getCullMask() & ~simgear::BACKGROUND_BIT);
669 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
671 cgroup->getViewer()->addSlave(camera, projection, view, useMasterSceneData);
672 installCullVisitor(camera);
673 int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
674 info->addCamera( MAIN_CAMERA, camera, slaveIndex );
675 camera->setRenderOrder(Camera::POST_RENDER, slaveIndex);
676 cgroup->addCamera(info);
680 class FGDeferredRenderingCameraCullCallback : public osg::NodeCallback {
682 FGDeferredRenderingCameraCullCallback( const std::string& k, CameraInfo* i, bool nd = false ) : kind( k ), info( i ), needsDuDv(nd) {}
683 virtual void operator()( osg::Node *n, osg::NodeVisitor *nv) {
684 simgear::EffectCullVisitor* cv = dynamic_cast<simgear::EffectCullVisitor*>(nv);
685 osg::Camera* camera = static_cast<osg::Camera*>(n);
687 cv->clearBufferList();
688 for (RenderBufferMap::iterator ii = info->buffers.begin(); ii != info->buffers.end(); ++ii) {
689 cv->addBuffer(ii->first, ii->second.texture);
692 if ( !info->getRenderStageInfo(kind).fullscreen )
693 info->setMatrices( camera );
696 osg::Matrix projInverse;
697 info->projInverse->get( projInverse );
699 osg::Vec4 p0 = osg::Vec4( -1.0, -1.0, 0.0, 1.0 ) * projInverse;
700 info->du->set( osg::Vec4( 1.0, -1.0, 0.0, 1.0 ) * projInverse - p0 );
701 info->dv->set( osg::Vec4( -1.0, 1.0, 0.0, 1.0 ) * projInverse - p0 );
704 cv->traverse( *camera );
706 if ( kind == GEOMETRY_CAMERA ) {
707 // Remove transparent bins. They will be renderer in the additional light stage (side effect)
708 osgUtil::RenderStage* renderStage = cv->getRenderStage();
709 osgUtil::RenderBin::RenderBinList& rbl = renderStage->getRenderBinList();
710 for (osgUtil::RenderBin::RenderBinList::iterator rbi = rbl.begin(); rbi != rbl.end(); ) {
711 if (rbi->second->getSortMode() == osgUtil::RenderBin::SORT_BACK_TO_FRONT) {
717 } else if ( kind == LIGHTING_CAMERA ) {
718 osg::ref_ptr<osg::Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
719 if (mainShadowCamera.valid()) {
720 osg::Switch* grp = mainShadowCamera->getChild(0)->asSwitch();
721 for (int i = 0; i < 4; ++i ) {
722 if (!grp->getValue(i))
725 osg::Camera* cascadeCam = static_cast<osg::Camera*>( grp->getChild(i) );
726 osg::Matrixf shadowMatrix = camera->getInverseViewMatrix() *
727 cascadeCam->getViewMatrix() *
728 cascadeCam->getProjectionMatrix() *
729 osg::Matrix::translate(1.0, 1.0, 1.0) *
730 osg::Matrix::scale(0.5f, 0.5f, 0.5f);
732 info->shadowMatrix[i]->set( shadowMatrix );
744 osg::Texture2D* buildDeferredBuffer(GLint internalFormat, GLenum sourceFormat, GLenum sourceType, GLenum wrapMode, bool shadowComparison = false)
746 osg::Texture2D* tex = new osg::Texture2D;
747 tex->setResizeNonPowerOfTwoHint( false );
748 tex->setInternalFormat( internalFormat );
749 tex->setShadowComparison(shadowComparison);
750 if (shadowComparison) {
751 tex->setShadowTextureMode(osg::Texture2D::LUMINANCE);
752 tex->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
754 tex->setSourceFormat(sourceFormat);
755 tex->setSourceType(sourceType);
756 tex->setFilter( osg::Texture2D::MIN_FILTER, osg::Texture2D::LINEAR );
757 tex->setFilter( osg::Texture2D::MAG_FILTER, osg::Texture2D::LINEAR );
758 tex->setWrap( osg::Texture::WRAP_S, (osg::Texture::WrapMode)wrapMode );
759 tex->setWrap( osg::Texture::WRAP_T, (osg::Texture::WrapMode)wrapMode );
763 void attachBufferToCamera( CameraInfo* info, osg::Camera* camera, osg::Camera::BufferComponent c, const std::string& ck, const std::string& bk )
765 camera->attach( c, info->getBuffer(bk) );
766 info->getRenderStageInfo(ck).buffers.insert( std::make_pair( c, bk ) );
769 void buildAttachments(CameraInfo* info, osg::Camera* camera, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments) {
770 BOOST_FOREACH(ref_ptr<FGRenderingPipeline::Attachment> attachment, attachments) {
771 if (attachment->valid())
772 attachBufferToCamera( info, camera, attachment->component, name, attachment->buffer );
776 osg::Camera* FGRenderer::buildDeferredGeometryCamera( CameraInfo* info, osg::GraphicsContext* gc, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
778 osg::Camera* camera = new osg::Camera;
779 info->addCamera(name, camera );
781 camera->setCullMask( ~simgear::MODELLIGHT_BIT );
782 camera->setName( "GeometryC" );
783 camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
784 camera->setGraphicsContext( gc );
785 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( name, info ) );
786 camera->setClearMask( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
787 camera->setClearColor( osg::Vec4( 0., 0., 0., 0. ) );
788 camera->setClearDepth( 1.0 );
789 camera->setColorMask(true, true, true, true);
790 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
791 camera->setRenderOrder(osg::Camera::NESTED_RENDER, 0);
792 camera->setViewport( new osg::Viewport );
793 buildAttachments(info, camera, name, attachments);
794 camera->setDrawBuffer(GL_FRONT);
795 camera->setReadBuffer(GL_FRONT);
797 osg::StateSet* ss = camera->getOrCreateStateSet();
798 ss->addUniform( _depthInColor );
800 camera->addChild( mDeferredRealRoot.get() );
805 static void setShadowCascadeStateSet( osg::Camera* cam ) {
806 osg::StateSet* ss = cam->getOrCreateStateSet();
807 ss->setAttribute( new osg::PolygonOffset( 1.1f, 5.0f ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
808 ss->setMode( GL_POLYGON_OFFSET_FILL, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
809 ss->setRenderBinDetails( 0, "RenderBin", osg::StateSet::OVERRIDE_RENDERBIN_DETAILS );
810 ss->setAttributeAndModes( new osg::AlphaFunc( osg::AlphaFunc::GREATER, 0.05 ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
811 ss->setAttributeAndModes( new osg::ColorMask( false, false, false, false ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
812 ss->setAttributeAndModes( new osg::CullFace( osg::CullFace::FRONT ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
813 osg::Program* program = new osg::Program;
814 ss->setAttribute( program, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
815 ss->setMode( GL_LIGHTING, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
816 ss->setMode( GL_BLEND, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
817 //ss->setTextureMode( 0, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
818 ss->setTextureMode( 0, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
819 ss->setTextureMode( 1, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
820 ss->setTextureMode( 1, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
821 ss->setTextureMode( 2, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
822 ss->setTextureMode( 2, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
825 static osg::Camera* createShadowCascadeCamera( int no, int cascadeSize ) {
826 osg::Camera* cascadeCam = new osg::Camera;
827 setShadowCascadeStateSet( cascadeCam );
829 std::ostringstream oss;
830 oss << "CascadeCamera" << (no + 1);
831 cascadeCam->setName( oss.str() );
832 cascadeCam->setClearMask(0);
833 cascadeCam->setCullMask( simgear::CASTSHADOW_BIT );
834 cascadeCam->setCullingMode( cascadeCam->getCullingMode() | osg::CullSettings::SMALL_FEATURE_CULLING );
835 cascadeCam->setAllowEventFocus(false);
836 cascadeCam->setReferenceFrame(osg::Transform::ABSOLUTE_RF_INHERIT_VIEWPOINT);
837 cascadeCam->setRenderOrder(osg::Camera::NESTED_RENDER);
838 cascadeCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
839 cascadeCam->setViewport( int( no / 2 ) * cascadeSize, (no & 1) * cascadeSize, cascadeSize, cascadeSize );
843 osg::Camera* FGRenderer::buildDeferredShadowCamera( CameraInfo* info, osg::GraphicsContext* gc, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
845 osg::Camera* mainShadowCamera = new osg::Camera;
846 info->addCamera(name, mainShadowCamera, 0.0f );
848 mainShadowCamera->setName( "ShadowC" );
849 mainShadowCamera->setClearMask( GL_DEPTH_BUFFER_BIT );
850 mainShadowCamera->setClearDepth( 1.0 );
851 mainShadowCamera->setAllowEventFocus(false);
852 mainShadowCamera->setGraphicsContext(gc);
853 mainShadowCamera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
854 buildAttachments(info, mainShadowCamera, name, attachments);
855 mainShadowCamera->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
856 mainShadowCamera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
857 mainShadowCamera->setProjectionMatrix(osg::Matrix::identity());
858 mainShadowCamera->setCullingMode( osg::CullSettings::NO_CULLING );
859 mainShadowCamera->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
860 mainShadowCamera->setDrawBuffer(GL_FRONT);
861 mainShadowCamera->setReadBuffer(GL_FRONT);
862 mainShadowCamera->setRenderOrder(Camera::NESTED_RENDER, 1);
864 osg::Switch* shadowSwitch = new osg::Switch;
865 mainShadowCamera->addChild( shadowSwitch );
867 for (int i = 0; i < 4; ++i ) {
868 osg::Camera* cascadeCam = createShadowCascadeCamera( i, _shadowMapSize/2 );
869 cascadeCam->addChild( mDeferredRealRoot.get() );
870 shadowSwitch->addChild( cascadeCam );
872 if (fgGetBool("/sim/rendering/shadows/enabled", true))
873 shadowSwitch->setAllChildrenOn();
875 shadowSwitch->setAllChildrenOff();
877 return mainShadowCamera;
880 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)
882 osg::Camera* cascade = static_cast<osg::Camera*>( grp->getChild(idx) );
883 osg::Matrixd &viewMatrix = cascade->getViewMatrix();
884 osg::Matrixd &projectionMatrix = cascade->getProjectionMatrix();
886 osg::BoundingSphere bs;
887 bs.expandBy(osg::Vec3(left,bottom,-zNear) * f1);
888 bs.expandBy(osg::Vec3(right,top,-zNear) * f2);
889 bs.expandBy(osg::Vec3(left,bottom,-zNear) * f2);
890 bs.expandBy(osg::Vec3(right,top,-zNear) * f1);
892 osg::Vec4 aim = osg::Vec4(bs.center(), 1.0) * camera->getInverseViewMatrix();
894 projectionMatrix.makeOrtho( -bs.radius(), bs.radius(), -bs.radius(), bs.radius(), 1., 15000.0 );
895 osg::Vec3 position( aim.x(), aim.y(), aim.z() );
896 viewMatrix.makeLookAt( position + (getSunDirection() * 10000.0), position, position );
899 osg::Vec3 FGRenderer::getSunDirection() const
902 _sunDirection->get( val );
906 void FGRenderer::updateShadowCamera(const CameraInfo* info, const osg::Vec3d& position)
908 ref_ptr<Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
909 if (mainShadowCamera.valid()) {
910 ref_ptr<Switch> shadowSwitch = mainShadowCamera->getChild( 0 )->asSwitch();
911 osg::Vec3d up = position,
912 dir = getSunDirection();
915 // cos(100 deg) == -0.17
916 if (up * dir < -0.17 || !fgGetBool("/sim/rendering/shadows/enabled", true)) {
917 shadowSwitch->setAllChildrenOff();
919 double left,right,bottom,top,zNear,zFar;
920 ref_ptr<Camera> camera = info->getCamera(GEOMETRY_CAMERA);
921 camera->getProjectionMatrix().getFrustum(left,right,bottom,top,zNear,zFar);
923 shadowSwitch->setAllChildrenOn();
924 if (_numCascades == 1) {
925 osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(0) );
926 cascadeCam->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
928 for (int no = 0; no < 4; ++no) {
929 osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(no) );
930 cascadeCam->setViewport( int( no / 2 ) * (_shadowMapSize/2), (no & 1) * (_shadowMapSize/2), (_shadowMapSize/2), (_shadowMapSize/2) );
933 updateShadowCascade(info, camera, shadowSwitch, 0, left, right, bottom, top, zNear, 1.0, _cascadeFar[0]/zNear);
934 if (_numCascades > 1) {
935 shadowSwitch->setValue(1, true);
936 updateShadowCascade(info, camera, shadowSwitch, 1, left, right, bottom, top, zNear, _cascadeFar[0]/zNear, _cascadeFar[1]/zNear);
938 shadowSwitch->setValue(1, false);
940 if (_numCascades > 2) {
941 shadowSwitch->setValue(2, true);
942 updateShadowCascade(info, camera, shadowSwitch, 2, left, right, bottom, top, zNear, _cascadeFar[1]/zNear, _cascadeFar[2]/zNear);
944 shadowSwitch->setValue(2, false);
946 if (_numCascades > 3) {
947 shadowSwitch->setValue(3, true);
948 updateShadowCascade(info, camera, shadowSwitch, 3, left, right, bottom, top, zNear, _cascadeFar[2]/zNear, _cascadeFar[3]/zNear);
950 shadowSwitch->setValue(3, false);
953 osg::Matrixd &viewMatrix = mainShadowCamera->getViewMatrix();
955 osg::Vec4 aim = osg::Vec4( 0.0, 0.0, 0.0, 1.0 ) * camera->getInverseViewMatrix();
957 osg::Vec3 position( aim.x(), aim.y(), aim.z() );
958 viewMatrix.makeLookAt( position, position + (getSunDirection() * 10000.0), position );
964 void FGRenderer::updateShadowMapSize(int mapSize)
966 if ( ((~( mapSize-1 )) & mapSize) != mapSize ) {
967 SG_LOG( SG_VIEW, SG_ALERT, "Map size is not a power of two" );
970 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
971 ii != CameraGroup::getDefault()->camerasEnd();
974 CameraInfo* info = ii->get();
975 Camera* camera = info->getCamera(SHADOW_CAMERA);
976 if (camera == 0) continue;
978 Texture2D* tex = info->getBuffer("shadow");
979 if (tex == 0) continue;
981 tex->setTextureSize( mapSize, mapSize );
982 tex->dirtyTextureObject();
984 Viewport* vp = camera->getViewport();
985 vp->width() = mapSize;
986 vp->height() = mapSize;
988 osgViewer::Renderer* renderer
989 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
990 for (int i = 0; i < 2; ++i) {
991 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
992 sceneView->getRenderStage()->setFrameBufferObject(0);
993 sceneView->getRenderStage()->setCameraRequiresSetUp(true);
994 if (sceneView->getRenderStageLeft()) {
995 sceneView->getRenderStageLeft()->setFrameBufferObject(0);
996 sceneView->getRenderStageLeft()->setCameraRequiresSetUp(true);
998 if (sceneView->getRenderStageRight()) {
999 sceneView->getRenderStageRight()->setFrameBufferObject(0);
1000 sceneView->getRenderStageRight()->setCameraRequiresSetUp(true);
1004 int cascadeSize = mapSize / 2;
1005 Group* grp = camera->getChild(0)->asGroup();
1006 for (int i = 0; i < 4; ++i ) {
1007 Camera* cascadeCam = static_cast<Camera*>( grp->getChild(i) );
1008 cascadeCam->setViewport( int( i / 2 ) * cascadeSize, (i & 1) * cascadeSize, cascadeSize, cascadeSize );
1011 _shadowMapSize = mapSize;
1015 void FGRenderer::enableShadows(bool enabled)
1017 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
1018 ii != CameraGroup::getDefault()->camerasEnd();
1021 CameraInfo* info = ii->get();
1022 Camera* camera = info->getCamera(SHADOW_CAMERA);
1023 if (camera == 0) continue;
1025 osg::Switch* shadowSwitch = camera->getChild(0)->asSwitch();
1027 shadowSwitch->setAllChildrenOn();
1029 shadowSwitch->setAllChildrenOff();
1033 void FGRenderer::updateCascadeFar(int index, float far_m)
1035 if (index < 0 || index > 3)
1037 _cascadeFar[index] = far_m;
1038 _shadowDistances->set( osg::Vec4f(_cascadeFar[0], _cascadeFar[1], _cascadeFar[2], _cascadeFar[3]) );
1041 void FGRenderer::updateCascadeNumber(size_t num)
1043 if (num < 1 || num > 4)
1046 _shadowNumber->set( (int)_numCascades );
1049 class DebugPassListener : public SGPropertyChangeListener {
1051 DebugPassListener(osg::Switch* sw, int i) : _switch(sw), _index(i) {}
1052 virtual void valueChanged(SGPropertyNode* node) {
1053 _switch->setValue(_index, node->getBoolValue());
1057 osg::ref_ptr<osg::Switch> _switch;
1062 FGRenderer::buildDeferredLightingCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc, const FGRenderingPipeline::Stage* stage )
1064 osg::Camera* camera = new osg::Camera;
1065 info->addCamera(stage->name, camera );
1067 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( stage->name, info ) );
1068 camera->setAllowEventFocus(false);
1069 camera->setGraphicsContext(gc);
1070 camera->setViewport(new Viewport);
1071 camera->setName(stage->name+"C");
1072 camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1073 camera->setRenderOrder(osg::Camera::NESTED_RENDER, stage->orderNum);
1074 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1075 camera->setViewport( new osg::Viewport );
1076 buildAttachments(info, camera, stage->name, stage->attachments);
1077 camera->setDrawBuffer(GL_FRONT);
1078 camera->setReadBuffer(GL_FRONT);
1079 camera->setClearColor( osg::Vec4( 0.5, 0.5, 0.5, 1. ) );
1080 camera->setClearMask( GL_COLOR_BUFFER_BIT );
1081 osg::StateSet* ss = camera->getOrCreateStateSet();
1082 ss->setAttribute( new osg::Depth(osg::Depth::LESS, 0.0, 1.0, false) );
1083 ss->addUniform( _depthInColor );
1085 osg::Switch* lightingGroup = new osg::Switch;
1087 BOOST_FOREACH( osg::ref_ptr<FGRenderingPipeline::Pass> pass, stage->passes ) {
1088 ref_ptr<Node> node = buildPass(info, pass);
1090 lightingGroup->addChild(node);
1091 if (!pass->debugProperty.empty()) {
1092 lightingGroup->setValue(lightingGroup->getNumChildren()-1, fgGetBool(pass->debugProperty));
1093 fgAddChangeListener(new DebugPassListener(lightingGroup, lightingGroup->getNumChildren()-1), pass->debugProperty);
1098 camera->addChild( lightingGroup );
1104 FGRenderer::buildDeferredPipeline(CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1105 const osg::Matrix& view,
1106 const osg::Matrix& projection,
1107 osg::GraphicsContext* gc)
1109 return buildCameraFromRenderingPipeline(_pipeline, cgroup, flags, camera, view, projection, gc);
1113 FGRenderer::buildDeferredFullscreenCamera( flightgear::CameraInfo* info, const FGRenderingPipeline::Pass* pass )
1115 osg::Camera* camera = new osg::Camera;
1117 camera->setClearMask( 0 );
1118 camera->setAllowEventFocus(false);
1119 camera->setName(pass->name+"C");
1120 camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1121 camera->setRenderOrder(osg::Camera::NESTED_RENDER, pass->orderNum);
1122 camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1123 camera->setViewMatrix(osg::Matrix::identity());
1124 camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1126 osg::StateSet* ss = camera->getOrCreateStateSet();
1127 ss->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1128 ss->addUniform( info->projInverse );
1129 ss->addUniform( info->viewInverse );
1130 ss->addUniform( info->view );
1131 ss->addUniform( info->bufferSize );
1132 ss->addUniform( info->worldPosCart );
1133 ss->addUniform( info->worldPosGeod );
1134 ss->addUniform( info->shadowMatrix[0] );
1135 ss->addUniform( info->shadowMatrix[1] );
1136 ss->addUniform( info->shadowMatrix[2] );
1137 ss->addUniform( info->shadowMatrix[3] );
1138 ss->addUniform( _ambientFactor );
1139 ss->addUniform( _sunDiffuse );
1140 ss->addUniform( _sunSpecular );
1141 ss->addUniform( _sunDirection );
1142 ss->addUniform( _planes );
1143 ss->addUniform( _shadowNumber );
1144 ss->addUniform( _shadowDistances );
1145 ss->addUniform( _fogColor );
1146 ss->addUniform( _fogDensity );
1148 osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1149 g->setUseDisplayList(false);
1150 simgear::EffectGeode* eg = new simgear::EffectGeode;
1151 osg::ref_ptr<SGReaderWriterOptions> opt;
1152 opt = SGReaderWriterOptions::fromPath(globals->get_fg_root());
1153 opt->setPropertyNode(globals->get_props());
1154 simgear::Effect* effect = simgear::makeEffect(pass->effect, true, opt.get());
1156 eg->setEffect( effect );
1159 eg->setName(pass->name+"Quad");
1160 eg->setCullingActive(false);
1162 camera->addChild(eg);
1168 FGRenderer::buildDeferredFullscreenCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc, const FGRenderingPipeline::Stage* stage )
1170 osg::Camera* camera = buildDeferredFullscreenCamera(info, static_cast<const FGRenderingPipeline::Pass*>(stage));
1171 info->addCamera(stage->name, camera, stage->scaleFactor, true);
1173 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback(stage->name, info, stage->needsDuDv) );
1174 camera->setGraphicsContext(gc);
1175 camera->setViewport(new Viewport);
1176 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1177 buildAttachments(info, camera, stage->name, stage->attachments);
1178 camera->setDrawBuffer(GL_FRONT);
1179 camera->setReadBuffer(GL_FRONT);
1180 camera->setClearColor( osg::Vec4( 1., 1., 1., 1. ) );
1181 camera->setClearMask( GL_COLOR_BUFFER_BIT );
1182 camera->setViewMatrix(osg::Matrix::identity());
1183 camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1185 osg::StateSet* ss = camera->getOrCreateStateSet();
1186 if (stage->needsDuDv) {
1187 ss->addUniform( info->du );
1188 ss->addUniform( info->dv );
1195 FGRenderer::buildDeferredDisplayCamera( osg::Camera* camera, flightgear::CameraInfo* info, const FGRenderingPipeline::Stage* stage, osg::GraphicsContext* gc )
1197 camera->setName( "DisplayC" );
1198 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( stage->name, info ) );
1199 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
1200 camera->setAllowEventFocus(false);
1201 osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1202 g->setUseDisplayList(false); //DEBUG
1203 simgear::EffectGeode* eg = new simgear::EffectGeode;
1204 osg::ref_ptr<SGReaderWriterOptions> opt;
1205 opt = SGReaderWriterOptions::fromPath(globals->get_fg_root());
1206 opt->setPropertyNode(globals->get_props());
1207 simgear::Effect* effect = simgear::makeEffect(stage->effect, true, opt.get());
1209 SG_LOG(SG_VIEW, SG_ALERT, stage->effect + " not found");
1212 eg->setEffect(effect);
1213 eg->setCullingActive(false);
1215 camera->setViewMatrix(osg::Matrix::identity());
1216 camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1217 camera->addChild(eg);
1219 osg::StateSet* ss = camera->getOrCreateStateSet();
1220 ss->addUniform( _depthInColor );
1221 ss->addUniform( info->projInverse );
1222 ss->addUniform( info->viewInverse );
1223 ss->addUniform( info->view );
1224 ss->addUniform( info->bufferSize );
1225 ss->addUniform( info->worldPosCart );
1226 ss->addUniform( info->worldPosGeod );
1227 ss->addUniform( info->shadowMatrix[0] );
1228 ss->addUniform( info->shadowMatrix[1] );
1229 ss->addUniform( info->shadowMatrix[2] );
1230 ss->addUniform( info->shadowMatrix[3] );
1231 ss->addUniform( _ambientFactor );
1232 ss->addUniform( _sunDiffuse );
1233 ss->addUniform( _sunSpecular );
1234 ss->addUniform( _sunDirection );
1235 ss->addUniform( _planes );
1236 ss->addUniform( _shadowNumber );
1237 ss->addUniform( _shadowDistances );
1238 ss->addUniform( _fogColor );
1239 ss->addUniform( _fogDensity );
1243 FGRenderer::buildStage(CameraInfo* info,
1244 FGRenderingPipeline::Stage* stage,
1245 CameraGroup* cgroup,
1246 osg::Camera* mainCamera,
1247 const osg::Matrix& view, const osg::Matrix& projection, osg::GraphicsContext* gc)
1249 if (!stage->valid())
1252 ref_ptr<Camera> camera;
1253 bool needOffsets = false;
1254 if (stage->type == "geometry") {
1255 camera = buildDeferredGeometryCamera(info, gc, stage->name, stage->attachments);
1257 } else if (stage->type == "lighting") {
1258 camera = buildDeferredLightingCamera(info, gc, stage);
1260 } else if (stage->type == "shadow")
1261 camera = buildDeferredShadowCamera(info, gc, stage->name, stage->attachments);
1262 else if (stage->type == "fullscreen")
1263 camera = buildDeferredFullscreenCamera(info, gc, stage);
1264 else if (stage->type == "display") {
1265 camera = mainCamera;
1266 buildDeferredDisplayCamera(camera, info, stage, gc);
1268 throw sg_exception("Stage type is not supported");
1271 cgroup->getViewer()->addSlave(camera, projection, view, false);
1273 cgroup->getViewer()->addSlave(camera, false);
1274 installCullVisitor(camera);
1275 int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1276 if (stage->type == "display")
1277 info->addCamera( stage->type, camera, slaveIndex, true );
1278 info->getRenderStageInfo(stage->name).slaveIndex = slaveIndex;
1282 FGRenderer::buildLightingSkyCloudsPass(FGRenderingPipeline::Pass* pass)
1284 Group* group = new Group;
1285 StateSet* ss = group->getOrCreateStateSet();
1286 ss->setAttributeAndModes( new osg::ColorMask( true, true, true, false ), osg::StateAttribute::ON );
1287 group->addChild( _sky->getPreRoot() );
1288 group->addChild( _sky->getCloudRoot() );
1293 FGRenderer::buildLightingLightsPass(CameraInfo* info, FGRenderingPipeline::Pass* pass)
1295 osg::Camera* lightCam = new osg::Camera;
1296 StateSet* ss = lightCam->getOrCreateStateSet();
1297 ss->addUniform( _planes );
1298 ss->addUniform( info->bufferSize );
1299 ss->addUniform( _fogColor );
1300 ss->addUniform( _fogDensity );
1301 lightCam->setName( "LightCamera" );
1302 lightCam->setClearMask(0);
1303 lightCam->setAllowEventFocus(false);
1304 lightCam->setReferenceFrame(osg::Transform::RELATIVE_RF);
1305 lightCam->setRenderOrder(osg::Camera::NESTED_RENDER,pass->orderNum);
1306 lightCam->setViewMatrix(osg::Matrix::identity());
1307 lightCam->setProjectionMatrix(osg::Matrix::identity());
1308 lightCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1309 lightCam->setCullMask( simgear::MODELLIGHT_BIT | simgear::PANEL2D_BIT | simgear::PERMANENTLIGHT_BIT);
1310 lightCam->setInheritanceMask( osg::CullSettings::ALL_VARIABLES & ~osg::CullSettings::CULL_MASK );
1311 lightCam->addChild( mDeferredRealRoot.get() );
1317 FGRenderer::buildPass(CameraInfo* info, FGRenderingPipeline::Pass* pass)
1323 if (pass->type == "sky-clouds")
1324 node = buildLightingSkyCloudsPass(pass);
1325 else if (pass->type == "fullscreen")
1326 node = buildDeferredFullscreenCamera(info, pass);
1327 else if (pass->type == "lights")
1328 node = buildLightingLightsPass(info, pass);
1330 throw sg_exception("Pass type is not supported");
1332 return node.release();
1336 FGRenderer::buildBuffers(FGRenderingPipeline* rpipe, CameraInfo* info)
1338 for (size_t i = 0; i < rpipe->buffers.size(); ++i) {
1339 osg::ref_ptr<FGRenderingPipeline::Buffer> buffer = rpipe->buffers[i];
1340 if (buffer->valid()) {
1341 bool fullscreen = buffer->width == -1 && buffer->height == -1;
1342 info->addBuffer(buffer->name, buildDeferredBuffer( buffer->internalFormat,
1343 buffer->sourceFormat,
1346 buffer->shadowComparison),
1347 fullscreen ? buffer->scaleFactor : 0.0f);
1349 info->getBuffer(buffer->name)->setTextureSize(buffer->width, buffer->height);
1355 CameraInfo* FGRenderer::buildCameraFromRenderingPipeline(FGRenderingPipeline* rpipe, CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1356 const osg::Matrix& view, const osg::Matrix& projection, osg::GraphicsContext* gc)
1358 CameraInfo* info = new CameraInfo(flags);
1359 buildBuffers(rpipe, info);
1361 for (size_t i = 0; i < rpipe->stages.size(); ++i) {
1362 osg::ref_ptr<FGRenderingPipeline::Stage> stage = rpipe->stages[i];
1363 buildStage(info, stage, cgroup, camera, view, projection, gc);
1366 cgroup->addCamera(info);
1372 FGRenderer::setupView( void )
1374 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1375 osg::initNotifyLevel();
1377 // The number of polygon-offset "units" to place between layers. In
1378 // principle, one is supposed to be enough. In practice, I find that
1379 // my hardware/driver requires many more.
1380 osg::PolygonOffset::setUnitsMultiplier(1);
1381 osg::PolygonOffset::setFactorMultiplier(1);
1384 // The sun and moon diameters are scaled down numbers of the
1385 // actual diameters. This was needed to fit both the sun and the
1386 // moon within the distance to the far clip plane.
1387 // Moon diameter: 3,476 kilometers
1388 // Sun diameter: 1,390,000 kilometers
1389 osg::ref_ptr<SGReaderWriterOptions> opt;
1390 opt = SGReaderWriterOptions::fromPath(globals->get_fg_root());
1391 opt->setPropertyNode(globals->get_props());
1392 _sky->build( 80000.0, 80000.0,
1394 *globals->get_ephem(),
1395 fgGetNode("/environment", true),
1399 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1401 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
1403 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
1405 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
1406 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1408 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
1409 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
1410 stateSet->setAttribute(new osg::BlendFunc);
1411 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
1413 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
1415 // this will be set below
1416 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
1418 osg::Material* material = new osg::Material;
1419 stateSet->setAttribute(material);
1421 stateSet->setTextureAttribute(0, new osg::TexEnv);
1422 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
1424 osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
1425 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
1426 stateSet->setAttribute(hint);
1427 hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
1428 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
1429 stateSet->setAttribute(hint);
1430 hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
1431 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
1432 stateSet->setAttribute(hint);
1433 hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
1434 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
1435 stateSet->setAttribute(hint);
1436 hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
1437 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
1438 stateSet->setAttribute(hint);
1440 osg::Group* sceneGroup = new osg::Group;
1441 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
1442 sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
1444 //sceneGroup->addChild(thesky->getCloudRoot());
1446 stateSet = sceneGroup->getOrCreateStateSet();
1447 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1449 // need to update the light on every frame
1450 // OSG LightSource objects are rather confusing. OSG only supports
1451 // the 10 lights specified by OpenGL itself; if more than one
1452 // LightSource in the scene graph have the same light number, it's
1453 // indeterminate which values will be used to render geometry that
1454 // has that light number enabled. Also, adding children to a
1455 // LightSource is just a shortcut for setting up a state set that
1456 // has the corresponding OpenGL light enabled: a LightSource will
1457 // affect geometry anywhere in the scene graph that has its light
1458 // number enabled in a state set.
1459 LightSource* lightSource = new LightSource;
1460 lightSource->getLight()->setDataVariance(Object::DYNAMIC);
1461 // relative because of CameraView being just a clever transform node
1462 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1463 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
1464 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
1465 mRealRoot->addChild(lightSource);
1466 // we need a white diffuse light for the phase of the moon
1467 osg::LightSource* sunLight = new osg::LightSource;
1468 sunLight->getLight()->setDataVariance(Object::DYNAMIC);
1469 sunLight->getLight()->setLightNum(1);
1470 sunLight->setUpdateCallback(new FGLightSourceUpdateCallback(true));
1471 sunLight->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1472 sunLight->setLocalStateSetModes(osg::StateAttribute::ON);
1474 // Hang a StateSet above the sky subgraph in order to turn off
1476 Group* skyGroup = new Group;
1477 StateSet* skySS = skyGroup->getOrCreateStateSet();
1478 skySS->setMode(GL_LIGHT0, StateAttribute::OFF);
1479 skyGroup->addChild(_sky->getPreRoot());
1480 sunLight->addChild(skyGroup);
1481 mRoot->addChild(sceneGroup);
1482 if ( _classicalRenderer )
1483 mRoot->addChild(sunLight);
1485 // Clouds are added to the scene graph later
1486 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
1487 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
1488 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
1489 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1491 // enable disable specular highlights.
1492 // is the place where we might plug in an other fragment shader ...
1493 osg::LightModel* lightModel = new osg::LightModel;
1494 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
1495 stateSet->setAttribute(lightModel);
1497 // switch to enable wireframe
1498 osg::PolygonMode* polygonMode = new osg::PolygonMode;
1499 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
1500 stateSet->setAttributeAndModes(polygonMode);
1502 // scene fog handling
1503 osg::Fog* fog = new osg::Fog;
1504 fog->setUpdateCallback(new FGFogUpdateCallback);
1505 stateSet->setAttributeAndModes(fog);
1506 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
1509 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
1512 osg::Geode* geode = new osg::Geode;
1513 geode->addDrawable(new SGPuDrawable);
1514 geode->addDrawable(new SGHUDDrawable);
1515 guiCamera->addChild(geode);
1518 guiCamera->addChild(FGPanelNode::create2DPanelNode());
1521 osg::Switch* sw = new osg::Switch;
1522 sw->setUpdateCallback(new FGScenerySwitchCallback);
1523 sw->addChild(mRoot.get());
1524 mRealRoot->addChild(sw);
1525 // The clouds are attached directly to the scene graph root
1526 // because, in theory, they don't want the same default state set
1527 // as the rest of the scene. This may not be true in practice.
1528 if ( _classicalRenderer ) {
1529 mRealRoot->addChild(_sky->getCloudRoot());
1530 mRealRoot->addChild(FGCreateRedoutNode());
1532 // Attach empty program to the scene root so that shader programs
1533 // don't leak into state sets (effects) that shouldn't have one.
1534 stateSet = mRealRoot->getOrCreateStateSet();
1535 stateSet->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON);
1537 mDeferredRealRoot->addChild( mRealRoot.get() );
1539 DeletionManager::install(mRealRoot.get());
1542 // Update all Visuals (redraws anything graphics related)
1544 FGRenderer::update( ) {
1545 if (!_scenery_loaded->getBoolValue())
1547 _splash_alpha->setDoubleValue(1.0);
1550 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1552 if (_splash_alpha->getDoubleValue()>0.0)
1554 // Fade out the splash screen
1555 const double fade_time = 0.5;
1556 const double fade_steps_per_sec = 10;
1557 double delay_time = SGMiscd::min(fade_time/fade_steps_per_sec,
1558 (SGTimeStamp::now() - _splash_time).toSecs());
1559 _splash_time = SGTimeStamp::now();
1560 double sAlpha = _splash_alpha->getDoubleValue();
1561 sAlpha -= SGMiscd::max(0.0,delay_time/fade_time);
1562 FGScenerySwitchCallback::scenery_enabled = (sAlpha<1.0);
1563 _splash_alpha->setDoubleValue((sAlpha < 0) ? 0.0 : sAlpha);
1566 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
1567 if (!_classicalRenderer ) {
1568 _ambientFactor->set( toOsg(l->scene_ambient()) );
1569 _sunDiffuse->set( toOsg(l->scene_diffuse()) );
1570 _sunSpecular->set( toOsg(l->scene_specular()) );
1571 _sunDirection->set( osg::Vec3f(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]) );
1574 // update fog params
1575 double actual_visibility;
1576 if (_cloud_status->getBoolValue()) {
1577 actual_visibility = _sky->get_visibility();
1579 actual_visibility = _visibility_m->getDoubleValue();
1582 // idle_state is now 1000 meaning we've finished all our
1583 // initializations and are running the main loop, so this will
1584 // now work without seg faulting the system.
1586 FGViewer *current__view = globals->get_current_view();
1587 // Force update of center dependent values ...
1588 current__view->set_dirty();
1590 osg::Camera *camera = viewer->getCamera();
1592 bool skyblend = _skyblend->getBoolValue();
1595 if ( _textures->getBoolValue() ) {
1596 SGVec4f clearColor(l->adj_fog_color());
1597 camera->setClearColor(toOsg(clearColor));
1600 SGVec4f clearColor(l->sky_color());
1601 camera->setClearColor(toOsg(clearColor));
1604 // update fog params if visibility has changed
1605 double visibility_meters = _visibility_m->getDoubleValue();
1606 _sky->set_visibility(visibility_meters);
1608 double altitude_m = _altitude_ft->getDoubleValue() * SG_FEET_TO_METER;
1609 _sky->modify_vis( altitude_m, 0.0 /* time factor, now unused */);
1611 // update the sky dome
1614 // The sun and moon distances are scaled down versions
1615 // of the actual distance to get both the moon and the sun
1616 // within the range of the far clip plane.
1617 // Moon distance: 384,467 kilometers
1618 // Sun distance: 150,000,000 kilometers
1620 double sun_horiz_eff, moon_horiz_eff;
1621 if (_horizon_effect->getBoolValue()) {
1623 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
1627 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
1631 sun_horiz_eff = moon_horiz_eff = 1.0;
1635 sstate.pos = current__view->getViewPosition();
1636 sstate.pos_geod = current__view->getPosition();
1637 sstate.ori = current__view->getViewOrientation();
1638 sstate.spin = l->get_sun_rotation();
1639 sstate.gst = globals->get_time_params()->getGst();
1640 sstate.sun_dist = 50000.0 * sun_horiz_eff;
1641 sstate.moon_dist = 40000.0 * moon_horiz_eff;
1642 sstate.sun_angle = l->get_sun_angle();
1645 scolor.sky_color = SGVec3f(l->sky_color().data());
1646 scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
1647 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
1648 scolor.cloud_color = SGVec3f(l->cloud_color().data());
1649 scolor.sun_angle = l->get_sun_angle();
1650 scolor.moon_angle = l->get_moon_angle();
1652 double delta_time_sec = _sim_delta_sec->getDoubleValue();
1653 _sky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
1654 _sky->repaint( scolor, *globals->get_ephem() );
1657 // shadows->setupShadows(
1658 // current__view->getLongitude_deg(),
1659 // current__view->getLatitude_deg(),
1660 // globals->get_time_params()->getGst(),
1661 // globals->get_ephem()->getSunRightAscension(),
1662 // globals->get_ephem()->getSunDeclination(),
1663 // l->get_sun_angle());
1667 // sgEnviro.setLight(l->adj_fog_color());
1668 // sgEnviro.startOfFrame(current__view->get_view_pos(),
1669 // current__view->get_world_up(),
1670 // current__view->getLongitude_deg(),
1671 // current__view->getLatitude_deg(),
1672 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
1676 // sgEnviro.drawLightning();
1678 // double current_view_origin_airspeed_horiz_kt =
1679 // fgGetDouble("/velocities/airspeed-kt", 0.0)
1680 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
1681 // * SGD_DEGREES_TO_RADIANS);
1684 // if( is_internal )
1685 // shadows->endOfFrame();
1687 // need to call the update visitor once
1688 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
1689 mUpdateVisitor->setViewData(current__view->getViewPosition(),
1690 current__view->getViewOrientation());
1691 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
1692 mUpdateVisitor->setLight(direction, l->scene_ambient(),
1693 l->scene_diffuse(), l->scene_specular(),
1695 l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
1696 mUpdateVisitor->setVisibility(actual_visibility);
1697 simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
1698 osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
1699 cullMask |= simgear::GroundLightManager::instance()
1700 ->getLightNodeMask(mUpdateVisitor.get());
1701 if (_panel_hotspots->getBoolValue())
1702 cullMask |= simgear::PICK_BIT;
1703 CameraGroup::getDefault()->setCameraCullMasks(cullMask);
1704 if ( !_classicalRenderer ) {
1705 _fogColor->set( toOsg( l->adj_fog_color() ) );
1706 _fogDensity->set( float( mUpdateVisitor->getFogExp2Density() ) );
1711 FGRenderer::resize( int width, int height )
1713 int curWidth = _xsize->getIntValue(),
1714 curHeight = _ysize->getIntValue();
1715 SG_LOG(SG_VIEW, SG_DEBUG, "FGRenderer::resize: new size " << width << " x " << height);
1716 if ((curHeight != height) || (curWidth != width)) {
1717 // must guard setting these, or PLIB-PUI fails with too many live interfaces
1718 _xsize->setIntValue(width);
1719 _ysize->setIntValue(height);
1724 FGRenderer::pick(std::vector<SGSceneryPick>& pickList,
1725 const osgGA::GUIEventAdapter* ea)
1727 // wipe out the return ...
1729 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
1730 Intersections intersections;
1732 if (!computeIntersections(CameraGroup::getDefault(), ea, intersections))
1734 for (Intersections::iterator hit = intersections.begin(),
1735 e = intersections.end();
1738 const osg::NodePath& np = hit->nodePath;
1739 osg::NodePath::const_reverse_iterator npi;
1740 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
1741 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
1744 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
1745 SGPickCallback* pickCallback = ud->getPickCallback(i);
1748 SGSceneryPick sceneryPick;
1749 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
1750 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
1751 sceneryPick.callback = pickCallback;
1752 pickList.push_back(sceneryPick);
1756 return !pickList.empty();
1760 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
1766 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
1768 eventHandler = eventHandler_;
1772 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
1774 mRealRoot->addChild(camera);
1778 FGRenderer::removeCamera(osg::Camera* camera)
1780 mRealRoot->removeChild(camera);
1784 FGRenderer::setPlanes( double zNear, double zFar )
1786 _planes->set( osg::Vec3f( - zFar, - zFar * zNear, zFar - zNear ) );
1790 fgDumpSceneGraphToFile(const char* filename)
1792 return osgDB::writeNodeFile(*mRealRoot.get(), filename);
1796 fgDumpTerrainBranchToFile(const char* filename)
1798 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
1804 fgDumpNodeToFile(osg::Node* node, const char* filename)
1806 return osgDB::writeNodeFile(*node, filename);
1809 namespace flightgear
1811 using namespace osg;
1813 class VisibleSceneInfoVistor : public NodeVisitor, CullStack
1816 VisibleSceneInfoVistor()
1817 : NodeVisitor(CULL_VISITOR, TRAVERSE_ACTIVE_CHILDREN)
1819 setCullingMode(CullSettings::SMALL_FEATURE_CULLING
1820 | CullSettings::VIEW_FRUSTUM_CULLING);
1821 setComputeNearFarMode(CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1824 VisibleSceneInfoVistor(const VisibleSceneInfoVistor& rhs)
1828 META_NodeVisitor("flightgear","VisibleSceneInfoVistor")
1830 typedef std::map<const std::string,int> InfoMap;
1832 void getNodeInfo(Node* node)
1834 const char* typeName = typeid(*node).name();
1835 classInfo[typeName]++;
1836 const std::string& nodeName = node->getName();
1837 if (!nodeName.empty())
1838 nodeInfo[nodeName]++;
1843 using namespace std;
1844 typedef vector<InfoMap::iterator> FreqVector;
1845 cout << "class info:\n";
1847 for (InfoMap::iterator itr = classInfo.begin(), end = classInfo.end();
1850 classes.push_back(itr);
1851 sort(classes.begin(), classes.end(), freqComp);
1852 for (FreqVector::iterator itr = classes.begin(), end = classes.end();
1855 cout << (*itr)->first << " " << (*itr)->second << "\n";
1857 cout << "\nnode info:\n";
1859 for (InfoMap::iterator itr = nodeInfo.begin(), end = nodeInfo.end();
1862 nodes.push_back(itr);
1864 sort (nodes.begin(), nodes.end(), freqComp);
1865 for (FreqVector::iterator itr = nodes.begin(), end = nodes.end();
1868 cout << (*itr)->first << " " << (*itr)->second << "\n";
1873 void doTraversal(Camera* camera, Node* root, Viewport* viewport)
1875 ref_ptr<RefMatrix> projection
1876 = createOrReuseMatrix(camera->getProjectionMatrix());
1877 ref_ptr<RefMatrix> mv = createOrReuseMatrix(camera->getViewMatrix());
1879 viewport = camera->getViewport();
1881 pushViewport(viewport);
1882 pushProjectionMatrix(projection.get());
1883 pushModelViewMatrix(mv.get(), Transform::ABSOLUTE_RF);
1884 root->accept(*this);
1885 popModelViewMatrix();
1886 popProjectionMatrix();
1892 void apply(Node& node)
1901 void apply(Group& node)
1911 void apply(Transform& node)
1916 ref_ptr<RefMatrix> matrix = createOrReuseMatrix(*getModelViewMatrix());
1917 node.computeLocalToWorldMatrix(*matrix,this);
1918 pushModelViewMatrix(matrix.get(), node.getReferenceFrame());
1921 popModelViewMatrix();
1925 void apply(Camera& camera)
1927 // Save current cull settings
1928 CullSettings saved_cull_settings(*this);
1930 // set cull settings from this Camera
1931 setCullSettings(camera);
1932 // inherit the settings from above
1933 inheritCullSettings(saved_cull_settings, camera.getInheritanceMask());
1935 // set the cull mask.
1936 unsigned int savedTraversalMask = getTraversalMask();
1937 bool mustSetCullMask = (camera.getInheritanceMask()
1938 & osg::CullSettings::CULL_MASK) == 0;
1939 if (mustSetCullMask)
1940 setTraversalMask(camera.getCullMask());
1942 osg::RefMatrix* projection = 0;
1943 osg::RefMatrix* modelview = 0;
1945 if (camera.getReferenceFrame()==osg::Transform::RELATIVE_RF) {
1946 if (camera.getTransformOrder()==osg::Camera::POST_MULTIPLY) {
1947 projection = createOrReuseMatrix(*getProjectionMatrix()
1948 *camera.getProjectionMatrix());
1949 modelview = createOrReuseMatrix(*getModelViewMatrix()
1950 * camera.getViewMatrix());
1952 else { // pre multiply
1953 projection = createOrReuseMatrix(camera.getProjectionMatrix()
1954 * (*getProjectionMatrix()));
1955 modelview = createOrReuseMatrix(camera.getViewMatrix()
1956 * (*getModelViewMatrix()));
1959 // an absolute reference frame
1960 projection = createOrReuseMatrix(camera.getProjectionMatrix());
1961 modelview = createOrReuseMatrix(camera.getViewMatrix());
1963 if (camera.getViewport())
1964 pushViewport(camera.getViewport());
1966 pushProjectionMatrix(projection);
1967 pushModelViewMatrix(modelview, camera.getReferenceFrame());
1971 // restore the previous model view matrix.
1972 popModelViewMatrix();
1974 // restore the previous model view matrix.
1975 popProjectionMatrix();
1977 if (camera.getViewport()) popViewport();
1979 // restore the previous traversal mask settings
1980 if (mustSetCullMask)
1981 setTraversalMask(savedTraversalMask);
1983 // restore the previous cull settings
1984 setCullSettings(saved_cull_settings);
1989 static bool freqComp(const InfoMap::iterator& lhs, const InfoMap::iterator& rhs)
1991 return lhs->second > rhs->second;
1997 bool printVisibleSceneInfo(FGRenderer* renderer)
1999 osgViewer::Viewer* viewer = renderer->getViewer();
2000 VisibleSceneInfoVistor vsv;
2002 if (!viewer->getCamera()->getViewport() && viewer->getNumSlaves() > 0) {
2003 const View::Slave& slave = viewer->getSlave(0);
2004 vp = slave._camera->getViewport();
2006 vsv.doTraversal(viewer->getCamera(), viewer->getSceneData(), vp);
2011 // end of renderer.cxx