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