]> git.mxchange.org Git - flightgear.git/blob - src/Main/renderer.cxx
minor upodate by John
[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 <osg/ref_ptr>
33 #include <osg/AlphaFunc>
34 #include <osg/BlendFunc>
35 #include <osg/Camera>
36 #include <osg/CullFace>
37 #include <osg/Depth>
38 #include <osg/Fog>
39 #include <osg/Group>
40 #include <osg/Hint>
41 #include <osg/Light>
42 #include <osg/LightModel>
43 #include <osg/LightSource>
44 #include <osg/Material>
45 #include <osg/Math>
46 #include <osg/NodeCallback>
47 #include <osg/Notify>
48 #include <osg/PolygonMode>
49 #include <osg/PolygonOffset>
50 #include <osg/Version>
51 #include <osg/TexEnv>
52
53 #include <osgUtil/LineSegmentIntersector>
54
55 #include <osg/io_utils>
56 #include <osgDB/WriteFile>
57
58 #include <simgear/math/SGMath.hxx>
59 #include <simgear/screen/extensions.hxx>
60 #include <simgear/scene/material/matlib.hxx>
61 #include <simgear/scene/model/animation.hxx>
62 #include <simgear/scene/model/placement.hxx>
63 #include <simgear/scene/sky/sky.hxx>
64 #include <simgear/scene/util/SGUpdateVisitor.hxx>
65 #include <simgear/scene/util/RenderConstants.hxx>
66 #include <simgear/scene/util/SGSceneUserData.hxx>
67 #include <simgear/scene/tgdb/GroundLightManager.hxx>
68 #include <simgear/scene/tgdb/pt_lights.hxx>
69 #include <simgear/props/props.hxx>
70 #include <simgear/timing/sg_time.hxx>
71 #include <simgear/ephemeris/ephemeris.hxx>
72 #include <simgear/math/sg_random.h>
73 #ifdef FG_JPEG_SERVER
74 #include <simgear/screen/jpgfactory.hxx>
75 #endif
76
77 #include <simgear/environment/visual_enviro.hxx>
78
79 #include <Time/light.hxx>
80 #include <Time/light.hxx>
81 #include <Aircraft/aircraft.hxx>
82 #include <Cockpit/panel.hxx>
83 #include <Cockpit/cockpit.hxx>
84 #include <Cockpit/hud.hxx>
85 #include <Model/panelnode.hxx>
86 #include <Model/modelmgr.hxx>
87 #include <Model/acmodel.hxx>
88 #include <Scenery/scenery.hxx>
89 #include <Scenery/redout.hxx>
90 #include <Scenery/tilemgr.hxx>
91 #include <GUI/new_gui.hxx>
92 #include <Instrumentation/instrument_mgr.hxx>
93 #include <Instrumentation/HUD/HUD.hxx>
94 #include <Environment/precipitation_mgr.hxx>
95
96 #include <Include/general.hxx>
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
104 using namespace osg;
105 using namespace simgear;
106 using namespace flightgear;
107
108 class FGHintUpdateCallback : public osg::StateAttribute::Callback {
109 public:
110   FGHintUpdateCallback(const char* configNode) :
111     mConfigNode(fgGetNode(configNode, true))
112   { }
113   virtual void operator()(osg::StateAttribute* stateAttribute,
114                           osg::NodeVisitor*)
115   {
116     assert(dynamic_cast<osg::Hint*>(stateAttribute));
117     osg::Hint* hint = static_cast<osg::Hint*>(stateAttribute);
118
119     const char* value = mConfigNode->getStringValue();
120     if (!value)
121       hint->setMode(GL_DONT_CARE);
122     else if (0 == strcmp(value, "nicest"))
123       hint->setMode(GL_NICEST);
124     else if (0 == strcmp(value, "fastest"))
125       hint->setMode(GL_FASTEST);
126     else
127       hint->setMode(GL_DONT_CARE);
128   }
129 private:
130   SGSharedPtr<SGPropertyNode> mConfigNode;
131 };
132
133
134 class SGPuDrawable : public osg::Drawable {
135 public:
136   SGPuDrawable()
137   {
138     // Dynamic stuff, do not store geometry
139     setUseDisplayList(false);
140
141     osg::StateSet* stateSet = getOrCreateStateSet();
142     stateSet->setRenderBinDetails(1001, "RenderBin");
143     // speed optimization?
144     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
145     // We can do translucent menus, so why not. :-)
146     stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
147     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
148     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
149
150     stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
151
152     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
153     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
154   }
155   virtual void drawImplementation(osg::RenderInfo& renderInfo) const
156   { drawImplementation(*renderInfo.getState()); }
157   void drawImplementation(osg::State& state) const
158   {
159     state.setActiveTextureUnit(0);
160     state.setClientActiveTextureUnit(0);
161
162     state.disableAllVertexArrays();
163
164     glPushAttrib(GL_ALL_ATTRIB_BITS);
165     glPushClientAttrib(~0u);
166
167     puDisplay();
168
169     glPopClientAttrib();
170     glPopAttrib();
171   }
172
173   virtual osg::Object* cloneType() const { return new SGPuDrawable; }
174   virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
175   
176 private:
177 };
178
179 class SGHUDAndPanelDrawable : public osg::Drawable {
180 public:
181   SGHUDAndPanelDrawable()
182   {
183     // Dynamic stuff, do not store geometry
184     setUseDisplayList(false);
185
186     osg::StateSet* stateSet = getOrCreateStateSet();
187     stateSet->setRenderBinDetails(1000, "RenderBin");
188
189     // speed optimization?
190     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
191     stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
192     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
193     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
194     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
195
196     stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
197   }
198   virtual void drawImplementation(osg::RenderInfo& renderInfo) const
199   { drawImplementation(*renderInfo.getState()); }
200   void drawImplementation(osg::State& state) const
201   {
202     state.setActiveTextureUnit(0);
203     state.setClientActiveTextureUnit(0);
204     state.disableAllVertexArrays();
205
206     glPushAttrib(GL_ALL_ATTRIB_BITS);
207     glPushClientAttrib(~0u);
208
209     fgCockpitUpdate(&state);
210
211     FGInstrumentMgr *instr = static_cast<FGInstrumentMgr*>(globals->get_subsystem("instrumentation"));
212     HUD *hud = static_cast<HUD*>(instr->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   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
236   {
237     assert(dynamic_cast<osg::LightSource*>(node));
238     osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
239     osg::Light* light = lightSource->getLight();
240     
241     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
242     light->setAmbient(toOsg(l->scene_ambient()));
243     light->setDiffuse(toOsg(l->scene_diffuse()));
244     light->setSpecular(toOsg(l->scene_specular()));
245     osg::Vec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
246     light->setPosition(position);
247     osg::Vec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
248     light->setDirection(direction);
249     light->setSpotExponent(0);
250     light->setSpotCutoff(180);
251     light->setConstantAttenuation(1);
252     light->setLinearAttenuation(0);
253     light->setQuadraticAttenuation(0);
254
255     traverse(node, nv);
256   }
257 };
258
259 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
260 public:
261   FGWireFrameModeUpdateCallback() :
262     mWireframe(fgGetNode("/sim/rendering/wireframe"))
263   { }
264   virtual void operator()(osg::StateAttribute* stateAttribute,
265                           osg::NodeVisitor*)
266   {
267     assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
268     osg::PolygonMode* polygonMode;
269     polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
270
271     if (mWireframe->getBoolValue())
272       polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
273                            osg::PolygonMode::LINE);
274     else
275       polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
276                            osg::PolygonMode::FILL);
277   }
278 private:
279   SGSharedPtr<SGPropertyNode> mWireframe;
280 };
281
282 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
283 public:
284   FGLightModelUpdateCallback() :
285     mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
286   { }
287   virtual void operator()(osg::StateAttribute* stateAttribute,
288                           osg::NodeVisitor*)
289   {
290     assert(dynamic_cast<osg::LightModel*>(stateAttribute));
291     osg::LightModel* lightModel;
292     lightModel = static_cast<osg::LightModel*>(stateAttribute);
293
294 #if 0
295     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
296     lightModel->setAmbientIntensity(toOsg(l->scene_ambient());
297 #else
298     lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
299 #endif
300     lightModel->setTwoSided(true);
301     lightModel->setLocalViewer(false);
302
303     if (mHighlights->getBoolValue()) {
304       lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
305     } else {
306       lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
307     }
308   }
309 private:
310   SGSharedPtr<SGPropertyNode> mHighlights;
311 };
312
313 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
314 public:
315   FGFogEnableUpdateCallback() :
316     mFogEnabled(fgGetNode("/sim/rendering/fog"))
317   { }
318   virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
319   {
320     if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
321       stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
322     } else {
323       stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
324     }
325   }
326 private:
327   SGSharedPtr<SGPropertyNode> mFogEnabled;
328 };
329
330 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
331 public:
332   virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
333   {
334     assert(dynamic_cast<SGUpdateVisitor*>(nv));
335     assert(dynamic_cast<osg::Fog*>(sa));
336     SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
337     osg::Fog* fog = static_cast<osg::Fog*>(sa);
338     fog->setMode(osg::Fog::EXP2);
339     fog->setColor(toOsg(updateVisitor->getFogColor()));
340     fog->setDensity(updateVisitor->getFogExp2Density());
341   }
342 };
343
344 // update callback for the switch node guarding that splash
345 class FGScenerySwitchCallback : public osg::NodeCallback {
346 public:
347   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
348   {
349     assert(dynamic_cast<osg::Switch*>(node));
350     osg::Switch* sw = static_cast<osg::Switch*>(node);
351
352     double t = globals->get_sim_time_sec();
353     bool enabled = 0 < t;
354     sw->setValue(0, enabled);
355     if (!enabled)
356       return;
357     traverse(node, nv);
358   }
359 };
360
361 // Sky structures
362 SGSky *thesky;
363
364 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
365 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
366
367 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
368
369 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
370
371 FGRenderer::FGRenderer()
372 {
373 #ifdef FG_JPEG_SERVER
374    jpgRenderFrame = FGRenderer::update;
375 #endif
376    eventHandler = new FGEventHandler;
377 }
378
379 FGRenderer::~FGRenderer()
380 {
381 #ifdef FG_JPEG_SERVER
382    jpgRenderFrame = NULL;
383 #endif
384 }
385
386 // Initialize various GL/view parameters
387 // XXX This should be called "preinit" or something, as it initializes
388 // critical parts of the scene graph in addition to the splash screen.
389 void
390 FGRenderer::splashinit( void ) {
391     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
392     mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
393     mRealRoot->addChild(fgCreateSplashNode());
394     mFrameStamp = viewer->getFrameStamp();
395     // Scene doesn't seem to pass the frame stamp to the update
396     // visitor automatically.
397     mUpdateVisitor->setFrameStamp(mFrameStamp.get());
398     viewer->setUpdateVisitor(mUpdateVisitor.get());
399 }
400
401 void
402 FGRenderer::init( void )
403 {
404     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
405     osg::initNotifyLevel();
406
407     // The number of polygon-offset "units" to place between layers.  In
408     // principle, one is supposed to be enough.  In practice, I find that
409     // my hardware/driver requires many more.
410     osg::PolygonOffset::setUnitsMultiplier(1);
411     osg::PolygonOffset::setFactorMultiplier(1);
412
413     // Go full screen if requested ...
414     if ( fgGetBool("/sim/startup/fullscreen") )
415         fgOSFullScreen();
416
417     viewer->getCamera()
418         ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
419     
420     osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
421
422     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
423     
424     stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
425     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
426
427     stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
428     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
429     stateSet->setAttribute(new osg::BlendFunc);
430     stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
431
432     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
433     
434     // this will be set below
435     stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
436
437     osg::Material* material = new osg::Material;
438     stateSet->setAttribute(material);
439     
440     stateSet->setTextureAttribute(0, new osg::TexEnv);
441     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
442
443     osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
444     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
445     stateSet->setAttribute(hint);
446     hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
447     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
448     stateSet->setAttribute(hint);
449     hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
450     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
451     stateSet->setAttribute(hint);
452     hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
453     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
454     stateSet->setAttribute(hint);
455     hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
456     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
457     stateSet->setAttribute(hint);
458
459     osg::Group* sceneGroup = new osg::Group;
460     sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
461     sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
462
463     //sceneGroup->addChild(thesky->getCloudRoot());
464
465     stateSet = sceneGroup->getOrCreateStateSet();
466     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
467
468     // need to update the light on every frame
469     osg::LightSource* lightSource = new osg::LightSource;
470     lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
471     // relative because of CameraView being just a clever transform node
472     lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
473     lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
474     
475     lightSource->addChild(sceneGroup);
476     lightSource->addChild(thesky->getPreRoot());
477     mRoot->addChild(lightSource);
478
479     stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
480     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
481     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
482     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
483
484     // enable disable specular highlights.
485     // is the place where we might plug in an other fragment shader ...
486     osg::LightModel* lightModel = new osg::LightModel;
487     lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
488     stateSet->setAttribute(lightModel);
489
490     // switch to enable wireframe
491     osg::PolygonMode* polygonMode = new osg::PolygonMode;
492     polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
493     stateSet->setAttributeAndModes(polygonMode);
494
495     // scene fog handling
496     osg::Fog* fog = new osg::Fog;
497     fog->setUpdateCallback(new FGFogUpdateCallback);
498     stateSet->setAttributeAndModes(fog);
499     stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
500
501     // plug in the GUI
502     osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
503     if (guiCamera) {
504         osg::Geode* geode = new osg::Geode;
505         geode->addDrawable(new SGPuDrawable);
506         geode->addDrawable(new SGHUDAndPanelDrawable);
507         guiCamera->addChild(geode);
508     }
509     osg::Switch* sw = new osg::Switch;
510     sw->setUpdateCallback(new FGScenerySwitchCallback);
511     sw->addChild(mRoot.get());
512     mRealRoot->addChild(sw);
513     mRealRoot->addChild(thesky->getCloudRoot());
514     mRealRoot->addChild(FGCreateRedoutNode());
515 }
516
517
518 // Update all Visuals (redraws anything graphics related)
519 void
520 FGRenderer::update( bool refresh_camera_settings ) {
521     bool scenery_loaded = fgGetBool("sim/sceneryloaded")
522                           || fgGetBool("sim/sceneryloaded-override");
523     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
524     if ( idle_state < 1000 || !scenery_loaded ) {
525         fgSetDouble("/sim/startup/splash-alpha", 1.0);
526
527         // Keep resetting sim time while the sim is initializing
528         // the splash screen is now in the scenegraph
529         globals->set_sim_time_sec( 0.0 );
530         return;
531     }
532
533     // Fade out the splash screen over the first three seconds.
534     double sAlpha = SGMiscd::max(0, (2.5 - globals->get_sim_time_sec()) / 2.5);
535     fgSetDouble("/sim/startup/splash-alpha", sAlpha);
536
537     bool skyblend = fgGetBool("/sim/rendering/skyblend");
538     bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
539     bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
540     bool distance_attenuation
541         = fgGetBool("/sim/rendering/distance-attenuation");
542     // OSGFIXME
543     SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
544                                   distance_attenuation );
545
546     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
547
548     // update fog params
549     double actual_visibility;
550     if (fgGetBool("/environment/clouds/status")) {
551         actual_visibility = thesky->get_visibility();
552     } else {
553         actual_visibility = fgGetDouble("/environment/visibility-m");
554     }
555
556     // idle_state is now 1000 meaning we've finished all our
557     // initializations and are running the main loop, so this will
558     // now work without seg faulting the system.
559
560     FGViewer *current__view = globals->get_current_view();
561     // Force update of center dependent values ...
562     current__view->set_dirty();
563
564     if ( refresh_camera_settings ) {
565         // update view port
566         resize( fgGetInt("/sim/startup/xsize"),
567                 fgGetInt("/sim/startup/ysize") );
568     }
569     osg::Camera *camera = viewer->getCamera();
570
571     if ( skyblend ) {
572         
573         if ( fgGetBool("/sim/rendering/textures") ) {
574             SGVec4f clearColor(l->adj_fog_color());
575             camera->setClearColor(toOsg(clearColor));
576         }
577     } else {
578         SGVec4f clearColor(l->sky_color());
579         camera->setClearColor(toOsg(clearColor));
580     }
581
582     // update fog params if visibility has changed
583     double visibility_meters = fgGetDouble("/environment/visibility-m");
584     thesky->set_visibility(visibility_meters);
585
586     thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
587                         ( global_multi_loop * fgGetInt("/sim/speed-up") )
588                         / (double)fgGetInt("/sim/model-hz") );
589
590     // update the sky dome
591     if ( skyblend ) {
592
593         // The sun and moon distances are scaled down versions
594         // of the actual distance to get both the moon and the sun
595         // within the range of the far clip plane.
596         // Moon distance:    384,467 kilometers
597         // Sun distance: 150,000,000 kilometers
598
599         double sun_horiz_eff, moon_horiz_eff;
600         if (fgGetBool("/sim/rendering/horizon-effect")) {
601             sun_horiz_eff
602                 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
603                                              0.0),
604                              0.33) / 3.0;
605             moon_horiz_eff
606                 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
607                                              0.0),
608                              0.33)/3.0;
609         } else {
610            sun_horiz_eff = moon_horiz_eff = 1.0;
611         }
612
613         SGSkyState sstate;
614
615         SGVec3d viewPos = current__view->getViewPosition();
616         sstate.view_pos  = toVec3f(viewPos);
617         SGGeod geodViewPos = SGGeod::fromCart(viewPos);
618         SGGeod geodZeroViewPos = SGGeod::fromGeodM(geodViewPos, 0);
619         sstate.zero_elev = toVec3f(SGVec3d::fromGeod(geodZeroViewPos));
620         SGQuatd hlOr = SGQuatd::fromLonLat(geodViewPos);
621         sstate.view_up   = toVec3f(hlOr.backTransform(-SGVec3d::e3()));
622         sstate.lon       = geodViewPos.getLongitudeRad();
623         sstate.lat       = geodViewPos.getLatitudeRad();
624         sstate.alt       = geodViewPos.getElevationM();
625         sstate.spin      = l->get_sun_rotation();
626         sstate.gst       = globals->get_time_params()->getGst();
627         sstate.sun_dist  = 50000.0 * sun_horiz_eff;
628         sstate.moon_dist = 40000.0 * moon_horiz_eff;
629         sstate.sun_angle = l->get_sun_angle();
630
631
632         /*
633          SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
634          << l->sky_color()[0] << " "
635          << l->sky_color()[1] << " "
636          << l->sky_color()[2] << " "
637          << l->sky_color()[3] );
638         SG_LOG( SG_GENERAL, SG_BULK, "    fog = "
639          << l->fog_color()[0] << " "
640          << l->fog_color()[1] << " "
641          << l->fog_color()[2] << " "
642          << l->fog_color()[3] );
643         SG_LOG( SG_GENERAL, SG_BULK,
644                 "    sun_angle = " << l->sun_angle
645          << "    moon_angle = " << l->moon_angle );
646         */
647
648         SGSkyColor scolor;
649
650         scolor.sky_color   = SGVec3f(l->sky_color().data());
651         scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
652         scolor.fog_color   = SGVec3f(l->adj_fog_color().data());
653         scolor.cloud_color = SGVec3f(l->cloud_color().data());
654         scolor.sun_angle   = l->get_sun_angle();
655         scolor.moon_angle  = l->get_moon_angle();
656
657         thesky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
658         thesky->repaint( scolor, *globals->get_ephem() );
659
660         /*
661         SG_LOG( SG_GENERAL, SG_BULK,
662                 "thesky->reposition( view_pos = " << view_pos[0] << " "
663          << view_pos[1] << " " << view_pos[2] );
664         SG_LOG( SG_GENERAL, SG_BULK,
665                 "    zero_elev = " << zero_elev[0] << " "
666          << zero_elev[1] << " " << zero_elev[2]
667          << " lon = " << cur_fdm_state->get_Longitude()
668          << " lat = " << cur_fdm_state->get_Latitude() );
669         SG_LOG( SG_GENERAL, SG_BULK,
670                 "    sun_rot = " << l->get_sun_rotation
671          << " gst = " << SGTime::cur_time_params->getGst() );
672         SG_LOG( SG_GENERAL, SG_BULK,
673              "    sun ra = " << globals->get_ephem()->getSunRightAscension()
674           << " sun dec = " << globals->get_ephem()->getSunDeclination()
675           << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
676           << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
677         */
678
679         //OSGFIXME
680 //         shadows->setupShadows(
681 //           current__view->getLongitude_deg(),
682 //           current__view->getLatitude_deg(),
683 //           globals->get_time_params()->getGst(),
684 //           globals->get_ephem()->getSunRightAscension(),
685 //           globals->get_ephem()->getSunDeclination(),
686 //           l->get_sun_angle());
687
688     }
689
690 //     sgEnviro.setLight(l->adj_fog_color());
691 //     sgEnviro.startOfFrame(current__view->get_view_pos(), 
692 //         current__view->get_world_up(),
693 //         current__view->getLongitude_deg(),
694 //         current__view->getLatitude_deg(),
695 //         current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
696 //         delta_time_sec);
697
698     // OSGFIXME
699 //     sgEnviro.drawLightning();
700
701 //        double current_view_origin_airspeed_horiz_kt =
702 //         fgGetDouble("/velocities/airspeed-kt", 0.0)
703 //                        * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
704 //                                * SGD_DEGREES_TO_RADIANS);
705
706     // OSGFIXME
707 //     if( is_internal )
708 //         shadows->endOfFrame();
709
710     // need to call the update visitor once
711     mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
712     mUpdateVisitor->setViewData(current__view->getViewPosition(),
713                                 current__view->getViewOrientation());
714     SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
715     mUpdateVisitor->setLight(direction, l->scene_ambient(),
716                              l->scene_diffuse(), l->scene_specular(),
717                              l->adj_fog_color(),
718                              l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
719     mUpdateVisitor->setVisibility(actual_visibility);
720     simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
721     bool hotspots = fgGetBool("/sim/panel-hotspots");
722     osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
723     cullMask |= simgear::GroundLightManager::instance()
724         ->getLightNodeMask(mUpdateVisitor.get());
725     if (hotspots)
726         cullMask |= simgear::PICK_BIT;
727     CameraGroup::getDefault()->setCameraCullMasks(cullMask);
728 }
729
730
731
732 // options.cxx needs to see this for toggle_panel()
733 // Handle new window size or exposure
734 void
735 FGRenderer::resize( int width, int height ) {
736     int view_h;
737
738     if ( (!fgGetBool("/sim/virtual-cockpit"))
739          && fgPanelVisible() && idle_state == 1000 ) {
740         view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
741                              globals->get_current_panel()->getYOffset()) / 768.0);
742     } else {
743         view_h = height;
744     }
745
746     static int lastwidth = 0;
747     static int lastheight = 0;
748     if (width != lastwidth)
749         fgSetInt("/sim/startup/xsize", lastwidth = width);
750     if (height != lastheight)
751         fgSetInt("/sim/startup/ysize", lastheight = height);
752
753     // for all views
754     FGViewMgr *viewmgr = globals->get_viewmgr();
755     if (viewmgr) {
756       for ( int i = 0; i < viewmgr->size(); ++i ) {
757         viewmgr->get_view(i)->
758           set_aspect_ratio((float)view_h / (float)width);
759       }
760     }
761 }
762
763 bool
764 FGRenderer::pick(std::vector<SGSceneryPick>& pickList,
765                  const osgGA::GUIEventAdapter* ea)
766 {
767     // wipe out the return ...
768     pickList.clear();
769     typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
770     Intersections intersections;
771
772     if (!computeIntersections(CameraGroup::getDefault(), ea, intersections))
773         return false;
774     for (Intersections::iterator hit = intersections.begin(),
775              e = intersections.end();
776          hit != e;
777          ++hit) {
778         const osg::NodePath& np = hit->nodePath;
779         osg::NodePath::const_reverse_iterator npi;
780         for (npi = np.rbegin(); npi != np.rend(); ++npi) {
781             SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
782             if (!ud)
783                 continue;
784             for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
785                 SGPickCallback* pickCallback = ud->getPickCallback(i);
786                 if (!pickCallback)
787                     continue;
788                 SGSceneryPick sceneryPick;
789                 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
790                 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
791                 sceneryPick.callback = pickCallback;
792                 pickList.push_back(sceneryPick);
793             }
794         }
795     }
796     return !pickList.empty();
797 }
798
799 void
800 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
801 {
802     viewer = viewer_;
803 }
804
805 void
806 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
807 {
808     eventHandler = eventHandler_;
809 }
810
811 void
812 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
813 {
814     mRealRoot->addChild(camera);
815 }
816
817 bool
818 fgDumpSceneGraphToFile(const char* filename)
819 {
820     return osgDB::writeNodeFile(*mRealRoot.get(), filename);
821 }
822
823 bool
824 fgDumpTerrainBranchToFile(const char* filename)
825 {
826     return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
827                                  filename );
828 }
829
830 // For debugging
831 bool
832 fgDumpNodeToFile(osg::Node* node, const char* filename)
833 {
834     return osgDB::writeNodeFile(*node, filename);
835 }
836 // end of renderer.cxx
837