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