]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Initialize the bump-mapped 3d clouds to true.
[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_KEEP, GL_KEEP, 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_KEEP, GL_KEEP, 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     SGCloudLayer::enable_bump_mapping = fgGetBool("/sim/rendering/bump-mapping",true);
1022
1023     // Update the elapsed time.
1024     static bool first_time = true;
1025     if ( first_time ) {
1026         last_time_stamp.stamp();
1027         first_time = false;
1028     }
1029
1030     double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
1031     if ( throttle_hz > 0.0 ) {
1032         // simple frame rate throttle
1033         double dt = 1000000.0 / throttle_hz;
1034         current_time_stamp.stamp();
1035         while ( current_time_stamp - last_time_stamp < dt ) {
1036             current_time_stamp.stamp();
1037         }
1038     } else {
1039         // run as fast as the app will go
1040         current_time_stamp.stamp();
1041     }
1042
1043     real_delta_time_sec
1044         = double(current_time_stamp - last_time_stamp) / 1000000.0;
1045     if ( clock_freeze->getBoolValue() ) {
1046         delta_time_sec = 0;
1047     } else {
1048         delta_time_sec = real_delta_time_sec;
1049     }
1050     last_time_stamp = current_time_stamp;
1051     globals->inc_sim_time_sec( delta_time_sec );
1052     SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
1053
1054     // These are useful, especially for Nasal scripts.
1055     fgSetDouble("/sim/time/delta-realtime-sec", real_delta_time_sec);
1056     fgSetDouble("/sim/time/delta-sec", delta_time_sec);
1057
1058     static long remainder = 0;
1059     long elapsed;
1060 #ifdef FANCY_FRAME_COUNTER
1061     int i;
1062     double accum;
1063 #else
1064     static time_t last_time = 0;
1065     static int frames = 0;
1066 #endif // FANCY_FRAME_COUNTER
1067
1068     SGTime *t = globals->get_time_params();
1069
1070     globals->get_event_mgr()->update(delta_time_sec);
1071
1072     SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
1073     SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
1074
1075 #if defined( ENABLE_PLIB_JOYSTICK )
1076     // Read joystick and update control settings
1077     // if ( fgGetString("/sim/control-mode") == "joystick" )
1078     // {
1079     //    fgJoystickRead();
1080     // }
1081 #endif
1082
1083     // Fix elevation.  I'm just sticking this here for now, it should
1084     // probably move eventually
1085
1086     /* printf("Before - ground = %.2f  runway = %.2f  alt = %.2f\n",
1087            scenery.get_cur_elev(),
1088            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1089            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1090
1091     /* printf("Adjustment - ground = %.2f  runway = %.2f  alt = %.2f\n",
1092            scenery.get_cur_elev(),
1093            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1094            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1095
1096     // cout << "Warp = " << globals->get_warp() << endl;
1097
1098     // update "time"
1099     static bool last_clock_freeze = false;
1100
1101     if ( clock_freeze->getBoolValue() ) {
1102         // clock freeze requested
1103         if ( cur_time_override->getLongValue() == 0 ) {
1104             fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
1105             globals->set_warp( 0 );
1106         }
1107     } else {
1108         // no clock freeze requested
1109         if ( last_clock_freeze == true ) {
1110             // clock just unfroze, let's set warp as the difference
1111             // between frozen time and current time so we don't get a
1112             // time jump (and corresponding sky object and lighting
1113             // jump.)
1114             globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
1115             fgSetLong( "/sim/time/cur-time-override", 0 );
1116         }
1117         if ( globals->get_warp_delta() != 0 ) {
1118             globals->inc_warp( globals->get_warp_delta() );
1119         }
1120     }
1121
1122     last_clock_freeze = clock_freeze->getBoolValue();
1123
1124     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1125                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1126                cur_time_override->getLongValue(),
1127                globals->get_warp() );
1128
1129     if (globals->get_warp_delta() != 0) {
1130         FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
1131         l->update( 0.5 );
1132     }
1133
1134     // update magvar model
1135     globals->get_mag()->update( longitude->getDoubleValue()
1136                               * SGD_DEGREES_TO_RADIANS,
1137                             latitude->getDoubleValue()
1138                               * SGD_DEGREES_TO_RADIANS,
1139                             altitude->getDoubleValue() * SG_FEET_TO_METER,
1140                             globals->get_time_params()->getJD() );
1141
1142     // Get elapsed time (in usec) for this past frame
1143     elapsed = fgGetTimeInterval();
1144     SG_LOG( SG_ALL, SG_DEBUG, 
1145             "Elapsed time interval is = " << elapsed 
1146             << ", previous remainder is = " << remainder );
1147
1148     // Calculate frame rate average
1149 #ifdef FANCY_FRAME_COUNTER
1150     /* old fps calculation */
1151     if ( elapsed > 0 ) {
1152         double tmp;
1153         accum = 0.0;
1154         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1155             tmp = general.get_frame(i);
1156             accum += tmp;
1157             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1158             general.set_frame(i+1,tmp);
1159         }
1160         tmp = 1000000.0 / (float)elapsed;
1161         general.set_frame(0,tmp);
1162         // printf("frame[0] = %.2f\n", general.frames[0]);
1163         accum += tmp;
1164         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1165         // printf("ave = %.2f\n", general.frame_rate);
1166     }
1167 #else
1168     if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1169         general.set_frame_rate( frames );
1170         fgSetInt("/sim/frame-rate", frames);
1171         SG_LOG( SG_ALL, SG_DEBUG, 
1172             "--> Frame rate is = " << general.get_frame_rate() );
1173         frames = 0;
1174     }
1175     last_time = t->get_cur_time();
1176     ++frames;
1177 #endif
1178
1179     // Run ATC subsystem
1180     if (fgGetBool("/sim/ATC/enabled"))
1181         globals->get_ATC_mgr()->update(delta_time_sec);
1182
1183     // Run the AI subsystem
1184     if (fgGetBool("/sim/ai-traffic/enabled"))
1185         globals->get_AI_mgr()->update(delta_time_sec);
1186
1187     // Run flight model
1188
1189     // Calculate model iterations needed for next frame
1190     elapsed += remainder;
1191
1192     global_multi_loop = (long)(((double)elapsed * 0.000001) * model_hz );
1193     remainder = elapsed - ( (global_multi_loop*1000000) / model_hz );
1194     SG_LOG( SG_ALL, SG_DEBUG, 
1195             "Model iterations needed = " << global_multi_loop
1196             << ", new remainder = " << remainder );
1197         
1198     // chop max interations to something reasonable if the sim was
1199     // delayed for an excesive amount of time
1200     if ( global_multi_loop > 2.0 * model_hz ) {
1201         global_multi_loop = (int)(2.0 * model_hz );
1202         remainder = 0;
1203     }
1204
1205     // flight model
1206     if ( global_multi_loop > 0 ) {
1207         fgUpdateTimeDepCalcs();
1208     } else {
1209         SG_LOG( SG_ALL, SG_DEBUG, 
1210             "Elapsed time is zero ... we're zinging" );
1211     }
1212
1213     // Do any I/O channel work that might need to be done
1214     globals->get_io()->update( real_delta_time_sec );
1215
1216     // see if we need to load any deferred-load textures
1217     globals->get_matlib()->load_next_deferred();
1218
1219     // Run audio scheduler
1220 #ifdef ENABLE_AUDIO_SUPPORT
1221     if ( globals->get_soundmgr()->is_working() ) {
1222         globals->get_soundmgr()->update( delta_time_sec );
1223     }
1224 #endif
1225
1226     globals->get_subsystem_mgr()->update(delta_time_sec);
1227
1228     //
1229     // Tile Manager updates - see if we need to load any new scenery tiles.
1230     //   this code ties together the fdm, viewer and scenery classes...
1231     //   we may want to move this to it's own class at some point
1232     //
1233     double visibility_meters = fgGetDouble("/environment/visibility-m");
1234     FGViewer *current_view = globals->get_current_view();
1235
1236     // get the location data for the primary FDM (now hardcoded to ac model)...
1237     SGLocation *acmodel_loc = NULL;
1238     acmodel_loc = (SGLocation *)globals->
1239         get_aircraft_model()->get3DModel()->getSGLocation();
1240
1241     // update tile manager for FDM...
1242     // ...only if location is different than the current-view location
1243     // (to avoid duplicating effort)
1244     if( !fgGetBool("/sim/current-view/config/from-model") ) {
1245         if( acmodel_loc != NULL ) {
1246             globals->get_tile_mgr()->prep_ssg_nodes( acmodel_loc,
1247                                                      visibility_meters );
1248             globals->get_tile_mgr()->
1249                 update( acmodel_loc, visibility_meters,
1250                         acmodel_loc->
1251                         get_absolute_view_pos(globals->
1252                                               get_scenery()->get_center()) );
1253             // save results of update in SGLocation for fdm...
1254             if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1255                 acmodel_loc->
1256                     set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1257                 fgSetDouble("/position/ground-elev-m",
1258                             globals->get_scenery()->get_cur_elev());
1259             }
1260             acmodel_loc->
1261                 set_tile_center( globals->get_scenery()->get_next_center() );
1262         }
1263     }
1264
1265     globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
1266                                              visibility_meters );
1267     // update tile manager for view...
1268     // IMPORTANT!!! the tilemgr update for view location _must_ be
1269     // done last after the FDM's until all of Flight Gear code
1270     // references the viewer's location for elevation instead of the
1271     // "scenery's" current elevation.
1272     SGLocation *view_location = globals->get_current_view()->getSGLocation();
1273     globals->get_tile_mgr()->update( view_location, visibility_meters,
1274                                      current_view->get_absolute_view_pos() );
1275     // save results of update in SGLocation for fdm...
1276     if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1277         current_view->getSGLocation()->
1278             set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1279     }
1280     current_view->getSGLocation()->
1281         set_tile_center( globals->get_scenery()->get_next_center() );
1282
1283 #ifdef ENABLE_AUDIO_SUPPORT
1284     // Right now we make a simplifying assumption that the primary
1285     // aircraft is the source of all sounds and that all sounds are
1286     // positioned relative to the current view position.
1287
1288     static sgVec3 last_pos_offset;
1289
1290     // set positional offset for sources
1291     sgVec3 source_pos_offset;
1292     sgSubVec3( source_pos_offset,
1293                view_location->get_view_pos(), acmodel_loc->get_view_pos() );
1294     // cout << "pos all = " << source_pos_offset[0] << " " << source_pos_offset[1] << " " << source_pos_offset[2] << endl;
1295     globals->get_soundmgr()->set_source_pos_all( source_pos_offset );
1296
1297     // set the velocity
1298     sgVec3 source_vel;
1299     sgSubVec3( source_vel, source_pos_offset, last_pos_offset );
1300     sgScaleVec3( source_vel, delta_time_sec );
1301     sgCopyVec3( last_pos_offset, source_pos_offset );
1302     // cout << "vel = " << source_vel[0] << " " << source_vel[1] << " " << source_vel[2] << endl;
1303     globals->get_soundmgr()->set_source_vel_all( source_vel );
1304
1305     // Right now we make a simplifying assumption that the listener is
1306     // always positioned at the origin.
1307     sgVec3 listener_pos;
1308     sgSetVec3( listener_pos, 0.0, 0.0, 0.0 );
1309     // cout << "listener = " << listener_pos[0] << " " << listener_pos[1] << " " << listener_pos[2] << endl;
1310     globals->get_soundmgr()->set_listener_pos( listener_pos );
1311 #endif
1312
1313     // If fdm location is same as viewer's then we didn't do the
1314     // update for fdm location above so we need to save the viewer
1315     // results in the fdm SGLocation as well...
1316     if( fgGetBool("/sim/current-view/config/from-model") ) {
1317         if( acmodel_loc != 0 ) {
1318             if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1319                 acmodel_loc->set_cur_elev_m( globals->get_scenery()->
1320                                              get_cur_elev() );
1321                 fgSetDouble("/position/ground-elev-m",
1322                             globals->get_scenery()->get_cur_elev());
1323             }
1324             acmodel_loc->set_tile_center( globals->get_scenery()->
1325                                           get_next_center() );
1326         }
1327     }
1328
1329     // END Tile Manager udpates
1330
1331     if (fgGetBool("/sim/rendering/specular-highlight")) {
1332         glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1333         // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
1334     } else {
1335         glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
1336         // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
1337     }
1338
1339     fgRequestRedraw();
1340
1341     SG_LOG( SG_ALL, SG_DEBUG, "" );
1342 }
1343
1344
1345 // This is the top level master main function that is registered as
1346 // our idle funciton
1347
1348 // The first few passes take care of initialization things (a couple
1349 // per pass) and once everything has been initialized fgMainLoop from
1350 // then on.
1351
1352 static void fgIdleFunction ( void ) {
1353     // printf("idle state == %d\n", idle_state);
1354
1355     if ( idle_state == 0 ) {
1356         fgSetBool("sim/initialised", false);
1357
1358         // Initialize the splash screen right away
1359         if ( fgGetBool("/sim/startup/splash-screen") ) {
1360             fgSplashInit(fgGetString("/sim/startup/splash-texture"));
1361         }
1362         
1363         idle_state++;
1364     } else if ( idle_state == 1 ) {
1365         // Initialize audio support
1366 #ifdef ENABLE_AUDIO_SUPPORT
1367
1368         // Start the intro music
1369         if ( fgGetBool("/sim/startup/intro-music") ) {
1370             SGPath mp3file( globals->get_fg_root() );
1371             mp3file.append( "Sounds/intro.mp3" );
1372
1373             SG_LOG( SG_GENERAL, SG_INFO, 
1374                 "Starting intro music: " << mp3file.str() );
1375
1376 #if defined( __CYGWIN__ )
1377             string command = "start /m `cygpath -w " + mp3file.str() + "`";
1378 #elif defined( WIN32 )
1379             string command = "start /m " + mp3file.str();
1380 #else
1381             string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1382 #endif
1383
1384             system ( command.c_str() );
1385         }
1386 #endif
1387
1388         idle_state++;
1389     } else if ( idle_state == 2 ) {
1390         // These are a few miscellaneous things that aren't really
1391         // "subsystems" but still need to be initialized.
1392
1393 #ifdef USE_GLIDE
1394         if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1395             grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1396         }
1397 #endif
1398
1399         idle_state++;
1400     } else if ( idle_state == 3 ) {
1401         // This is the top level init routine which calls all the
1402         // other subsystem initialization routines.  If you are adding
1403         // a subsystem to flightgear, its initialization call should
1404         // located in this routine.
1405         if( !fgInitSubsystems()) {
1406             SG_LOG( SG_GENERAL, SG_ALERT,
1407                 "Subsystem initializations failed ..." );
1408             exit(-1);
1409         }
1410
1411         idle_state++;
1412     } else if ( idle_state == 4 ) {
1413         // Initialize the time offset (warp) after fgInitSubsystem
1414         // (which initializes the lighting interpolation tables.)
1415         fgInitTimeOffset();
1416
1417         // setup OpenGL view parameters
1418         fgInitVisuals();
1419
1420         // Read the list of available aircrafts
1421         fgReadAircraft();
1422
1423         idle_state++;
1424     } else if ( idle_state == 5 ) {
1425
1426         idle_state++;
1427     } else if ( idle_state == 6 ) {
1428         // sleep(1);
1429
1430         idle_state = 1000;
1431
1432         SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
1433         fgReshape( fgGetInt("/sim/startup/xsize"),
1434                fgGetInt("/sim/startup/ysize") );
1435
1436     } 
1437
1438     if ( idle_state == 1000 ) {
1439         // We've finished all our initialization steps, from now on we
1440         // run the main loop.
1441         fgSetBool("sim/initialised",true);
1442
1443         fgRegisterIdleHandler(fgMainLoop);
1444     } else {
1445         if ( fgGetBool("/sim/startup/splash-screen") ) {
1446             fgSplashUpdate(0.0, 1.0);
1447         }
1448     }
1449 }
1450
1451 // options.cxx needs to see this for toggle_panel()
1452 // Handle new window size or exposure
1453 void fgReshape( int width, int height ) {
1454     int view_h;
1455
1456     if ( (!fgGetBool("/sim/virtual-cockpit"))
1457          && fgPanelVisible() && idle_state == 1000 ) {
1458         view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
1459                              globals->get_current_panel()->getYOffset()) / 768.0);
1460     } else {
1461         view_h = height;
1462     }
1463
1464     glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1465
1466     fgSetInt("/sim/startup/xsize", width);
1467     fgSetInt("/sim/startup/ysize", height);
1468     guiInitMouse(width, height);
1469
1470     // for all views
1471     FGViewMgr *viewmgr = globals->get_viewmgr();
1472     if (viewmgr) {
1473       for ( int i = 0; i < viewmgr->size(); ++i ) {
1474         viewmgr->get_view(i)->
1475           set_aspect_ratio((float)view_h / (float)width);
1476       }
1477
1478       ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1479                viewmgr->get_current_view()->get_v_fov() );
1480
1481 #ifdef FG_USE_CLOUDS_3D
1482       sgClouds3d->Resize( viewmgr->get_current_view()->get_h_fov(),
1483                viewmgr->get_current_view()->get_v_fov() );
1484 #endif
1485     }
1486
1487     fgHUDReshape();
1488
1489 }
1490
1491
1492 // do some clean up on exit.  Specifically we want to call alutExit()
1493 // which happens in the sound manager destructor.
1494 void fgExitCleanup() {
1495     delete globals;
1496     fgOSExit(0);
1497 }
1498
1499
1500 // Main top level initialization
1501 bool fgMainInit( int argc, char **argv ) {
1502
1503 #if defined( macintosh )
1504     freopen ("stdout.txt", "w", stdout );
1505     freopen ("stderr.txt", "w", stderr );
1506     argc = ccommand( &argv );
1507 #endif
1508
1509     // set default log levels
1510     sglog().setLogLevels( SG_ALL, SG_ALERT );
1511
1512     atexit(fgExitCleanup);
1513
1514     string version;
1515 #ifdef FLIGHTGEAR_VERSION
1516     version = FLIGHTGEAR_VERSION;
1517 #else
1518     version = "unknown version";
1519 #endif
1520     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
1521             << version );
1522     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
1523
1524     // Allocate global data structures.  This needs to happen before
1525     // we parse command line options
1526
1527     globals = new FGGlobals;
1528
1529     // seed the random number generater
1530     sg_srandom_time();
1531
1532     FGControls *controls = new FGControls;
1533     globals->set_controls( controls );
1534
1535     string_list *col = new string_list;
1536     globals->set_channel_options_list( col );
1537
1538     // Scan the config file(s) and command line options to see if
1539     // fg_root was specified (ignore all other options for now)
1540     fgInitFGRoot(argc, argv);
1541
1542     // Check for the correct base package version
1543     static char required_version[] = "0.9.4";
1544     string base_version = fgBasePackageVersion();
1545     if ( !(base_version == required_version) ) {
1546         // tell the operator how to use this application
1547
1548         SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
1549         cerr << endl << "Base package check failed ... " \
1550              << "Found version " << base_version << " at: " \
1551              << globals->get_fg_root() << endl;
1552         cerr << "Please upgrade to version: " << required_version << endl;
1553 #ifdef _MSC_VER
1554         cerr << "Hit a key to continue..." << endl;
1555         cin.get();
1556 #endif
1557         exit(-1);
1558     }
1559
1560     // Initialize the Aircraft directory to "" (UIUC)
1561     aircraft_dir = "";
1562
1563     // Load the configuration parameters.  (Command line options
1564     // overrides config file options.  Config file options override
1565     // defaults.)
1566     if ( !fgInitConfig(argc, argv) ) {
1567         SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1568         exit(-1);
1569     }
1570
1571     // Initialize the Window/Graphics environment.
1572 #if !defined(__APPLE__) || defined(OSX_BUNDLE)
1573     // Mac OS X command line ("non-bundle") applications call this
1574     // from main(), in bootstrap.cxx.  Andy doesn't know why, someone
1575     // feel free to add comments...
1576     fgOSInit(&argc, argv);
1577 #endif
1578
1579     fgRegisterWindowResizeHandler( fgReshape );
1580     fgRegisterIdleHandler( fgIdleFunction );
1581     fgRegisterDrawHandler( fgRenderFrame );
1582
1583 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
1584     bool get_stencil_buffer = true;
1585 #else
1586     bool get_stencil_buffer = false;
1587 #endif
1588
1589     // Clouds3D requires an alpha channel
1590     // clouds may require stencil buffer
1591     fgOSOpenWindow( fgGetInt("/sim/startup/xsize"),
1592                     fgGetInt("/sim/startup/ysize"),
1593                     fgGetInt("/sim/rendering/bits-per-pixel"),
1594                     fgGetBool("/sim/rendering/clouds3d"),
1595                     get_stencil_buffer,
1596                     fgGetBool("/sim/startup/fullscreen") );
1597
1598     // This seems to be the absolute earliest in the init sequence
1599     // that these calls will return valid info.  Too bad it's after
1600     // we've already created and sized out window. :-(
1601     general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1602     general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1603     general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1604     SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1605
1606     GLint tmp;
1607     glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1608     general.set_glMaxTexSize( tmp );
1609     SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1610
1611     glGetIntegerv( GL_DEPTH_BITS, &tmp );
1612     general.set_glDepthBits( tmp );
1613     SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1614
1615     // Initialize plib net interface
1616     netInit( &argc, argv );
1617
1618     // Initialize ssg (from plib).  Needs to come before we do any
1619     // other ssg stuff, but after opengl has been initialized.
1620     ssgInit();
1621
1622     // Initialize the user interface (we need to do this before
1623     // passing off control to the OS main loop and before
1624     // fgInitGeneral to get our fonts !!!
1625     guiInit();
1626
1627     // Read the list of available aircrafts
1628     fgReadAircraft();
1629
1630 #ifdef GL_EXT_texture_lod_bias
1631     glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1632 #endif
1633
1634             // get the address of our OpenGL extensions
1635     if ( fgGetBool("/sim/rendering/distance-attenuation") )
1636     {
1637         if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
1638             glPointParameterIsSupported = true;
1639             glPointParameterfPtr = (glPointParameterfProc)
1640                                    SGLookupFunction("glPointParameterfEXT");
1641             glPointParameterfvPtr = (glPointParameterfvProc)
1642                                     SGLookupFunction("glPointParameterfvEXT");
1643
1644         } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
1645             glPointParameterIsSupported = true;
1646             glPointParameterfPtr = (glPointParameterfProc)
1647                                    SGLookupFunction("glPointParameterfARB");
1648             glPointParameterfvPtr = (glPointParameterfvProc)
1649                                     SGLookupFunction("glPointParameterfvARB");
1650         } else
1651             glPointParameterIsSupported = false;
1652    }
1653
1654     // based on the requested presets, calculate the true starting
1655     // lon, lat
1656     fgInitNav();
1657     fgInitPosition();
1658
1659     SGTime *t = fgInitTime();
1660     globals->set_time_params( t );
1661
1662     // Do some quick general initializations
1663     if( !fgInitGeneral()) {
1664         SG_LOG( SG_GENERAL, SG_ALERT, 
1665             "General initializations failed ..." );
1666         exit(-1);
1667     }
1668
1669     ////////////////////////////////////////////////////////////////////
1670     // Initialize the property-based built-in commands
1671     ////////////////////////////////////////////////////////////////////
1672     fgInitCommands();
1673
1674     ////////////////////////////////////////////////////////////////////
1675     // Initialize the material manager
1676     ////////////////////////////////////////////////////////////////////
1677     globals->set_matlib( new SGMaterialLib );
1678
1679     globals->set_model_lib(new SGModelLib);
1680
1681     ////////////////////////////////////////////////////////////////////
1682     // Initialize the TG scenery subsystem.
1683     ////////////////////////////////////////////////////////////////////
1684     globals->set_scenery( new FGScenery );
1685     globals->get_scenery()->init();
1686     globals->get_scenery()->bind();
1687     globals->set_tile_mgr( new FGTileMgr );
1688
1689     ////////////////////////////////////////////////////////////////////
1690     // Initialize the general model subsystem.
1691     ////////////////////////////////////////////////////////////////////
1692     globals->set_model_mgr(new FGModelMgr);
1693     globals->get_model_mgr()->init();
1694     globals->get_model_mgr()->bind();
1695
1696     ////////////////////////////////////////////////////////////////////
1697     // Initialize the 3D aircraft model subsystem (has a dependency on
1698     // the scenery subsystem.)
1699     ////////////////////////////////////////////////////////////////////
1700     globals->set_aircraft_model(new FGAircraftModel);
1701     globals->get_aircraft_model()->init();
1702     globals->get_aircraft_model()->bind();
1703
1704     ////////////////////////////////////////////////////////////////////
1705     // Initialize the view manager subsystem.
1706     ////////////////////////////////////////////////////////////////////
1707     FGViewMgr *viewmgr = new FGViewMgr;
1708     globals->set_viewmgr( viewmgr );
1709     viewmgr->init();
1710     viewmgr->bind();
1711
1712
1713     // Initialize the sky
1714     SGPath ephem_data_path( globals->get_fg_root() );
1715     ephem_data_path.append( "Astro" );
1716     SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1717     ephem->update( globals->get_time_params()->getMjd(),
1718                    globals->get_time_params()->getLst(),
1719                    0.0 );
1720     globals->set_ephem( ephem );
1721
1722     // TODO: move to environment mgr
1723     thesky = new SGSky;
1724     SGPath texture_path(globals->get_fg_root());
1725     texture_path.append("Textures");
1726     texture_path.append("Sky");
1727     for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
1728         SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
1729         thesky->add_cloud_layer(layer);
1730     }
1731
1732     SGPath sky_tex_path( globals->get_fg_root() );
1733     sky_tex_path.append( "Textures" );
1734     sky_tex_path.append( "Sky" );
1735     thesky->texture_path( sky_tex_path.str() );
1736
1737     // The sun and moon diameters are scaled down numbers of the
1738     // actual diameters. This was needed to fit bot the sun and the
1739     // moon within the distance to the far clip plane.
1740     // Moon diameter:    3,476 kilometers
1741     // Sun diameter: 1,390,000 kilometers
1742     thesky->build( 80000.0, 80000.0,
1743                    463.3, 361.8,
1744                    globals->get_ephem()->getNumPlanets(), 
1745                    globals->get_ephem()->getPlanets(),
1746                    globals->get_ephem()->getNumStars(),
1747                    globals->get_ephem()->getStars() );
1748
1749     // Initialize MagVar model
1750     SGMagVar *magvar = new SGMagVar();
1751     globals->set_mag( magvar );
1752
1753
1754                                 // kludge to initialize mag compass
1755                                 // (should only be done for in-flight
1756                                 // startup)
1757     // update magvar model
1758     globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
1759                                 * SGD_DEGREES_TO_RADIANS,
1760                                 fgGetDouble("/position/latitude-deg")
1761                                 * SGD_DEGREES_TO_RADIANS,
1762                                 fgGetDouble("/position/altitude-ft")
1763                                 * SG_FEET_TO_METER,
1764                                 globals->get_time_params()->getJD() );
1765     double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
1766     fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
1767
1768     // airport = new ssgBranch;
1769     // airport->setName( "Airport Lighting" );
1770     // lighting->addKid( airport );
1771
1772     // build our custom render states
1773     fgBuildRenderStates();
1774
1775     try {
1776         // pass control off to the master event handler
1777         fgOSMainLoop();
1778     } catch (...) {
1779         SG_LOG( SG_ALL, SG_ALERT,
1780             "Unknown exception in the main loop. Aborting..." );
1781     }
1782
1783     // we never actually get here ... but to avoid compiler warnings,
1784     // etc.
1785     return false;
1786 }
1787
1788
1789 // end of main.cxx