]> git.mxchange.org Git - flightgear.git/blob - src/Main/renderer.cxx
Clean up scenery center handling. It is set now less often.
[flightgear.git] / src / Main / renderer.cxx
1 // renderer.cxx -- top level sim routines
2 //
3 // Written by Curtis Olson, started May 1997.
4 // This file contains parts of main.cxx prior to october 2004
5 //
6 // Copyright (C) 1997 - 2002  Curtis L. Olson  - http://www.flightgear.org/~curt
7 //
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 //
22 // $Id$
23
24
25 #ifdef HAVE_CONFIG_H
26 #  include <config.h>
27 #endif
28
29 #include <simgear/compiler.h>
30
31 #ifdef HAVE_WINDOWS_H
32 #  include <windows.h>
33 #endif
34
35 #include <plib/ssg.h>
36 #include <plib/netSocket.h>
37
38 #include <simgear/screen/extensions.hxx>
39 #include <simgear/scene/material/matlib.hxx>
40 #include <simgear/scene/model/animation.hxx>
41 #include <simgear/scene/model/model.hxx>
42 #include <simgear/scene/model/modellib.hxx>
43 #include <simgear/scene/model/placement.hxx>
44 #include <simgear/scene/tgdb/pt_lights.hxx>
45 #include <simgear/props/props.hxx>
46 #include <simgear/timing/sg_time.hxx>
47 #include <simgear/ephemeris/ephemeris.hxx>
48 #include <simgear/math/sg_random.h>
49 #ifdef FG_JPEG_SERVER
50 #include <simgear/screen/jpgfactory.hxx>
51 #endif
52
53 #include <simgear/environment/visual_enviro.hxx>
54
55 #include <simgear/scene/model/shadowvolume.hxx>
56
57 #include <Scenery/tileentry.hxx>
58 #include <Time/light.hxx>
59 #include <Time/light.hxx>
60 #include <Aircraft/aircraft.hxx>
61 // #include <Aircraft/replay.hxx>
62 #include <Cockpit/panel.hxx>
63 #include <Cockpit/cockpit.hxx>
64 #include <Cockpit/hud.hxx>
65 #include <Model/panelnode.hxx>
66 #include <Model/modelmgr.hxx>
67 #include <Model/acmodel.hxx>
68 #include <Scenery/scenery.hxx>
69 #include <Scenery/tilemgr.hxx>
70 #include <ATC/ATCdisplay.hxx>
71 #include <GUI/new_gui.hxx>
72 #include <Instrumentation/instrument_mgr.hxx>
73 #include <Instrumentation/HUD/HUD.hxx>
74
75 #include "splash.hxx"
76 #include "renderer.hxx"
77 #include "main.hxx"
78
79
80 extern void sgShaderFrameInit(double delta_time_sec);
81
82 float default_attenuation[3] = {1.0, 0.0, 0.0};
83
84 // Clip plane settings...
85 float scene_nearplane = 0.5f;
86 float scene_farplane = 120000.0f;
87
88 glPointParameterfProc glPointParameterfPtr = 0;
89 glPointParameterfvProc glPointParameterfvPtr = 0;
90 bool glPointParameterIsSupported = false;
91 bool glPointSpriteIsSupported = false;
92
93
94 // fog constants.  I'm a little nervous about putting actual code out
95 // here but it seems to work (?)
96 static const double m_log01 = -log( 0.01 );
97 static const double sqrt_m_log01 = sqrt( m_log01 );
98 static GLfloat fog_exp_density;
99 static GLfloat fog_exp2_density;
100 static GLfloat rwy_exp2_punch_through;
101 static GLfloat taxi_exp2_punch_through;
102 static GLfloat ground_exp2_punch_through;
103
104 // Sky structures
105 SGSky *thesky;
106
107 ssgSharedPtr<ssgSimpleState> default_state;
108 ssgSharedPtr<ssgSimpleState> hud_and_panel;
109 ssgSharedPtr<ssgSimpleState> menus;
110
111 SGShadowVolume *shadows;
112
113 FGRenderer::FGRenderer()
114 {
115 #ifdef FG_JPEG_SERVER
116    jpgRenderFrame = FGRenderer::update;
117 #endif
118 }
119
120 FGRenderer::~FGRenderer()
121 {
122 #ifdef FG_JPEG_SERVER
123    jpgRenderFrame = NULL;
124 #endif
125 }
126
127
128 void
129 FGRenderer::build_states( void ) {
130     default_state = new ssgSimpleState;
131     default_state->disable( GL_TEXTURE_2D );
132     default_state->enable( GL_CULL_FACE );
133     default_state->enable( GL_COLOR_MATERIAL );
134     default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
135     default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
136     default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
137     default_state->disable( GL_BLEND );
138     default_state->disable( GL_ALPHA_TEST );
139     default_state->disable( GL_LIGHTING );
140
141     hud_and_panel = new ssgSimpleState;
142     hud_and_panel->disable( GL_CULL_FACE );
143     hud_and_panel->disable( GL_TEXTURE_2D );
144     hud_and_panel->disable( GL_LIGHTING );
145     hud_and_panel->enable( GL_BLEND );
146
147     menus = new ssgSimpleState;
148     menus->disable( GL_CULL_FACE );
149     menus->disable( GL_TEXTURE_2D );
150     menus->enable( GL_BLEND );
151
152     shadows = new SGShadowVolume( globals->get_scenery()->get_scene_graph() );
153     shadows->init( fgGetNode("/sim/rendering", true) );
154     shadows->addOccluder( globals->get_scenery()->get_aircraft_branch(), SGShadowVolume::occluderTypeAircraft );
155
156 }
157
158
159 // Initialize various GL/view parameters
160 void
161 FGRenderer::init( void ) {
162
163     FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
164
165     // Go full screen if requested ...
166     if ( fgGetBool("/sim/startup/fullscreen") ) {
167         fgOSFullScreen();
168     }
169
170     // If enabled, normal vectors specified with glNormal are scaled
171     // to unit length after transformation.  Enabling this has
172     // performance implications.  See the docs for glNormal.
173     // glEnable( GL_NORMALIZE );
174
175     glEnable( GL_LIGHTING );
176     glEnable( GL_LIGHT0 );
177     // glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );  // done later with ssg
178
179     sgVec3 sunpos;
180     sgSetVec3( sunpos, l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2] );
181     ssgGetLight( 0 ) -> setPosition( sunpos );
182
183     glFogi (GL_FOG_MODE, GL_EXP2);
184     if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) || 
185          (!fgGetBool("/sim/rendering/shading"))) {
186         // if fastest fog requested, or if flat shading force fastest
187         glHint ( GL_FOG_HINT, GL_FASTEST );
188     } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
189         glHint ( GL_FOG_HINT, GL_DONT_CARE );
190     }
191     if ( fgGetBool("/sim/rendering/wireframe") ) {
192         // draw wire frame
193         glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
194     }
195
196     // This is the default anyways, but it can't hurt
197     glFrontFace ( GL_CCW );
198
199     // Just testing ...
200     if ( SGIsOpenGLExtensionSupported("GL_ARB_point_sprite") ||
201          SGIsOpenGLExtensionSupported("GL_NV_point_sprite") )
202     {
203         GLuint handle = thesky->get_sun_texture_id();
204         glBindTexture ( GL_TEXTURE_2D, handle ) ;
205         glTexEnvf(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
206         glEnable(GL_POINT_SPRITE);
207         // glEnable(GL_POINT_SMOOTH);
208         glPointSpriteIsSupported = true;
209     }
210     glEnable(GL_LINE_SMOOTH);
211     // glEnable(GL_POLYGON_SMOOTH);      
212     glHint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
213     glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
214     glHint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
215 }
216
217
218
219 // Update all Visuals (redraws anything graphics related)
220 void
221 FGRenderer::update( bool refresh_camera_settings ) {
222     bool scenery_loaded = fgGetBool("sim/sceneryloaded") \
223                           || fgGetBool("sim/sceneryloaded-override");
224
225     if ( idle_state < 1000 || !scenery_loaded ) {
226         // still initializing, draw the splash screen
227         fgSplashUpdate(1.0);
228
229         // Keep resetting sim time while the sim is initializing
230         globals->set_sim_time_sec( 0.0 );
231         SGAnimation::set_sim_time_sec( 0.0 );
232         return;
233     }
234
235     // Let the scenery center follow the current view position with
236     // 30m increments.
237     //
238     // Having the scenery center near the view position will eliminate
239     // jitter of objects which are placed very near the view position
240     // and haveing it's center near that view position.
241     // So the 3d insruments of the aircraft will not jitter with this.
242     // 
243     // Following the view position exactly would introduce jitter of
244     // the scenery tiles (they would be from their center up to 10000m
245     // to the view and this will introduce roundoff too). By stepping
246     // at 30m incements the roundoff error of the scenery tiles is
247     // still present, but we will make exactly the same roundoff error
248     // at each frame until the center is switched to a new
249     // position. This roundoff is still visible but you will most
250     // propably not notice.
251     double *vp = globals->get_current_view()->get_absolute_view_pos();
252     SGVec3d cntr(vp);
253     if (30.0*30.0 < distSqr(cntr, globals->get_scenery()->get_center()))
254       globals->get_scenery()->set_center( cntr );
255
256     bool draw_otw = fgGetBool("/sim/rendering/draw-otw");
257     bool skyblend = fgGetBool("/sim/rendering/skyblend");
258     bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
259     bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
260     bool distance_attenuation
261         = fgGetBool("/sim/rendering/distance-attenuation");
262     sgConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
263                                   distance_attenuation );
264     bool volumetric_clouds = sgEnviro.get_clouds_enable_state();
265 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
266     bool multi_pass_clouds = fgGetBool("/sim/rendering/multi-pass-clouds") && 
267                                 !volumetric_clouds &&
268                                 !SGCloudLayer::enable_bump_mapping;  // ugly artefact now
269 #else
270     bool multi_pass_clouds = false;
271 #endif
272     bool draw_clouds = fgGetBool("/environment/clouds/status");
273
274     GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
275     GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
276
277     // static const SGPropertyNode *longitude
278     //     = fgGetNode("/position/longitude-deg");
279     // static const SGPropertyNode *latitude
280     //     = fgGetNode("/position/latitude-deg");
281     // static const SGPropertyNode *altitude
282     //     = fgGetNode("/position/altitude-ft");
283     static const SGPropertyNode *groundlevel_nearplane
284         = fgGetNode("/sim/current-view/ground-level-nearplane-m");
285
286     FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
287     static double last_visibility = -9999;
288
289     // update fog params
290     double actual_visibility;
291     if (fgGetBool("/environment/clouds/status")) {
292         actual_visibility = thesky->get_visibility();
293     } else {
294         actual_visibility = fgGetDouble("/environment/visibility-m");
295     }
296
297         // TODO:TEST only, don't commit that !!
298 //      sgFXperFrameInit();
299
300     sgShaderFrameInit(delta_time_sec);
301
302     if ( actual_visibility != last_visibility ) {
303         last_visibility = actual_visibility;
304
305         fog_exp_density = m_log01 / actual_visibility;
306         fog_exp2_density = sqrt_m_log01 / actual_visibility;
307         ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
308         if ( actual_visibility < 8000 ) {
309             rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
310             taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
311         } else {
312             rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
313             taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
314         }
315     }
316
317     // double angle;
318     // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
319     // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
320     // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
321     // GLfloat mat_shininess[] = { 10.0 };
322     GLbitfield clear_mask;
323
324     // idle_state is now 1000 meaning we've finished all our
325     // initializations and are running the main loop, so this will
326     // now work without seg faulting the system.
327
328     FGViewer *current__view = globals->get_current_view();
329     // Force update of center dependent values ...
330     current__view->set_dirty();
331
332     if ( refresh_camera_settings ) {
333         // update view port
334         resize( fgGetInt("/sim/startup/xsize"),
335                 fgGetInt("/sim/startup/ysize") );
336
337         // Tell GL we are switching to model view parameters
338         glMatrixMode(GL_MODELVIEW);
339         glLoadIdentity();
340         ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
341     }
342
343     clear_mask = GL_DEPTH_BUFFER_BIT;
344     if ( fgGetBool("/sim/rendering/wireframe") ) {
345         clear_mask |= GL_COLOR_BUFFER_BIT;
346     }
347
348     if ( skyblend ) {
349         if ( fgGetBool("/sim/rendering/textures") ) {
350         // glClearColor(black[0], black[1], black[2], black[3]);
351         glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
352                      l->adj_fog_color()[2], l->adj_fog_color()[3]);
353         clear_mask |= GL_COLOR_BUFFER_BIT;
354         }
355     } else {
356         glClearColor(l->sky_color()[0], l->sky_color()[1],
357                      l->sky_color()[2], l->sky_color()[3]);
358         clear_mask |= GL_COLOR_BUFFER_BIT;
359     }
360     if ( multi_pass_clouds && draw_clouds ) {
361         glClearStencil( 0 );
362         clear_mask |= GL_STENCIL_BUFFER_BIT;
363     }
364     glClear( clear_mask );
365
366     // set the opengl state to known default values
367     default_state->force();
368
369     // update fog params if visibility has changed
370     double visibility_meters = fgGetDouble("/environment/visibility-m");
371     thesky->set_visibility(visibility_meters);
372
373     thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
374                         ( global_multi_loop * fgGetInt("/sim/speed-up") )
375                         / (double)fgGetInt("/sim/model-hz") );
376
377     // Set correct opengl fog density
378     glFogf (GL_FOG_DENSITY, fog_exp2_density);
379
380     // update the sky dome
381     if ( skyblend ) {
382
383         // The sun and moon distances are scaled down versions
384         // of the actual distance to get both the moon and the sun
385         // within the range of the far clip plane.
386         // Moon distance:    384,467 kilometers
387         // Sun distance: 150,000,000 kilometers
388
389         double sun_horiz_eff, moon_horiz_eff;
390         if (fgGetBool("/sim/rendering/horizon-effect")) {
391            sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
392            moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
393         } else {
394            sun_horiz_eff = moon_horiz_eff = 1.0;
395         }
396
397         static SGSkyState sstate;
398
399         sstate.view_pos  = current__view->get_view_pos();
400         sstate.zero_elev = current__view->get_zero_elev();
401         sstate.view_up   = current__view->get_world_up();
402         sstate.lon       = current__view->getLongitude_deg()
403                             * SGD_DEGREES_TO_RADIANS;
404         sstate.lat       = current__view->getLatitude_deg()
405                             * SGD_DEGREES_TO_RADIANS;
406         sstate.alt       = current__view->getAltitudeASL_ft()
407                             * SG_FEET_TO_METER;
408         sstate.spin      = l->get_sun_rotation();
409         sstate.gst       = globals->get_time_params()->getGst();
410         sstate.sun_ra    = globals->get_ephem()->getSunRightAscension();
411         sstate.sun_dec   = globals->get_ephem()->getSunDeclination();
412         sstate.sun_dist  = 50000.0 * sun_horiz_eff;
413         sstate.moon_ra   = globals->get_ephem()->getMoonRightAscension();
414         sstate.moon_dec  = globals->get_ephem()->getMoonDeclination();
415         sstate.moon_dist = 40000.0 * moon_horiz_eff;
416         sstate.sun_angle = l->get_sun_angle();
417
418
419         /*
420          SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
421          << l->sky_color()[0] << " "
422          << l->sky_color()[1] << " "
423          << l->sky_color()[2] << " "
424          << l->sky_color()[3] );
425         SG_LOG( SG_GENERAL, SG_BULK, "    fog = "
426          << l->fog_color()[0] << " "
427          << l->fog_color()[1] << " "
428          << l->fog_color()[2] << " "
429          << l->fog_color()[3] );
430         SG_LOG( SG_GENERAL, SG_BULK,
431                 "    sun_angle = " << l->sun_angle
432          << "    moon_angle = " << l->moon_angle );
433         */
434
435         static SGSkyColor scolor;
436 //        FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
437
438         scolor.sky_color   = l->sky_color();
439         scolor.fog_color   = l->adj_fog_color();
440         scolor.cloud_color = l->cloud_color();
441         scolor.sun_angle   = l->get_sun_angle();
442         scolor.moon_angle  = l->get_moon_angle();
443         scolor.nplanets    = globals->get_ephem()->getNumPlanets();
444         scolor.nstars      = globals->get_ephem()->getNumStars();
445         scolor.planet_data = globals->get_ephem()->getPlanets();
446         scolor.star_data   = globals->get_ephem()->getStars();
447
448         thesky->reposition( sstate, delta_time_sec );
449         thesky->repaint( scolor );
450
451         /*
452         SG_LOG( SG_GENERAL, SG_BULK,
453                 "thesky->reposition( view_pos = " << view_pos[0] << " "
454          << view_pos[1] << " " << view_pos[2] );
455         SG_LOG( SG_GENERAL, SG_BULK,
456                 "    zero_elev = " << zero_elev[0] << " "
457          << zero_elev[1] << " " << zero_elev[2]
458          << " lon = " << cur_fdm_state->get_Longitude()
459          << " lat = " << cur_fdm_state->get_Latitude() );
460         SG_LOG( SG_GENERAL, SG_BULK,
461                 "    sun_rot = " << l->get_sun_rotation
462          << " gst = " << SGTime::cur_time_params->getGst() );
463         SG_LOG( SG_GENERAL, SG_BULK,
464              "    sun ra = " << globals->get_ephem()->getSunRightAscension()
465           << " sun dec = " << globals->get_ephem()->getSunDeclination()
466           << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
467           << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
468         */
469
470         shadows->setupShadows(
471           current__view->getLongitude_deg(),
472           current__view->getLatitude_deg(),
473           globals->get_time_params()->getGst(),
474           globals->get_ephem()->getSunRightAscension(),
475           globals->get_ephem()->getSunDeclination(),
476           l->get_sun_angle());
477
478     }
479
480     glEnable( GL_DEPTH_TEST );
481     if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
482         glEnable( GL_FOG );
483         glFogi( GL_FOG_MODE, GL_EXP2 );
484         glFogfv( GL_FOG_COLOR, l->adj_fog_color() );
485     } else
486         glDisable( GL_FOG ); 
487
488     // set sun/lighting parameters
489     ssgGetLight( 0 ) -> setPosition( l->sun_vec() );
490
491     // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
492     // we only update GL_AMBIENT for our lights we will never get
493     // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
494     // explicitely to black.
495     glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
496
497     ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
498     ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
499     ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular() );
500
501     sgEnviro.setLight(l->adj_fog_color());
502
503     // texture parameters
504     // glEnable( GL_TEXTURE_2D );
505     glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
506     glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
507
508     double agl = current__view->getAltitudeASL_ft()*SG_FEET_TO_METER
509       - current__view->getSGLocation()->get_cur_elev_m();
510
511     if ( agl > 10.0 ) {
512         scene_nearplane = 10.0f;
513         scene_farplane = 120000.0f;
514     } else {
515         scene_nearplane = groundlevel_nearplane->getDoubleValue();
516         scene_farplane = 120000.0f;
517     }
518
519     setNearFar( scene_nearplane, scene_farplane );
520
521     sgEnviro.startOfFrame(current__view->get_view_pos(), 
522         current__view->get_world_up(),
523         current__view->getLongitude_deg(),
524         current__view->getLatitude_deg(),
525         current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
526         delta_time_sec);
527
528     if ( draw_otw && skyblend ) {
529         // draw the sky backdrop
530
531         // we need a white diffuse light for the phase of the moon
532         ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
533         thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
534                          fog_exp2_density );
535         // return to the desired diffuse color
536         ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
537     }
538
539     // draw the ssg scene
540     glEnable( GL_DEPTH_TEST );
541
542     if ( fgGetBool("/sim/rendering/wireframe") ) {
543         // draw wire frame
544         glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
545     }
546     if ( draw_otw ) {
547         if ( draw_clouds ) {
548
549             // Draw the terrain
550             FGTileMgr::set_tile_filter( true );
551             sgSetModelFilter( false );
552             globals->get_aircraft_model()->select( false );
553             ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
554
555             // Disable depth buffer update, draw the clouds
556             glDepthMask( GL_FALSE );
557             if( !volumetric_clouds )
558                 thesky->drawUpperClouds();
559             if ( multi_pass_clouds ) {
560                 thesky->drawLowerClouds();
561             }
562             glDepthMask( GL_TRUE );
563
564             if ( multi_pass_clouds ) {
565                 // Draw the objects except the aircraft
566                 //  and update the stencil buffer with 1
567                 glEnable( GL_STENCIL_TEST );
568                 glStencilFunc( GL_ALWAYS, 1, 1 );
569                 glStencilOp( GL_KEEP, GL_KEEP, GL_REPLACE );
570             }
571             FGTileMgr::set_tile_filter( false );
572             sgSetModelFilter( true );
573             ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
574         } else {
575             FGTileMgr::set_tile_filter( true );
576             sgSetModelFilter( true );
577             globals->get_aircraft_model()->select( false );
578             ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
579         }
580     }
581
582     // This is a bit kludgy.  Every 200 frames, do an extra
583     // traversal of the scene graph without drawing anything, but
584     // with the field-of-view set to 360x360 degrees.  This
585     // ensures that out-of-range random objects that are not in
586     // the current view frustum will still be freed properly.
587     static int counter = 0;
588     counter++;
589     if (counter >= 200) {
590         sgFrustum f;
591         f.setFOV(360, 360);
592                 // No need to put the near plane too close;
593                 // this way, at least the aircraft can be
594                 // culled.
595         f.setNearFar(1000, 1000000);
596         sgMat4 m;
597         ssgGetModelviewMatrix(m);
598         FGTileMgr::set_tile_filter( true );
599         sgSetModelFilter( true );
600         globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
601         counter = 0;
602     }
603
604     // change state for lighting here
605
606     // draw runway lighting
607     glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
608
609     // CLO - 02/25/2005 - DO WE NEED THIS extra fgSetNearFar()?
610     // fgSetNearFar( scene_nearplane, scene_farplane );
611
612     if ( use_point_sprites ) {
613         glEnable(GL_POINT_SPRITE);
614     } else {
615         glDisable(GL_POINT_SPRITE);
616     }
617
618     if ( enhanced_lighting ) {
619
620         // Enable states for drawing points with GL_extension
621         glEnable(GL_POINT_SMOOTH);
622
623         if ( distance_attenuation && glPointParameterIsSupported )
624         {
625             // Enable states for drawing points with GL_extension
626             glEnable(GL_POINT_SMOOTH);
627
628             float quadratic[3] = {1.0, 0.001, 0.0000001};
629             // makes the points fade as they move away
630             glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT, quadratic);
631             // glPointParameterfPtr(GL_POINT_SIZE_MIN_EXT, 1.0); 
632         }
633
634         glPointSize(4.0);
635
636         // blending function for runway lights
637         glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
638     }
639
640     glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
641     glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
642     glEnable(GL_TEXTURE_GEN_S);
643     glEnable(GL_TEXTURE_GEN_T);
644     glPolygonMode(GL_FRONT, GL_POINT);
645
646     // draw runway lighting
647     if ( draw_otw ) {
648         ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
649         ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
650     }
651
652     // change punch through and then draw taxi lighting
653     glFogf ( GL_FOG_DENSITY, fog_exp2_density );
654     // sgVec3 taxi_fog;
655     // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
656     // glFogfv ( GL_FOG_COLOR, taxi_fog );
657     if ( draw_otw ) {
658         ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
659     }
660
661     // clean up lighting
662     glPolygonMode(GL_FRONT, GL_FILL);
663     glDisable(GL_TEXTURE_GEN_S);
664     glDisable(GL_TEXTURE_GEN_T);
665
666     //static int _frame_count = 0;
667     //if (_frame_count % 30 == 0) {
668     //  printf("SSG: %s\n", ssgShowStats());
669     //}
670     //else {
671     //  ssgShowStats();
672     //}
673     //_frame_count++;
674
675
676     if ( enhanced_lighting ) {
677         if ( distance_attenuation && glPointParameterIsSupported ) {
678             glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT,
679                                   default_attenuation);
680         }
681
682         glPointSize(1.0);
683         glDisable(GL_POINT_SMOOTH);
684     }
685
686     // draw ground lighting
687     glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
688     if ( draw_otw ) {
689         ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
690     }
691
692     sgEnviro.drawLightning();
693
694     if ( draw_otw && draw_clouds ) {
695         if ( multi_pass_clouds ) {
696             // Disable depth buffer update, draw the clouds where the
697             //  objects overwrite the already drawn clouds, by testing
698             //  the stencil buffer against 1
699             glDepthMask( GL_FALSE );
700             glStencilFunc( GL_EQUAL, 1, 1 );
701             glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
702             thesky->drawUpperClouds();
703             thesky->drawLowerClouds();
704             glDepthMask( GL_TRUE );
705             glDisable( GL_STENCIL_TEST );
706         } else {
707             glDepthMask( GL_FALSE );
708             if( volumetric_clouds )
709                 thesky->drawUpperClouds();
710             thesky->drawLowerClouds();
711             glDepthMask( GL_TRUE );
712         }
713     }
714        double current_view_origin_airspeed_horiz_kt =
715         fgGetDouble("/velocities/airspeed-kt", 0.0)
716                        * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
717                                * SGD_DEGREES_TO_RADIANS);
718        // TODO:find the real view speed, not the AC one
719     sgEnviro.drawPrecipitation(
720         fgGetDouble("/environment/metar/rain-norm", 0.0),
721         fgGetDouble("/environment/metar/snow-norm", 0.0),
722         fgGetDouble("/environment/metar/hail-norm", 0.0),
723         current__view->getPitch_deg() + current__view->getPitchOffset_deg(),
724         current__view->getRoll_deg() + current__view->getRollOffset_deg(),
725         - current__view->getHeadingOffset_deg(),
726                current_view_origin_airspeed_horiz_kt
727                );
728
729     // compute shadows and project them on screen
730     bool is_internal = globals->get_current_view()->getInternal();
731     // draw before ac because ac internal rendering clear the depth buffer
732
733         globals->get_aircraft_model()->select( true );
734     if( is_internal )
735         shadows->endOfFrame();
736
737     if ( draw_otw ) {
738         FGTileMgr::set_tile_filter( false );
739         sgSetModelFilter( false );
740         globals->get_aircraft_model()->select( true );
741         globals->get_model_mgr()->draw();
742         globals->get_aircraft_model()->draw();
743
744         FGTileMgr::set_tile_filter( true );
745         sgSetModelFilter( true );
746         globals->get_aircraft_model()->select( true );
747     }
748         // in 'external' view the ac can be culled, so shadows have not been draw in the
749         // posttrav callback, this would be a rare case if the getInternal was acting
750         // as expected (ie in internal view, getExternal returns false)
751         if( !is_internal )
752                 shadows->endOfFrame();
753
754     // display HUD && Panel
755     glDisable( GL_FOG );
756     glDisable( GL_DEPTH_TEST );
757     // glDisable( GL_CULL_FACE );
758     // glDisable( GL_TEXTURE_2D );
759
760     // update the controls subsystem
761     globals->get_controls()->update(delta_time_sec);
762
763     hud_and_panel->apply();
764     fgCockpitUpdate();
765
766     FGInstrumentMgr *instr = static_cast<FGInstrumentMgr *>(globals->get_subsystem("instrumentation"));
767     HUD *hud = static_cast<HUD *>(instr->get_subsystem("hud"));
768     hud->draw();
769
770     // Use the hud_and_panel ssgSimpleState for rendering the ATC output
771     // This only works properly if called before the panel call
772     if((fgGetBool("/sim/atc/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
773         globals->get_ATC_display()->update(delta_time_sec);
774
775     // update the panel subsystem
776     if ( globals->get_current_panel() != NULL ) {
777         globals->get_current_panel()->update(delta_time_sec);
778     }
779     fgUpdate3DPanels();
780
781     // We can do translucent menus, so why not. :-)
782     menus->apply();
783     glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
784     puDisplay();
785     // glDisable ( GL_BLEND ) ;
786
787     glEnable( GL_DEPTH_TEST );
788     glEnable( GL_FOG );
789
790     // Fade out the splash screen over the first three seconds.
791     double t = globals->get_sim_time_sec();
792     if (t <= 2.5)
793         fgSplashUpdate((2.5 - t) / 2.5);
794 }
795
796
797
798 // options.cxx needs to see this for toggle_panel()
799 // Handle new window size or exposure
800 void
801 FGRenderer::resize( int width, int height ) {
802     int view_h;
803
804     if ( (!fgGetBool("/sim/virtual-cockpit"))
805          && fgPanelVisible() && idle_state == 1000 ) {
806         view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
807                              globals->get_current_panel()->getYOffset()) / 768.0);
808     } else {
809         view_h = height;
810     }
811
812     glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
813
814     static int lastwidth = 0;
815     static int lastheight = 0;
816     if (width != lastwidth)
817         fgSetInt("/sim/startup/xsize", lastwidth = width);
818     if (height != lastheight)
819         fgSetInt("/sim/startup/ysize", lastheight = height);
820
821     guiInitMouse(width, height);
822
823     // for all views
824     FGViewMgr *viewmgr = globals->get_viewmgr();
825     if (viewmgr) {
826       for ( int i = 0; i < viewmgr->size(); ++i ) {
827         viewmgr->get_view(i)->
828           set_aspect_ratio((float)view_h / (float)width);
829       }
830
831       setFOV( viewmgr->get_current_view()->get_h_fov(),
832               viewmgr->get_current_view()->get_v_fov() );
833       // cout << "setFOV(" << viewmgr->get_current_view()->get_h_fov()
834       //      << ", " << viewmgr->get_current_view()->get_v_fov() << ")"
835       //      << endl;
836
837     }
838
839     fgHUDReshape();
840
841 }
842
843
844 // These are wrapper functions around ssgSetNearFar() and ssgSetFOV()
845 // which will post process and rewrite the resulting frustum if we
846 // want to do asymmetric view frustums.
847
848 static void fgHackFrustum() {
849
850     // specify a percent of the configured view frustum to actually
851     // display.  This is a bit of a hack to achieve asymmetric view
852     // frustums.  For instance, if you want to display two monitors
853     // side by side, you could specify each with a double fov, a 0.5
854     // aspect ratio multiplier, and then the left side monitor would
855     // have a left_pct = 0.0, a right_pct = 0.5, a bottom_pct = 0.0,
856     // and a top_pct = 1.0.  The right side monitor would have a
857     // left_pct = 0.5 and a right_pct = 1.0.
858
859     static SGPropertyNode *left_pct
860         = fgGetNode("/sim/current-view/frustum-left-pct");
861     static SGPropertyNode *right_pct
862         = fgGetNode("/sim/current-view/frustum-right-pct");
863     static SGPropertyNode *bottom_pct
864         = fgGetNode("/sim/current-view/frustum-bottom-pct");
865     static SGPropertyNode *top_pct
866         = fgGetNode("/sim/current-view/frustum-top-pct");
867
868     sgFrustum *f = ssgGetFrustum();
869
870     // cout << " l = " << f->getLeft()
871     //      << " r = " << f->getRight()
872     //      << " b = " << f->getBot()
873     //      << " t = " << f->getTop()
874     //      << " n = " << f->getNear()
875     //      << " f = " << f->getFar()
876     //      << endl;
877
878     double width = f->getRight() - f->getLeft();
879     double height = f->getTop() - f->getBot();
880
881     double l, r, t, b;
882
883     if ( left_pct != NULL ) {
884         l = f->getLeft() + width * left_pct->getDoubleValue();
885     } else {
886         l = f->getLeft();
887     }
888
889     if ( right_pct != NULL ) {
890         r = f->getLeft() + width * right_pct->getDoubleValue();
891     } else {
892         r = f->getRight();
893     }
894
895     if ( bottom_pct != NULL ) {
896         b = f->getBot() + height * bottom_pct->getDoubleValue();
897     } else {
898         b = f->getBot();
899     }
900
901     if ( top_pct != NULL ) {
902         t = f->getBot() + height * top_pct->getDoubleValue();
903     } else {
904         t = f->getTop();
905     }
906
907     ssgSetFrustum(l, r, b, t, f->getNear(), f->getFar());
908 }
909
910
911 // we need some static storage space for these values.  However, we
912 // can't store it in a renderer class object because the functions
913 // that manipulate these are static.  They are static so they can
914 // interface to the display callback system.  There's probably a
915 // better way, there has to be a better way, but I'm not seeing it
916 // right now.
917 static float fov_width = 55.0;
918 static float fov_height = 42.0;
919 static float fov_near = 1.0;
920 static float fov_far = 1000.0;
921
922
923 /** FlightGear code should use this routine to set the FOV rather than
924  *  calling the ssg routine directly
925  */
926 void FGRenderer::setFOV( float w, float h ) {
927     fov_width = w;
928     fov_height = h;
929
930     // fully specify the view frustum before hacking it (so we don't
931     // accumulate hacked effects
932     ssgSetFOV( w, h );
933     ssgSetNearFar( fov_near, fov_far );
934     fgHackFrustum();
935     sgEnviro.setFOV( w, h );
936 }
937
938
939 /** FlightGear code should use this routine to set the Near/Far clip
940  *  planes rather than calling the ssg routine directly
941  */
942 void FGRenderer::setNearFar( float n, float f ) {
943     fov_near = n;
944     fov_far = f;
945
946     // fully specify the view frustum before hacking it (so we don't
947     // accumulate hacked effects
948     ssgSetNearFar( n, f );
949     ssgSetFOV( fov_width, fov_height );
950
951     fgHackFrustum();
952 }
953
954 bool FGRenderer::getPickInfo( SGVec3d& pt, SGVec3d& dir,
955                               unsigned x, unsigned y )
956 {
957   // Get the matrices involved in the transform from global to screen
958   // coordinates.
959   sgMat4 pm;
960   ssgGetProjectionMatrix(pm);
961   sgMat4 mv;
962   ssgGetModelviewMatrix(mv);
963   
964   // Compose ...
965   sgMat4 m;
966   sgMultMat4(m, pm, mv);
967   // ... and invert
968   sgInvertMat4(m);
969   
970   // Get the width and height of the display to be able to normalize the
971   // mouse coordinate
972   float width = fgGetInt("/sim/startup/xsize");
973   float height = fgGetInt("/sim/startup/ysize");
974   
975   // Compute some coordinates of in the line from the eyepoint to the
976   // mouse click coodinates.
977   // First build the normalized projection coordinates
978   sgVec4 normPt;
979   sgSetVec4(normPt, (2*x - width)/width, -(2*y - height)/height, 1, 1);
980   // Transform them into the real world
981   sgVec4 worldPt;
982   sgXformPnt4(worldPt, normPt, m);
983   if (worldPt[3] == 0)
984     return false;
985   sgScaleVec3(worldPt, 1/worldPt[3]);
986
987   // Now build a direction from the point
988   FGViewer* view = globals->get_current_view();
989   sgVec4 fDir;
990   sgSubVec3(fDir, worldPt, view->get_view_pos());
991   sgdSetVec3(dir.sg(), fDir);
992   sgdNormalizeVec3(dir.sg());
993
994   // Copy the start point
995   sgdCopyVec3(pt.sg(), view->get_absolute_view_pos());
996
997   return true;
998 }
999
1000 // end of renderer.cxx
1001