]> git.mxchange.org Git - flightgear.git/blob - src/Main/renderer.cxx
The view frustum is defined in plib apps using calls to ssgSetFOV() and
[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 #ifdef FG_USE_CLOUDS_3D
53 #  include <simgear/scene/sky/clouds3d/SkySceneLoader.hpp>
54 #  include <simgear/scene/sky/clouds3d/SkyUtil.hpp>
55 #endif
56
57 #include <Scenery/tileentry.hxx>
58 #include <Time/light.hxx>
59 #include <Time/light.hxx>
60 #include <Aircraft/aircraft.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 <ATC/ATCdisplay.hxx>
70 #include <Replay/replay.hxx>
71 #include <GUI/new_gui.hxx>
72
73 #include "splash.hxx"
74 #include "renderer.hxx"
75 #include "main.hxx"
76
77
78 float default_attenuation[3] = {1.0, 0.0, 0.0};
79
80 ssgSelector *lightpoints_brightness = new ssgSelector;
81 ssgTransform *lightpoints_transform = new ssgTransform;
82 FGTileEntry *dummy_tile;
83 sgVec3 rway_ols;
84
85 // Clip plane settings...
86 float scene_nearplane = 0.5f;
87 float scene_farplane = 120000.0f;
88
89 glPointParameterfProc glPointParameterfPtr = 0;
90 glPointParameterfvProc glPointParameterfvPtr = 0;
91 bool glPointParameterIsSupported = 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 #ifdef FG_USE_CLOUDS_3D
108   SkySceneLoader *sgClouds3d;
109   bool _bcloud_orig = true;
110 #endif
111
112 // hack
113 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
114 {
115   {  1.0f,  0.0f,  0.0f,  0.0f },
116   {  0.0f,  0.0f, -1.0f,  0.0f },
117   {  0.0f,  1.0f,  0.0f,  0.0f },
118   {  0.0f,  0.0f,  0.0f,  1.0f }
119 };
120
121 ssgSimpleState *cloud3d_imposter_state;
122 ssgSimpleState *default_state;
123 ssgSimpleState *hud_and_panel;
124 ssgSimpleState *menus;
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->ref();
145     default_state->disable( GL_TEXTURE_2D );
146     default_state->enable( GL_CULL_FACE );
147     default_state->enable( GL_COLOR_MATERIAL );
148     default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
149     default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
150     default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
151     default_state->disable( GL_BLEND );
152     default_state->disable( GL_ALPHA_TEST );
153     default_state->disable( GL_LIGHTING );
154
155     cloud3d_imposter_state = new ssgSimpleState;
156     cloud3d_imposter_state->ref();
157     cloud3d_imposter_state->enable( GL_TEXTURE_2D );
158     cloud3d_imposter_state->enable( GL_CULL_FACE );
159     cloud3d_imposter_state->enable( GL_COLOR_MATERIAL );
160     cloud3d_imposter_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
161     cloud3d_imposter_state->setMaterial( GL_DIFFUSE, 1, 1, 1, 1 );
162     cloud3d_imposter_state->setMaterial( GL_AMBIENT, 1, 1, 1, 1 );
163     cloud3d_imposter_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
164     cloud3d_imposter_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
165     cloud3d_imposter_state->enable( GL_BLEND );
166     cloud3d_imposter_state->enable( GL_ALPHA_TEST );
167     cloud3d_imposter_state->disable( GL_LIGHTING );
168
169     hud_and_panel = new ssgSimpleState;
170     hud_and_panel->ref();
171     hud_and_panel->disable( GL_CULL_FACE );
172     hud_and_panel->disable( GL_TEXTURE_2D );
173     hud_and_panel->disable( GL_LIGHTING );
174     hud_and_panel->enable( GL_BLEND );
175
176     menus = new ssgSimpleState;
177     menus->ref();
178     menus->disable( GL_CULL_FACE );
179     menus->disable( GL_TEXTURE_2D );
180     menus->enable( GL_BLEND );
181 }
182
183
184 // Initialize various GL/view parameters
185 void
186 FGRenderer::init( void ) {
187
188     FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
189
190     // Go full screen if requested ...
191     if ( fgGetBool("/sim/startup/fullscreen") ) {
192         fgOSFullScreen();
193     }
194
195     // If enabled, normal vectors specified with glNormal are scaled
196     // to unit length after transformation.  Enabling this has
197     // performance implications.  See the docs for glNormal.
198     // glEnable( GL_NORMALIZE );
199
200     glEnable( GL_LIGHTING );
201     glEnable( GL_LIGHT0 );
202     // glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );  // done later with ssg
203
204     sgVec3 sunpos;
205     sgSetVec3( sunpos, l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2] );
206     ssgGetLight( 0 ) -> setPosition( sunpos );
207
208     glFogi (GL_FOG_MODE, GL_EXP2);
209     if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) || 
210          (!fgGetBool("/sim/rendering/shading"))) {
211         // if fastest fog requested, or if flat shading force fastest
212         glHint ( GL_FOG_HINT, GL_FASTEST );
213     } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
214         glHint ( GL_FOG_HINT, GL_NICEST );
215     }
216     if ( fgGetBool("/sim/rendering/wireframe") ) {
217         // draw wire frame
218         glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
219     }
220
221     // This is the default anyways, but it can't hurt
222     glFrontFace ( GL_CCW );
223
224     // Just testing ...
225     // glEnable(GL_POINT_SMOOTH);
226     // glEnable(GL_LINE_SMOOTH);
227     // glEnable(GL_POLYGON_SMOOTH);      
228 }
229
230
231
232 // Update all Visuals (redraws anything graphics related)
233 void
234 FGRenderer::update( bool refresh_camera_settings ) {
235     bool scenery_loaded = fgGetBool("sim/sceneryloaded") || fgGetBool("sim/sceneryloaded-override");
236     bool draw_otw = fgGetBool("/sim/rendering/draw-otw");
237     bool skyblend = fgGetBool("/sim/rendering/skyblend");
238     bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
239     bool distance_attenuation = fgGetBool("/sim/rendering/distance-attenuation");
240 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
241     bool multi_pass_clouds = fgGetBool("/sim/rendering/multi-pass-clouds") && 
242                                 !SGCloudLayer::enable_bump_mapping;  // ugly artefact now
243 #else
244     bool multi_pass_clouds = false;
245 #endif
246     bool draw_clouds = fgGetBool("/environment/clouds/status");
247
248     GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
249     GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
250
251     // static const SGPropertyNode *longitude
252     //     = fgGetNode("/position/longitude-deg");
253     // static const SGPropertyNode *latitude
254     //     = fgGetNode("/position/latitude-deg");
255     // static const SGPropertyNode *altitude
256     //     = fgGetNode("/position/altitude-ft");
257     static const SGPropertyNode *groundlevel_nearplane
258         = fgGetNode("/sim/current-view/ground-level-nearplane-m");
259
260     FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
261     static double last_visibility = -9999;
262
263     // update fog params
264     double actual_visibility;
265     if (fgGetBool("/environment/clouds/status")) {
266         actual_visibility = thesky->get_visibility();
267     } else {
268         actual_visibility = fgGetDouble("/environment/visibility-m");
269     }
270
271     if ( actual_visibility != last_visibility ) {
272         last_visibility = actual_visibility;
273
274         fog_exp_density = m_log01 / actual_visibility;
275         fog_exp2_density = sqrt_m_log01 / actual_visibility;
276         ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
277         if ( actual_visibility < 8000 ) {
278             rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
279             taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
280         } else {
281             rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
282             taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
283         }
284     }
285
286     // double angle;
287     // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
288     // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
289     // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
290     // GLfloat mat_shininess[] = { 10.0 };
291     GLbitfield clear_mask;
292
293     if ( idle_state != 1000 || !scenery_loaded ) {
294         // still initializing, draw the splash screen
295         if ( fgGetBool("/sim/startup/splash-screen") ) {
296             fgSplashUpdate(0.0, 1.0);
297         }
298         // Keep resetting sim time while the sim is initializing
299         globals->set_sim_time_sec( 0.0 );
300         SGAnimation::set_sim_time_sec( 0.0 );
301     } else {
302         // idle_state is now 1000 meaning we've finished all our
303         // initializations and are running the main loop, so this will
304         // now work without seg faulting the system.
305
306         FGViewer *current__view = globals->get_current_view();
307
308         // calculate our current position in cartesian space
309         globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
310
311         if ( refresh_camera_settings ) {
312             // update view port
313             resize( fgGetInt("/sim/startup/xsize"),
314                     fgGetInt("/sim/startup/ysize") );
315
316             // Tell GL we are switching to model view parameters
317             glMatrixMode(GL_MODELVIEW);
318             glLoadIdentity();
319             ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
320         }
321
322         if ( fgGetBool("/sim/rendering/clouds3d") ) {
323             glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
324             cloud3d_imposter_state->force();
325             glDisable( GL_FOG );
326             glColor4f( 1.0, 1.0, 1.0, 1.0 );
327             glEnable(GL_DEPTH_TEST);
328             glEnable(GL_BLEND);
329             glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
330
331 #ifdef FG_USE_CLOUDS_3D
332             if ( _bcloud_orig ) {
333                 Point3D c = globals->get_scenery()->get_center();
334                 sgClouds3d->Set_Cloud_Orig( &c );
335                 _bcloud_orig = false;
336             }
337             sgClouds3d->Update( current__view->get_absolute_view_pos() );
338 #endif
339             glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
340             glDisable(GL_DEPTH_TEST);
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              SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
384              << l->sky_color()[0] << " "
385              << l->sky_color()[1] << " "
386              << l->sky_color()[2] << " "
387              << l->sky_color()[3] );
388             SG_LOG( SG_GENERAL, SG_BULK, "    fog = "
389              << l->fog_color()[0] << " "
390              << l->fog_color()[1] << " "
391              << l->fog_color()[2] << " "
392              << l->fog_color()[3] ); 
393             SG_LOG( SG_GENERAL, SG_BULK,
394                     "    sun_angle = " << l->sun_angle
395              << "    moon_angle = " << l->moon_angle );
396             */
397
398             static SGSkyColor scolor;
399             FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
400
401             scolor.sky_color   = l->sky_color();
402             scolor.fog_color   = l->adj_fog_color();
403             scolor.cloud_color = l->cloud_color();
404             scolor.sun_angle   = l->get_sun_angle();
405             scolor.moon_angle  = l->get_moon_angle();
406             scolor.nplanets    = globals->get_ephem()->getNumPlanets();
407             scolor.nstars      = globals->get_ephem()->getNumStars();
408             scolor.planet_data = globals->get_ephem()->getPlanets();
409             scolor.star_data   = globals->get_ephem()->getStars();
410
411             thesky->repaint( scolor );
412
413             /*
414             SG_LOG( SG_GENERAL, SG_BULK,
415                     "thesky->reposition( view_pos = " << view_pos[0] << " "
416              << view_pos[1] << " " << view_pos[2] );
417             SG_LOG( SG_GENERAL, SG_BULK,
418                     "    zero_elev = " << zero_elev[0] << " "
419              << zero_elev[1] << " " << zero_elev[2]
420              << " lon = " << cur_fdm_state->get_Longitude()
421              << " lat = " << cur_fdm_state->get_Latitude() );
422             SG_LOG( SG_GENERAL, SG_BULK,
423                     "    sun_rot = " << l->get_sun_rotation
424              << " gst = " << SGTime::cur_time_params->getGst() );
425             SG_LOG( SG_GENERAL, SG_BULK,
426                  "    sun ra = " << globals->get_ephem()->getSunRightAscension()
427               << " sun dec = " << globals->get_ephem()->getSunDeclination()
428               << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
429               << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
430             */
431
432             // The sun and moon distances are scaled down versions
433             // of the actual distance to get both the moon and the sun
434             // within the range of the far clip plane.
435             // Moon distance:    384,467 kilometers
436             // Sun distance: 150,000,000 kilometers
437             double sun_horiz_eff, moon_horiz_eff;
438             if (fgGetBool("/sim/rendering/horizon-effect")) {
439             sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
440             moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
441             } else {
442                sun_horiz_eff = moon_horiz_eff = 1.0;
443             }
444
445             static SGSkyState sstate;
446
447             sstate.view_pos  = current__view->get_view_pos();
448             sstate.zero_elev = current__view->get_zero_elev();
449             sstate.view_up   = current__view->get_world_up();
450             sstate.lon       = current__view->getLongitude_deg()
451                                 * SGD_DEGREES_TO_RADIANS;
452             sstate.lat       = current__view->getLatitude_deg()
453                                 * SGD_DEGREES_TO_RADIANS;
454             sstate.alt       = current__view->getAltitudeASL_ft()
455                                 * SG_FEET_TO_METER;
456             sstate.spin      = l->get_sun_rotation();
457             sstate.gst       = globals->get_time_params()->getGst();
458             sstate.sun_ra    = globals->get_ephem()->getSunRightAscension();
459             sstate.sun_dec   = globals->get_ephem()->getSunDeclination();
460             sstate.sun_dist  = 50000.0 * sun_horiz_eff;
461             sstate.moon_ra   = globals->get_ephem()->getMoonRightAscension();
462             sstate.moon_dec  = globals->get_ephem()->getMoonDeclination();
463             sstate.moon_dist = 40000.0 * moon_horiz_eff;
464
465             thesky->reposition( sstate, delta_time_sec );
466         }
467
468         glEnable( GL_DEPTH_TEST );
469         if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
470             glEnable( GL_FOG );
471             glFogi( GL_FOG_MODE, GL_EXP2 );
472             glFogfv( GL_FOG_COLOR, l->adj_fog_color() );
473         }
474
475         // set sun/lighting parameters
476         ssgGetLight( 0 ) -> setPosition( l->sun_vec() );
477
478         // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
479         // we only update GL_AMBIENT for our lights we will never get
480         // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
481         // explicitely to black.
482         glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
483
484         ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
485         ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
486         ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular() );
487
488         // texture parameters
489         // glEnable( GL_TEXTURE_2D );
490         glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
491         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
492
493         double agl =
494             current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
495             - globals->get_scenery()->get_cur_elev();
496
497         if ( agl > 10.0 ) {
498             scene_nearplane = 10.0f;
499             scene_farplane = 120000.0f;
500         } else {
501             scene_nearplane = groundlevel_nearplane->getDoubleValue();
502             scene_farplane = 120000.0f;
503         }
504
505         setNearFar( scene_nearplane, scene_farplane );
506
507         if ( draw_otw && skyblend ) {
508             // draw the sky backdrop
509
510             // we need a white diffuse light for the phase of the moon
511             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
512             thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
513                              fog_exp2_density );
514             // return to the desired diffuse color
515             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
516         }
517
518         // draw the ssg scene
519         glEnable( GL_DEPTH_TEST );
520
521         if ( fgGetBool("/sim/rendering/wireframe") ) {
522             // draw wire frame
523             glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
524         }
525         if ( draw_otw ) {
526             if ( draw_clouds ) {
527
528                 // Draw the terrain
529                 FGTileMgr::set_tile_filter( true );
530                 sgSetModelFilter( false );
531                 globals->get_aircraft_model()->select( false );
532                 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
533
534                 // Disable depth buffer update, draw the clouds
535                 glDepthMask( GL_FALSE );
536                 thesky->drawUpperClouds();
537                 if ( multi_pass_clouds ) {
538                     thesky->drawLowerClouds();
539                 }
540                 glDepthMask( GL_TRUE );
541
542                 if ( multi_pass_clouds ) {
543                     // Draw the objects except the aircraft
544                     //  and update the stencil buffer with 1
545                     glEnable( GL_STENCIL_TEST );
546                     glStencilFunc( GL_ALWAYS, 1, 1 );
547                     glStencilOp( GL_KEEP, GL_KEEP, GL_REPLACE );
548                 }
549                 FGTileMgr::set_tile_filter( false );
550                 sgSetModelFilter( true );
551                 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
552             } else {
553                 FGTileMgr::set_tile_filter( true );
554                 sgSetModelFilter( true );
555                 globals->get_aircraft_model()->select( false );
556                 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
557             }
558         }
559
560         // This is a bit kludgy.  Every 200 frames, do an extra
561         // traversal of the scene graph without drawing anything, but
562         // with the field-of-view set to 360x360 degrees.  This
563         // ensures that out-of-range random objects that are not in
564         // the current view frustum will still be freed properly.
565         static int counter = 0;
566         counter++;
567         if (counter >= 200) {
568             sgFrustum f;
569             f.setFOV(360, 360);
570                     // No need to put the near plane too close;
571                     // this way, at least the aircraft can be
572                     // culled.
573             f.setNearFar(1000, 1000000);
574             sgMat4 m;
575             ssgGetModelviewMatrix(m);
576             FGTileMgr::set_tile_filter( true );
577             sgSetModelFilter( true );
578             globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
579             counter = 0;
580         }
581
582         // change state for lighting here
583
584         // draw runway lighting
585         glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
586
587         // CLO - 02/25/2005 - DO WE NEED THIS extra fgSetNearFar()?
588         // fgSetNearFar( scene_nearplane, scene_farplane );
589
590         if ( enhanced_lighting ) {
591
592             // Enable states for drawing points with GL_extension
593             glEnable(GL_POINT_SMOOTH);
594
595             if ( distance_attenuation && glPointParameterIsSupported )
596             {
597                 // Enable states for drawing points with GL_extension
598                 glEnable(GL_POINT_SMOOTH);
599
600                 float quadratic[3] = {1.0, 0.001, 0.0000001};
601                 // makes the points fade as they move away
602                 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT, quadratic);
603                 glPointParameterfPtr(GL_POINT_SIZE_MIN_EXT, 1.0); 
604             }
605
606             glPointSize(4.0);
607
608             // blending function for runway lights
609             glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
610         }
611
612         glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
613         glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
614         glEnable(GL_TEXTURE_GEN_S);
615         glEnable(GL_TEXTURE_GEN_T);
616         glPolygonMode(GL_FRONT, GL_POINT);
617
618         // draw runway lighting
619         if ( draw_otw ) {
620             ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
621             ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
622         }
623
624         // change punch through and then draw taxi lighting
625         glFogf ( GL_FOG_DENSITY, fog_exp2_density );
626         // sgVec3 taxi_fog;
627         // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
628         // glFogfv ( GL_FOG_COLOR, taxi_fog );
629         if ( draw_otw ) {
630             ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
631         }
632
633         // clean up lighting
634         glPolygonMode(GL_FRONT, GL_FILL);
635         glDisable(GL_TEXTURE_GEN_S);
636         glDisable(GL_TEXTURE_GEN_T);
637
638         //static int _frame_count = 0;
639         //if (_frame_count % 30 == 0) {
640         //  printf("SSG: %s\n", ssgShowStats());
641         //}
642         //else {
643         //  ssgShowStats();
644         //}
645         //_frame_count++;
646
647
648         if ( enhanced_lighting ) {
649             if ( distance_attenuation && glPointParameterIsSupported ) {
650                 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT,
651                                       default_attenuation);
652             }
653
654             glPointSize(1.0);
655             glDisable(GL_POINT_SMOOTH);
656         }
657
658         // draw ground lighting
659         glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
660         if ( draw_otw ) {
661             ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
662         }
663
664         if ( draw_otw && fgGetBool("/sim/rendering/clouds3d") ) {
665             glDisable( GL_FOG );
666             glDisable( GL_LIGHTING );
667             // cout << "drawing new clouds" << endl;
668
669             glEnable(GL_DEPTH_TEST);
670             glEnable(GL_BLEND);
671             glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
672
673             /*
674             glEnable( GL_TEXTURE_2D );
675             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
676             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
677             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
678             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
679             */
680
681 #ifdef FG_USE_CLOUDS_3D
682             sgClouds3d->Draw((sgVec4 *)current__view->get_VIEW());
683 #endif
684             glEnable( GL_FOG );
685             glEnable( GL_LIGHTING );
686             glEnable( GL_DEPTH_TEST );
687             glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
688         }
689
690         if ( draw_otw && draw_clouds ) {
691             if ( multi_pass_clouds ) {
692                 // Disable depth buffer update, draw the clouds where the
693                 //  objects overwrite the already drawn clouds, by testing
694                 //  the stencil buffer against 1
695                 glDepthMask( GL_FALSE );
696                 glStencilFunc( GL_EQUAL, 1, 1 );
697                 glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
698                 thesky->drawUpperClouds();
699                 thesky->drawLowerClouds();
700                 glDepthMask( GL_TRUE );
701                 glDisable( GL_STENCIL_TEST );
702             } else {
703                 glDepthMask( GL_FALSE );
704                 thesky->drawLowerClouds();
705                 glDepthMask( GL_TRUE );
706             }
707         }
708
709         if ( draw_otw ) {
710             FGTileMgr::set_tile_filter( false );
711             sgSetModelFilter( false );
712             globals->get_aircraft_model()->select( true );
713             globals->get_model_mgr()->draw();
714             globals->get_aircraft_model()->draw();
715             // If the view is internal, the previous line draw the 
716             //  cockpit with modified near/far clip planes and deselect
717             //  the aircraft in the global scenegraph
718             // Otherwise, it just enables the aircraft: The scenegraph
719             //  must be drawn again to see the plane.
720             ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
721             FGTileMgr::set_tile_filter( true );
722             sgSetModelFilter( true );
723             globals->get_aircraft_model()->select( true );
724         }
725
726         // display HUD && Panel
727         glDisable( GL_FOG );
728         glDisable( GL_DEPTH_TEST );
729         // glDisable( GL_CULL_FACE );
730         // glDisable( GL_TEXTURE_2D );
731
732         // update the controls subsystem
733         globals->get_controls()->update(delta_time_sec);
734
735         hud_and_panel->apply();
736         fgCockpitUpdate();
737
738         // Use the hud_and_panel ssgSimpleState for rendering the ATC output
739         // This only works properly if called before the panel call
740         if((fgGetBool("/sim/ATC/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
741             globals->get_ATC_display()->update(delta_time_sec);
742
743         // update the panel subsystem
744         if ( globals->get_current_panel() != NULL ) {
745             globals->get_current_panel()->update(delta_time_sec);
746         }
747         fgUpdate3DPanels();
748
749         // We can do translucent menus, so why not. :-)
750         menus->apply();
751         glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
752         puDisplay();
753         // glDisable ( GL_BLEND ) ;
754
755         glEnable( GL_DEPTH_TEST );
756         glEnable( GL_FOG );
757
758         // Fade out the splash screen over the first three seconds.
759         double t = globals->get_sim_time_sec();
760         if ( t <= 1.0 ) {
761             fgSplashUpdate(0.0, 1.0);
762         } else if ( t <= 3.0) {
763             fgSplashUpdate(0.0, (3.0 - t) / 2.0);
764         }
765     }
766 }
767
768
769
770 // options.cxx needs to see this for toggle_panel()
771 // Handle new window size or exposure
772 void
773 FGRenderer::resize( int width, int height ) {
774     int view_h;
775
776     if ( (!fgGetBool("/sim/virtual-cockpit"))
777          && fgPanelVisible() && idle_state == 1000 ) {
778         view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
779                              globals->get_current_panel()->getYOffset()) / 768.0);
780     } else {
781         view_h = height;
782     }
783
784     glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
785
786     fgSetInt("/sim/startup/xsize", width);
787     fgSetInt("/sim/startup/ysize", height);
788     guiInitMouse(width, height);
789
790     // for all views
791     FGViewMgr *viewmgr = globals->get_viewmgr();
792     if (viewmgr) {
793       for ( int i = 0; i < viewmgr->size(); ++i ) {
794         viewmgr->get_view(i)->
795           set_aspect_ratio((float)view_h / (float)width);
796       }
797
798       setFOV( viewmgr->get_current_view()->get_h_fov(),
799               viewmgr->get_current_view()->get_v_fov() );
800
801 #ifdef FG_USE_CLOUDS_3D
802       sgClouds3d->Resize( viewmgr->get_current_view()->get_h_fov(),
803                           viewmgr->get_current_view()->get_v_fov() );
804 #endif
805     }
806
807     fgHUDReshape();
808
809 }
810
811
812 // These are wrapper functions around ssgSetNearFar() and ssgSetFOV()
813 // which will post process and rewrite the resulting frustum if we
814 // want to do asymmetric view frustums.
815
816 static void fgHackFrustum() {
817
818     /* experiment in assymetric view frustums */
819     sgFrustum *f = ssgGetFrustum();
820     cout << " l = " << f->getLeft()
821          << " r = " << f->getRight()
822          << " b = " << f->getBot()
823          << " t = " << f->getTop()
824          << " n = " << f->getNear()
825          << " f = " << f->getFar()
826          << endl;
827     static double incr = 0.0;
828     double factor = (sin(incr) + 1.0) / 2.0; // map to [0-1]
829     double w = (f->getRight() - f->getLeft()) / 2.0;
830     double l = f->getLeft() + w * factor;
831     double r = l + w;
832     ssgSetFrustum(l, r, f->getBot(), f->getTop(), f->getNear(), f->getFar());
833     incr += 0.001;
834 }
835
836
837 // we need some static storage space for these values.  However, we
838 // can't store it in a renderer class object because the functions
839 // that manipulate these are static.  They are static so they can
840 // interface to the display callback system.  There's probably a
841 // better way, there has to be a better way, but I'm not seeing it
842 // right now.
843 static float width, height, near, far;
844
845
846 /** FlightGear code should use this routine to set the FOV rather than
847  *  calling the ssg routine directly
848  */
849 void FGRenderer::setFOV( float w, float h ) {
850     width = w;
851     height = h;
852
853     // fully specify the view frustum before hacking it (so we don't
854     // accumulate hacked effects
855     ssgSetFOV( w, h );
856     ssgSetNearFar( near, far );
857
858     fgHackFrustum();
859 }
860
861
862 /** FlightGear code should use this routine to set the Near/Far clip
863  *  planes rather than calling the ssg routine directly
864  */
865 void FGRenderer::setNearFar( float n, float f ) {
866     near = n;
867     far = f;
868
869     // fully specify the view frustum before hacking it (so we don't
870     // accumulate hacked effects
871     ssgSetNearFar( n, f );
872     ssgSetFOV( width, height );
873
874     fgHackFrustum();
875 }
876
877 // end of renderer.cxx