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