]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Attempt #1 to sort out confusion between left / right / parking brake
[flightgear.git] / src / Main / main.cxx
1 // main.cxx -- top level sim routines
2 //
3 // Written by Curtis Olson, started May 1997.
4 //
5 // Copyright (C) 1997 - 2002  Curtis L. Olson  - curt@flightgear.org
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29
30 #if defined(__linux__) && defined(__i386__)
31 #  include <fpu_control.h>
32 #  include <signal.h>
33 #endif
34
35 #ifdef SG_MATH_EXCEPTION_CLASH
36 #  include <math.h>
37 #endif
38
39 #ifdef HAVE_WINDOWS_H
40 #  include <windows.h>
41 #  include <float.h>
42 #endif
43
44 #include <plib/ssg.h>
45 #include <plib/pu.h>
46 #include <plib/netSocket.h>
47
48 #include <simgear/screen/extensions.hxx>
49 #include <simgear/scene/material/matlib.hxx>
50 #include <simgear/props/props.hxx>
51 #include <simgear/scene/sky/sky.hxx>
52 #include <simgear/timing/sg_time.hxx>
53 #include <simgear/scene/model/animation.hxx>
54 #include <simgear/ephemeris/ephemeris.hxx>
55 #include <simgear/scene/model/placement.hxx>
56 #include <simgear/math/sg_random.h>
57 #include <simgear/route/route.hxx>
58 #include <simgear/scene/model/modellib.hxx>
59
60 #ifdef FG_USE_CLOUDS_3D
61 #  include <simgear/scene/sky/clouds3d/SkySceneLoader.hpp>
62 #  include <simgear/scene/sky/clouds3d/SkyUtil.hpp>
63 #endif
64
65 #include <Include/general.hxx>
66 #include <Scenery/tileentry.hxx>
67 #include <Time/light.hxx>
68 #include <Time/light.hxx>
69 #include <Aircraft/aircraft.hxx>
70 #include <Cockpit/panel.hxx>
71 #include <Cockpit/cockpit.hxx>
72 #include <Cockpit/radiostack.hxx>
73 #include <Cockpit/hud.hxx>
74 #include <Model/panelnode.hxx>
75 #include <Model/modelmgr.hxx>
76 #include <Model/acmodel.hxx>
77 #include <Scenery/scenery.hxx>
78 #include <Scenery/tilemgr.hxx>
79 #include <FDM/flight.hxx>
80 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
81 #include <FDM/ADA.hxx>
82 #include <ATC/ATCdisplay.hxx>
83 #include <ATC/ATCmgr.hxx>
84 #include <ATC/AIMgr.hxx>
85 #include <Autopilot/newauto.hxx>
86 #include <Replay/replay.hxx>
87 #include <Time/tmp.hxx>
88 #include <Time/fg_timer.hxx>
89 #include <Environment/environment_mgr.hxx>
90
91 #ifdef FG_MPLAYER_AS
92 #include <MultiPlayer/multiplaytxmgr.hxx>
93 #include <MultiPlayer/multiplayrxmgr.hxx>
94 #endif
95
96 #include "splash.hxx"
97 #include "fg_commands.hxx"
98 #include "fg_io.hxx"
99 #include "main.hxx"
100
101 float default_attenuation[3] = {1.0, 0.0, 0.0};
102 ssgSelector *ship_sel=NULL;
103 // upto 32 instances of a same object can be loaded.
104 ssgTransform *ship_pos[32];
105 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
106 int objc=0;
107 ssgSelector *lightpoints_brightness = new ssgSelector;
108 ssgTransform *lightpoints_transform = new ssgTransform;
109 FGTileEntry *dummy_tile;
110 sgVec3 rway_ols;
111 // ADA
112 // Clip plane settings...
113 float scene_nearplane = 0.5f;
114 float scene_farplane = 120000.0f;
115
116 static double real_delta_time_sec = 0.0;
117 static double delta_time_sec = 0.0;
118
119 glPointParameterfProc glPointParameterfPtr = 0;
120 glPointParameterfvProc glPointParameterfvPtr = 0;
121 bool glPointParameterIsSupported = false;
122
123
124 #ifdef FG_WEATHERCM
125 #  include <WeatherCM/FGLocalWeatherDatabase.h>
126 #endif
127
128 #ifdef macintosh
129 #  include <console.h>          // -dw- for command line dialog
130 #endif
131
132 // This is a record containing a bit of global housekeeping information
133 FGGeneral general;
134
135 // Specify our current idle function state.  This is used to run all
136 // our initializations out of the glutIdleLoop() so that we can get a
137 // splash screen up and running right away.
138 static int idle_state = 0;
139 static long global_multi_loop;
140
141 // fog constants.  I'm a little nervous about putting actual code out
142 // here but it seems to work (?)
143 static const double m_log01 = -log( 0.01 );
144 static const double sqrt_m_log01 = sqrt( m_log01 );
145 static GLfloat fog_exp_density;
146 static GLfloat fog_exp2_density;
147 static GLfloat rwy_exp2_punch_through;
148 static GLfloat taxi_exp2_punch_through;
149 static GLfloat ground_exp2_punch_through;
150
151 // Sky structures
152 SGSky *thesky;
153
154 #ifdef FG_USE_CLOUDS_3D
155   SkySceneLoader *sgClouds3d;
156   bool _bcloud_orig = true;
157 #endif
158
159 // hack
160 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
161 {
162   {  1.0f,  0.0f,  0.0f,  0.0f },
163   {  0.0f,  0.0f, -1.0f,  0.0f },
164   {  0.0f,  1.0f,  0.0f,  0.0f },
165   {  0.0f,  0.0f,  0.0f,  1.0f }
166 };
167
168 // The following defines flightgear options. Because glutlib will also
169 // want to parse its own options, those options must not be included here
170 // or they will get parsed by the main program option parser. Hence case
171 // is significant for any option added that might be in conflict with
172 // glutlib's parser.
173 //
174 // glutlib parses for:
175 //    -display
176 //    -direct   (invalid in Win32)
177 //    -geometry
178 //    -gldebug
179 //    -iconized
180 //    -indirect (invalid in Win32)
181 //    -synce
182 //
183 // Note that glutlib depends upon strings while this program's
184 // option parser wants only initial characters followed by numbers
185 // or pathnames.
186 //
187
188
189 ssgSimpleState *cloud3d_imposter_state;
190 ssgSimpleState *default_state;
191 ssgSimpleState *hud_and_panel;
192 ssgSimpleState *menus;
193
194 SGTimeStamp last_time_stamp;
195 SGTimeStamp current_time_stamp;
196
197
198 void fgBuildRenderStates( void ) {
199     default_state = new ssgSimpleState;
200     default_state->ref();
201     default_state->disable( GL_TEXTURE_2D );
202     default_state->enable( GL_CULL_FACE );
203     default_state->enable( GL_COLOR_MATERIAL );
204     default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
205     default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
206     default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
207     default_state->disable( GL_BLEND );
208     default_state->disable( GL_ALPHA_TEST );
209     default_state->disable( GL_LIGHTING );
210
211     cloud3d_imposter_state = new ssgSimpleState;
212     cloud3d_imposter_state->ref();
213     cloud3d_imposter_state->enable( GL_TEXTURE_2D );
214     cloud3d_imposter_state->enable( GL_CULL_FACE );
215     cloud3d_imposter_state->enable( GL_COLOR_MATERIAL );
216     cloud3d_imposter_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
217     cloud3d_imposter_state->setMaterial( GL_DIFFUSE, 1, 1, 1, 1 );
218     cloud3d_imposter_state->setMaterial( GL_AMBIENT, 1, 1, 1, 1 );
219     cloud3d_imposter_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
220     cloud3d_imposter_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
221     cloud3d_imposter_state->enable( GL_BLEND );
222     cloud3d_imposter_state->enable( GL_ALPHA_TEST );
223     cloud3d_imposter_state->disable( GL_LIGHTING );
224
225     hud_and_panel = new ssgSimpleState;
226     hud_and_panel->ref();
227     hud_and_panel->disable( GL_CULL_FACE );
228     hud_and_panel->disable( GL_TEXTURE_2D );
229     hud_and_panel->disable( GL_LIGHTING );
230     hud_and_panel->enable( GL_BLEND );
231
232     menus = new ssgSimpleState;
233     menus->ref();
234     menus->disable( GL_CULL_FACE );
235     menus->disable( GL_TEXTURE_2D );
236     menus->enable( GL_BLEND );
237 }
238
239
240 // fgInitVisuals() -- Initialize various GL/view parameters
241 void fgInitVisuals( void ) {
242
243     FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
244
245 #ifndef GLUT_WRONG_VERSION
246     // Go full screen if requested ...
247     if ( fgGetBool("/sim/startup/fullscreen") ) {
248         glutFullScreen();
249     }
250 #endif
251
252     // If enabled, normal vectors specified with glNormal are scaled
253     // to unit length after transformation.  Enabling this has
254     // performance implications.  See the docs for glNormal.
255     // glEnable( GL_NORMALIZE );
256
257     glEnable( GL_LIGHTING );
258     glEnable( GL_LIGHT0 );
259     // glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );  // done later with ssg
260
261     sgVec3 sunpos;
262     sgSetVec3( sunpos, l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2] );
263     ssgGetLight( 0 ) -> setPosition( sunpos );
264
265     glFogi (GL_FOG_MODE, GL_EXP2);
266     if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) || 
267          (!fgGetBool("/sim/rendering/shading"))) {
268         // if fastest fog requested, or if flat shading force fastest
269         glHint ( GL_FOG_HINT, GL_FASTEST );
270     } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
271         glHint ( GL_FOG_HINT, GL_NICEST );
272     }
273     if ( fgGetBool("/sim/rendering/wireframe") ) {
274         // draw wire frame
275         glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
276     }
277
278     // This is the default anyways, but it can't hurt
279     glFrontFace ( GL_CCW );
280
281     // Just testing ...
282     // glEnable(GL_POINT_SMOOTH);
283     // glEnable(GL_LINE_SMOOTH);
284     // glEnable(GL_POLYGON_SMOOTH);      
285 }
286
287
288 // For HiRes screen Dumps using Brian Pauls TR Library
289 void trRenderFrame( void ) {
290
291     if ( fgPanelVisible() ) {
292         GLfloat height = fgGetInt("/sim/startup/ysize");
293         GLfloat view_h =
294             (globals->get_current_panel()->getViewHeight() - globals->get_current_panel()->getYOffset())
295             * (height / 768.0) + 1;
296         glTranslatef( 0.0, view_h, 0.0 );
297     }
298
299     static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
300     static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
301
302     FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
303
304     glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1], 
305                  l->adj_fog_color()[2], l->adj_fog_color()[3]);
306
307     glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
308
309     // set the opengl state to known default values
310     default_state->force();
311
312     glEnable( GL_FOG );
313     glFogf  ( GL_FOG_DENSITY, fog_exp2_density);
314     glFogi  ( GL_FOG_MODE,    GL_EXP2 );
315     glFogfv ( GL_FOG_COLOR,   l->adj_fog_color() );
316
317     // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
318     // we only update GL_AMBIENT for our lights we will never get
319     // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
320     // explicitely to black.
321     glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
322     glLightModeli( GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE );
323
324     ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
325
326     // texture parameters
327     glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
328     glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
329
330     // we need a white diffuse light for the phase of the moon
331     ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
332     thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER, fog_exp2_density );
333
334     // draw the ssg scene
335     // return to the desired diffuse color
336     ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
337     glEnable( GL_DEPTH_TEST );
338     ssgSetNearFar( scene_nearplane, scene_farplane );
339     ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
340
341     // draw the lights
342     glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
343     ssgSetNearFar( scene_nearplane, scene_farplane );
344     ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
345     ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
346
347     ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
348
349     if (fgGetBool("/environment/clouds/status"))
350         thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
351
352     globals->get_model_mgr()->draw();
353     globals->get_aircraft_model()->draw();
354 }
355
356
357 // Update all Visuals (redraws anything graphics related)
358 void fgRenderFrame() {
359     bool draw_otw = fgGetBool("/sim/rendering/draw-otw");
360     bool skyblend = fgGetBool("/sim/rendering/skyblend");
361     bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
362     bool distance_attenuation = fgGetBool("/sim/rendering/distance-attenuation");
363
364     GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
365     GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
366
367     // static const SGPropertyNode *longitude
368     //     = fgGetNode("/position/longitude-deg");
369     // static const SGPropertyNode *latitude
370     //     = fgGetNode("/position/latitude-deg");
371     // static const SGPropertyNode *altitude
372     //     = fgGetNode("/position/altitude-ft");
373     static const SGPropertyNode *groundlevel_nearplane
374         = fgGetNode("/sim/current-view/ground-level-nearplane-m");
375
376     // Update the default (kludged) properties.
377     fgUpdateProps();
378
379     FGViewer *current__view = globals->get_current_view();
380
381     FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
382     static double last_visibility = -9999;
383
384     // update fog params
385     double actual_visibility;
386     if (fgGetBool("/environment/clouds/status"))
387         actual_visibility = thesky->get_visibility();
388     else
389         actual_visibility = fgGetDouble("/environment/visibility-m");
390     if ( actual_visibility != last_visibility ) {
391         last_visibility = actual_visibility;
392
393         fog_exp_density = m_log01 / actual_visibility;
394         fog_exp2_density = sqrt_m_log01 / actual_visibility;
395         ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
396         if ( actual_visibility < 8000 ) {
397             rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
398             taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
399         } else {
400             rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
401             taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
402         }
403     }
404
405     // double angle;
406     // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
407     // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
408     // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
409     // GLfloat mat_shininess[] = { 10.0 };
410     GLbitfield clear_mask;
411
412     if ( idle_state != 1000 ) {
413         // still initializing, draw the splash screen
414         if ( fgGetBool("/sim/startup/splash-screen") ) {
415             fgSplashUpdate(0.0, 1.0);
416         }
417         // Keep resetting sim time while the sim is initializing
418         globals->set_sim_time_sec( 0.0 );
419         SGAnimation::set_sim_time_sec( 0.0 );
420     } else {
421         // idle_state is now 1000 meaning we've finished all our
422         // initializations and are running the main loop, so this will
423         // now work without seg faulting the system.
424
425         // calculate our current position in cartesian space
426         globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
427
428         // update view port
429         fgReshape( fgGetInt("/sim/startup/xsize"),
430                    fgGetInt("/sim/startup/ysize") );
431
432         if ( fgGetBool("/sim/rendering/clouds3d") ) {
433             glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
434             cloud3d_imposter_state->force();
435             glDisable( GL_FOG );
436             glColor4f( 1.0, 1.0, 1.0, 1.0 );
437             glEnable(GL_DEPTH_TEST);
438             glEnable(GL_BLEND);
439             glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
440
441 #ifdef FG_USE_CLOUDS_3D
442             if ( _bcloud_orig ) {
443                 Point3D c = globals->get_scenery()->get_center();
444                 sgClouds3d->Set_Cloud_Orig( &c );
445                 _bcloud_orig = false;
446             }
447             sgClouds3d->Update( current__view->get_absolute_view_pos() );
448 #endif
449             glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
450             glDisable(GL_DEPTH_TEST);
451         }
452
453         clear_mask = GL_DEPTH_BUFFER_BIT;
454         if ( fgGetBool("/sim/rendering/wireframe") ) {
455             clear_mask |= GL_COLOR_BUFFER_BIT;
456         }
457
458         if ( skyblend ) {
459             if ( fgGetBool("/sim/rendering/textures") ) {
460             // glClearColor(black[0], black[1], black[2], black[3]);
461             glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
462                          l->adj_fog_color()[2], l->adj_fog_color()[3]);
463             clear_mask |= GL_COLOR_BUFFER_BIT;
464             }
465         } else {
466             glClearColor(l->sky_color()[0], l->sky_color()[1],
467                          l->sky_color()[2], l->sky_color()[3]);
468             clear_mask |= GL_COLOR_BUFFER_BIT;
469         }
470         glClear( clear_mask );
471
472         // Tell GL we are switching to model view parameters
473
474         // I really should create a derived ssg node or use a call
475         // back or something so that I can draw the sky within the
476         // ssgCullAndDraw() function, but for now I just mimic what
477         // ssg does to set up the model view matrix
478         glMatrixMode(GL_MODELVIEW);
479         glLoadIdentity();
480         ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
481
482         // set the opengl state to known default values
483         default_state->force();
484
485         // update fog params if visibility has changed
486         double visibility_meters = fgGetDouble("/environment/visibility-m");
487         thesky->set_visibility(visibility_meters);
488
489         thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
490                             ( global_multi_loop * fgGetInt("/sim/speed-up") )
491                             / (double)fgGetInt("/sim/model-hz") );
492
493         // Set correct opengl fog density
494         glFogf (GL_FOG_DENSITY, fog_exp2_density);
495
496         // update the sky dome
497         if ( skyblend ) {
498             /*
499              SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
500              << l->sky_color()[0] << " "
501              << l->sky_color()[1] << " "
502              << l->sky_color()[2] << " "
503              << l->sky_color()[3] );
504             SG_LOG( SG_GENERAL, SG_BULK, "    fog = "
505              << l->fog_color()[0] << " "
506              << l->fog_color()[1] << " "
507              << l->fog_color()[2] << " "
508              << l->fog_color()[3] ); 
509             SG_LOG( SG_GENERAL, SG_BULK,
510                     "    sun_angle = " << l->sun_angle
511              << "    moon_angle = " << l->moon_angle );
512             */
513
514             static SGSkyColor scolor;
515             FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
516
517             scolor.sky_color   = l->sky_color();
518             scolor.fog_color   = l->adj_fog_color();
519             scolor.cloud_color = l->cloud_color();
520             scolor.sun_angle   = l->get_sun_angle();
521             scolor.moon_angle  = l->get_moon_angle();
522             scolor.nplanets    = globals->get_ephem()->getNumPlanets();
523             scolor.nstars      = globals->get_ephem()->getNumStars();
524             scolor.planet_data = globals->get_ephem()->getPlanets();
525             scolor.star_data   = globals->get_ephem()->getStars();
526
527             thesky->repaint( scolor );
528
529             /*
530             SG_LOG( SG_GENERAL, SG_BULK,
531                     "thesky->reposition( view_pos = " << view_pos[0] << " "
532              << view_pos[1] << " " << view_pos[2] );
533             SG_LOG( SG_GENERAL, SG_BULK,
534                     "    zero_elev = " << zero_elev[0] << " "
535              << zero_elev[1] << " " << zero_elev[2]
536              << " lon = " << cur_fdm_state->get_Longitude()
537              << " lat = " << cur_fdm_state->get_Latitude() );
538             SG_LOG( SG_GENERAL, SG_BULK,
539                     "    sun_rot = " << l->get_sun_rotation
540              << " gst = " << SGTime::cur_time_params->getGst() );
541             SG_LOG( SG_GENERAL, SG_BULK,
542                  "    sun ra = " << globals->get_ephem()->getSunRightAscension()
543               << " sun dec = " << globals->get_ephem()->getSunDeclination()
544               << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
545               << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
546             */
547
548             // The sun and moon distances are scaled down versions
549             // of the actual distance to get both the moon and the sun
550             // within the range of the far clip plane.
551             // Moon distance:    384,467 kilometers
552             // Sun distance: 150,000,000 kilometers
553             double sun_horiz_eff, moon_horiz_eff;
554             if (fgGetBool("/sim/rendering/horizon-effect")) {
555             sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
556             moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
557             } else {
558                sun_horiz_eff = moon_horiz_eff = 1.0;
559             }
560
561             static SGSkyState sstate;
562
563             sstate.view_pos  = current__view->get_view_pos();
564             sstate.zero_elev = current__view->get_zero_elev();
565             sstate.view_up   = current__view->get_world_up();
566             sstate.lon       = current__view->getLongitude_deg()
567                                 * SGD_DEGREES_TO_RADIANS;
568             sstate.lat       = current__view->getLatitude_deg()
569                                 * SGD_DEGREES_TO_RADIANS;
570             sstate.alt       = current__view->getAltitudeASL_ft()
571                                 * SG_FEET_TO_METER;
572             sstate.spin      = l->get_sun_rotation();
573             sstate.gst       = globals->get_time_params()->getGst();
574             sstate.sun_ra    = globals->get_ephem()->getSunRightAscension();
575             sstate.sun_dec   = globals->get_ephem()->getSunDeclination();
576             sstate.sun_dist  = 50000.0 * sun_horiz_eff;
577             sstate.moon_ra   = globals->get_ephem()->getMoonRightAscension();
578             sstate.moon_dec  = globals->get_ephem()->getMoonDeclination();
579             sstate.moon_dist = 40000.0 * moon_horiz_eff;
580
581             thesky->reposition( sstate, delta_time_sec );
582         }
583
584         glEnable( GL_DEPTH_TEST );
585         if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
586             glEnable( GL_FOG );
587             glFogi( GL_FOG_MODE, GL_EXP2 );
588             glFogfv( GL_FOG_COLOR, l->adj_fog_color() );
589         }
590
591         // set sun/lighting parameters
592         ssgGetLight( 0 ) -> setPosition( l->sun_vec() );
593
594         // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
595         // we only update GL_AMBIENT for our lights we will never get
596         // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
597         // explicitely to black.
598         glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
599
600         ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
601         ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
602         ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular() );
603
604         // texture parameters
605         // glEnable( GL_TEXTURE_2D );
606         glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
607         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
608
609         // glMatrixMode( GL_PROJECTION );
610         // glLoadIdentity();
611         ssgSetFOV( current__view->get_h_fov(),
612                    current__view->get_v_fov() );
613
614         double agl =
615             current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
616             - globals->get_scenery()->get_cur_elev();
617
618         if ( agl > 10.0 ) {
619             scene_nearplane = 10.0f;
620             scene_farplane = 120000.0f;
621         } else {
622             scene_nearplane = groundlevel_nearplane->getDoubleValue();
623             scene_farplane = 120000.0f;
624         }
625
626         ssgSetNearFar( scene_nearplane, scene_farplane );
627
628 #ifdef FG_MPLAYER_AS
629         // Update any multiplayer models
630         globals->get_multiplayer_rx_mgr()->Update();
631 #endif
632
633         if ( draw_otw && skyblend )
634         {
635             // draw the sky backdrop
636
637             // we need a white diffuse light for the phase of the moon
638             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
639
640             thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER, fog_exp2_density );
641
642             // return to the desired diffuse color
643             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
644         }
645
646         // draw the ssg scene
647         glEnable( GL_DEPTH_TEST );
648
649         ssgSetNearFar( scene_nearplane, scene_farplane );
650
651         if ( fgGetBool("/sim/rendering/wireframe") ) {
652             // draw wire frame
653             glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
654         }
655         if ( draw_otw ) {
656             ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
657         }
658
659         // This is a bit kludgy.  Every 200 frames, do an extra
660         // traversal of the scene graph without drawing anything, but
661         // with the field-of-view set to 360x360 degrees.  This
662         // ensures that out-of-range random objects that are not in
663         // the current view frustum will still be freed properly.
664         static int counter = 0;
665         counter++;
666         if (counter == 200) {
667           sgFrustum f;
668           f.setFOV(360, 360);
669                             // No need to put the near plane too close;
670                             // this way, at least the aircraft can be
671                             // culled.
672           f.setNearFar(1000, 1000000);
673           sgMat4 m;
674           ssgGetModelviewMatrix(m);
675           globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
676           counter = 0;
677         }
678
679         // change state for lighting here
680
681         // draw runway lighting
682         glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
683         ssgSetNearFar( scene_nearplane, scene_farplane );
684
685         if ( enhanced_lighting ) {
686
687             // Enable states for drawing points with GL_extension
688             glEnable(GL_POINT_SMOOTH);
689
690             if ( distance_attenuation && glPointParameterIsSupported )
691             {
692                 // Enable states for drawing points with GL_extension
693                 glEnable(GL_POINT_SMOOTH);
694
695                 float quadratic[3] = {1.0, 0.001, 0.0000001};
696                 // makes the points fade as they move away
697                 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT, quadratic);
698                 glPointParameterfPtr(GL_POINT_SIZE_MIN_EXT, 1.0); 
699             }
700
701             glPointSize(4.0);
702
703             // blending function for runway lights
704             glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
705         }
706
707         glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
708         glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
709         glEnable(GL_TEXTURE_GEN_S);
710         glEnable(GL_TEXTURE_GEN_T);
711         glPolygonMode(GL_FRONT, GL_POINT);
712
713         // draw runway lighting
714         if ( draw_otw ) {
715             ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
716             ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
717         }
718
719         // change punch through and then draw taxi lighting
720         glFogf ( GL_FOG_DENSITY, fog_exp2_density );
721         // sgVec3 taxi_fog;
722         // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
723         // glFogfv ( GL_FOG_COLOR, taxi_fog );
724         if ( draw_otw ) {
725             ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
726         }
727
728         // clean up lighting
729         glPolygonMode(GL_FRONT, GL_FILL);
730         glDisable(GL_TEXTURE_GEN_S);
731         glDisable(GL_TEXTURE_GEN_T);
732
733         //static int _frame_count = 0;
734         //if (_frame_count % 30 == 0) {
735         //  printf("SSG: %s\n", ssgShowStats());
736         //}
737         //else {
738         //  ssgShowStats();
739         //}
740         //_frame_count++;
741
742
743         if ( enhanced_lighting ) {
744             if ( distance_attenuation && glPointParameterIsSupported )
745             {
746                 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT,
747                                       default_attenuation);
748             }
749
750             glPointSize(1.0);
751             glDisable(GL_POINT_SMOOTH);
752         }
753
754         // draw ground lighting
755         glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
756         if ( draw_otw ) {
757             ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
758         }
759
760         if ( skyblend ) {
761             // draw the sky cloud layers
762             if ( draw_otw && fgGetBool("/environment/clouds/status") )
763             {
764                 thesky->postDraw( cur_fdm_state->get_Altitude()
765                                   * SG_FEET_TO_METER );
766             }
767         }
768
769         if ( draw_otw && fgGetBool("/sim/rendering/clouds3d") )
770         {
771             glDisable( GL_FOG );
772             glDisable( GL_LIGHTING );
773             // cout << "drawing new clouds" << endl;
774
775             glEnable(GL_DEPTH_TEST);
776             glEnable(GL_BLEND);
777             glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
778
779             /*
780             glEnable( GL_TEXTURE_2D );
781             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
782             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
783             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
784             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
785             */
786
787 #ifdef FG_USE_CLOUDS_3D
788             sgClouds3d->Draw((sgVec4 *)current__view->get_VIEW());
789 #endif
790             glEnable( GL_FOG );
791             glEnable( GL_LIGHTING );
792             glEnable( GL_DEPTH_TEST );
793             glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
794         }
795
796         if ( draw_otw ) {
797             globals->get_model_mgr()->draw();
798             globals->get_aircraft_model()->draw();
799         }
800
801         // display HUD && Panel
802         glDisable( GL_FOG );
803         glDisable( GL_DEPTH_TEST );
804         // glDisable( GL_CULL_FACE );
805         // glDisable( GL_TEXTURE_2D );
806
807         // update the controls subsystem
808         globals->get_controls()->update(delta_time_sec);
809
810         hud_and_panel->apply();
811         fgCockpitUpdate();
812
813         // Use the hud_and_panel ssgSimpleState for rendering the ATC output
814         // This only works properly if called before the panel call
815         if((fgGetBool("/sim/ATC/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
816             globals->get_ATC_display()->update(delta_time_sec);
817
818         // update the panel subsystem
819         if ( globals->get_current_panel() != NULL ) {
820             globals->get_current_panel()->update(delta_time_sec);
821         }
822         fgUpdate3DPanels();
823
824         // We can do translucent menus, so why not. :-)
825         menus->apply();
826         glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
827         puDisplay();
828         // glDisable ( GL_BLEND ) ;
829
830         glEnable( GL_DEPTH_TEST );
831         glEnable( GL_FOG );
832
833         // Fade out the splash screen over the first three seconds.
834         double t = globals->get_sim_time_sec();
835         if ( t <= 1.0 ) {
836             fgSplashUpdate(0.0, 1.0);
837         } else if ( t <= 3.0) {
838             fgSplashUpdate(0.0, (3.0 - t) / 2.0);
839         }
840     }
841
842     glutSwapBuffers();
843 }
844
845
846 // Update internal time dependent calculations (i.e. flight model)
847 // FIXME: this distinction is obsolete; all subsystems now get delta
848 // time on update.
849 void fgUpdateTimeDepCalcs() {
850     static bool inited = false;
851
852     static const SGPropertyNode *replay_master
853         = fgGetNode( "/sim/freeze/replay", true );
854     static SGPropertyNode *replay_time
855         = fgGetNode( "/sim/replay/time", true );
856     static const SGPropertyNode *replay_end_time
857         = fgGetNode( "/sim/replay/end-time", true );
858
859     //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
860
861     // Initialize the FDM here if it hasn't been and if we have a
862     // scenery elevation hit.
863
864     // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited() 
865     //      << " cur_elev = " << scenery.get_cur_elev() << endl;
866
867     if ( !cur_fdm_state->get_inited() &&
868          globals->get_scenery()->get_cur_elev() > -9990 )
869     {
870         SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");  
871         cur_fdm_state->init();
872         if ( cur_fdm_state->get_bound() ) {
873             cur_fdm_state->unbind();
874         }
875         cur_fdm_state->bind();
876     }
877
878     // conceptually, the following block could be done for each fdm
879     // instance ...
880     if ( cur_fdm_state->get_inited() ) {
881         // we have been inited, and  we are good to go ...
882
883         if ( !inited ) {
884             inited = true;
885         }
886
887         if ( ! replay_master->getBoolValue() ) {
888             globals->get_autopilot()->update( delta_time_sec );
889             cur_fdm_state->update( delta_time_sec );
890         } else {
891             FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
892             r->replay( replay_time->getDoubleValue() );
893             replay_time->setDoubleValue( replay_time->getDoubleValue()
894                                          + ( delta_time_sec
895                                              * fgGetInt("/sim/speed-up") ) );
896         }
897     } else {
898         // do nothing, fdm isn't inited yet
899     }
900
901     globals->get_model_mgr()->update(delta_time_sec);
902     globals->get_aircraft_model()->update(delta_time_sec);
903
904     // update the view angle
905     globals->get_viewmgr()->update(delta_time_sec);
906
907     // Update solar system
908     globals->get_ephem()->update( globals->get_time_params()->getMjd(),
909                                   globals->get_time_params()->getLst(),
910                                   cur_fdm_state->get_Latitude() );
911
912     // Update radio stack model
913     current_radiostack->update(delta_time_sec);
914 }
915
916
917 void fgInitTimeDepCalcs( void ) {
918     // noop for now
919 }
920
921
922 static const double alt_adjust_ft = 3.758099;
923 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
924
925
926 // What should we do when we have nothing else to do?  Let's get ready
927 // for the next move and update the display?
928 static void fgMainLoop( void ) {
929     int model_hz = fgGetInt("/sim/model-hz");
930
931     static const SGPropertyNode *longitude
932         = fgGetNode("/position/longitude-deg");
933     static const SGPropertyNode *latitude
934         = fgGetNode("/position/latitude-deg");
935     static const SGPropertyNode *altitude
936         = fgGetNode("/position/altitude-ft");
937     static const SGPropertyNode *clock_freeze
938         = fgGetNode("/sim/freeze/clock", true);
939     static const SGPropertyNode *cur_time_override
940         = fgGetNode("/sim/time/cur-time-override", true);
941     static const SGPropertyNode *replay_master
942         = fgGetNode("/sim/freeze/replay", true);
943
944     // Update the elapsed time.
945     static bool first_time = true;
946     if ( first_time ) {
947         last_time_stamp.stamp();
948         first_time = false;
949     }
950
951     double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
952     if ( throttle_hz > 0.0 ) {
953         // simple frame rate throttle
954         double dt = 1000000.0 / throttle_hz;
955         current_time_stamp.stamp();
956         while ( current_time_stamp - last_time_stamp < dt ) {
957             current_time_stamp.stamp();
958         }
959     } else {
960         // run as fast as the app will go
961         current_time_stamp.stamp();
962     }
963
964     real_delta_time_sec
965         = double(current_time_stamp - last_time_stamp) / 1000000.0;
966     if ( clock_freeze->getBoolValue() ) {
967         delta_time_sec = 0;
968     } else {
969         delta_time_sec = real_delta_time_sec;
970     }
971     last_time_stamp = current_time_stamp;
972     globals->inc_sim_time_sec( delta_time_sec );
973     SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
974
975     // These are useful, especially for Nasal scripts.
976     fgSetDouble("/sim/time/delta-realtime-sec", real_delta_time_sec);
977     fgSetDouble("/sim/time/delta-sec", delta_time_sec);
978
979     static long remainder = 0;
980     long elapsed;
981 #ifdef FANCY_FRAME_COUNTER
982     int i;
983     double accum;
984 #else
985     static time_t last_time = 0;
986     static int frames = 0;
987 #endif // FANCY_FRAME_COUNTER
988
989     SGTime *t = globals->get_time_params();
990
991     globals->get_event_mgr()->update(delta_time_sec);
992
993     SGLocation * acmodel_location = 0;
994     if(cur_fdm_state->getACModel() != 0) {
995       acmodel_location = (SGLocation *)  cur_fdm_state->getACModel()->get3DModel()->getSGLocation();
996     }
997
998     SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
999     SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
1000
1001 #if defined( ENABLE_PLIB_JOYSTICK )
1002     // Read joystick and update control settings
1003     // if ( fgGetString("/sim/control-mode") == "joystick" )
1004     // {
1005     //    fgJoystickRead();
1006     // }
1007 #elif defined( ENABLE_GLUT_JOYSTICK )
1008     // Glut joystick support works by feeding a joystick handler
1009     // function to glut.  This is taken care of once in the joystick
1010     // init routine and we don't have to worry about it again.
1011 #endif
1012
1013     // Fix elevation.  I'm just sticking this here for now, it should
1014     // probably move eventually
1015
1016     /* printf("Before - ground = %.2f  runway = %.2f  alt = %.2f\n",
1017            scenery.get_cur_elev(),
1018            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1019            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1020
1021     /* printf("Adjustment - ground = %.2f  runway = %.2f  alt = %.2f\n",
1022            scenery.get_cur_elev(),
1023            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1024            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1025
1026     // cout << "Warp = " << globals->get_warp() << endl;
1027
1028     // update "time"
1029     static bool last_clock_freeze = false;
1030
1031     if ( clock_freeze->getBoolValue() ) {
1032         // clock freeze requested
1033         if ( cur_time_override->getLongValue() == 0 ) {
1034             fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
1035             globals->set_warp( 0 );
1036         }
1037     } else {
1038         // no clock freeze requested
1039         if ( last_clock_freeze == true ) {
1040             // clock just unfroze, let's set warp as the difference
1041             // between frozen time and current time so we don't get a
1042             // time jump (and corresponding sky object and lighting
1043             // jump.)
1044             globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
1045             fgSetLong( "/sim/time/cur-time-override", 0 );
1046         }
1047         if ( globals->get_warp_delta() != 0 ) {
1048             globals->inc_warp( globals->get_warp_delta() );
1049         }
1050     }
1051
1052     last_clock_freeze = clock_freeze->getBoolValue();
1053
1054     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1055                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1056                cur_time_override->getLongValue(),
1057                globals->get_warp() );
1058
1059     if (globals->get_warp_delta() != 0) {
1060         FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
1061         l->update( 0.5 );
1062     }
1063
1064     // update magvar model
1065     globals->get_mag()->update( longitude->getDoubleValue()
1066                               * SGD_DEGREES_TO_RADIANS,
1067                             latitude->getDoubleValue()
1068                               * SGD_DEGREES_TO_RADIANS,
1069                             altitude->getDoubleValue() * SG_FEET_TO_METER,
1070                             globals->get_time_params()->getJD() );
1071
1072     // Get elapsed time (in usec) for this past frame
1073     elapsed = fgGetTimeInterval();
1074     SG_LOG( SG_ALL, SG_DEBUG, 
1075             "Elapsed time interval is = " << elapsed 
1076             << ", previous remainder is = " << remainder );
1077
1078     // Calculate frame rate average
1079 #ifdef FANCY_FRAME_COUNTER
1080     /* old fps calculation */
1081     if ( elapsed > 0 ) {
1082         double tmp;
1083         accum = 0.0;
1084         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1085             tmp = general.get_frame(i);
1086             accum += tmp;
1087             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1088             general.set_frame(i+1,tmp);
1089         }
1090         tmp = 1000000.0 / (float)elapsed;
1091         general.set_frame(0,tmp);
1092         // printf("frame[0] = %.2f\n", general.frames[0]);
1093         accum += tmp;
1094         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1095         // printf("ave = %.2f\n", general.frame_rate);
1096     }
1097 #else
1098     if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1099         general.set_frame_rate( frames );
1100         fgSetInt("/sim/frame-rate", frames);
1101         SG_LOG( SG_ALL, SG_DEBUG, 
1102             "--> Frame rate is = " << general.get_frame_rate() );
1103         frames = 0;
1104     }
1105     last_time = t->get_cur_time();
1106     ++frames;
1107 #endif
1108
1109     // Run ATC subsystem
1110     if (fgGetBool("/sim/ATC/enabled"))
1111         globals->get_ATC_mgr()->update(delta_time_sec);
1112
1113     // Run the AI subsystem
1114     if (fgGetBool("/sim/ai-traffic/enabled"))
1115         globals->get_AI_mgr()->update(delta_time_sec);
1116
1117     // Run flight model
1118
1119     // Calculate model iterations needed for next frame
1120     elapsed += remainder;
1121
1122     global_multi_loop = (long)(((double)elapsed * 0.000001) * model_hz );
1123     remainder = elapsed - ( (global_multi_loop*1000000) / model_hz );
1124     SG_LOG( SG_ALL, SG_DEBUG, 
1125             "Model iterations needed = " << global_multi_loop
1126             << ", new remainder = " << remainder );
1127         
1128     // chop max interations to something reasonable if the sim was
1129     // delayed for an excesive amount of time
1130     if ( global_multi_loop > 2.0 * model_hz ) {
1131         global_multi_loop = (int)(2.0 * model_hz );
1132         remainder = 0;
1133     }
1134
1135     // flight model
1136     if ( global_multi_loop > 0 ) {
1137         fgUpdateTimeDepCalcs();
1138     } else {
1139         SG_LOG( SG_ALL, SG_DEBUG, 
1140             "Elapsed time is zero ... we're zinging" );
1141     }
1142
1143     // Do any I/O channel work that might need to be done
1144     globals->get_io()->update( real_delta_time_sec );
1145
1146     // see if we need to load any deferred-load textures
1147     globals->get_matlib()->load_next_deferred();
1148
1149     // Run audio scheduler
1150 #ifdef ENABLE_AUDIO_SUPPORT
1151     if ( fgGetBool("/sim/sound/audible")
1152            && globals->get_soundmgr()->is_working() ) {
1153         globals->get_soundmgr()->update( delta_time_sec );
1154     }
1155 #endif
1156
1157     globals->get_subsystem_mgr()->update(delta_time_sec);
1158
1159     //
1160     // Tile Manager updates - see if we need to load any new scenery tiles.
1161     //   this code ties together the fdm, viewer and scenery classes...
1162     //   we may want to move this to it's own class at some point
1163     //
1164     double visibility_meters = fgGetDouble("/environment/visibility-m");
1165     FGViewer *current_view = globals->get_current_view();
1166
1167     // update tile manager for FDM...
1168     // ...only if location is different than the viewer (to avoid duplicating effort)
1169     if( acmodel_location != current_view->getSGLocation() ) {
1170       if( acmodel_location != 0 ) {
1171         globals->get_tile_mgr()->prep_ssg_nodes( acmodel_location,
1172                                                  visibility_meters );
1173         globals->get_tile_mgr()->
1174             update( acmodel_location, visibility_meters,
1175                     acmodel_location->get_absolute_view_pos(globals->get_scenery()->get_center()) );
1176         // save results of update in SGLocation for fdm...
1177         if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1178           acmodel_location->
1179               set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1180         }
1181         acmodel_location->
1182             set_tile_center( globals->get_scenery()->get_next_center() );
1183       }
1184     }
1185
1186     globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
1187                                              visibility_meters );
1188     // update tile manager for view...
1189     // IMPORTANT!!! the tilemgr update for view location _must_ be done last 
1190     // after the FDM's until all of Flight Gear code references the viewer's location
1191     // for elevation instead of the "scenery's" current elevation.
1192     SGLocation *view_location = globals->get_current_view()->getSGLocation();
1193     globals->get_tile_mgr()->update( view_location, visibility_meters,
1194                                      current_view->get_absolute_view_pos() );
1195     // save results of update in SGLocation for fdm...
1196     if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1197       current_view->getSGLocation()->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1198     }
1199     current_view->getSGLocation()->set_tile_center( globals->get_scenery()->get_next_center() );
1200
1201     // If fdm location is same as viewer's then we didn't do the update for fdm location 
1202     //   above so we need to save the viewer results in the fdm SGLocation as well...
1203     if( acmodel_location == current_view->getSGLocation() ) {
1204       if( acmodel_location != 0 ) {
1205         if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1206           acmodel_location->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1207         }
1208         acmodel_location->set_tile_center( globals->get_scenery()->get_next_center() );
1209       }
1210     }
1211
1212     // END Tile Manager udpates
1213
1214     if (fgGetBool("/sim/rendering/specular-highlight")) {
1215         glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1216         // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
1217     } else {
1218         glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
1219         // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
1220     }
1221
1222     // redraw display
1223     fgRenderFrame();
1224
1225     SG_LOG( SG_ALL, SG_DEBUG, "" );
1226 }
1227
1228
1229 // This is the top level master main function that is registered as
1230 // our idle funciton
1231
1232 // The first few passes take care of initialization things (a couple
1233 // per pass) and once everything has been initialized fgMainLoop from
1234 // then on.
1235
1236 static void fgIdleFunction ( void ) {
1237     // printf("idle state == %d\n", idle_state);
1238
1239     if ( idle_state == 0 ) {
1240         // Initialize the splash screen right away
1241         if ( fgGetBool("/sim/startup/splash-screen") ) {
1242             fgSplashInit(fgGetString("/sim/startup/splash-texture"));
1243         }
1244         
1245         idle_state++;
1246     } else if ( idle_state == 1 ) {
1247         // Initialize audio support
1248 #ifdef ENABLE_AUDIO_SUPPORT
1249
1250         // Start the intro music
1251         if ( fgGetBool("/sim/startup/intro-music") ) {
1252             SGPath mp3file( globals->get_fg_root() );
1253             mp3file.append( "Sounds/intro.mp3" );
1254
1255             SG_LOG( SG_GENERAL, SG_INFO, 
1256                 "Starting intro music: " << mp3file.str() );
1257
1258 #if defined( __CYGWIN__ )
1259             string command = "start /m `cygpath -w " + mp3file.str() + "`";
1260 #elif defined( WIN32 )
1261             string command = "start /m " + mp3file.str();
1262 #else
1263             string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1264 #endif
1265
1266             system ( command.c_str() );
1267         }
1268 #endif
1269
1270         idle_state++;
1271     } else if ( idle_state == 2 ) {
1272         // These are a few miscellaneous things that aren't really
1273         // "subsystems" but still need to be initialized.
1274
1275 #ifdef USE_GLIDE
1276         if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1277             grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1278         }
1279 #endif
1280
1281         idle_state++;
1282     } else if ( idle_state == 3 ) {
1283         // This is the top level init routine which calls all the
1284         // other subsystem initialization routines.  If you are adding
1285         // a subsystem to flightgear, its initialization call should
1286         // located in this routine.
1287         if( !fgInitSubsystems()) {
1288             SG_LOG( SG_GENERAL, SG_ALERT,
1289                 "Subsystem initializations failed ..." );
1290             exit(-1);
1291         }
1292
1293         idle_state++;
1294     } else if ( idle_state == 4 ) {
1295         // Initialize the time offset (warp) after fgInitSubsystem
1296         // (which initializes the lighting interpolation tables.)
1297         fgInitTimeOffset();
1298
1299         // setup OpenGL view parameters
1300         fgInitVisuals();
1301
1302         // Read the list of available aircrafts
1303         fgReadAircraft();
1304
1305         idle_state++;
1306     } else if ( idle_state == 5 ) {
1307
1308         idle_state++;
1309     } else if ( idle_state == 6 ) {
1310         // sleep(1);
1311
1312         idle_state = 1000;
1313
1314         SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
1315         fgReshape( fgGetInt("/sim/startup/xsize"),
1316                fgGetInt("/sim/startup/ysize") );
1317
1318     } 
1319
1320     if ( idle_state == 1000 ) {
1321         // We've finished all our initialization steps, from now on we
1322         // run the main loop.
1323
1324         glutIdleFunc(fgMainLoop);
1325     } else {
1326         if ( fgGetBool("/sim/startup/splash-screen") ) {
1327             fgSplashUpdate(0.0, 1.0);
1328         }
1329     }
1330 }
1331
1332 // options.cxx needs to see this for toggle_panel()
1333 // Handle new window size or exposure
1334 void fgReshape( int width, int height ) {
1335     int view_h;
1336
1337     if ( (!fgGetBool("/sim/virtual-cockpit"))
1338          && fgPanelVisible() && idle_state == 1000 ) {
1339         view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
1340                              globals->get_current_panel()->getYOffset()) / 768.0);
1341     } else {
1342         view_h = height;
1343     }
1344
1345     // for all views
1346     FGViewMgr *viewmgr = globals->get_viewmgr();
1347     for ( int i = 0; i < viewmgr->size(); ++i ) {
1348       viewmgr->get_view(i)->
1349         set_aspect_ratio((float)view_h / (float)width);
1350     }
1351
1352     glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1353
1354     fgSetInt("/sim/startup/xsize", width);
1355     fgSetInt("/sim/startup/ysize", height);
1356     guiInitMouse(width, height);
1357
1358     ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1359                viewmgr->get_current_view()->get_v_fov() );
1360
1361     fgHUDReshape();
1362
1363 #ifdef FG_USE_CLOUDS_3D
1364     sgClouds3d->Resize( viewmgr->get_current_view()->get_h_fov(),
1365                         viewmgr->get_current_view()->get_v_fov() );
1366 #endif
1367
1368 }
1369
1370 // Initialize GLUT and define a main window
1371 static bool fgGlutInit( int *argc, char **argv ) {
1372
1373 #if !defined( macintosh )
1374     // GLUT will extract all glut specific options so later on we only
1375     // need wory about our own.
1376     glutInit(argc, argv);
1377 #endif
1378
1379     // Define Display Parameters. Clouds3d works best with --bpp32 option
1380     if ( fgGetBool("/sim/rendering/clouds3d") ) {
1381         glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE | GLUT_ALPHA );
1382     } else {
1383         glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1384     }
1385
1386     SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1387             fgGetInt("/sim/startup/xsize") << "x"
1388             << fgGetInt("/sim/startup/ysize") );
1389
1390     // Define initial window size
1391     glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1392                     fgGetInt("/sim/startup/ysize") );
1393
1394     // Initialize windows
1395     if ( !fgGetBool("/sim/startup/game-mode")) {
1396         // Open the regular window
1397         glutCreateWindow("FlightGear");
1398 #ifndef GLUT_WRONG_VERSION
1399     } else {
1400         // Open the cool new 'game mode' window
1401         char game_mode_str[256];
1402 //#define SYNC_OPENGL_WITH_DESKTOP_SETTINGS
1403 #if defined(WIN32) && defined(SYNC_OPENGL_WITH_DESKTOP_SETTINGS)
1404 #ifndef ENUM_CURRENT_SETTINGS
1405 #define ENUM_CURRENT_SETTINGS       ((DWORD)-1)
1406 #define ENUM_REGISTRY_SETTINGS      ((DWORD)-2)
1407 #endif
1408
1409         DEVMODE dm;
1410         dm.dmSize = sizeof(DEVMODE);
1411         EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm);
1412         fgSetInt("/sim/startup/xsize", dm.dmPelsWidth);
1413         fgSetInt("/sim/startup/ysize", dm.dmPelsHeight);
1414         glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1415                             fgGetInt("/sim/startup/ysize") );
1416         sprintf( game_mode_str, "%dx%d:%d@%d",
1417                      dm.dmPelsWidth,
1418                      dm.dmPelsHeight,
1419                      dm.dmBitsPerPel,
1420                      dm.dmDisplayFrequency );
1421 #else
1422         // Open the cool new 'game mode' window
1423         sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1424              fgGetInt("/sim/startup/xsize"),
1425              fgGetInt("/sim/startup/ysize"),
1426              fgGetInt("/sim/rendering/bits-per-pixel"));
1427
1428 #endif // HAVE_WINDOWS_H
1429         SG_LOG( SG_GENERAL, SG_INFO, 
1430             "game mode params = " << game_mode_str );
1431         glutGameModeString( game_mode_str );
1432         glutEnterGameMode();
1433 #endif // GLUT_WRONG_VERSION
1434     }
1435
1436     // This seems to be the absolute earliest in the init sequence
1437     // that these calls will return valid info.  Too bad it's after
1438     // we've already created and sized out window. :-(
1439     general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1440     general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1441     general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1442     SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1443
1444     GLint tmp;
1445     glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1446     general.set_glMaxTexSize( tmp );
1447     SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1448
1449     glGetIntegerv( GL_DEPTH_BITS, &tmp );
1450     general.set_glDepthBits( tmp );
1451     SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1452
1453     return true;
1454 }
1455
1456
1457 // Initialize GLUT event handlers
1458 static bool fgGlutInitEvents( void ) {
1459     // call fgReshape() on window resizes
1460     glutReshapeFunc( fgReshape );
1461
1462     // keyboard and mouse callbacks are set in FGInput::init
1463
1464     // call fgMainLoop() whenever there is
1465     // nothing else to do
1466     glutIdleFunc( fgIdleFunction );
1467
1468     // draw the scene
1469     glutDisplayFunc( fgRenderFrame );
1470
1471     return true;
1472 }
1473
1474 // Main top level initialization
1475 bool fgMainInit( int argc, char **argv ) {
1476
1477 #if defined( macintosh )
1478     freopen ("stdout.txt", "w", stdout );
1479     freopen ("stderr.txt", "w", stderr );
1480     argc = ccommand( &argv );
1481 #endif
1482
1483     // set default log levels
1484     sglog().setLogLevels( SG_ALL, SG_ALERT );
1485
1486     string version;
1487 #ifdef FLIGHTGEAR_VERSION
1488     version = FLIGHTGEAR_VERSION;
1489 #else
1490     version = "unknown version";
1491 #endif
1492     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
1493             << version );
1494     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
1495
1496     // Allocate global data structures.  This needs to happen before
1497     // we parse command line options
1498
1499     globals = new FGGlobals;
1500
1501     // seed the random number generater
1502     sg_srandom_time();
1503
1504     SGRoute *route = new SGRoute;
1505     globals->set_route( route );
1506
1507     FGControls *controls = new FGControls;
1508     globals->set_controls( controls );
1509
1510     string_list *col = new string_list;
1511     globals->set_channel_options_list( col );
1512
1513     // Scan the config file(s) and command line options to see if
1514     // fg_root was specified (ignore all other options for now)
1515     fgInitFGRoot(argc, argv);
1516
1517     // Check for the correct base package version
1518     static char required_version[] = "0.9.3";
1519     string base_version = fgBasePackageVersion();
1520     if ( !(base_version == required_version) ) {
1521         // tell the operator how to use this application
1522
1523         cerr << endl << "Base package check failed ... " \
1524              << "Found version " << base_version << " at: " \
1525              << globals->get_fg_root() << endl;
1526         cerr << "Please upgrade to version: " << required_version << endl;
1527         exit(-1);
1528     }
1529
1530     // Initialize the Aircraft directory to "" (UIUC)
1531     aircraft_dir = "";
1532
1533     // Load the configuration parameters.  (Command line options
1534     // overrides config file options.  Config file options override
1535     // defaults.)
1536     if ( !fgInitConfig(argc, argv) ) {
1537         SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1538         exit(-1);
1539     }
1540
1541     // Initialize the Window/Graphics environment.
1542     if( !fgGlutInit(&argc, argv) ) {
1543         SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1544         exit(-1);
1545     }
1546
1547     // Initialize the various GLUT Event Handlers.
1548     if( !fgGlutInitEvents() ) {
1549         SG_LOG( SG_GENERAL, SG_ALERT, 
1550                 "GLUT event handler initialization failed ..." );
1551         exit(-1);
1552     }
1553
1554     // Initialize plib net interface
1555     netInit( &argc, argv );
1556
1557     // Initialize ssg (from plib).  Needs to come before we do any
1558     // other ssg stuff, but after opengl/glut has been initialized.
1559     ssgInit();
1560
1561     // Initialize the user interface (we need to do this before
1562     // passing off control to glut and before fgInitGeneral to get our
1563     // fonts !!!
1564     guiInit();
1565
1566     // Read the list of available aircrafts
1567     fgReadAircraft();
1568
1569 #ifdef GL_EXT_texture_lod_bias
1570     glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1571 #endif
1572
1573             // get the address of our OpenGL extensions
1574     if ( fgGetBool("/sim/rendering/distance-attenuation") )
1575     {
1576         if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
1577             glPointParameterIsSupported = true;
1578             glPointParameterfPtr = (glPointParameterfProc)
1579                                    SGLookupFunction("glPointParameterfEXT");
1580             glPointParameterfvPtr = (glPointParameterfvProc)
1581                                     SGLookupFunction("glPointParameterfvEXT");
1582
1583         } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
1584             glPointParameterIsSupported = true;
1585             glPointParameterfPtr = (glPointParameterfProc)
1586                                    SGLookupFunction("glPointParameterfARB");
1587             glPointParameterfvPtr = (glPointParameterfvProc)
1588                                     SGLookupFunction("glPointParameterfvARB");
1589         } else
1590             glPointParameterIsSupported = false;
1591    }
1592
1593     // based on the requested presets, calculate the true starting
1594     // lon, lat
1595     fgInitNav();
1596     fgInitPosition();
1597
1598     SGTime *t = fgInitTime();
1599     globals->set_time_params( t );
1600
1601     // Do some quick general initializations
1602     if( !fgInitGeneral()) {
1603         SG_LOG( SG_GENERAL, SG_ALERT, 
1604             "General initializations failed ..." );
1605         exit(-1);
1606     }
1607
1608     ////////////////////////////////////////////////////////////////////
1609     // Initialize the property-based built-in commands
1610     ////////////////////////////////////////////////////////////////////
1611     fgInitCommands();
1612
1613     ////////////////////////////////////////////////////////////////////
1614     // Initialize the material manager
1615     ////////////////////////////////////////////////////////////////////
1616     globals->set_matlib( new SGMaterialLib );
1617
1618     globals->set_model_lib(new SGModelLib);
1619
1620     ////////////////////////////////////////////////////////////////////
1621     // Initialize the TG scenery subsystem.
1622     ////////////////////////////////////////////////////////////////////
1623     globals->set_scenery( new FGScenery );
1624     globals->get_scenery()->init();
1625     globals->get_scenery()->bind();
1626     globals->set_tile_mgr( new FGTileMgr );
1627
1628     ////////////////////////////////////////////////////////////////////
1629     // Initialize the general model subsystem.
1630     ////////////////////////////////////////////////////////////////////
1631     globals->set_model_mgr(new FGModelMgr);
1632     globals->get_model_mgr()->init();
1633     globals->get_model_mgr()->bind();
1634
1635     ////////////////////////////////////////////////////////////////////
1636     // Initialize the 3D aircraft model subsystem (has a dependency on
1637     // the scenery subsystem.)
1638     ////////////////////////////////////////////////////////////////////
1639     globals->set_aircraft_model(new FGAircraftModel);
1640     globals->get_aircraft_model()->init();
1641     globals->get_aircraft_model()->bind();
1642
1643     ////////////////////////////////////////////////////////////////////
1644     // Initialize the view manager subsystem.
1645     ////////////////////////////////////////////////////////////////////
1646     FGViewMgr *viewmgr = new FGViewMgr;
1647     globals->set_viewmgr( viewmgr );
1648     viewmgr->init();
1649     viewmgr->bind();
1650
1651
1652     // Initialize the sky
1653     SGPath ephem_data_path( globals->get_fg_root() );
1654     ephem_data_path.append( "Astro" );
1655     SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1656     ephem->update( globals->get_time_params()->getMjd(),
1657                    globals->get_time_params()->getLst(),
1658                    0.0 );
1659     globals->set_ephem( ephem );
1660
1661     // TODO: move to environment mgr
1662     thesky = new SGSky;
1663     SGPath texture_path(globals->get_fg_root());
1664     texture_path.append("Textures");
1665     texture_path.append("Sky");
1666     for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
1667         SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
1668         thesky->add_cloud_layer(layer);
1669     }
1670
1671     SGPath sky_tex_path( globals->get_fg_root() );
1672     sky_tex_path.append( "Textures" );
1673     sky_tex_path.append( "Sky" );
1674     thesky->texture_path( sky_tex_path.str() );
1675
1676     // The sun and moon diameters are scaled down numbers of the
1677     // actual diameters. This was needed to fit bot the sun and the
1678     // moon within the distance to the far clip plane.
1679     // Moon diameter:    3,476 kilometers
1680     // Sun diameter: 1,390,000 kilometers
1681     thesky->build( 80000.0, 80000.0,
1682                    463.3, 361.8,
1683                    globals->get_ephem()->getNumPlanets(), 
1684                    globals->get_ephem()->getPlanets(),
1685                    globals->get_ephem()->getNumStars(),
1686                    globals->get_ephem()->getStars() );
1687
1688     // Initialize MagVar model
1689     SGMagVar *magvar = new SGMagVar();
1690     globals->set_mag( magvar );
1691
1692
1693                                 // kludge to initialize mag compass
1694                                 // (should only be done for in-flight
1695                                 // startup)
1696     // update magvar model
1697     globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
1698                                 * SGD_DEGREES_TO_RADIANS,
1699                                 fgGetDouble("/position/latitude-deg")
1700                                 * SGD_DEGREES_TO_RADIANS,
1701                                 fgGetDouble("/position/altitude-ft")
1702                                 * SG_FEET_TO_METER,
1703                                 globals->get_time_params()->getJD() );
1704     double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
1705     fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
1706
1707     // airport = new ssgBranch;
1708     // airport->setName( "Airport Lighting" );
1709     // lighting->addKid( airport );
1710
1711     // build our custom render states
1712     fgBuildRenderStates();
1713     
1714     // pass control off to the master GLUT event handler
1715     glutMainLoop();
1716
1717     // we never actually get here ... but to avoid compiler warnings,
1718     // etc.
1719     return false;
1720 }
1721
1722
1723 // end of main.cxx