]> git.mxchange.org Git - flightgear.git/blob - src/Main/renderer.cxx
header cleanups
[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 #include <osg/ref_ptr>
29 #include <osg/AlphaFunc>
30 #include <osg/BlendFunc>
31 #include <osg/Camera>
32 #include <osg/CullFace>
33 #include <osg/Depth>
34 #include <osg/Fog>
35 #include <osg/Group>
36 #include <osg/Hint>
37 #include <osg/Light>
38 #include <osg/LightModel>
39 #include <osg/LightSource>
40 #include <osg/NodeCallback>
41 #include <osg/Notify>
42 #include <osg/PolygonMode>
43 #include <osg/PolygonOffset>
44 #include <osg/ShadeModel>
45 #include <osg/Version>
46 #include <osg/TexEnv>
47
48 #include <osgUtil/SceneView>
49 #include <osgUtil/UpdateVisitor>
50 #include <osgUtil/IntersectVisitor>
51 #include <osgUtil/LineSegmentIntersector>
52
53 #include <osg/io_utils>
54 #include <osgDB/WriteFile>
55 #include <osgDB/ReadFile>
56 #include <sstream>
57
58 #include <simgear/math/SGMath.hxx>
59 #include <simgear/screen/extensions.hxx>
60 #include <simgear/scene/material/matlib.hxx>
61 #include <simgear/scene/model/animation.hxx>
62 #include <simgear/scene/model/placement.hxx>
63 #include <simgear/scene/util/SGUpdateVisitor.hxx>
64 #include <simgear/scene/util/RenderConstants.hxx>
65 #include <simgear/scene/tgdb/GroundLightManager.hxx>
66 #include <simgear/scene/tgdb/pt_lights.hxx>
67 #include <simgear/props/props.hxx>
68 #include <simgear/timing/sg_time.hxx>
69 #include <simgear/ephemeris/ephemeris.hxx>
70 #include <simgear/math/sg_random.h>
71 #ifdef FG_JPEG_SERVER
72 #include <simgear/screen/jpgfactory.hxx>
73 #endif
74
75 #include <simgear/environment/visual_enviro.hxx>
76
77 #include <Time/light.hxx>
78 #include <Time/light.hxx>
79 #include <Aircraft/aircraft.hxx>
80 #include <Cockpit/panel.hxx>
81 #include <Cockpit/cockpit.hxx>
82 #include <Cockpit/hud.hxx>
83 #include <Model/panelnode.hxx>
84 #include <Model/modelmgr.hxx>
85 #include <Model/acmodel.hxx>
86 #include <Scenery/scenery.hxx>
87 #include <Scenery/redout.hxx>
88 #include <Scenery/tilemgr.hxx>
89 #include <GUI/new_gui.hxx>
90 #include <Instrumentation/instrument_mgr.hxx>
91 #include <Instrumentation/HUD/HUD.hxx>
92 #include <Environment/precipitation_mgr.hxx>
93
94 #include <Include/general.hxx>
95 #include "splash.hxx"
96 #include "renderer.hxx"
97 #include "main.hxx"
98 #include "ViewPartitionNode.hxx"
99
100 // XXX Make this go away when OSG 2.2 is released.
101 #if (FG_OSG_VERSION >= 21004)
102 #define UPDATE_VISITOR_IN_VIEWER 1
103 #endif
104
105 class FGHintUpdateCallback : public osg::StateAttribute::Callback {
106 public:
107   FGHintUpdateCallback(const char* configNode) :
108     mConfigNode(fgGetNode(configNode, true))
109   { }
110   virtual void operator()(osg::StateAttribute* stateAttribute,
111                           osg::NodeVisitor*)
112   {
113     assert(dynamic_cast<osg::Hint*>(stateAttribute));
114     osg::Hint* hint = static_cast<osg::Hint*>(stateAttribute);
115
116     const char* value = mConfigNode->getStringValue();
117     if (!value)
118       hint->setMode(GL_DONT_CARE);
119     else if (0 == strcmp(value, "nicest"))
120       hint->setMode(GL_NICEST);
121     else if (0 == strcmp(value, "fastest"))
122       hint->setMode(GL_FASTEST);
123     else
124       hint->setMode(GL_DONT_CARE);
125   }
126 private:
127   SGSharedPtr<SGPropertyNode> mConfigNode;
128 };
129
130
131 class SGPuDrawable : public osg::Drawable {
132 public:
133   SGPuDrawable()
134   {
135     // Dynamic stuff, do not store geometry
136     setUseDisplayList(false);
137
138     osg::StateSet* stateSet = getOrCreateStateSet();
139     stateSet->setRenderBinDetails(1001, "RenderBin");
140     // speed optimization?
141     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
142     // We can do translucent menus, so why not. :-)
143     stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
144     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
145     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
146
147     stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
148
149     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
150     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
151   }
152   virtual void drawImplementation(osg::RenderInfo& renderInfo) const
153   { drawImplementation(*renderInfo.getState()); }
154   void drawImplementation(osg::State& state) const
155   {
156     if (!fgOSIsMainContext(state.getGraphicsContext()))
157       return;
158     state.setActiveTextureUnit(0);
159     state.setClientActiveTextureUnit(0);
160
161     state.disableAllVertexArrays();
162
163     glPushAttrib(GL_ALL_ATTRIB_BITS);
164     glPushClientAttrib(~0u);
165
166     puDisplay();
167
168     glPopClientAttrib();
169     glPopAttrib();
170   }
171
172   virtual osg::Object* cloneType() const { return new SGPuDrawable; }
173   virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
174   
175 private:
176 };
177
178 class SGHUDAndPanelDrawable : public osg::Drawable {
179 public:
180   SGHUDAndPanelDrawable()
181   {
182     // Dynamic stuff, do not store geometry
183     setUseDisplayList(false);
184
185     osg::StateSet* stateSet = getOrCreateStateSet();
186     stateSet->setRenderBinDetails(1000, "RenderBin");
187
188     // speed optimization?
189     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
190     stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
191     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
192     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
193     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
194
195     stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
196   }
197   virtual void drawImplementation(osg::RenderInfo& renderInfo) const
198   { drawImplementation(*renderInfo.getState()); }
199   void drawImplementation(osg::State& state) const
200   {
201     if (!fgOSIsMainContext(state.getGraphicsContext()))
202       return;
203     state.setActiveTextureUnit(0);
204     state.setClientActiveTextureUnit(0);
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
228   virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
229   virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
230   
231 private:
232 };
233
234 class FGLightSourceUpdateCallback : public osg::NodeCallback {
235 public:
236   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
237   {
238     assert(dynamic_cast<osg::LightSource*>(node));
239     osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
240     osg::Light* light = lightSource->getLight();
241     
242     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
243     light->setAmbient(l->scene_ambient().osg());
244     light->setDiffuse(l->scene_diffuse().osg());
245     light->setSpecular(l->scene_specular().osg());
246     SGVec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
247     light->setPosition(position.osg());
248     SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
249     light->setDirection(direction.osg());
250     light->setSpotExponent(0);
251     light->setSpotCutoff(180);
252     light->setConstantAttenuation(1);
253     light->setLinearAttenuation(0);
254     light->setQuadraticAttenuation(0);
255
256     traverse(node, nv);
257   }
258 };
259
260 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
261 public:
262   FGWireFrameModeUpdateCallback() :
263     mWireframe(fgGetNode("/sim/rendering/wireframe"))
264   { }
265   virtual void operator()(osg::StateAttribute* stateAttribute,
266                           osg::NodeVisitor*)
267   {
268     assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
269     osg::PolygonMode* polygonMode;
270     polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
271
272     if (mWireframe->getBoolValue())
273       polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
274                            osg::PolygonMode::LINE);
275     else
276       polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
277                            osg::PolygonMode::FILL);
278   }
279 private:
280   SGSharedPtr<SGPropertyNode> mWireframe;
281 };
282
283 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
284 public:
285   FGLightModelUpdateCallback() :
286     mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
287   { }
288   virtual void operator()(osg::StateAttribute* stateAttribute,
289                           osg::NodeVisitor*)
290   {
291     assert(dynamic_cast<osg::LightModel*>(stateAttribute));
292     osg::LightModel* lightModel;
293     lightModel = static_cast<osg::LightModel*>(stateAttribute);
294
295 #if 0
296     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
297     lightModel->setAmbientIntensity(l->scene_ambient().osg());
298 #else
299     lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
300 #endif
301     lightModel->setTwoSided(true);
302     lightModel->setLocalViewer(false);
303
304     if (mHighlights->getBoolValue()) {
305       lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
306     } else {
307       lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
308     }
309   }
310 private:
311   SGSharedPtr<SGPropertyNode> mHighlights;
312 };
313
314 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
315 public:
316   FGFogEnableUpdateCallback() :
317     mFogEnabled(fgGetNode("/sim/rendering/fog"))
318   { }
319   virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
320   {
321     if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
322       stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
323     } else {
324       stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
325     }
326   }
327 private:
328   SGSharedPtr<SGPropertyNode> mFogEnabled;
329 };
330
331 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
332 public:
333   virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
334   {
335     assert(dynamic_cast<SGUpdateVisitor*>(nv));
336     assert(dynamic_cast<osg::Fog*>(sa));
337     SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
338     osg::Fog* fog = static_cast<osg::Fog*>(sa);
339     fog->setMode(osg::Fog::EXP2);
340     fog->setColor(updateVisitor->getFogColor().osg());
341     fog->setDensity(updateVisitor->getFogExp2Density());
342   }
343 };
344
345 // update callback for the switch node guarding that splash
346 class FGScenerySwitchCallback : public osg::NodeCallback {
347 public:
348   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
349   {
350     assert(dynamic_cast<osg::Switch*>(node));
351     osg::Switch* sw = static_cast<osg::Switch*>(node);
352
353     double t = globals->get_sim_time_sec();
354     bool enabled = 0 < t;
355     sw->setValue(0, enabled);
356     if (!enabled)
357       return;
358     traverse(node, nv);
359   }
360 };
361
362 // Sky structures
363 SGSky *thesky;
364
365 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
366 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
367
368 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
369
370 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
371
372 static osg::ref_ptr<ViewPartitionNode> viewPartition = new ViewPartitionNode;
373
374 FGRenderer::FGRenderer()
375 {
376 #ifdef FG_JPEG_SERVER
377    jpgRenderFrame = FGRenderer::update;
378 #endif
379    manipulator = new FGManipulator;
380 }
381
382 FGRenderer::~FGRenderer()
383 {
384 #ifdef FG_JPEG_SERVER
385    jpgRenderFrame = NULL;
386 #endif
387 }
388
389 // Initialize various GL/view parameters
390 // XXX This should be called "preinit" or something, as it initializes
391 // critical parts of the scene graph in addition to the splash screen.
392 void
393 FGRenderer::splashinit( void ) {
394     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
395     mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
396     mRealRoot->addChild(fgCreateSplashNode());
397     mFrameStamp = viewer->getFrameStamp();
398     // Scene doesn't seem to pass the frame stamp to the update
399     // visitor automatically.
400     mUpdateVisitor->setFrameStamp(mFrameStamp.get());
401 #ifdef UPDATE_VISITOR_IN_VIEWER
402     viewer->setUpdateVisitor(mUpdateVisitor.get());
403 #else
404     osgViewer::Scene* scene = viewer->getScene();
405     scene->setUpdateVisitor(mUpdateVisitor.get());
406 #endif
407 }
408
409 namespace
410 {
411 // Create a slave camera that will be used to render a fixed GUI-like
412 // element.
413 osg::Camera*
414 makeSlaveCamera(osg::Camera::RenderOrder renderOrder, int orderNum)
415 {
416     using namespace osg;
417     Camera* camera = new osg::Camera;
418     GraphicsContext *gc = fgOSGetMainContext();
419     
420     camera->setRenderOrder(renderOrder, orderNum);
421     camera->setClearMask(0);
422     camera->setInheritanceMask(CullSettings::ALL_VARIABLES
423                                & ~(CullSettings::COMPUTE_NEAR_FAR_MODE
424                                    | CullSettings::CULLING_MODE));
425     camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
426     camera->setCullingMode(osg::CullSettings::NO_CULLING);
427     camera->setGraphicsContext(gc);
428     // Establish an initial viewport. This may be altered,
429     // particularly when drawing a 2d panel.
430     const GraphicsContext::Traits *traits = gc->getTraits();
431     camera->setViewport(new Viewport(0, 0, traits->width, traits->height));
432     camera->setProjectionResizePolicy(Camera::FIXED);
433     camera->setReferenceFrame(Transform::ABSOLUTE_RF);
434     camera->setAllowEventFocus(false);
435     globals->get_renderer()->getViewer()->addSlave(camera, false);
436     return camera;
437 }
438
439 }
440
441 void
442 FGRenderer::init( void )
443 {
444     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
445     osg::initNotifyLevel();
446
447     // The number of polygon-offset "units" to place between layers.  In
448     // principle, one is supposed to be enough.  In practice, I find that
449     // my hardware/driver requires many more.
450     osg::PolygonOffset::setUnitsMultiplier(1);
451     osg::PolygonOffset::setFactorMultiplier(1);
452
453     // Go full screen if requested ...
454     if ( fgGetBool("/sim/startup/fullscreen") )
455         fgOSFullScreen();
456
457     viewer->getCamera()
458         ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
459     
460     osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
461
462     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
463     
464     stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
465     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
466
467     stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
468     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
469     stateSet->setAttribute(new osg::BlendFunc);
470     stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
471
472     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
473     
474     // this will be set below
475     stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
476
477     osg::Material* material = new osg::Material;
478     stateSet->setAttribute(material);
479     
480     stateSet->setTextureAttribute(0, new osg::TexEnv);
481     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
482
483     osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
484     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
485     stateSet->setAttribute(hint);
486     hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
487     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
488     stateSet->setAttribute(hint);
489     hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
490     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
491     stateSet->setAttribute(hint);
492     hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
493     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
494     stateSet->setAttribute(hint);
495     hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
496     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
497     stateSet->setAttribute(hint);
498
499     osg::Group* sceneGroup = new osg::Group;
500     sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
501     sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
502
503     //sceneGroup->addChild(thesky->getCloudRoot());
504
505     stateSet = sceneGroup->getOrCreateStateSet();
506     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
507     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
508
509     // need to update the light on every frame
510     osg::LightSource* lightSource = new osg::LightSource;
511     lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
512     // relative because of CameraView being just a clever transform node
513     lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
514     lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
515     
516     lightSource->addChild(sceneGroup);
517     lightSource->addChild(thesky->getPreRoot());
518     mRoot->addChild(lightSource);
519
520     stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
521     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
522     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
523     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
524     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
525
526     // enable disable specular highlights.
527     // is the place where we might plug in an other fragment shader ...
528     osg::LightModel* lightModel = new osg::LightModel;
529     lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
530     stateSet->setAttribute(lightModel);
531
532     // switch to enable wireframe
533     osg::PolygonMode* polygonMode = new osg::PolygonMode;
534     polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
535     stateSet->setAttributeAndModes(polygonMode);
536
537     // scene fog handling
538     osg::Fog* fog = new osg::Fog;
539     fog->setUpdateCallback(new FGFogUpdateCallback);
540     stateSet->setAttributeAndModes(fog);
541     stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
542
543     // plug in the GUI
544     osg::Camera* guiCamera = makeSlaveCamera(osg::Camera::POST_RENDER, 100);
545     guiCamera->setName("GUI");
546     osg::Geode* geode = new osg::Geode;
547     geode->addDrawable(new SGPuDrawable);
548     geode->addDrawable(new SGHUDAndPanelDrawable);
549     guiCamera->addChild(geode);
550
551     osg::Switch* sw = new osg::Switch;
552     sw->setUpdateCallback(new FGScenerySwitchCallback);
553     sw->addChild(mRoot.get());
554     viewPartition->addChild(sw);
555     viewPartition->addChild(thesky->getCloudRoot());
556
557     mRealRoot->addChild(viewPartition.get());
558     mRealRoot->addChild(FGCreateRedoutNode());
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     // for all views
833     FGViewMgr *viewmgr = globals->get_viewmgr();
834     if (viewmgr) {
835       for ( int i = 0; i < viewmgr->size(); ++i ) {
836         viewmgr->get_view(i)->
837           set_aspect_ratio((float)view_h / (float)width);
838       }
839     }
840 }
841
842 void FGRenderer::setCameraParameters(float vfov, float aspectRatio,
843                                      float zNear, float zFar)
844 {
845     zNear = .1;
846     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
847     viewer->getCamera()->setProjectionMatrixAsPerspective(vfov,
848                                                           1.0f / aspectRatio,
849                                                           zNear, zFar);
850     
851 }
852 bool
853 FGRenderer::pick( unsigned x, unsigned y,
854                   std::vector<SGSceneryPick>& pickList,
855                   const osgGA::GUIEventAdapter* ea )
856 {
857   osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
858   // wipe out the return ...
859   pickList.resize(0);
860
861   if (viewer) {
862     // just compute intersections in the viewers method ...
863     typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
864     Intersections intersections;
865     viewer->computeIntersections(ea->getX(), ea->getY(), intersections);
866
867     Intersections::iterator hit;
868     for (hit = intersections.begin(); hit != intersections.end(); ++hit) {
869       const osg::NodePath& np = hit->nodePath;
870       osg::NodePath::const_reverse_iterator npi;
871       for (npi = np.rbegin(); npi != np.rend(); ++npi) {
872         SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
873         if (!ud)
874           continue;
875         for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
876           SGPickCallback* pickCallback = ud->getPickCallback(i);
877           if (!pickCallback)
878             continue;
879           SGSceneryPick sceneryPick;
880           sceneryPick.info.local = SGVec3d(hit->getLocalIntersectPoint());
881           sceneryPick.info.wgs84 = SGVec3d(hit->getWorldIntersectPoint());
882           sceneryPick.callback = pickCallback;
883           pickList.push_back(sceneryPick);
884         }
885       }
886     }
887     return !pickList.empty();
888   } else {                      // we can get called early ...
889     return false;
890   }
891 }
892
893 void
894 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
895 {
896     mRealRoot->addChild(camera);
897 }
898
899 bool
900 fgDumpSceneGraphToFile(const char* filename)
901 {
902     return osgDB::writeNodeFile(*mRealRoot.get(), filename);
903 }
904
905 bool
906 fgDumpTerrainBranchToFile(const char* filename)
907 {
908     return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
909                                  filename );
910 }
911
912 // For debugging
913 bool
914 fgDumpNodeToFile(osg::Node* node, const char* filename)
915 {
916     return osgDB::writeNodeFile(*node, filename);
917 }
918 // end of renderer.cxx
919