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