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