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