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