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