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