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