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