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