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