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