]> git.mxchange.org Git - flightgear.git/blob - src/Main/renderer.cxx
Update GroundLightManager
[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 // $Id$
23
24
25 #ifdef HAVE_CONFIG_H
26 #  include <config.h>
27 #endif
28
29 #include <simgear/compiler.h>
30
31 #ifdef HAVE_WINDOWS_H
32 #  include <windows.h>
33 #endif
34
35 #include <osg/ref_ptr>
36 #include <osg/AlphaFunc>
37 #include <osg/BlendFunc>
38 #include <osg/Camera>
39 #include <osg/CameraView>
40 #include <osg/CullFace>
41 #include <osg/Depth>
42 #include <osg/Fog>
43 #include <osg/Group>
44 #include <osg/Light>
45 #include <osg/LightModel>
46 #include <osg/LightSource>
47 #include <osg/NodeCallback>
48 #include <osg/Notify>
49 #include <osg/PolygonMode>
50 #include <osg/PolygonOffset>
51 #include <osg/ShadeModel>
52 #include <osg/Version>
53 #include <osg/TexEnv>
54
55 #include <osgUtil/SceneView>
56 #include <osgUtil/UpdateVisitor>
57 #include <osgUtil/IntersectVisitor>
58 #include <osgUtil/LineSegmentIntersector>
59
60 #include <osg/io_utils>
61 #include <osgDB/WriteFile>
62 #include <osgDB/ReadFile>
63 #include <sstream>
64
65 #include <simgear/math/SGMath.hxx>
66 #include <simgear/screen/extensions.hxx>
67 #include <simgear/scene/material/matlib.hxx>
68 #include <simgear/scene/model/animation.hxx>
69 #include <simgear/scene/model/model.hxx>
70 #include <simgear/scene/model/modellib.hxx>
71 #include <simgear/scene/model/placement.hxx>
72 #include <simgear/scene/util/SGUpdateVisitor.hxx>
73 #include <simgear/scene/util/RenderConstants.hxx>
74 #include <simgear/scene/tgdb/GroundLightManager.hxx>
75 #include <simgear/scene/tgdb/pt_lights.hxx>
76 #include <simgear/props/props.hxx>
77 #include <simgear/timing/sg_time.hxx>
78 #include <simgear/ephemeris/ephemeris.hxx>
79 #include <simgear/math/sg_random.h>
80 #ifdef FG_JPEG_SERVER
81 #include <simgear/screen/jpgfactory.hxx>
82 #endif
83
84 #include <simgear/environment/visual_enviro.hxx>
85
86 #include <Scenery/tileentry.hxx>
87 #include <Time/light.hxx>
88 #include <Time/light.hxx>
89 #include <Aircraft/aircraft.hxx>
90 #include <Cockpit/panel.hxx>
91 #include <Cockpit/cockpit.hxx>
92 #include <Cockpit/hud.hxx>
93 #include <Model/panelnode.hxx>
94 #include <Model/modelmgr.hxx>
95 #include <Model/acmodel.hxx>
96 #include <Scenery/scenery.hxx>
97 #include <Scenery/redout.hxx>
98 #include <Scenery/tilemgr.hxx>
99 #include <GUI/new_gui.hxx>
100 #include <Instrumentation/instrument_mgr.hxx>
101 #include <Instrumentation/HUD/HUD.hxx>
102
103 #include <Include/general.hxx>
104 #include "splash.hxx"
105 #include "renderer.hxx"
106 #include "main.hxx"
107
108 // XXX Make this go away when OSG 2.2 is released.
109 #if (FG_OSG_VERSION >= 21004)
110 #define UPDATE_VISITOR_IN_VIEWER 1
111 #endif
112
113 class SGPuDrawable : public osg::Drawable {
114 public:
115   SGPuDrawable()
116   {
117     // Dynamic stuff, do not store geometry
118     setUseDisplayList(false);
119
120     osg::StateSet* stateSet = getOrCreateStateSet();
121     stateSet->setRenderBinDetails(1001, "RenderBin");
122     // speed optimization?
123     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
124     // We can do translucent menus, so why not. :-)
125     stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
126     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
127     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
128
129     stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
130
131     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
132     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
133   }
134   virtual void drawImplementation(osg::RenderInfo& renderInfo) const
135   { drawImplementation(*renderInfo.getState()); }
136   void drawImplementation(osg::State& state) const
137   {
138     if (!fgOSIsMainContext(state.getGraphicsContext()))
139       return;
140
141     state.pushStateSet(getStateSet());
142     state.apply();
143     state.setActiveTextureUnit(0);
144     state.setClientActiveTextureUnit(0);
145     state.disableAllVertexArrays();
146
147     glPushAttrib(GL_ALL_ATTRIB_BITS);
148     glPushClientAttrib(~0u);
149
150     puDisplay();
151
152     glPopClientAttrib();
153     glPopAttrib();
154
155     state.popStateSet();
156     state.dirtyAllModes();
157     state.dirtyAllAttributes();
158     state.dirtyAllVertexArrays();
159   }
160
161   virtual osg::Object* cloneType() const { return new SGPuDrawable; }
162   virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
163   
164 private:
165 };
166
167 class SGHUDAndPanelDrawable : public osg::Drawable {
168 public:
169   SGHUDAndPanelDrawable()
170   {
171     // Dynamic stuff, do not store geometry
172     setUseDisplayList(false);
173
174     osg::StateSet* stateSet = getOrCreateStateSet();
175     stateSet->setRenderBinDetails(1000, "RenderBin");
176
177     // speed optimization?
178     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
179     stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
180     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
181     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
182     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
183
184     stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
185   }
186   virtual void drawImplementation(osg::RenderInfo& renderInfo) const
187   { drawImplementation(*renderInfo.getState()); }
188   void drawImplementation(osg::State& state) const
189   {
190 //     std::cout << state.getGraphicsContext() << std::endl;
191     if (!fgOSIsMainContext(state.getGraphicsContext()))
192       return;
193
194     state.pushStateSet(getStateSet());
195     state.apply();
196     state.setActiveTextureUnit(0);
197     state.setClientActiveTextureUnit(0);
198     state.disableAllVertexArrays();
199
200     glPushAttrib(GL_ALL_ATTRIB_BITS);
201     glPushClientAttrib(~0u);
202
203     fgCockpitUpdate(&state);
204
205     FGInstrumentMgr *instr = static_cast<FGInstrumentMgr*>(globals->get_subsystem("instrumentation"));
206     HUD *hud = static_cast<HUD*>(instr->get_subsystem("hud"));
207     hud->draw(state);
208
209     // update the panel subsystem
210     if ( globals->get_current_panel() != NULL )
211         globals->get_current_panel()->update(state);
212     // We don't need a state here - can be safely removed when we can pick
213     // correctly
214     fgUpdate3DPanels();
215
216     glPopClientAttrib();
217     glPopAttrib();
218
219     state.popStateSet();
220     state.dirtyAllModes();
221     state.dirtyAllAttributes();
222     state.dirtyAllVertexArrays();
223   }
224
225   virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
226   virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
227   
228 private:
229 };
230
231 class FGLightSourceUpdateCallback : public osg::NodeCallback {
232 public:
233   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
234   {
235     assert(dynamic_cast<osg::LightSource*>(node));
236     osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
237     osg::Light* light = lightSource->getLight();
238     
239     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
240     light->setAmbient(l->scene_ambient().osg());
241     light->setDiffuse(l->scene_diffuse().osg());
242     light->setSpecular(l->scene_specular().osg());
243     SGVec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
244     light->setPosition(position.osg());
245     SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
246     light->setDirection(direction.osg());
247     light->setSpotExponent(0);
248     light->setSpotCutoff(180);
249     light->setConstantAttenuation(1);
250     light->setLinearAttenuation(0);
251     light->setQuadraticAttenuation(0);
252
253     traverse(node, nv);
254   }
255 };
256
257 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
258 public:
259   FGWireFrameModeUpdateCallback() :
260     mWireframe(fgGetNode("/sim/rendering/wireframe"))
261   { }
262   virtual void operator()(osg::StateAttribute* stateAttribute,
263                           osg::NodeVisitor*)
264   {
265     assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
266     osg::PolygonMode* polygonMode;
267     polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
268
269     if (mWireframe->getBoolValue())
270       polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
271                            osg::PolygonMode::LINE);
272     else
273       polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
274                            osg::PolygonMode::FILL);
275   }
276 private:
277   SGSharedPtr<SGPropertyNode> mWireframe;
278 };
279
280 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
281 public:
282   FGLightModelUpdateCallback() :
283     mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
284   { }
285   virtual void operator()(osg::StateAttribute* stateAttribute,
286                           osg::NodeVisitor*)
287   {
288     assert(dynamic_cast<osg::LightModel*>(stateAttribute));
289     osg::LightModel* lightModel;
290     lightModel = static_cast<osg::LightModel*>(stateAttribute);
291
292 #if 0
293     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
294     lightModel->setAmbientIntensity(l->scene_ambient().osg());
295 #else
296     lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
297 #endif
298     lightModel->setTwoSided(true);
299     lightModel->setLocalViewer(false);
300
301     if (mHighlights->getBoolValue()) {
302       lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
303     } else {
304       lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
305     }
306   }
307 private:
308   SGSharedPtr<SGPropertyNode> mHighlights;
309 };
310
311 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
312 public:
313   FGFogEnableUpdateCallback() :
314     mFogEnabled(fgGetNode("/sim/rendering/fog"))
315   { }
316   virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
317   {
318     if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
319       stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
320     } else {
321       stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
322     }
323   }
324 private:
325   SGSharedPtr<SGPropertyNode> mFogEnabled;
326 };
327
328 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
329 public:
330   virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
331   {
332     assert(dynamic_cast<SGUpdateVisitor*>(nv));
333     assert(dynamic_cast<osg::Fog*>(sa));
334     SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
335     osg::Fog* fog = static_cast<osg::Fog*>(sa);
336     fog->setMode(osg::Fog::EXP2);
337     fog->setColor(updateVisitor->getFogColor().osg());
338     fog->setDensity(updateVisitor->getFogExp2Density());
339   }
340 };
341
342 // update callback for the switch node guarding that splash
343 class FGScenerySwitchCallback : public osg::NodeCallback {
344 public:
345   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
346   {
347     assert(dynamic_cast<osg::Switch*>(node));
348     osg::Switch* sw = static_cast<osg::Switch*>(node);
349
350     double t = globals->get_sim_time_sec();
351     bool enabled = 0 < t;
352     sw->setValue(0, enabled);
353     if (!enabled)
354       return;
355     traverse(node, nv);
356   }
357 };
358
359 // Sky structures
360 SGSky *thesky;
361
362 osg::ref_ptr<osgUtil::SceneView> sceneView = new osgUtil::SceneView;  // This SceneView is used by class FGJpegHttpd ( jpg-httpd.cxx )
363 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
364 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
365
366 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
367
368 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
369
370 static osg::ref_ptr<osg::CameraView> mCameraView = new osg::CameraView;
371 static osg::ref_ptr<osg::Camera> mBackGroundCamera = new osg::Camera;
372
373 FGRenderer::FGRenderer()
374 {
375 #ifdef FG_JPEG_SERVER
376    jpgRenderFrame = FGRenderer::update;
377 #endif
378    manipulator = new FGManipulator;
379 }
380
381 FGRenderer::~FGRenderer()
382 {
383 #ifdef FG_JPEG_SERVER
384    jpgRenderFrame = NULL;
385 #endif
386 }
387
388 // Initialize various GL/view parameters
389 // XXX This should be called "preinit" or something, as it initializes
390 // critical parts of the scene graph in addition to the splash screen.
391 void
392 FGRenderer::splashinit( void ) {
393     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
394     if (viewer) {
395         sceneView = 0;
396         mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
397         mRealRoot->addChild(fgCreateSplashNode());
398         mFrameStamp = viewer->getFrameStamp();
399         // Scene doesn't seem to pass the frame stamp to the update
400         // visitor automatically.
401         mUpdateVisitor->setFrameStamp(mFrameStamp.get());
402 #ifdef UPDATE_VISITOR_IN_VIEWER
403         viewer->setUpdateVisitor(mUpdateVisitor.get());
404 #else
405         osgViewer::Scene* scene = viewer->getScene();
406         scene->setUpdateVisitor(mUpdateVisitor.get());
407 #endif
408     } else {
409         // Add the splash screen node
410         mRealRoot->addChild(fgCreateSplashNode());
411         sceneView->setSceneData(mRealRoot.get());
412         sceneView->setDefaults(osgUtil::SceneView::COMPILE_GLOBJECTS_AT_INIT);
413         sceneView->setFrameStamp(mFrameStamp.get());
414         sceneView->setUpdateVisitor(mUpdateVisitor.get());
415     }
416 }
417
418 void
419 FGRenderer::init( void ) {
420     // The viewer can call this before the graphics context is current
421     // in the main thread; indeed, in a multithreaded setup it might
422     // never be current in the main thread.
423     fgMakeCurrent();
424     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
425     osg::initNotifyLevel();
426
427     // The number of polygon-offset "units" to place between layers.  In
428     // principle, one is supposed to be enough.  In practice, I find that
429     // my hardware/driver requires many more.
430     osg::PolygonOffset::setUnitsMultiplier(1);
431     osg::PolygonOffset::setFactorMultiplier(1);
432
433     // Go full screen if requested ...
434     if ( fgGetBool("/sim/startup/fullscreen") )
435         fgOSFullScreen();
436
437     if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) || 
438          (!fgGetBool("/sim/rendering/shading"))) {
439         // if fastest fog requested, or if flat shading force fastest
440         glHint ( GL_FOG_HINT, GL_FASTEST );
441     } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
442         glHint ( GL_FOG_HINT, GL_DONT_CARE );
443     }
444
445     glHint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
446     glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
447     glHint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
448
449     if (viewer) {
450       viewer->getCamera()
451             ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
452     } else {
453         sceneView->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
454         sceneView->getCamera()->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
455     }
456
457
458     osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
459
460     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
461     
462     stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
463     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
464
465     stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
466     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
467     stateSet->setAttribute(new osg::BlendFunc);
468     stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
469
470     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
471     
472     // this will be set below
473     stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
474
475     osg::Material* material = new osg::Material;
476     stateSet->setAttribute(material);
477     
478     stateSet->setTextureAttribute(0, new osg::TexEnv);
479     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
480
481
482 //     stateSet->setAttribute(new osg::CullFace(osg::CullFace::BACK));
483 //     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::ON);
484
485     // this is the topmost scenegraph node for osg
486     mBackGroundCamera->addChild(thesky->getPreRoot());
487     mBackGroundCamera->setClearMask(0);
488
489     GLbitfield inheritanceMask = osg::CullSettings::ALL_VARIABLES;
490     inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
491     inheritanceMask &= ~osg::CullSettings::NEAR_FAR_RATIO;
492     inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
493     mBackGroundCamera->setInheritanceMask(inheritanceMask);
494     mBackGroundCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
495     mBackGroundCamera->setCullingMode(osg::CullSettings::NO_CULLING);
496     mBackGroundCamera->setRenderOrder(osg::Camera::NESTED_RENDER);
497
498     stateSet = mBackGroundCamera->getOrCreateStateSet();
499     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
500
501     osg::Group* sceneGroup = new osg::Group;
502     sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
503     sceneGroup->addChild(thesky->getCloudRoot());
504
505     stateSet = sceneGroup->getOrCreateStateSet();
506     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
507     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
508
509     // need to update the light on every frame
510     osg::LightSource* lightSource = new osg::LightSource;
511     lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
512     // relative because of CameraView being just a clever transform node
513     lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
514     lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
515     mRoot->addChild(lightSource);
516
517     lightSource->addChild(mBackGroundCamera.get());
518     lightSource->addChild(sceneGroup);
519
520
521     stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
522     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
523     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
524     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
525     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
526
527     // enable disable specular highlights.
528     // is the place where we might plug in an other fragment shader ...
529     osg::LightModel* lightModel = new osg::LightModel;
530     lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
531     stateSet->setAttribute(lightModel);
532
533     // switch to enable wireframe
534     osg::PolygonMode* polygonMode = new osg::PolygonMode;
535     polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
536     stateSet->setAttributeAndModes(polygonMode);
537
538     // scene fog handling
539     osg::Fog* fog = new osg::Fog;
540     fog->setUpdateCallback(new FGFogUpdateCallback);
541     stateSet->setAttributeAndModes(fog);
542     stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
543
544     // plug in the GUI
545     osg::Camera* guiCamera = new osg::Camera;
546     guiCamera->setRenderOrder(osg::Camera::POST_RENDER, 100);
547     guiCamera->setClearMask(0);
548     inheritanceMask = osg::CullSettings::ALL_VARIABLES;
549     inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
550     inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
551     guiCamera->setInheritanceMask(inheritanceMask);
552     guiCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
553     guiCamera->setCullingMode(osg::CullSettings::NO_CULLING);
554     osg::Geode* geode = new osg::Geode;
555     geode->addDrawable(new SGPuDrawable);
556     geode->addDrawable(new SGHUDAndPanelDrawable);
557     guiCamera->addChild(geode);
558
559     mCameraView->addChild(mRoot.get());
560
561     osg::Switch* sw = new osg::Switch;
562     sw->setUpdateCallback(new FGScenerySwitchCallback);
563     sw->addChild(mCameraView.get());
564
565     mRealRoot->addChild(sw);
566     mRealRoot->addChild(FGCreateRedoutNode());
567     mRealRoot->addChild(guiCamera);
568 //  sceneView->getState()->setCheckForGLErrors(osg::State::ONCE_PER_ATTRIBUTE);
569 }
570
571
572 // Update all Visuals (redraws anything graphics related)
573 void
574 FGRenderer::update( bool refresh_camera_settings ) {
575     bool scenery_loaded = fgGetBool("sim/sceneryloaded")
576                           || fgGetBool("sim/sceneryloaded-override");
577     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
578     if ( idle_state < 1000 || !scenery_loaded ) {
579         fgSetDouble("/sim/startup/splash-alpha", 1.0);
580
581         // Keep resetting sim time while the sim is initializing
582         globals->set_sim_time_sec( 0.0 );
583
584         // the splash screen is now in the scenegraph
585         if (!viewer) {
586             sceneView->update();
587             sceneView->cull();
588             sceneView->draw();
589         }
590         return;
591     }
592
593     // Fade out the splash screen over the first three seconds.
594     double sAlpha = SGMiscd::max(0, (2.5 - globals->get_sim_time_sec()) / 2.5);
595     fgSetDouble("/sim/startup/splash-alpha", sAlpha);
596
597     bool skyblend = fgGetBool("/sim/rendering/skyblend");
598     bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
599     bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
600     bool distance_attenuation
601         = fgGetBool("/sim/rendering/distance-attenuation");
602     // OSGFIXME
603     SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
604                                   distance_attenuation );
605
606     static const SGPropertyNode *groundlevel_nearplane
607         = fgGetNode("/sim/current-view/ground-level-nearplane-m");
608
609     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
610
611     // update fog params
612     double actual_visibility;
613     if (fgGetBool("/environment/clouds/status")) {
614         actual_visibility = thesky->get_visibility();
615     } else {
616         actual_visibility = fgGetDouble("/environment/visibility-m");
617     }
618
619     // idle_state is now 1000 meaning we've finished all our
620     // initializations and are running the main loop, so this will
621     // now work without seg faulting the system.
622
623     FGViewer *current__view = globals->get_current_view();
624     // Force update of center dependent values ...
625     current__view->set_dirty();
626
627     if ( refresh_camera_settings ) {
628         // update view port
629         resize( fgGetInt("/sim/startup/xsize"),
630                 fgGetInt("/sim/startup/ysize") );
631
632         SGVec3d position = current__view->getViewPosition();
633         SGQuatd attitude = current__view->getViewOrientation();
634         SGVec3d osgPosition = attitude.transform(-position);
635         if (viewer) {
636             FGManipulator *manipulator
637                 = globals->get_renderer()->getManipulator();
638             manipulator->setPosition(position.osg());
639             manipulator->setAttitude(attitude.osg());
640         } else {
641             mCameraView->setPosition(osgPosition.osg());
642             mCameraView->setAttitude(inverse(attitude).osg());
643         }
644     }
645     osg::Camera *camera;
646     if (viewer)
647         camera = viewer->getCamera();
648     else
649         camera = sceneView->getCamera();
650     if ( skyblend ) {
651         
652         if ( fgGetBool("/sim/rendering/textures") ) {
653             SGVec4f clearColor(l->adj_fog_color());
654             camera->setClearColor(clearColor.osg());
655         }
656     } else {
657         SGVec4f clearColor(l->sky_color());
658         camera->setClearColor(clearColor.osg());
659     }
660
661     // update fog params if visibility has changed
662     double visibility_meters = fgGetDouble("/environment/visibility-m");
663     thesky->set_visibility(visibility_meters);
664
665     thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
666                         ( global_multi_loop * fgGetInt("/sim/speed-up") )
667                         / (double)fgGetInt("/sim/model-hz") );
668
669     // update the sky dome
670     if ( skyblend ) {
671
672         // The sun and moon distances are scaled down versions
673         // of the actual distance to get both the moon and the sun
674         // within the range of the far clip plane.
675         // Moon distance:    384,467 kilometers
676         // Sun distance: 150,000,000 kilometers
677
678         double sun_horiz_eff, moon_horiz_eff;
679         if (fgGetBool("/sim/rendering/horizon-effect")) {
680            sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
681            moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
682         } else {
683            sun_horiz_eff = moon_horiz_eff = 1.0;
684         }
685
686         static SGSkyState sstate;
687
688         sstate.view_pos  = toVec3f(current__view->get_view_pos());
689         sstate.zero_elev = toVec3f(current__view->get_zero_elev());
690         sstate.view_up   = current__view->get_world_up();
691         sstate.lon       = current__view->getLongitude_deg()
692                             * SGD_DEGREES_TO_RADIANS;
693         sstate.lat       = current__view->getLatitude_deg()
694                             * SGD_DEGREES_TO_RADIANS;
695         sstate.alt       = current__view->getAltitudeASL_ft()
696                             * SG_FEET_TO_METER;
697         sstate.spin      = l->get_sun_rotation();
698         sstate.gst       = globals->get_time_params()->getGst();
699         sstate.sun_ra    = globals->get_ephem()->getSunRightAscension();
700         sstate.sun_dec   = globals->get_ephem()->getSunDeclination();
701         sstate.sun_dist  = 50000.0 * sun_horiz_eff;
702         sstate.moon_ra   = globals->get_ephem()->getMoonRightAscension();
703         sstate.moon_dec  = globals->get_ephem()->getMoonDeclination();
704         sstate.moon_dist = 40000.0 * moon_horiz_eff;
705         sstate.sun_angle = l->get_sun_angle();
706
707
708         /*
709          SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
710          << l->sky_color()[0] << " "
711          << l->sky_color()[1] << " "
712          << l->sky_color()[2] << " "
713          << l->sky_color()[3] );
714         SG_LOG( SG_GENERAL, SG_BULK, "    fog = "
715          << l->fog_color()[0] << " "
716          << l->fog_color()[1] << " "
717          << l->fog_color()[2] << " "
718          << l->fog_color()[3] );
719         SG_LOG( SG_GENERAL, SG_BULK,
720                 "    sun_angle = " << l->sun_angle
721          << "    moon_angle = " << l->moon_angle );
722         */
723
724         static SGSkyColor scolor;
725
726         scolor.sky_color   = SGVec3f(l->sky_color().data());
727         scolor.fog_color   = SGVec3f(l->adj_fog_color().data());
728         scolor.cloud_color = SGVec3f(l->cloud_color().data());
729         scolor.sun_angle   = l->get_sun_angle();
730         scolor.moon_angle  = l->get_moon_angle();
731         scolor.nplanets    = globals->get_ephem()->getNumPlanets();
732         scolor.nstars      = globals->get_ephem()->getNumStars();
733         scolor.planet_data = globals->get_ephem()->getPlanets();
734         scolor.star_data   = globals->get_ephem()->getStars();
735
736         thesky->reposition( sstate, delta_time_sec );
737         thesky->repaint( scolor );
738
739         /*
740         SG_LOG( SG_GENERAL, SG_BULK,
741                 "thesky->reposition( view_pos = " << view_pos[0] << " "
742          << view_pos[1] << " " << view_pos[2] );
743         SG_LOG( SG_GENERAL, SG_BULK,
744                 "    zero_elev = " << zero_elev[0] << " "
745          << zero_elev[1] << " " << zero_elev[2]
746          << " lon = " << cur_fdm_state->get_Longitude()
747          << " lat = " << cur_fdm_state->get_Latitude() );
748         SG_LOG( SG_GENERAL, SG_BULK,
749                 "    sun_rot = " << l->get_sun_rotation
750          << " gst = " << SGTime::cur_time_params->getGst() );
751         SG_LOG( SG_GENERAL, SG_BULK,
752              "    sun ra = " << globals->get_ephem()->getSunRightAscension()
753           << " sun dec = " << globals->get_ephem()->getSunDeclination()
754           << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
755           << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
756         */
757
758         //OSGFIXME
759 //         shadows->setupShadows(
760 //           current__view->getLongitude_deg(),
761 //           current__view->getLatitude_deg(),
762 //           globals->get_time_params()->getGst(),
763 //           globals->get_ephem()->getSunRightAscension(),
764 //           globals->get_ephem()->getSunDeclination(),
765 //           l->get_sun_angle());
766
767     }
768
769 //     sgEnviro.setLight(l->adj_fog_color());
770
771     // texture parameters
772     glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
773
774     double agl = current__view->getAltitudeASL_ft()*SG_FEET_TO_METER
775       - current__view->getSGLocation()->get_cur_elev_m();
776
777     float scene_nearplane, scene_farplane;
778     if ( agl > 10.0 ) {
779         scene_nearplane = 10.0f;
780         scene_farplane = 120000.0f;
781     } else {
782         scene_nearplane = groundlevel_nearplane->getDoubleValue();
783         scene_farplane = 120000.0f;
784     }
785     setNearFar( scene_nearplane, scene_farplane );
786
787 //     sgEnviro.startOfFrame(current__view->get_view_pos(), 
788 //         current__view->get_world_up(),
789 //         current__view->getLongitude_deg(),
790 //         current__view->getLatitude_deg(),
791 //         current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
792 //         delta_time_sec);
793
794     // OSGFIXME
795 //     sgEnviro.drawLightning();
796
797 //        double current_view_origin_airspeed_horiz_kt =
798 //         fgGetDouble("/velocities/airspeed-kt", 0.0)
799 //                        * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
800 //                                * SGD_DEGREES_TO_RADIANS);
801        // TODO:find the real view speed, not the AC one
802 //     sgEnviro.drawPrecipitation(
803 //         fgGetDouble("/environment/metar/rain-norm", 0.0),
804 //         fgGetDouble("/environment/metar/snow-norm", 0.0),
805 //         fgGetDouble("/environment/metar/hail-norm", 0.0),
806 //         current__view->getPitch_deg() + current__view->getPitchOffset_deg(),
807 //         current__view->getRoll_deg() + current__view->getRollOffset_deg(),
808 //         - current__view->getHeadingOffset_deg(),
809 //                current_view_origin_airspeed_horiz_kt
810 //                );
811
812     // OSGFIXME
813 //     if( is_internal )
814 //         shadows->endOfFrame();
815
816     // need to call the update visitor once
817     if (!viewer) {
818         mFrameStamp->setReferenceTime(globals->get_sim_time_sec());
819         mFrameStamp->setSimulationTime(globals->get_sim_time_sec());
820         mFrameStamp->setFrameNumber(1+mFrameStamp->getFrameNumber());
821     }
822     mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
823     mUpdateVisitor->setViewData(current__view->getViewPosition(),
824                                 current__view->getViewOrientation());
825     SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
826     mUpdateVisitor->setLight(direction, l->scene_ambient(),
827                              l->scene_diffuse(), l->scene_specular(),
828                              l->adj_fog_color(),
829                              l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
830     mUpdateVisitor->setVisibility(actual_visibility);
831     simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
832     bool hotspots = fgGetBool("/sim/panel-hotspots");
833     osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
834     cullMask |= simgear::GroundLightManager::instance()
835         ->getLightNodeMask(mUpdateVisitor.get());
836     if (hotspots)
837         cullMask |= simgear::PICK_BIT;
838     if (viewer) {
839         camera->setCullMask(cullMask);
840         for (int i = 0; i < viewer->getNumSlaves(); ++i)
841             viewer->getSlave(i)._camera->setCullMask(cullMask);
842     } else {
843         sceneView->setCullMask(cullMask);
844         sceneView->update();
845         sceneView->cull();
846         sceneView->draw();
847     }
848 }
849
850
851
852 // options.cxx needs to see this for toggle_panel()
853 // Handle new window size or exposure
854 void
855 FGRenderer::resize( int width, int height ) {
856     int view_h;
857
858     if ( (!fgGetBool("/sim/virtual-cockpit"))
859          && fgPanelVisible() && idle_state == 1000 ) {
860         view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
861                              globals->get_current_panel()->getYOffset()) / 768.0);
862     } else {
863         view_h = height;
864     }
865     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
866     if (viewer)
867         ;
868   //       viewer->getCamera()->getViewport()->setViewport(0, height - view_h,
869 //                                                         width, view_h);
870     else
871         sceneView->getViewport()->setViewport(0, height - view_h,
872                                               width, view_h);
873
874     static int lastwidth = 0;
875     static int lastheight = 0;
876     if (width != lastwidth)
877         fgSetInt("/sim/startup/xsize", lastwidth = width);
878     if (height != lastheight)
879         fgSetInt("/sim/startup/ysize", lastheight = height);
880
881     guiInitMouse(width, height);
882
883     // for all views
884     FGViewMgr *viewmgr = globals->get_viewmgr();
885     if (viewmgr) {
886       for ( int i = 0; i < viewmgr->size(); ++i ) {
887         viewmgr->get_view(i)->
888           set_aspect_ratio((float)view_h / (float)width);
889       }
890
891       setFOV( viewmgr->get_current_view()->get_h_fov(),
892               viewmgr->get_current_view()->get_v_fov() );
893     }
894 }
895
896
897 // we need some static storage space for these values.  However, we
898 // can't store it in a renderer class object because the functions
899 // that manipulate these are static.  They are static so they can
900 // interface to the display callback system.  There's probably a
901 // better way, there has to be a better way, but I'm not seeing it
902 // right now.
903 static float fov_width = 55.0;
904 static float fov_height = 42.0;
905 static float fov_near = 1.0;
906 static float fov_far = 1000.0;
907
908
909 /** FlightGear code should use this routine to set the FOV rather than
910  *  calling the ssg routine directly
911  */
912 void FGRenderer::setFOV( float w, float h ) {
913     fov_width = w;
914     fov_height = h;
915     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
916     if (viewer)
917         viewer->getCamera()->setProjectionMatrixAsPerspective(fov_height, 4.0/3.0, fov_near, fov_far);
918     else
919         sceneView->setProjectionMatrixAsPerspective(fov_height,
920                                                     fov_width/fov_height,
921                                                     fov_near, fov_far);
922 }
923
924
925 /** FlightGear code should use this routine to set the Near/Far clip
926  *  planes rather than calling the ssg routine directly
927  */
928 void FGRenderer::setNearFar( float n, float f ) {
929 // OSGFIXME: we have currently too much z-buffer fights
930 n = 0.1;
931     fov_near = n;
932     fov_far = f;
933     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
934     if (viewer)
935         viewer->getCamera()->setProjectionMatrixAsPerspective(fov_height, 4.0/3.0, fov_near, fov_far);
936     else
937         sceneView->setProjectionMatrixAsPerspective(fov_height,
938                                                     fov_width/fov_height,
939                                                     fov_near, fov_far);
940
941 }
942
943 bool
944 FGRenderer::pick( unsigned x, unsigned y,
945                   std::vector<SGSceneryPick>& pickList,
946                   const osgGA::GUIEventAdapter* ea )
947 {
948   osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
949   // wipe out the return ...
950   pickList.resize(0);
951
952   if (sceneView.valid()) {
953     osg::Node* sceneData = globals->get_scenery()->get_scene_graph();
954     if (!sceneData)
955       return false;
956
957     osg::Viewport* viewport = sceneView->getViewport();
958     if (!viewport)
959       return false;
960     // don't know why, but the update has partly happened somehow,
961     // so update the scenery part of the viewer
962     FGViewer *current_view = globals->get_current_view();
963     // Force update of center dependent values ...
964     current_view->set_dirty();
965     SGVec3d position = current_view->getViewPosition();
966     SGQuatd attitude = current_view->getViewOrientation();
967     SGVec3d osgPosition = attitude.transform(-position);
968     mCameraView->setPosition(osgPosition.osg());
969     mCameraView->setAttitude(inverse(attitude).osg());
970
971     osg::Matrix projection(sceneView->getProjectionMatrix());
972     osg::Matrix modelview(sceneView->getViewMatrix());
973
974     osg::NodePathList nodePath = sceneData->getParentalNodePaths();
975     // modify the view matrix so that it accounts for this nodePath's
976     // accumulated transform
977     if (!nodePath.empty())
978       modelview.preMult(computeLocalToWorld(nodePath.front()));
979
980     // swap the y values ...
981     y = viewport->height() - y;
982     // set up the pick visitor
983     osgUtil::PickVisitor pickVisitor(viewport, projection, modelview, x, y);
984     sceneData->accept(pickVisitor);
985     if (!pickVisitor.hits())
986       return false;
987     
988     // collect all interaction callbacks on the pick ray.
989     // They get stored in the pickCallbacks list where they are sorted back
990     // to front and croasest to finest wrt the scenery node they are attached to
991     osgUtil::PickVisitor::LineSegmentHitListMap::const_iterator mi;
992     for (mi = pickVisitor.getSegHitList().begin();
993          mi != pickVisitor.getSegHitList().end();
994          ++mi) {
995       osgUtil::IntersectVisitor::HitList::const_iterator hi;
996       for (hi = mi->second.begin(); hi != mi->second.end(); ++hi) {
997         // ok, go back the nodes and ask for intersection callbacks,
998         // execute them in top down order
999         const osg::NodePath& np = hi->getNodePath();
1000         osg::NodePath::const_reverse_iterator npi;
1001         for (npi = np.rbegin(); npi != np.rend(); ++npi) {
1002           SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
1003           if (!ud)
1004             continue;
1005           for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
1006             SGPickCallback* pickCallback = ud->getPickCallback(i);
1007             if (!pickCallback)
1008               continue;
1009             SGSceneryPick sceneryPick;
1010             /// note that this is done totally in doubles instead of
1011             /// just using getWorldIntersectionPoint
1012             osg::Vec3d localPt = hi->getLocalIntersectPoint();
1013             sceneryPick.info.local = SGVec3d(localPt);
1014             if (hi->getMatrix())
1015               sceneryPick.info.wgs84 = SGVec3d(localPt*(*hi->getMatrix()));
1016             else
1017               sceneryPick.info.wgs84 = SGVec3d(localPt);
1018             sceneryPick.callback = pickCallback;
1019             pickList.push_back(sceneryPick);
1020           }
1021         }
1022       }
1023     }
1024     
1025     return !pickList.empty();
1026
1027   } else if (viewer) {
1028
1029     // just compute intersections in the viewers method ...
1030     typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
1031     Intersections intersections;
1032     viewer->computeIntersections(ea->getX(), ea->getY(), intersections);
1033
1034     Intersections::iterator hit;
1035     for (hit = intersections.begin(); hit != intersections.end(); ++hit) {
1036       const osg::NodePath& np = hit->nodePath;
1037       osg::NodePath::const_reverse_iterator npi;
1038       for (npi = np.rbegin(); npi != np.rend(); ++npi) {
1039         SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
1040         if (!ud)
1041           continue;
1042         for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
1043           SGPickCallback* pickCallback = ud->getPickCallback(i);
1044           if (!pickCallback)
1045             continue;
1046           SGSceneryPick sceneryPick;
1047           sceneryPick.info.local = SGVec3d(hit->getLocalIntersectPoint());
1048           sceneryPick.info.wgs84 = SGVec3d(hit->getWorldIntersectPoint());
1049           sceneryPick.callback = pickCallback;
1050           pickList.push_back(sceneryPick);
1051         }
1052       }
1053     }
1054
1055     return !pickList.empty();
1056   } else {                      // we can get called early ...
1057     return false;
1058   }
1059 }
1060
1061 void
1062 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
1063 {
1064     mRealRoot->addChild(camera);
1065 }
1066
1067 bool
1068 fgDumpSceneGraphToFile(const char* filename)
1069 {
1070     return osgDB::writeNodeFile(*mRealRoot.get(), filename);
1071 }
1072
1073 bool
1074 fgDumpTerrainBranchToFile(const char* filename)
1075 {
1076     return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
1077                                  filename );
1078 }
1079
1080 // end of renderer.cxx
1081