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