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