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