]> git.mxchange.org Git - flightgear.git/blob - src/Main/renderer.cxx
Merge branch 'next' of D:\Git_New\flightgear into next
[flightgear.git] / src / Main / renderer.cxx
1 // renderer.cxx -- top level sim routines
2 //
3 // Written by Curtis Olson, started May 1997.
4 // This file contains parts of main.cxx prior to october 2004
5 //
6 // Copyright (C) 1997 - 2002  Curtis L. Olson  - http://www.flightgear.org/~curt
7 //
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.
12 //
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.
17 //
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.
21
22 #ifdef HAVE_CONFIG_H
23 #  include <config.h>
24 #endif
25
26 #ifdef HAVE_WINDOWS_H
27 #  include <windows.h>
28 #endif
29
30 #include <simgear/compiler.h>
31
32 #include <algorithm>
33 #include <iostream>
34 #include <map>
35 #include <vector>
36 #include <typeinfo>
37
38 #include <osg/ref_ptr>
39 #include <osg/AlphaFunc>
40 #include <osg/BlendFunc>
41 #include <osg/Camera>
42 #include <osg/CullFace>
43 #include <osg/CullStack>
44 #include <osg/Depth>
45 #include <osg/Fog>
46 #include <osg/Group>
47 #include <osg/Hint>
48 #include <osg/Light>
49 #include <osg/LightModel>
50 #include <osg/LightSource>
51 #include <osg/Material>
52 #include <osg/Math>
53 #include <osg/NodeCallback>
54 #include <osg/Notify>
55 #include <osg/PolygonMode>
56 #include <osg/PolygonOffset>
57 #include <osg/Program>
58 #include <osg/Version>
59 #include <osg/TexEnv>
60
61 #include <osgUtil/LineSegmentIntersector>
62
63 #include <osg/io_utils>
64 #include <osgDB/WriteFile>
65
66 #include <simgear/math/SGMath.hxx>
67 #include <simgear/scene/material/matlib.hxx>
68 #include <simgear/scene/model/animation.hxx>
69 #include <simgear/scene/model/placement.hxx>
70 #include <simgear/scene/sky/sky.hxx>
71 #include <simgear/scene/util/SGUpdateVisitor.hxx>
72 #include <simgear/scene/util/RenderConstants.hxx>
73 #include <simgear/scene/util/SGSceneUserData.hxx>
74 #include <simgear/scene/tgdb/GroundLightManager.hxx>
75 #include <simgear/scene/tgdb/pt_lights.hxx>
76 #include <simgear/structure/OSGUtils.hxx>
77 #include <simgear/props/props.hxx>
78 #include <simgear/timing/sg_time.hxx>
79 #include <simgear/ephemeris/ephemeris.hxx>
80 #include <simgear/math/sg_random.h>
81 #ifdef FG_JPEG_SERVER
82 #include <simgear/screen/jpgfactory.hxx>
83 #endif
84
85 #include <simgear/environment/visual_enviro.hxx>
86
87 #include <Time/light.hxx>
88 #include <Time/light.hxx>
89 #include <Cockpit/panel.hxx>
90 #include <Model/panelnode.hxx>
91 #include <Model/modelmgr.hxx>
92 #include <Model/acmodel.hxx>
93 #include <Scenery/scenery.hxx>
94 #include <Scenery/redout.hxx>
95 #include <Scenery/tilemgr.hxx>
96 #include <GUI/new_gui.hxx>
97 #include <Instrumentation/HUD/HUD.hxx>
98 #include <Environment/precipitation_mgr.hxx>
99
100 #include "splash.hxx"
101 #include "renderer.hxx"
102 #include "main.hxx"
103 #include "CameraGroup.hxx"
104 #include "FGEventHandler.hxx"
105 #include <Main/viewer.hxx>
106 #include <Main/viewmgr.hxx>
107
108 using namespace osg;
109 using namespace simgear;
110 using namespace flightgear;
111
112 class FGHintUpdateCallback : public osg::StateAttribute::Callback {
113 public:
114   FGHintUpdateCallback(const char* configNode) :
115     mConfigNode(fgGetNode(configNode, true))
116   { }
117   virtual void operator()(osg::StateAttribute* stateAttribute,
118                           osg::NodeVisitor*)
119   {
120     assert(dynamic_cast<osg::Hint*>(stateAttribute));
121     osg::Hint* hint = static_cast<osg::Hint*>(stateAttribute);
122
123     const char* value = mConfigNode->getStringValue();
124     if (!value)
125       hint->setMode(GL_DONT_CARE);
126     else if (0 == strcmp(value, "nicest"))
127       hint->setMode(GL_NICEST);
128     else if (0 == strcmp(value, "fastest"))
129       hint->setMode(GL_FASTEST);
130     else
131       hint->setMode(GL_DONT_CARE);
132   }
133 private:
134   SGSharedPtr<SGPropertyNode> mConfigNode;
135 };
136
137
138 class SGPuDrawable : public osg::Drawable {
139 public:
140   SGPuDrawable()
141   {
142     // Dynamic stuff, do not store geometry
143     setUseDisplayList(false);
144     setDataVariance(Object::DYNAMIC);
145
146     osg::StateSet* stateSet = getOrCreateStateSet();
147     stateSet->setRenderBinDetails(1001, "RenderBin");
148     // speed optimization?
149     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
150     // We can do translucent menus, so why not. :-)
151     stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
152     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
153     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
154
155     stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
156
157     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
158     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
159   }
160   virtual void drawImplementation(osg::RenderInfo& renderInfo) const
161   { drawImplementation(*renderInfo.getState()); }
162   void drawImplementation(osg::State& state) const
163   {
164     state.setActiveTextureUnit(0);
165     state.setClientActiveTextureUnit(0);
166
167     state.disableAllVertexArrays();
168
169     glPushAttrib(GL_ALL_ATTRIB_BITS);
170     glPushClientAttrib(~0u);
171
172     puDisplay();
173
174     glPopClientAttrib();
175     glPopAttrib();
176   }
177
178   virtual osg::Object* cloneType() const { return new SGPuDrawable; }
179   virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
180   
181 private:
182 };
183
184 class SGHUDAndPanelDrawable : public osg::Drawable {
185 public:
186   SGHUDAndPanelDrawable()
187   {
188     // Dynamic stuff, do not store geometry
189     setUseDisplayList(false);
190     setDataVariance(Object::DYNAMIC);
191
192     osg::StateSet* stateSet = getOrCreateStateSet();
193     stateSet->setRenderBinDetails(1000, "RenderBin");
194
195     // speed optimization?
196     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
197     stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
198     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
199     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
200     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
201
202     stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
203   }
204   virtual void drawImplementation(osg::RenderInfo& renderInfo) const
205   { drawImplementation(*renderInfo.getState()); }
206   void drawImplementation(osg::State& state) const
207   {
208     state.setActiveTextureUnit(0);
209     state.setClientActiveTextureUnit(0);
210     state.disableAllVertexArrays();
211
212     glPushAttrib(GL_ALL_ATTRIB_BITS);
213     glPushClientAttrib(~0u);
214
215     HUD *hud = static_cast<HUD*>(globals->get_subsystem("hud"));
216     hud->draw(state);
217
218     // update the panel subsystem
219     if ( globals->get_current_panel() != NULL )
220         globals->get_current_panel()->update(state);
221     // We don't need a state here - can be safely removed when we can pick
222     // correctly
223     fgUpdate3DPanels();
224
225     glPopClientAttrib();
226     glPopAttrib();
227
228   }
229
230   virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
231   virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
232   
233 private:
234 };
235
236 class FGLightSourceUpdateCallback : public osg::NodeCallback {
237 public:
238   
239   /**
240    * @param isSun true if the light is the actual sun i.e., for
241    * illuminating the moon.
242    */
243   FGLightSourceUpdateCallback(bool isSun = false) : _isSun(isSun) {}
244   FGLightSourceUpdateCallback(const FGLightSourceUpdateCallback& nc,
245                               const CopyOp& op)
246     : NodeCallback(nc, op), _isSun(nc._isSun)
247   {}
248   META_Object(flightgear,FGLightSourceUpdateCallback);
249   
250   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
251   {
252     assert(dynamic_cast<osg::LightSource*>(node));
253     osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
254     osg::Light* light = lightSource->getLight();
255     
256     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
257     if (_isSun) {
258       light->setAmbient(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
259       light->setDiffuse(Vec4(1.0f, 1.0f, 1.0f, 1.0f));
260       light->setSpecular(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
261     } else {
262       light->setAmbient(toOsg(l->scene_ambient()));
263       light->setDiffuse(toOsg(l->scene_diffuse()));
264       light->setSpecular(toOsg(l->scene_specular()));
265     }
266     osg::Vec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
267     light->setPosition(position);
268
269     traverse(node, nv);
270   }
271 private:
272   const bool _isSun;
273 };
274
275 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
276 public:
277   FGWireFrameModeUpdateCallback() :
278     mWireframe(fgGetNode("/sim/rendering/wireframe"))
279   { }
280   virtual void operator()(osg::StateAttribute* stateAttribute,
281                           osg::NodeVisitor*)
282   {
283     assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
284     osg::PolygonMode* polygonMode;
285     polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
286
287     if (mWireframe->getBoolValue())
288       polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
289                            osg::PolygonMode::LINE);
290     else
291       polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
292                            osg::PolygonMode::FILL);
293   }
294 private:
295   SGSharedPtr<SGPropertyNode> mWireframe;
296 };
297
298 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
299 public:
300   FGLightModelUpdateCallback() :
301     mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
302   { }
303   virtual void operator()(osg::StateAttribute* stateAttribute,
304                           osg::NodeVisitor*)
305   {
306     assert(dynamic_cast<osg::LightModel*>(stateAttribute));
307     osg::LightModel* lightModel;
308     lightModel = static_cast<osg::LightModel*>(stateAttribute);
309
310 #if 0
311     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
312     lightModel->setAmbientIntensity(toOsg(l->scene_ambient());
313 #else
314     lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
315 #endif
316     lightModel->setTwoSided(true);
317     lightModel->setLocalViewer(false);
318
319     if (mHighlights->getBoolValue()) {
320       lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
321     } else {
322       lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
323     }
324   }
325 private:
326   SGSharedPtr<SGPropertyNode> mHighlights;
327 };
328
329 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
330 public:
331   FGFogEnableUpdateCallback() :
332     mFogEnabled(fgGetNode("/sim/rendering/fog"))
333   { }
334   virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
335   {
336     if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
337       stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
338     } else {
339       stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
340     }
341   }
342 private:
343   SGSharedPtr<SGPropertyNode> mFogEnabled;
344 };
345
346 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
347 public:
348   virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
349   {
350     assert(dynamic_cast<SGUpdateVisitor*>(nv));
351     assert(dynamic_cast<osg::Fog*>(sa));
352     SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
353     osg::Fog* fog = static_cast<osg::Fog*>(sa);
354     fog->setMode(osg::Fog::EXP2);
355     fog->setColor(toOsg(updateVisitor->getFogColor()));
356     fog->setDensity(updateVisitor->getFogExp2Density());
357   }
358 };
359
360 // update callback for the switch node guarding that splash
361 class FGScenerySwitchCallback : public osg::NodeCallback {
362 public:
363   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
364   {
365     assert(dynamic_cast<osg::Switch*>(node));
366     osg::Switch* sw = static_cast<osg::Switch*>(node);
367
368     double t = globals->get_sim_time_sec();
369     bool enabled = 0 < t;
370     sw->setValue(0, enabled);
371     if (!enabled)
372       return;
373     traverse(node, nv);
374   }
375 };
376
377 // Sky structures
378 SGSky *thesky;
379
380 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
381 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
382
383 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
384
385 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
386
387 FGRenderer::FGRenderer()
388 {
389 #ifdef FG_JPEG_SERVER
390    jpgRenderFrame = FGRenderer::update;
391 #endif
392    eventHandler = new FGEventHandler;
393 }
394
395 FGRenderer::~FGRenderer()
396 {
397 #ifdef FG_JPEG_SERVER
398    jpgRenderFrame = NULL;
399 #endif
400 }
401
402 // Initialize various GL/view parameters
403 // XXX This should be called "preinit" or something, as it initializes
404 // critical parts of the scene graph in addition to the splash screen.
405 void
406 FGRenderer::splashinit( void ) {
407     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
408     mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
409     mRealRoot->addChild(fgCreateSplashNode());
410     mFrameStamp = viewer->getFrameStamp();
411     // Scene doesn't seem to pass the frame stamp to the update
412     // visitor automatically.
413     mUpdateVisitor->setFrameStamp(mFrameStamp.get());
414     viewer->setUpdateVisitor(mUpdateVisitor.get());
415 }
416
417 void
418 FGRenderer::init( void )
419 {
420     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
421     osg::initNotifyLevel();
422
423     // The number of polygon-offset "units" to place between layers.  In
424     // principle, one is supposed to be enough.  In practice, I find that
425     // my hardware/driver requires many more.
426     osg::PolygonOffset::setUnitsMultiplier(1);
427     osg::PolygonOffset::setFactorMultiplier(1);
428
429     // Go full screen if requested ...
430     if ( fgGetBool("/sim/startup/fullscreen") )
431         fgOSFullScreen();
432
433     viewer->getCamera()
434         ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
435     
436     osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
437
438     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
439     
440     stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
441     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
442
443     stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
444     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
445     stateSet->setAttribute(new osg::BlendFunc);
446     stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
447
448     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
449     
450     // this will be set below
451     stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
452
453     osg::Material* material = new osg::Material;
454     stateSet->setAttribute(material);
455     
456     stateSet->setTextureAttribute(0, new osg::TexEnv);
457     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
458
459     osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
460     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
461     stateSet->setAttribute(hint);
462     hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
463     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
464     stateSet->setAttribute(hint);
465     hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
466     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
467     stateSet->setAttribute(hint);
468     hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
469     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
470     stateSet->setAttribute(hint);
471     hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
472     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
473     stateSet->setAttribute(hint);
474
475     osg::Group* sceneGroup = new osg::Group;
476     sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
477     sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
478
479     //sceneGroup->addChild(thesky->getCloudRoot());
480
481     stateSet = sceneGroup->getOrCreateStateSet();
482     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
483
484     // need to update the light on every frame
485     // OSG LightSource objects are rather confusing. OSG only supports
486     // the 10 lights specified by OpenGL itself; if more than one
487     // LightSource in the scene graph have the same light number, it's
488     // indeterminate which values will be used to render geometry that
489     // has that light number enabled. Also, adding children to a
490     // LightSource is just a shortcut for setting up a state set that
491     // has the corresponding OpenGL light enabled: a LightSource will
492     // affect geometry anywhere in the scene graph that has its light
493     // number enabled in a state set. 
494     LightSource* lightSource = new LightSource;
495     lightSource->getLight()->setDataVariance(Object::DYNAMIC);
496     // relative because of CameraView being just a clever transform node
497     lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
498     lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
499     lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
500     mRealRoot->addChild(lightSource);
501     // we need a white diffuse light for the phase of the moon
502     osg::LightSource* sunLight = new osg::LightSource;
503     sunLight->getLight()->setDataVariance(Object::DYNAMIC);
504     sunLight->getLight()->setLightNum(1);
505     sunLight->setUpdateCallback(new FGLightSourceUpdateCallback(true));
506     sunLight->setReferenceFrame(osg::LightSource::RELATIVE_RF);
507     sunLight->setLocalStateSetModes(osg::StateAttribute::ON);
508     // Hang a StateSet above the sky subgraph in order to turn off
509     // light 0
510     Group* skyGroup = new Group;
511     StateSet* skySS = skyGroup->getOrCreateStateSet();
512     skySS->setMode(GL_LIGHT0, StateAttribute::OFF);
513     skyGroup->addChild(thesky->getPreRoot());
514     sunLight->addChild(skyGroup);
515     mRoot->addChild(sceneGroup);
516     mRoot->addChild(sunLight);
517     // Clouds are added to the scene graph later
518     stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
519     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
520     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
521     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
522
523     // enable disable specular highlights.
524     // is the place where we might plug in an other fragment shader ...
525     osg::LightModel* lightModel = new osg::LightModel;
526     lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
527     stateSet->setAttribute(lightModel);
528
529     // switch to enable wireframe
530     osg::PolygonMode* polygonMode = new osg::PolygonMode;
531     polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
532     stateSet->setAttributeAndModes(polygonMode);
533
534     // scene fog handling
535     osg::Fog* fog = new osg::Fog;
536     fog->setUpdateCallback(new FGFogUpdateCallback);
537     stateSet->setAttributeAndModes(fog);
538     stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
539
540     // plug in the GUI
541     osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
542     if (guiCamera) {
543         osg::Geode* geode = new osg::Geode;
544         geode->addDrawable(new SGPuDrawable);
545         geode->addDrawable(new SGHUDAndPanelDrawable);
546         guiCamera->addChild(geode);
547     }
548     osg::Switch* sw = new osg::Switch;
549     sw->setUpdateCallback(new FGScenerySwitchCallback);
550     sw->addChild(mRoot.get());
551     mRealRoot->addChild(sw);
552     // The clouds are attached directly to the scene graph root
553     // because, in theory, they don't want the same default state set
554     // as the rest of the scene. This may not be true in practice.
555     mRealRoot->addChild(thesky->getCloudRoot());
556     mRealRoot->addChild(FGCreateRedoutNode());
557     // Attach empty program to the scene root so that shader programs
558     // don't leak into state sets (effects) that shouldn't have one.
559     stateSet = mRealRoot->getOrCreateStateSet();
560     stateSet->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON);
561 }
562
563
564 // Update all Visuals (redraws anything graphics related)
565 void
566 FGRenderer::update( bool refresh_camera_settings ) {
567     bool scenery_loaded = fgGetBool("sim/sceneryloaded", false)
568                           || fgGetBool("sim/sceneryloaded-override");
569     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
570     if (!scenery_loaded) {
571       fgSetDouble("/sim/startup/splash-alpha", 1.0);
572       return;
573     }
574
575     // Fade out the splash screen over the first three seconds.
576     double sAlpha = SGMiscd::max(0, (2.5 - globals->get_sim_time_sec()) / 2.5);
577     fgSetDouble("/sim/startup/splash-alpha", sAlpha);
578
579     bool skyblend = fgGetBool("/sim/rendering/skyblend");
580     bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
581     bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
582     bool distance_attenuation
583         = fgGetBool("/sim/rendering/distance-attenuation");
584     // OSGFIXME
585     SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
586                                   distance_attenuation );
587
588     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
589
590     // update fog params
591     double actual_visibility;
592     if (fgGetBool("/environment/clouds/status")) {
593         actual_visibility = thesky->get_visibility();
594     } else {
595         actual_visibility = fgGetDouble("/environment/visibility-m");
596     }
597
598     // idle_state is now 1000 meaning we've finished all our
599     // initializations and are running the main loop, so this will
600     // now work without seg faulting the system.
601
602     FGViewer *current__view = globals->get_current_view();
603     // Force update of center dependent values ...
604     current__view->set_dirty();
605
606     if ( refresh_camera_settings ) {
607         // update view port
608         resize( fgGetInt("/sim/startup/xsize"),
609                 fgGetInt("/sim/startup/ysize") );
610     }
611     osg::Camera *camera = viewer->getCamera();
612
613     if ( skyblend ) {
614         
615         if ( fgGetBool("/sim/rendering/textures") ) {
616             SGVec4f clearColor(l->adj_fog_color());
617             camera->setClearColor(toOsg(clearColor));
618         }
619     } else {
620         SGVec4f clearColor(l->sky_color());
621         camera->setClearColor(toOsg(clearColor));
622     }
623
624     // update fog params if visibility has changed
625     double visibility_meters = fgGetDouble("/environment/visibility-m");
626     thesky->set_visibility(visibility_meters);
627
628     double altitude_m = fgGetDouble("/position/altitude-ft") * SG_FEET_TO_METER;
629     thesky->modify_vis( altitude_m, 0.0 /* time factor, now unused */);
630
631     // update the sky dome
632     if ( skyblend ) {
633
634         // The sun and moon distances are scaled down versions
635         // of the actual distance to get both the moon and the sun
636         // within the range of the far clip plane.
637         // Moon distance:    384,467 kilometers
638         // Sun distance: 150,000,000 kilometers
639
640         double sun_horiz_eff, moon_horiz_eff;
641         if (fgGetBool("/sim/rendering/horizon-effect")) {
642             sun_horiz_eff
643                 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
644                                              0.0),
645                              0.33) / 3.0;
646             moon_horiz_eff
647                 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
648                                              0.0),
649                              0.33)/3.0;
650         } else {
651            sun_horiz_eff = moon_horiz_eff = 1.0;
652         }
653
654         SGSkyState sstate;
655         sstate.pos       = current__view->getViewPosition();
656         sstate.pos_geod  = current__view->getPosition();
657         sstate.ori       = current__view->getViewOrientation();
658         sstate.spin      = l->get_sun_rotation();
659         sstate.gst       = globals->get_time_params()->getGst();
660         sstate.sun_dist  = 50000.0 * sun_horiz_eff;
661         sstate.moon_dist = 40000.0 * moon_horiz_eff;
662         sstate.sun_angle = l->get_sun_angle();
663
664         SGSkyColor scolor;
665         scolor.sky_color   = SGVec3f(l->sky_color().data());
666         scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
667         scolor.fog_color   = SGVec3f(l->adj_fog_color().data());
668         scolor.cloud_color = SGVec3f(l->cloud_color().data());
669         scolor.sun_angle   = l->get_sun_angle();
670         scolor.moon_angle  = l->get_moon_angle();
671   
672         double delta_time_sec = fgGetDouble("/sim/time/delta-sec");
673         thesky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
674         thesky->repaint( scolor, *globals->get_ephem() );
675
676             //OSGFIXME
677 //         shadows->setupShadows(
678 //           current__view->getLongitude_deg(),
679 //           current__view->getLatitude_deg(),
680 //           globals->get_time_params()->getGst(),
681 //           globals->get_ephem()->getSunRightAscension(),
682 //           globals->get_ephem()->getSunDeclination(),
683 //           l->get_sun_angle());
684
685     }
686
687 //     sgEnviro.setLight(l->adj_fog_color());
688 //     sgEnviro.startOfFrame(current__view->get_view_pos(), 
689 //         current__view->get_world_up(),
690 //         current__view->getLongitude_deg(),
691 //         current__view->getLatitude_deg(),
692 //         current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
693 //         delta_time_sec);
694
695     // OSGFIXME
696 //     sgEnviro.drawLightning();
697
698 //        double current_view_origin_airspeed_horiz_kt =
699 //         fgGetDouble("/velocities/airspeed-kt", 0.0)
700 //                        * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
701 //                                * SGD_DEGREES_TO_RADIANS);
702
703     // OSGFIXME
704 //     if( is_internal )
705 //         shadows->endOfFrame();
706
707     // need to call the update visitor once
708     mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
709     mUpdateVisitor->setViewData(current__view->getViewPosition(),
710                                 current__view->getViewOrientation());
711     SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
712     mUpdateVisitor->setLight(direction, l->scene_ambient(),
713                              l->scene_diffuse(), l->scene_specular(),
714                              l->adj_fog_color(),
715                              l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
716     mUpdateVisitor->setVisibility(actual_visibility);
717     simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
718     bool hotspots = fgGetBool("/sim/panel-hotspots");
719     osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
720     cullMask |= simgear::GroundLightManager::instance()
721         ->getLightNodeMask(mUpdateVisitor.get());
722     if (hotspots)
723         cullMask |= simgear::PICK_BIT;
724     CameraGroup::getDefault()->setCameraCullMasks(cullMask);
725 }
726
727
728
729 // options.cxx needs to see this for toggle_panel()
730 // Handle new window size or exposure
731 void
732 FGRenderer::resize( int width, int height ) {
733     int view_h;
734
735     if ( (!fgGetBool("/sim/virtual-cockpit"))
736          && fgPanelVisible() && idle_state == 1000 ) {
737         view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
738                              globals->get_current_panel()->getYOffset()) / 768.0);
739     } else {
740         view_h = height;
741     }
742
743     static int lastwidth = 0;
744     static int lastheight = 0;
745     if (width != lastwidth)
746         fgSetInt("/sim/startup/xsize", lastwidth = width);
747     if (height != lastheight)
748         fgSetInt("/sim/startup/ysize", lastheight = height);
749
750     // for all views
751     FGViewMgr *viewmgr = globals->get_viewmgr();
752     if (viewmgr) {
753       for ( int i = 0; i < viewmgr->size(); ++i ) {
754         viewmgr->get_view(i)->
755           set_aspect_ratio((float)view_h / (float)width);
756       }
757     }
758 }
759
760 bool
761 FGRenderer::pick(std::vector<SGSceneryPick>& pickList,
762                  const osgGA::GUIEventAdapter* ea)
763 {
764     // wipe out the return ...
765     pickList.clear();
766     typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
767     Intersections intersections;
768
769     if (!computeIntersections(CameraGroup::getDefault(), ea, intersections))
770         return false;
771     for (Intersections::iterator hit = intersections.begin(),
772              e = intersections.end();
773          hit != e;
774          ++hit) {
775         const osg::NodePath& np = hit->nodePath;
776         osg::NodePath::const_reverse_iterator npi;
777         for (npi = np.rbegin(); npi != np.rend(); ++npi) {
778             SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
779             if (!ud)
780                 continue;
781             for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
782                 SGPickCallback* pickCallback = ud->getPickCallback(i);
783                 if (!pickCallback)
784                     continue;
785                 SGSceneryPick sceneryPick;
786                 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
787                 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
788                 sceneryPick.callback = pickCallback;
789                 pickList.push_back(sceneryPick);
790             }
791         }
792     }
793     return !pickList.empty();
794 }
795
796 void
797 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
798 {
799     viewer = viewer_;
800 }
801
802 void
803 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
804 {
805     eventHandler = eventHandler_;
806 }
807
808 void
809 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
810 {
811     mRealRoot->addChild(camera);
812 }
813
814 bool
815 fgDumpSceneGraphToFile(const char* filename)
816 {
817     return osgDB::writeNodeFile(*mRealRoot.get(), filename);
818 }
819
820 bool
821 fgDumpTerrainBranchToFile(const char* filename)
822 {
823     return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
824                                  filename );
825 }
826
827 // For debugging
828 bool
829 fgDumpNodeToFile(osg::Node* node, const char* filename)
830 {
831     return osgDB::writeNodeFile(*node, filename);
832 }
833
834 namespace flightgear
835 {
836 using namespace osg;
837
838 class VisibleSceneInfoVistor : public NodeVisitor, CullStack
839 {
840 public:
841     VisibleSceneInfoVistor()
842         : NodeVisitor(CULL_VISITOR, TRAVERSE_ACTIVE_CHILDREN)
843     {
844         setCullingMode(CullSettings::SMALL_FEATURE_CULLING
845                        | CullSettings::VIEW_FRUSTUM_CULLING);
846         setComputeNearFarMode(CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
847     }
848
849     VisibleSceneInfoVistor(const VisibleSceneInfoVistor& rhs)
850     {
851     }
852
853     META_NodeVisitor("flightgear","VisibleSceneInfoVistor")
854
855     typedef std::map<const std::string,int> InfoMap;
856
857     void getNodeInfo(Node* node)
858     {
859         const char* typeName = typeid(*node).name();
860         classInfo[typeName]++;
861         const std::string& nodeName = node->getName();
862         if (!nodeName.empty())
863             nodeInfo[nodeName]++;
864     }
865
866     void dumpInfo()
867     {
868         using namespace std;
869         typedef vector<InfoMap::iterator> FreqVector;
870         cout << "class info:\n";
871         FreqVector classes;
872         for (InfoMap::iterator itr = classInfo.begin(), end = classInfo.end();
873              itr != end;
874              ++itr)
875             classes.push_back(itr);
876         sort(classes.begin(), classes.end(), freqComp);
877         for (FreqVector::iterator itr = classes.begin(), end = classes.end();
878              itr != end;
879              ++itr) {
880             cout << (*itr)->first << " " << (*itr)->second << "\n";
881         }
882         cout << "\nnode info:\n";
883         FreqVector nodes;
884         for (InfoMap::iterator itr = nodeInfo.begin(), end = nodeInfo.end();
885              itr != end;
886              ++itr)
887             nodes.push_back(itr);
888
889         sort (nodes.begin(), nodes.end(), freqComp);
890         for (FreqVector::iterator itr = nodes.begin(), end = nodes.end();
891              itr != end;
892              ++itr) {
893             cout << (*itr)->first << " " << (*itr)->second << "\n";
894         }
895         cout << endl;
896     }
897     
898     void doTraversal(Camera* camera, Node* root, Viewport* viewport)
899     {
900         ref_ptr<RefMatrix> projection
901             = createOrReuseMatrix(camera->getProjectionMatrix());
902         ref_ptr<RefMatrix> mv = createOrReuseMatrix(camera->getViewMatrix());
903         if (!viewport)
904             viewport = camera->getViewport();
905         if (viewport)
906             pushViewport(viewport);
907         pushProjectionMatrix(projection.get());
908         pushModelViewMatrix(mv.get(), Transform::ABSOLUTE_RF);
909         root->accept(*this);
910         popModelViewMatrix();
911         popProjectionMatrix();
912         if (viewport)
913             popViewport();
914         dumpInfo();
915     }
916
917     void apply(Node& node)
918     {
919         if (isCulled(node))
920             return;
921         pushCurrentMask();
922         getNodeInfo(&node);
923         traverse(node);
924         popCurrentMask();
925     }
926     void apply(Group& node)
927     {
928         if (isCulled(node))
929             return;
930         pushCurrentMask();
931         getNodeInfo(&node);
932         traverse(node);
933         popCurrentMask();
934     }
935
936     void apply(Transform& node)
937     {
938         if (isCulled(node))
939             return;
940         pushCurrentMask();
941         ref_ptr<RefMatrix> matrix = createOrReuseMatrix(*getModelViewMatrix());
942         node.computeLocalToWorldMatrix(*matrix,this);
943         pushModelViewMatrix(matrix.get(), node.getReferenceFrame());
944         getNodeInfo(&node);
945         traverse(node);
946         popModelViewMatrix();
947         popCurrentMask();
948     }
949
950     void apply(Camera& camera)
951     {
952         // Save current cull settings
953         CullSettings saved_cull_settings(*this);
954
955         // set cull settings from this Camera
956         setCullSettings(camera);
957         // inherit the settings from above
958         inheritCullSettings(saved_cull_settings, camera.getInheritanceMask());
959
960         // set the cull mask.
961         unsigned int savedTraversalMask = getTraversalMask();
962         bool mustSetCullMask = (camera.getInheritanceMask()
963                                 & osg::CullSettings::CULL_MASK) == 0;
964         if (mustSetCullMask)
965             setTraversalMask(camera.getCullMask());
966
967         osg::RefMatrix* projection = 0;
968         osg::RefMatrix* modelview = 0;
969
970         if (camera.getReferenceFrame()==osg::Transform::RELATIVE_RF) {
971             if (camera.getTransformOrder()==osg::Camera::POST_MULTIPLY) {
972                 projection = createOrReuseMatrix(*getProjectionMatrix()
973                                                  *camera.getProjectionMatrix());
974                 modelview = createOrReuseMatrix(*getModelViewMatrix()
975                                                 * camera.getViewMatrix());
976             }
977             else {              // pre multiply 
978                 projection = createOrReuseMatrix(camera.getProjectionMatrix()
979                                                  * (*getProjectionMatrix()));
980                 modelview = createOrReuseMatrix(camera.getViewMatrix()
981                                                 * (*getModelViewMatrix()));
982             }
983         } else {
984             // an absolute reference frame
985             projection = createOrReuseMatrix(camera.getProjectionMatrix());
986             modelview = createOrReuseMatrix(camera.getViewMatrix());
987         }
988         if (camera.getViewport())
989             pushViewport(camera.getViewport());
990
991         pushProjectionMatrix(projection);
992         pushModelViewMatrix(modelview, camera.getReferenceFrame());    
993
994         traverse(camera);
995     
996         // restore the previous model view matrix.
997         popModelViewMatrix();
998
999         // restore the previous model view matrix.
1000         popProjectionMatrix();
1001
1002         if (camera.getViewport()) popViewport();
1003
1004         // restore the previous traversal mask settings
1005         if (mustSetCullMask)
1006             setTraversalMask(savedTraversalMask);
1007
1008         // restore the previous cull settings
1009         setCullSettings(saved_cull_settings);
1010     }
1011
1012 protected:
1013     // sort in reverse
1014     static bool freqComp(const InfoMap::iterator& lhs, const InfoMap::iterator& rhs)
1015     {
1016         return lhs->second > rhs->second;
1017     }
1018     InfoMap classInfo;
1019     InfoMap nodeInfo;
1020 };
1021
1022 bool printVisibleSceneInfo(FGRenderer* renderer)
1023 {
1024     osgViewer::Viewer* viewer = renderer->getViewer();
1025     VisibleSceneInfoVistor vsv;
1026     Viewport* vp = 0;
1027     if (!viewer->getCamera()->getViewport() && viewer->getNumSlaves() > 0) {
1028         const View::Slave& slave = viewer->getSlave(0);
1029         vp = slave._camera->getViewport();
1030     }
1031     vsv.doTraversal(viewer->getCamera(), viewer->getSceneData(), vp);
1032     return true;
1033 }
1034 }
1035 // end of renderer.cxx
1036