]> git.mxchange.org Git - flightgear.git/blob - src/Main/renderer.cxx
6fcbe0165a13f0aae11d18a7f0b8612e8c5c597c
[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  - curt@flightgear.org
7 //
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 //
22 // $Id$
23
24
25 #ifdef HAVE_CONFIG_H
26 #  include <config.h>
27 #endif
28
29 #include <simgear/compiler.h>
30
31 #ifdef HAVE_WINDOWS_H
32 #  include <windows.h>
33 #endif
34
35 #include <plib/ssg.h>
36 #include <plib/netSocket.h>
37
38 #include <simgear/screen/extensions.hxx>
39 #include <simgear/scene/material/matlib.hxx>
40 #include <simgear/props/props.hxx>
41 #include <simgear/timing/sg_time.hxx>
42 #include <simgear/scene/model/animation.hxx>
43 #include <simgear/ephemeris/ephemeris.hxx>
44 #include <simgear/scene/model/placement.hxx>
45 #include <simgear/math/sg_random.h>
46 #include <simgear/scene/model/modellib.hxx>
47 #include <simgear/scene/model/model.hxx>
48
49 #ifdef FG_USE_CLOUDS_3D
50 #  include <simgear/scene/sky/clouds3d/SkySceneLoader.hpp>
51 #  include <simgear/scene/sky/clouds3d/SkyUtil.hpp>
52 #endif
53
54 #include <Scenery/tileentry.hxx>
55 #include <Time/light.hxx>
56 #include <Time/light.hxx>
57 #include <Aircraft/aircraft.hxx>
58 #include <Cockpit/panel.hxx>
59 #include <Cockpit/cockpit.hxx>
60 #include <Cockpit/radiostack.hxx>
61 #include <Cockpit/hud.hxx>
62 #include <Model/panelnode.hxx>
63 #include <Model/modelmgr.hxx>
64 #include <Model/acmodel.hxx>
65 #include <Scenery/scenery.hxx>
66 #include <Scenery/tilemgr.hxx>
67 #include <ATC/ATCdisplay.hxx>
68 #include <Replay/replay.hxx>
69 #include <GUI/new_gui.hxx>
70
71 #include "splash.hxx"
72 #include "renderer.hxx"
73 #include "main.hxx"
74
75
76 float default_attenuation[3] = {1.0, 0.0, 0.0};
77
78 ssgSelector *lightpoints_brightness = new ssgSelector;
79 ssgTransform *lightpoints_transform = new ssgTransform;
80 FGTileEntry *dummy_tile;
81 sgVec3 rway_ols;
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
91
92 // fog constants.  I'm a little nervous about putting actual code out
93 // here but it seems to work (?)
94 static const double m_log01 = -log( 0.01 );
95 static const double sqrt_m_log01 = sqrt( m_log01 );
96 static GLfloat fog_exp_density;
97 static GLfloat fog_exp2_density;
98 static GLfloat rwy_exp2_punch_through;
99 static GLfloat taxi_exp2_punch_through;
100 static GLfloat ground_exp2_punch_through;
101
102 // Sky structures
103 SGSky *thesky;
104
105 #ifdef FG_USE_CLOUDS_3D
106   SkySceneLoader *sgClouds3d;
107   bool _bcloud_orig = true;
108 #endif
109
110 // hack
111 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
112 {
113   {  1.0f,  0.0f,  0.0f,  0.0f },
114   {  0.0f,  0.0f, -1.0f,  0.0f },
115   {  0.0f,  1.0f,  0.0f,  0.0f },
116   {  0.0f,  0.0f,  0.0f,  1.0f }
117 };
118
119 ssgSimpleState *cloud3d_imposter_state;
120 ssgSimpleState *default_state;
121 ssgSimpleState *hud_and_panel;
122 ssgSimpleState *menus;
123
124
125 void
126 FGRenderer::build_states( void ) {
127     default_state = new ssgSimpleState;
128     default_state->ref();
129     default_state->disable( GL_TEXTURE_2D );
130     default_state->enable( GL_CULL_FACE );
131     default_state->enable( GL_COLOR_MATERIAL );
132     default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
133     default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
134     default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
135     default_state->disable( GL_BLEND );
136     default_state->disable( GL_ALPHA_TEST );
137     default_state->disable( GL_LIGHTING );
138
139     cloud3d_imposter_state = new ssgSimpleState;
140     cloud3d_imposter_state->ref();
141     cloud3d_imposter_state->enable( GL_TEXTURE_2D );
142     cloud3d_imposter_state->enable( GL_CULL_FACE );
143     cloud3d_imposter_state->enable( GL_COLOR_MATERIAL );
144     cloud3d_imposter_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
145     cloud3d_imposter_state->setMaterial( GL_DIFFUSE, 1, 1, 1, 1 );
146     cloud3d_imposter_state->setMaterial( GL_AMBIENT, 1, 1, 1, 1 );
147     cloud3d_imposter_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
148     cloud3d_imposter_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
149     cloud3d_imposter_state->enable( GL_BLEND );
150     cloud3d_imposter_state->enable( GL_ALPHA_TEST );
151     cloud3d_imposter_state->disable( GL_LIGHTING );
152
153     hud_and_panel = new ssgSimpleState;
154     hud_and_panel->ref();
155     hud_and_panel->disable( GL_CULL_FACE );
156     hud_and_panel->disable( GL_TEXTURE_2D );
157     hud_and_panel->disable( GL_LIGHTING );
158     hud_and_panel->enable( GL_BLEND );
159
160     menus = new ssgSimpleState;
161     menus->ref();
162     menus->disable( GL_CULL_FACE );
163     menus->disable( GL_TEXTURE_2D );
164     menus->enable( GL_BLEND );
165 }
166
167
168 // Initialize various GL/view parameters
169 void
170 FGRenderer::init( void ) {
171
172     FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
173
174     // Go full screen if requested ...
175     if ( fgGetBool("/sim/startup/fullscreen") ) {
176         fgOSFullScreen();
177     }
178
179     // If enabled, normal vectors specified with glNormal are scaled
180     // to unit length after transformation.  Enabling this has
181     // performance implications.  See the docs for glNormal.
182     // glEnable( GL_NORMALIZE );
183
184     glEnable( GL_LIGHTING );
185     glEnable( GL_LIGHT0 );
186     // glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );  // done later with ssg
187
188     sgVec3 sunpos;
189     sgSetVec3( sunpos, l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2] );
190     ssgGetLight( 0 ) -> setPosition( sunpos );
191
192     glFogi (GL_FOG_MODE, GL_EXP2);
193     if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) || 
194          (!fgGetBool("/sim/rendering/shading"))) {
195         // if fastest fog requested, or if flat shading force fastest
196         glHint ( GL_FOG_HINT, GL_FASTEST );
197     } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
198         glHint ( GL_FOG_HINT, GL_NICEST );
199     }
200     if ( fgGetBool("/sim/rendering/wireframe") ) {
201         // draw wire frame
202         glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
203     }
204
205     // This is the default anyways, but it can't hurt
206     glFrontFace ( GL_CCW );
207
208     // Just testing ...
209     // glEnable(GL_POINT_SMOOTH);
210     // glEnable(GL_LINE_SMOOTH);
211     // glEnable(GL_POLYGON_SMOOTH);      
212 }
213
214
215 // For HiRes screen Dumps using Brian Pauls TR Library
216 void
217 FGRenderer::screendump( void ) {
218 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
219     bool multi_pass_clouds = fgGetBool("/sim/rendering/multi-pass-clouds") &&
220                             !SGCloudLayer::enable_bump_mapping; // ugly artefact now
221 #else
222     bool multi_pass_clouds = false;
223 #endif
224     bool draw_clouds = fgGetBool("/environment/clouds/status");
225
226     if ( fgPanelVisible() ) {
227         GLfloat height = fgGetInt("/sim/startup/ysize");
228         GLfloat view_h =
229             (globals->get_current_panel()->getViewHeight() - globals->get_current_panel()->getYOffset())
230             * (height / 768.0) + 1;
231         glTranslatef( 0.0, view_h, 0.0 );
232     }
233
234     static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
235     static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
236
237     FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
238
239     glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1], 
240                  l->adj_fog_color()[2], l->adj_fog_color()[3]);
241
242     glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
243
244     // set the opengl state to known default values
245     default_state->force();
246
247     glEnable( GL_FOG );
248     glFogf  ( GL_FOG_DENSITY, fog_exp2_density);
249     glFogi  ( GL_FOG_MODE,    GL_EXP2 );
250     glFogfv ( GL_FOG_COLOR,   l->adj_fog_color() );
251
252     // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
253     // we only update GL_AMBIENT for our lights we will never get
254     // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
255     // explicitely to black.
256     glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
257     glLightModeli( GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE );
258
259     ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
260
261     // texture parameters
262     glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
263     glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
264
265     // we need a white diffuse light for the phase of the moon
266     ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
267     thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
268                      fog_exp2_density );
269
270     // draw the ssg scene
271     // return to the desired diffuse color
272     ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
273     glEnable( GL_DEPTH_TEST );
274     ssgSetNearFar( scene_nearplane, scene_farplane );
275     if ( draw_clouds ) {
276         // Draw the terrain
277         FGTileMgr::set_tile_filter( true );
278         sgSetModelFilter( false );
279         globals->get_aircraft_model()->select( false );
280         ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
281         // Disable depth buffer update, draw the clouds
282         glDepthMask( GL_FALSE );
283         thesky->drawUpperClouds();
284         if ( multi_pass_clouds ) {
285             thesky->drawLowerClouds();
286         }
287         glDepthMask( GL_TRUE );
288         if ( multi_pass_clouds ) {
289             // Draw the objects except the aircraft
290             //  and update the stencil buffer with 1
291             glEnable( GL_STENCIL_TEST );
292             glStencilFunc( GL_ALWAYS, 1, 1 );
293             glStencilOp( GL_KEEP, GL_KEEP, GL_REPLACE );
294         }
295         FGTileMgr::set_tile_filter( false );
296         sgSetModelFilter( true );
297         ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
298     } else {
299         FGTileMgr::set_tile_filter( true );
300         sgSetModelFilter( true );
301         globals->get_aircraft_model()->select( false );
302         ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
303     }
304
305     // draw the lights
306     glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
307     ssgSetNearFar( scene_nearplane, scene_farplane );
308     ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
309     ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
310
311     ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
312
313     if ( draw_clouds ) {
314         if ( multi_pass_clouds ) {
315             // Disable depth buffer update, draw the clouds where the
316             //  objects overwrite the already drawn clouds, by testing
317             //  the stencil buffer against 1
318             glDepthMask( GL_FALSE );
319             glStencilFunc( GL_EQUAL, 1, 1 );
320             glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
321             thesky->drawUpperClouds();
322             thesky->drawLowerClouds();
323             glDepthMask( GL_TRUE );
324             glDisable( GL_STENCIL_TEST );
325         } else {
326             glDepthMask( GL_FALSE );
327             thesky->drawLowerClouds();
328             glDepthMask( GL_TRUE );
329         }
330     }
331
332     globals->get_aircraft_model()->select( true );
333     globals->get_model_mgr()->draw();
334     globals->get_aircraft_model()->draw();
335 }
336
337
338 // Update all Visuals (redraws anything graphics related)
339 void
340 FGRenderer::update() {
341     bool scenery_loaded = fgGetBool("sim/sceneryloaded") || fgGetBool("sim/sceneryloaded-override");
342     bool draw_otw = fgGetBool("/sim/rendering/draw-otw");
343     bool skyblend = fgGetBool("/sim/rendering/skyblend");
344     bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
345     bool distance_attenuation = fgGetBool("/sim/rendering/distance-attenuation");
346 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
347     bool multi_pass_clouds = fgGetBool("/sim/rendering/multi-pass-clouds") && 
348                                 !SGCloudLayer::enable_bump_mapping;  // ugly artefact now
349 #else
350     bool multi_pass_clouds = false;
351 #endif
352     bool draw_clouds = fgGetBool("/environment/clouds/status");
353
354     GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
355     GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
356
357     // static const SGPropertyNode *longitude
358     //     = fgGetNode("/position/longitude-deg");
359     // static const SGPropertyNode *latitude
360     //     = fgGetNode("/position/latitude-deg");
361     // static const SGPropertyNode *altitude
362     //     = fgGetNode("/position/altitude-ft");
363     static const SGPropertyNode *groundlevel_nearplane
364         = fgGetNode("/sim/current-view/ground-level-nearplane-m");
365
366     FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
367     static double last_visibility = -9999;
368
369     // update fog params
370     double actual_visibility;
371     if (fgGetBool("/environment/clouds/status"))
372         actual_visibility = thesky->get_visibility();
373     else
374         actual_visibility = fgGetDouble("/environment/visibility-m");
375     if ( actual_visibility != last_visibility ) {
376         last_visibility = actual_visibility;
377
378         fog_exp_density = m_log01 / actual_visibility;
379         fog_exp2_density = sqrt_m_log01 / actual_visibility;
380         ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
381         if ( actual_visibility < 8000 ) {
382             rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
383             taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
384         } else {
385             rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
386             taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
387         }
388     }
389
390     // double angle;
391     // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
392     // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
393     // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
394     // GLfloat mat_shininess[] = { 10.0 };
395     GLbitfield clear_mask;
396
397     if ( idle_state != 1000 || !scenery_loaded ) {
398         // still initializing, draw the splash screen
399         if ( fgGetBool("/sim/startup/splash-screen") ) {
400             fgSplashUpdate(0.0, 1.0);
401         }
402         // Keep resetting sim time while the sim is initializing
403         globals->set_sim_time_sec( 0.0 );
404         SGAnimation::set_sim_time_sec( 0.0 );
405     } else {
406         // idle_state is now 1000 meaning we've finished all our
407         // initializations and are running the main loop, so this will
408         // now work without seg faulting the system.
409
410         FGViewer *current__view = globals->get_current_view();
411
412         // calculate our current position in cartesian space
413         globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
414
415         // update view port
416         resize( fgGetInt("/sim/startup/xsize"),
417                    fgGetInt("/sim/startup/ysize") );
418
419         if ( fgGetBool("/sim/rendering/clouds3d") ) {
420             glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
421             cloud3d_imposter_state->force();
422             glDisable( GL_FOG );
423             glColor4f( 1.0, 1.0, 1.0, 1.0 );
424             glEnable(GL_DEPTH_TEST);
425             glEnable(GL_BLEND);
426             glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
427
428 #ifdef FG_USE_CLOUDS_3D
429             if ( _bcloud_orig ) {
430                 Point3D c = globals->get_scenery()->get_center();
431                 sgClouds3d->Set_Cloud_Orig( &c );
432                 _bcloud_orig = false;
433             }
434             sgClouds3d->Update( current__view->get_absolute_view_pos() );
435 #endif
436             glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
437             glDisable(GL_DEPTH_TEST);
438         }
439
440         clear_mask = GL_DEPTH_BUFFER_BIT;
441         if ( fgGetBool("/sim/rendering/wireframe") ) {
442             clear_mask |= GL_COLOR_BUFFER_BIT;
443         }
444
445         if ( skyblend ) {
446             if ( fgGetBool("/sim/rendering/textures") ) {
447             // glClearColor(black[0], black[1], black[2], black[3]);
448             glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
449                          l->adj_fog_color()[2], l->adj_fog_color()[3]);
450             clear_mask |= GL_COLOR_BUFFER_BIT;
451             }
452         } else {
453             glClearColor(l->sky_color()[0], l->sky_color()[1],
454                          l->sky_color()[2], l->sky_color()[3]);
455             clear_mask |= GL_COLOR_BUFFER_BIT;
456         }
457         if ( multi_pass_clouds && draw_clouds ) {
458             glClearStencil( 0 );
459             clear_mask |= GL_STENCIL_BUFFER_BIT;
460         }
461         glClear( clear_mask );
462
463         // Tell GL we are switching to model view parameters
464
465         // I really should create a derived ssg node or use a call
466         // back or something so that I can draw the sky within the
467         // ssgCullAndDraw() function, but for now I just mimic what
468         // ssg does to set up the model view matrix
469         glMatrixMode(GL_MODELVIEW);
470         glLoadIdentity();
471         ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
472
473         // set the opengl state to known default values
474         default_state->force();
475
476         // update fog params if visibility has changed
477         double visibility_meters = fgGetDouble("/environment/visibility-m");
478         thesky->set_visibility(visibility_meters);
479
480         thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
481                             ( global_multi_loop * fgGetInt("/sim/speed-up") )
482                             / (double)fgGetInt("/sim/model-hz") );
483
484         // Set correct opengl fog density
485         glFogf (GL_FOG_DENSITY, fog_exp2_density);
486
487         // update the sky dome
488         if ( skyblend ) {
489             /*
490              SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
491              << l->sky_color()[0] << " "
492              << l->sky_color()[1] << " "
493              << l->sky_color()[2] << " "
494              << l->sky_color()[3] );
495             SG_LOG( SG_GENERAL, SG_BULK, "    fog = "
496              << l->fog_color()[0] << " "
497              << l->fog_color()[1] << " "
498              << l->fog_color()[2] << " "
499              << l->fog_color()[3] ); 
500             SG_LOG( SG_GENERAL, SG_BULK,
501                     "    sun_angle = " << l->sun_angle
502              << "    moon_angle = " << l->moon_angle );
503             */
504
505             static SGSkyColor scolor;
506             FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
507
508             scolor.sky_color   = l->sky_color();
509             scolor.fog_color   = l->adj_fog_color();
510             scolor.cloud_color = l->cloud_color();
511             scolor.sun_angle   = l->get_sun_angle();
512             scolor.moon_angle  = l->get_moon_angle();
513             scolor.nplanets    = globals->get_ephem()->getNumPlanets();
514             scolor.nstars      = globals->get_ephem()->getNumStars();
515             scolor.planet_data = globals->get_ephem()->getPlanets();
516             scolor.star_data   = globals->get_ephem()->getStars();
517
518             thesky->repaint( scolor );
519
520             /*
521             SG_LOG( SG_GENERAL, SG_BULK,
522                     "thesky->reposition( view_pos = " << view_pos[0] << " "
523              << view_pos[1] << " " << view_pos[2] );
524             SG_LOG( SG_GENERAL, SG_BULK,
525                     "    zero_elev = " << zero_elev[0] << " "
526              << zero_elev[1] << " " << zero_elev[2]
527              << " lon = " << cur_fdm_state->get_Longitude()
528              << " lat = " << cur_fdm_state->get_Latitude() );
529             SG_LOG( SG_GENERAL, SG_BULK,
530                     "    sun_rot = " << l->get_sun_rotation
531              << " gst = " << SGTime::cur_time_params->getGst() );
532             SG_LOG( SG_GENERAL, SG_BULK,
533                  "    sun ra = " << globals->get_ephem()->getSunRightAscension()
534               << " sun dec = " << globals->get_ephem()->getSunDeclination()
535               << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
536               << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
537             */
538
539             // The sun and moon distances are scaled down versions
540             // of the actual distance to get both the moon and the sun
541             // within the range of the far clip plane.
542             // Moon distance:    384,467 kilometers
543             // Sun distance: 150,000,000 kilometers
544             double sun_horiz_eff, moon_horiz_eff;
545             if (fgGetBool("/sim/rendering/horizon-effect")) {
546             sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
547             moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
548             } else {
549                sun_horiz_eff = moon_horiz_eff = 1.0;
550             }
551
552             static SGSkyState sstate;
553
554             sstate.view_pos  = current__view->get_view_pos();
555             sstate.zero_elev = current__view->get_zero_elev();
556             sstate.view_up   = current__view->get_world_up();
557             sstate.lon       = current__view->getLongitude_deg()
558                                 * SGD_DEGREES_TO_RADIANS;
559             sstate.lat       = current__view->getLatitude_deg()
560                                 * SGD_DEGREES_TO_RADIANS;
561             sstate.alt       = current__view->getAltitudeASL_ft()
562                                 * SG_FEET_TO_METER;
563             sstate.spin      = l->get_sun_rotation();
564             sstate.gst       = globals->get_time_params()->getGst();
565             sstate.sun_ra    = globals->get_ephem()->getSunRightAscension();
566             sstate.sun_dec   = globals->get_ephem()->getSunDeclination();
567             sstate.sun_dist  = 50000.0 * sun_horiz_eff;
568             sstate.moon_ra   = globals->get_ephem()->getMoonRightAscension();
569             sstate.moon_dec  = globals->get_ephem()->getMoonDeclination();
570             sstate.moon_dist = 40000.0 * moon_horiz_eff;
571
572             thesky->reposition( sstate, delta_time_sec );
573         }
574
575         glEnable( GL_DEPTH_TEST );
576         if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
577             glEnable( GL_FOG );
578             glFogi( GL_FOG_MODE, GL_EXP2 );
579             glFogfv( GL_FOG_COLOR, l->adj_fog_color() );
580         }
581
582         // set sun/lighting parameters
583         ssgGetLight( 0 ) -> setPosition( l->sun_vec() );
584
585         // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
586         // we only update GL_AMBIENT for our lights we will never get
587         // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
588         // explicitely to black.
589         glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
590
591         ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
592         ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
593         ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular() );
594
595         // texture parameters
596         // glEnable( GL_TEXTURE_2D );
597         glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
598         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
599
600         // glMatrixMode( GL_PROJECTION );
601         // glLoadIdentity();
602         ssgSetFOV( current__view->get_h_fov(),
603                    current__view->get_v_fov() );
604
605         double agl =
606             current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
607             - globals->get_scenery()->get_cur_elev();
608
609         if ( agl > 10.0 ) {
610             scene_nearplane = 10.0f;
611             scene_farplane = 120000.0f;
612         } else {
613             scene_nearplane = groundlevel_nearplane->getDoubleValue();
614             scene_farplane = 120000.0f;
615         }
616
617         ssgSetNearFar( scene_nearplane, scene_farplane );
618
619         if ( draw_otw && skyblend ) {
620             // draw the sky backdrop
621
622             // we need a white diffuse light for the phase of the moon
623             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
624             thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
625                              fog_exp2_density );
626             // return to the desired diffuse color
627             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
628         }
629
630         // draw the ssg scene
631         glEnable( GL_DEPTH_TEST );
632
633         ssgSetNearFar( scene_nearplane, scene_farplane );
634
635         if ( fgGetBool("/sim/rendering/wireframe") ) {
636             // draw wire frame
637             glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
638         }
639         if ( draw_otw ) {
640             if ( draw_clouds ) {
641
642                 // Draw the terrain
643                 FGTileMgr::set_tile_filter( true );
644                 sgSetModelFilter( false );
645                 globals->get_aircraft_model()->select( false );
646                 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
647
648                 // Disable depth buffer update, draw the clouds
649                 glDepthMask( GL_FALSE );
650                 thesky->drawUpperClouds();
651                 if ( multi_pass_clouds ) {
652                     thesky->drawLowerClouds();
653                 }
654                 glDepthMask( GL_TRUE );
655
656                 if ( multi_pass_clouds ) {
657                     // Draw the objects except the aircraft
658                     //  and update the stencil buffer with 1
659                     glEnable( GL_STENCIL_TEST );
660                     glStencilFunc( GL_ALWAYS, 1, 1 );
661                     glStencilOp( GL_KEEP, GL_KEEP, GL_REPLACE );
662                 }
663                 FGTileMgr::set_tile_filter( false );
664                 sgSetModelFilter( true );
665                 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
666             } else {
667                 FGTileMgr::set_tile_filter( true );
668                 sgSetModelFilter( true );
669                 globals->get_aircraft_model()->select( false );
670                 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
671             }
672         }
673
674         // This is a bit kludgy.  Every 200 frames, do an extra
675         // traversal of the scene graph without drawing anything, but
676         // with the field-of-view set to 360x360 degrees.  This
677         // ensures that out-of-range random objects that are not in
678         // the current view frustum will still be freed properly.
679         static int counter = 0;
680         counter++;
681         if (counter == 200) {
682             sgFrustum f;
683             f.setFOV(360, 360);
684                     // No need to put the near plane too close;
685                     // this way, at least the aircraft can be
686                     // culled.
687             f.setNearFar(1000, 1000000);
688             sgMat4 m;
689             ssgGetModelviewMatrix(m);
690             FGTileMgr::set_tile_filter( true );
691             sgSetModelFilter( true );
692             globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
693             counter = 0;
694         }
695
696         // change state for lighting here
697
698         // draw runway lighting
699         glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
700         ssgSetNearFar( scene_nearplane, scene_farplane );
701
702         if ( enhanced_lighting ) {
703
704             // Enable states for drawing points with GL_extension
705             glEnable(GL_POINT_SMOOTH);
706
707             if ( distance_attenuation && glPointParameterIsSupported )
708             {
709                 // Enable states for drawing points with GL_extension
710                 glEnable(GL_POINT_SMOOTH);
711
712                 float quadratic[3] = {1.0, 0.001, 0.0000001};
713                 // makes the points fade as they move away
714                 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT, quadratic);
715                 glPointParameterfPtr(GL_POINT_SIZE_MIN_EXT, 1.0); 
716             }
717
718             glPointSize(4.0);
719
720             // blending function for runway lights
721             glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
722         }
723
724         glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
725         glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
726         glEnable(GL_TEXTURE_GEN_S);
727         glEnable(GL_TEXTURE_GEN_T);
728         glPolygonMode(GL_FRONT, GL_POINT);
729
730         // draw runway lighting
731         if ( draw_otw ) {
732             ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
733             ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
734         }
735
736         // change punch through and then draw taxi lighting
737         glFogf ( GL_FOG_DENSITY, fog_exp2_density );
738         // sgVec3 taxi_fog;
739         // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
740         // glFogfv ( GL_FOG_COLOR, taxi_fog );
741         if ( draw_otw ) {
742             ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
743         }
744
745         // clean up lighting
746         glPolygonMode(GL_FRONT, GL_FILL);
747         glDisable(GL_TEXTURE_GEN_S);
748         glDisable(GL_TEXTURE_GEN_T);
749
750         //static int _frame_count = 0;
751         //if (_frame_count % 30 == 0) {
752         //  printf("SSG: %s\n", ssgShowStats());
753         //}
754         //else {
755         //  ssgShowStats();
756         //}
757         //_frame_count++;
758
759
760         if ( enhanced_lighting ) {
761             if ( distance_attenuation && glPointParameterIsSupported ) {
762                 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT,
763                                       default_attenuation);
764             }
765
766             glPointSize(1.0);
767             glDisable(GL_POINT_SMOOTH);
768         }
769
770         // draw ground lighting
771         glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
772         if ( draw_otw ) {
773             ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
774         }
775
776         if ( draw_otw && fgGetBool("/sim/rendering/clouds3d") ) {
777             glDisable( GL_FOG );
778             glDisable( GL_LIGHTING );
779             // cout << "drawing new clouds" << endl;
780
781             glEnable(GL_DEPTH_TEST);
782             glEnable(GL_BLEND);
783             glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
784
785             /*
786             glEnable( GL_TEXTURE_2D );
787             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
788             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
789             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
790             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
791             */
792
793 #ifdef FG_USE_CLOUDS_3D
794             sgClouds3d->Draw((sgVec4 *)current__view->get_VIEW());
795 #endif
796             glEnable( GL_FOG );
797             glEnable( GL_LIGHTING );
798             glEnable( GL_DEPTH_TEST );
799             glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
800         }
801
802         if ( draw_otw && draw_clouds ) {
803             if ( multi_pass_clouds ) {
804                 // Disable depth buffer update, draw the clouds where the
805                 //  objects overwrite the already drawn clouds, by testing
806                 //  the stencil buffer against 1
807                 glDepthMask( GL_FALSE );
808                 glStencilFunc( GL_EQUAL, 1, 1 );
809                 glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
810                 thesky->drawUpperClouds();
811                 thesky->drawLowerClouds();
812                 glDepthMask( GL_TRUE );
813                 glDisable( GL_STENCIL_TEST );
814             } else {
815                 glDepthMask( GL_FALSE );
816                 thesky->drawLowerClouds();
817                 glDepthMask( GL_TRUE );
818             }
819         }
820
821         if ( draw_otw ) {
822             FGTileMgr::set_tile_filter( false );
823             sgSetModelFilter( false );
824             globals->get_aircraft_model()->select( true );
825             globals->get_model_mgr()->draw();
826             globals->get_aircraft_model()->draw();
827             // If the view is internal, the previous line draw the 
828             //  cockpit with modified near/far clip planes and deselect
829             //  the aircraft in the global scenegraph
830             // Otherwise, it just enables the aircraft: The scenegraph
831             //  must be drawn again to see the plane.
832             ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
833             FGTileMgr::set_tile_filter( true );
834             sgSetModelFilter( true );
835             globals->get_aircraft_model()->select( true );
836         }
837
838         // display HUD && Panel
839         glDisable( GL_FOG );
840         glDisable( GL_DEPTH_TEST );
841         // glDisable( GL_CULL_FACE );
842         // glDisable( GL_TEXTURE_2D );
843
844         // update the controls subsystem
845         globals->get_controls()->update(delta_time_sec);
846
847         hud_and_panel->apply();
848         fgCockpitUpdate();
849
850         // Use the hud_and_panel ssgSimpleState for rendering the ATC output
851         // This only works properly if called before the panel call
852         if((fgGetBool("/sim/ATC/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
853             globals->get_ATC_display()->update(delta_time_sec);
854
855         // update the panel subsystem
856         if ( globals->get_current_panel() != NULL ) {
857             globals->get_current_panel()->update(delta_time_sec);
858         }
859         fgUpdate3DPanels();
860
861         // We can do translucent menus, so why not. :-)
862         menus->apply();
863         glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
864         puDisplay();
865         // glDisable ( GL_BLEND ) ;
866
867         glEnable( GL_DEPTH_TEST );
868         glEnable( GL_FOG );
869
870         // Fade out the splash screen over the first three seconds.
871         double t = globals->get_sim_time_sec();
872         if ( t <= 1.0 ) {
873             fgSplashUpdate(0.0, 1.0);
874         } else if ( t <= 3.0) {
875             fgSplashUpdate(0.0, (3.0 - t) / 2.0);
876         }
877     }
878 }
879
880
881
882 // options.cxx needs to see this for toggle_panel()
883 // Handle new window size or exposure
884 void
885 FGRenderer::resize( int width, int height ) {
886     int view_h;
887
888     if ( (!fgGetBool("/sim/virtual-cockpit"))
889          && fgPanelVisible() && idle_state == 1000 ) {
890         view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
891                              globals->get_current_panel()->getYOffset()) / 768.0);
892     } else {
893         view_h = height;
894     }
895
896     glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
897
898     fgSetInt("/sim/startup/xsize", width);
899     fgSetInt("/sim/startup/ysize", height);
900     guiInitMouse(width, height);
901
902     // for all views
903     FGViewMgr *viewmgr = globals->get_viewmgr();
904     if (viewmgr) {
905       for ( int i = 0; i < viewmgr->size(); ++i ) {
906         viewmgr->get_view(i)->
907           set_aspect_ratio((float)view_h / (float)width);
908       }
909
910       ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
911                viewmgr->get_current_view()->get_v_fov() );
912
913 #ifdef FG_USE_CLOUDS_3D
914       sgClouds3d->Resize( viewmgr->get_current_view()->get_h_fov(),
915                viewmgr->get_current_view()->get_v_fov() );
916 #endif
917     }
918
919     fgHUDReshape();
920
921 }
922
923
924 // end of renderer.cxx