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