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