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