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