]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Update required for the fastmath module
[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 #if defined(__linux__) && defined(__i386__)
29 #  include <fpu_control.h>
30 #  include <signal.h>
31 #endif
32
33 #include <simgear/compiler.h>
34
35 #include STL_IOSTREAM
36 SG_USING_STD(cerr);
37 SG_USING_STD(endl);
38
39 #include <simgear/misc/exception.hxx>
40 #include <simgear/ephemeris/ephemeris.hxx>
41 #include <simgear/route/route.hxx>
42 #include <simgear/screen/extensions.hxx>
43
44 #include <Environment/environment_mgr.hxx>
45
46 #ifdef SG_MATH_EXCEPTION_CLASH
47 #  include <math.h>
48 #endif
49
50 #ifdef HAVE_WINDOWS_H
51 #  include <windows.h>
52 #  include <float.h>
53 #endif
54
55 #include GLUT_H
56
57 #include <stdio.h>
58 #include <string.h>             // for strcmp()
59 #include <string>
60
61 #ifdef HAVE_STDLIB_H
62 #   include <stdlib.h>
63 #endif
64
65 #ifdef HAVE_SYS_STAT_H
66 #  include <sys/stat.h>         // for stat()
67 #endif
68
69 #ifdef HAVE_UNISTD_H
70 #  include <unistd.h>           // for stat()
71 #endif
72
73 #include <plib/netChat.h>
74 #include <plib/pu.h>
75 #include <plib/sg.h>
76 #include <plib/ssg.h>
77
78 #include <simgear/constants.h>  // for VERSION
79 #include <simgear/debug/logstream.hxx>
80 #include <simgear/math/polar3d.hxx>
81 #include <simgear/math/sg_random.h>
82 #include <simgear/misc/sg_path.hxx>
83 #include <simgear/scene/material/matlib.hxx>
84 #include <simgear/scene/model/animation.hxx>
85 #include <simgear/scene/model/location.hxx>
86 #include <simgear/scene/model/model.hxx>
87 #include <simgear/scene/model/modellib.hxx>
88 #ifdef FG_USE_CLOUDS_3D
89 #  include <simgear/scene/sky/clouds3d/SkySceneLoader.hpp>
90 #  include <simgear/scene/sky/clouds3d/SkyUtil.hpp>
91 #endif
92 #include <simgear/scene/sky/sky.hxx>
93 #include <simgear/timing/sg_time.hxx>
94
95 #include <Include/general.hxx>
96
97 #include <Aircraft/aircraft.hxx>
98
99 #include <ATC/ATCmgr.hxx>
100 #include <ATC/ATCdisplay.hxx>
101 #include <ATC/AIMgr.hxx>
102
103 #include <Autopilot/newauto.hxx>
104
105 #include <Cockpit/hud.hxx>
106 #include <Cockpit/cockpit.hxx>
107 #include <Cockpit/radiostack.hxx>
108
109 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
110 #include <GUI/gui.h>
111 #include <Model/acmodel.hxx>
112 #include <Model/modelmgr.hxx>
113 #include <Model/panelnode.hxx>
114 #ifdef FG_NETWORK_OLK
115 #include <NetworkOLK/network.h>
116 #endif
117
118 #ifdef FG_MPLAYER_AS
119 #include <MultiPlayer/multiplaytxmgr.hxx>
120 #include <MultiPlayer/multiplayrxmgr.hxx>
121 #endif
122
123 #include <Scenery/scenery.hxx>
124 #include <Scenery/tilemgr.hxx>
125 #ifdef ENABLE_AUDIO_SUPPORT
126 #  include <Sound/fg_fx.hxx>
127 #  include <Sound/morse.hxx>
128 #endif
129 #include <Systems/system_mgr.hxx>
130 #include <Instrumentation/instrument_mgr.hxx>
131 #include <Time/FGEventMgr.hxx>
132 #include <Time/fg_timer.hxx>
133 #include <Time/light.hxx>
134 #include <Time/sunpos.hxx>
135 #include <Time/tmp.hxx>
136
137 // ADA
138 #include <simgear/misc/sgstream.hxx>
139 #include <simgear/math/point3d.hxx>
140 #include <FDM/flight.hxx>
141 #include <FDM/ADA.hxx>
142 #include <Scenery/tileentry.hxx>
143
144 #include "fg_commands.hxx"
145
146 glPointParameterfProc glPointParameterfPtr = 0;
147 glPointParameterfvProc glPointParameterfvPtr = 0;
148
149 float default_attenuation[3] = {1.0, 0.0, 0.0};
150 //Required for using GL_extensions
151 void fgLoadDCS (void);
152 void fgUpdateDCS (void);
153 ssgSelector *ship_sel=NULL;
154 // upto 32 instances of a same object can be loaded.
155 ssgTransform *ship_pos[32];
156 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
157 int objc=0;
158 ssgSelector *lightpoints_brightness = new ssgSelector;
159 ssgTransform *lightpoints_transform = new ssgTransform;
160 FGTileEntry *dummy_tile;
161 sgVec3 rway_ols;
162 // ADA
163 // Clip plane settings...
164 float scene_nearplane = 0.5f;
165 float scene_farplane = 120000.0f;
166
167 static double delta_time_sec = 0;
168
169
170 #ifdef FG_WEATHERCM
171 #  include <WeatherCM/FGLocalWeatherDatabase.h>
172 #endif
173
174 #include "version.h"
175
176 #include "fg_init.hxx"
177 #include "fg_io.hxx"
178 #include "fg_props.hxx"
179 #include "globals.hxx"
180 #include "splash.hxx"
181 #include "viewmgr.hxx"
182 #include "options.hxx"
183 #include "logger.hxx"
184
185 #ifdef macintosh
186 #  include <console.h>          // -dw- for command line dialog
187 #endif
188
189
190 FGEventMgr global_events;
191
192 // This is a record containing a bit of global housekeeping information
193 FGGeneral general;
194
195 // Specify our current idle function state.  This is used to run all
196 // our initializations out of the glutIdleLoop() so that we can get a
197 // splash screen up and running right away.
198 static int idle_state = 0;
199 static long global_multi_loop;
200
201 // fog constants.  I'm a little nervous about putting actual code out
202 // here but it seems to work (?)
203 static const double m_log01 = -log( 0.01 );
204 static const double sqrt_m_log01 = sqrt( m_log01 );
205 static GLfloat fog_exp_density;
206 static GLfloat fog_exp2_density;
207 static GLfloat rwy_exp2_punch_through;
208 static GLfloat taxi_exp2_punch_through;
209 static GLfloat ground_exp2_punch_through;
210
211 #ifdef FG_NETWORK_OLK
212 ssgSelector *fgd_sel = NULL;
213 ssgTransform *fgd_pos = NULL;
214 #endif
215
216 // Sky structures
217 SGSky *thesky;
218
219 #ifdef FG_USE_CLOUDS_3D
220   SkySceneLoader *sgClouds3d;
221   bool _bcloud_orig = true;
222 #endif
223
224 // hack
225 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
226 {
227   {  1.0f,  0.0f,  0.0f,  0.0f },
228   {  0.0f,  0.0f, -1.0f,  0.0f },
229   {  0.0f,  1.0f,  0.0f,  0.0f },
230   {  0.0f,  0.0f,  0.0f,  1.0f }
231 };
232
233 // The following defines flightgear options. Because glutlib will also
234 // want to parse its own options, those options must not be included here
235 // or they will get parsed by the main program option parser. Hence case
236 // is significant for any option added that might be in conflict with
237 // glutlib's parser.
238 //
239 // glutlib parses for:
240 //    -display
241 //    -direct   (invalid in Win32)
242 //    -geometry
243 //    -gldebug
244 //    -iconized
245 //    -indirect (invalid in Win32)
246 //    -synce
247 //
248 // Note that glutlib depends upon strings while this program's
249 // option parser wants only initial characters followed by numbers
250 // or pathnames.
251 //
252
253
254 ssgSimpleState *cloud3d_imposter_state;
255 ssgSimpleState *default_state;
256 ssgSimpleState *hud_and_panel;
257 ssgSimpleState *menus;
258
259 SGTimeStamp last_time_stamp;
260 SGTimeStamp current_time_stamp;
261
262
263 void fgBuildRenderStates( void ) {
264     default_state = new ssgSimpleState;
265     default_state->ref();
266     default_state->disable( GL_TEXTURE_2D );
267     default_state->enable( GL_CULL_FACE );
268     default_state->enable( GL_COLOR_MATERIAL );
269     default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
270     default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
271     default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
272     default_state->disable( GL_BLEND );
273     default_state->disable( GL_ALPHA_TEST );
274     default_state->disable( GL_LIGHTING );
275
276     cloud3d_imposter_state = new ssgSimpleState;
277     cloud3d_imposter_state->ref();
278     cloud3d_imposter_state->enable( GL_TEXTURE_2D );
279     cloud3d_imposter_state->enable( GL_CULL_FACE );
280     cloud3d_imposter_state->enable( GL_COLOR_MATERIAL );
281     cloud3d_imposter_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
282     cloud3d_imposter_state->setMaterial( GL_DIFFUSE, 1, 1, 1, 1 );
283     cloud3d_imposter_state->setMaterial( GL_AMBIENT, 1, 1, 1, 1 );
284     cloud3d_imposter_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
285     cloud3d_imposter_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
286     cloud3d_imposter_state->enable( GL_BLEND );
287     cloud3d_imposter_state->enable( GL_ALPHA_TEST );
288     cloud3d_imposter_state->disable( GL_LIGHTING );
289
290     hud_and_panel = new ssgSimpleState;
291     hud_and_panel->ref();
292     hud_and_panel->disable( GL_CULL_FACE );
293     hud_and_panel->disable( GL_TEXTURE_2D );
294     hud_and_panel->disable( GL_LIGHTING );
295     hud_and_panel->enable( GL_BLEND );
296
297     menus = new ssgSimpleState;
298     menus->ref();
299     menus->disable( GL_CULL_FACE );
300     menus->disable( GL_TEXTURE_2D );
301     menus->enable( GL_BLEND );
302 }
303
304
305 // fgInitVisuals() -- Initialize various GL/view parameters
306 void fgInitVisuals( void ) {
307     fgLIGHT *l;
308
309     l = &cur_light_params;
310
311 #ifndef GLUT_WRONG_VERSION
312     // Go full screen if requested ...
313     if ( fgGetBool("/sim/startup/fullscreen") ) {
314         glutFullScreen();
315     }
316 #endif
317
318     // If enabled, normal vectors specified with glNormal are scaled
319     // to unit length after transformation.  Enabling this has
320     // performance implications.  See the docs for glNormal.
321     // glEnable( GL_NORMALIZE );
322
323     glEnable( GL_LIGHTING );
324     glEnable( GL_LIGHT0 );
325     // glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );  // done later with ssg
326
327     sgVec3 sunpos;
328     sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
329     ssgGetLight( 0 ) -> setPosition( sunpos );
330
331     glFogi (GL_FOG_MODE, GL_EXP2);
332     if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) || 
333          (!fgGetBool("/sim/rendering/shading"))) {
334         // if fastest fog requested, or if flat shading force fastest
335         glHint ( GL_FOG_HINT, GL_FASTEST );
336     } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
337         glHint ( GL_FOG_HINT, GL_NICEST );
338     }
339     if ( fgGetBool("/sim/rendering/wireframe") ) {
340         // draw wire frame
341         glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
342     }
343
344     // This is the default anyways, but it can't hurt
345     glFrontFace ( GL_CCW );
346
347     // Just testing ...
348     // glEnable(GL_POINT_SMOOTH);
349     // glEnable(GL_LINE_SMOOTH);
350     // glEnable(GL_POLYGON_SMOOTH);      
351 }
352
353
354 // For HiRes screen Dumps using Brian Pauls TR Library
355 void trRenderFrame( void ) {
356
357     if ( fgPanelVisible() ) {
358         GLfloat height = fgGetInt("/sim/startup/ysize");
359         GLfloat view_h =
360             (globals->get_current_panel()->getViewHeight() - globals->get_current_panel()->getYOffset())
361             * (height / 768.0) + 1;
362         glTranslatef( 0.0, view_h, 0.0 );
363     }
364
365     static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
366     static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
367
368     fgLIGHT *l = &cur_light_params;
369
370     glClearColor(l->adj_fog_color[0], l->adj_fog_color[1], 
371                  l->adj_fog_color[2], l->adj_fog_color[3]);
372
373     glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
374
375     // set the opengl state to known default values
376     default_state->force();
377
378     glEnable( GL_FOG );
379     glFogf  ( GL_FOG_DENSITY, fog_exp2_density);
380     glFogi  ( GL_FOG_MODE,    GL_EXP2 );
381     glFogfv ( GL_FOG_COLOR,   l->adj_fog_color );
382
383     // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
384     // we only update GL_AMBIENT for our lights we will never get
385     // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
386     // explicitely to black.
387     glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
388     glLightModeli( GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE );
389
390     ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
391
392     // texture parameters
393     glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
394     glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
395
396     // we need a white diffuse light for the phase of the moon
397     ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
398     thesky->preDraw();
399
400     // draw the ssg scene
401     // return to the desired diffuse color
402     ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
403     glEnable( GL_DEPTH_TEST );
404     ssgSetNearFar( scene_nearplane, scene_farplane );
405     ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
406
407     // draw the lights
408     glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
409     ssgSetNearFar( scene_nearplane, scene_farplane );
410     ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
411
412     ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
413
414     if (fgGetBool("/environment/clouds/status"))
415         thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
416
417     globals->get_model_mgr()->draw();
418     globals->get_aircraft_model()->draw();
419 }
420
421
422 // Update all Visuals (redraws anything graphics related)
423 void fgRenderFrame() {
424
425     GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
426     GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
427
428     // Process/manage pending events
429     global_events.update( delta_time_sec );
430
431     // static const SGPropertyNode *longitude
432     //     = fgGetNode("/position/longitude-deg");
433     // static const SGPropertyNode *latitude
434     //     = fgGetNode("/position/latitude-deg");
435     // static const SGPropertyNode *altitude
436     //     = fgGetNode("/position/altitude-ft");
437     static const SGPropertyNode *groundlevel_nearplane
438         = fgGetNode("/sim/current-view/ground-level-nearplane-m");
439
440     // Update the default (kludged) properties.
441     fgUpdateProps();
442
443     FGViewer *current__view = globals->get_current_view();
444
445     fgLIGHT *l = &cur_light_params;
446     static double last_visibility = -9999;
447
448     // update fog params
449     double actual_visibility;
450     if (fgGetBool("/environment/clouds/status"))
451         actual_visibility = thesky->get_visibility();
452     else
453         actual_visibility = fgGetDouble("/environment/visibility-m");
454     if ( actual_visibility != last_visibility ) {
455         last_visibility = actual_visibility;
456
457         fog_exp_density = m_log01 / actual_visibility;
458         fog_exp2_density = sqrt_m_log01 / actual_visibility;
459         ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
460         if ( actual_visibility < 8000 ) {
461             rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
462             taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
463         } else {
464             rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
465             taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
466         }
467     }
468
469     // double angle;
470     // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
471     // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
472     // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
473     // GLfloat mat_shininess[] = { 10.0 };
474     GLbitfield clear_mask;
475
476     if ( idle_state != 1000 ) {
477         // still initializing, draw the splash screen
478         if ( fgGetBool("/sim/startup/splash-screen") ) {
479             fgSplashUpdate(0.0, 1.0);
480         }
481         // Keep resetting sim time while the sim is initializing
482         globals->set_sim_time_sec( 0.0 );
483         SGAnimation::set_sim_time_sec( 0.0 );
484     } else {
485         // idle_state is now 1000 meaning we've finished all our
486         // initializations and are running the main loop, so this will
487         // now work without seg faulting the system.
488
489         // calculate our current position in cartesian space
490         globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
491
492         // update view port
493         fgReshape( fgGetInt("/sim/startup/xsize"),
494                    fgGetInt("/sim/startup/ysize") );
495
496         if ( fgGetBool("/sim/rendering/clouds3d") ) {
497             glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
498             cloud3d_imposter_state->force();
499             glDisable( GL_FOG );
500             glColor4f( 1.0, 1.0, 1.0, 1.0 );
501             glEnable(GL_DEPTH_TEST);
502             glEnable(GL_BLEND);
503             glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
504
505 #ifdef FG_USE_CLOUDS_3D
506             if ( _bcloud_orig ) {
507                 Point3D c = globals->get_scenery()->get_center();
508                 sgClouds3d->Set_Cloud_Orig( &c );
509                 _bcloud_orig = false;
510             }
511             sgClouds3d->Update( current__view->get_absolute_view_pos() );
512 #endif
513             glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
514             glDisable(GL_DEPTH_TEST);
515         }
516
517         clear_mask = GL_DEPTH_BUFFER_BIT;
518         if ( fgGetBool("/sim/rendering/wireframe") ) {
519             clear_mask |= GL_COLOR_BUFFER_BIT;
520         }
521
522         if ( fgGetBool("/sim/rendering/skyblend") ) {
523             if ( fgGetBool("/sim/rendering/textures") ) {
524             // glClearColor(black[0], black[1], black[2], black[3]);
525             glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
526                          l->adj_fog_color[2], l->adj_fog_color[3]);
527             clear_mask |= GL_COLOR_BUFFER_BIT;
528             }
529         } else {
530             glClearColor(l->sky_color[0], l->sky_color[1],
531                      l->sky_color[2], l->sky_color[3]);
532             clear_mask |= GL_COLOR_BUFFER_BIT;
533         }
534         glClear( clear_mask );
535
536         // Tell GL we are switching to model view parameters
537
538         // I really should create a derived ssg node or use a call
539         // back or something so that I can draw the sky within the
540         // ssgCullAndDraw() function, but for now I just mimic what
541         // ssg does to set up the model view matrix
542         glMatrixMode(GL_MODELVIEW);
543         glLoadIdentity();
544         ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
545
546         // set the opengl state to known default values
547         default_state->force();
548
549         // update fog params if visibility has changed
550         double visibility_meters = fgGetDouble("/environment/visibility-m");
551         thesky->set_visibility(visibility_meters);
552
553         thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
554                         ( global_multi_loop * fgGetInt("/sim/speed-up") )
555                             / (double)fgGetInt("/sim/model-hz") );
556
557         // Set correct opengl fog density
558         glFogf (GL_FOG_DENSITY, fog_exp2_density);
559
560         // update the sky dome
561         if ( fgGetBool("/sim/rendering/skyblend") ) {
562             /*
563              SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
564              << cur_light_params.sky_color[0] << " "
565              << cur_light_params.sky_color[1] << " "
566              << cur_light_params.sky_color[2] << " "
567              << cur_light_params.sky_color[3] );
568             SG_LOG( SG_GENERAL, SG_BULK, "    fog = "
569              << cur_light_params.fog_color[0] << " "
570              << cur_light_params.fog_color[1] << " "
571              << cur_light_params.fog_color[2] << " "
572              << cur_light_params.fog_color[3] ); 
573             SG_LOG( SG_GENERAL, SG_BULK,
574                     "    sun_angle = " << cur_light_params.sun_angle
575              << "    moon_angle = " << cur_light_params.moon_angle );
576             */
577             thesky->repaint( cur_light_params.sky_color,
578                              cur_light_params.adj_fog_color,
579                              cur_light_params.cloud_color,
580                              cur_light_params.sun_angle,
581                              cur_light_params.moon_angle,
582                              globals->get_ephem()->getNumPlanets(),
583                              globals->get_ephem()->getPlanets(),
584                              globals->get_ephem()->getNumStars(),
585                              globals->get_ephem()->getStars() );
586
587             /*
588             SG_LOG( SG_GENERAL, SG_BULK,
589                     "thesky->reposition( view_pos = " << view_pos[0] << " "
590              << view_pos[1] << " " << view_pos[2] );
591             SG_LOG( SG_GENERAL, SG_BULK,
592                     "    zero_elev = " << zero_elev[0] << " "
593              << zero_elev[1] << " " << zero_elev[2]
594              << " lon = " << cur_fdm_state->get_Longitude()
595              << " lat = " << cur_fdm_state->get_Latitude() );
596             SG_LOG( SG_GENERAL, SG_BULK,
597                     "    sun_rot = " << cur_light_params.sun_rotation
598              << " gst = " << SGTime::cur_time_params->getGst() );
599             SG_LOG( SG_GENERAL, SG_BULK,
600                  "    sun ra = " << globals->get_ephem()->getSunRightAscension()
601               << " sun dec = " << globals->get_ephem()->getSunDeclination()
602               << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
603               << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
604             */
605
606             // The sun and moon distances are scaled down versions
607             // of the actual distance to get both the moon and the sun
608             // within the range of the far clip plane.
609             // Moon distance:    384,467 kilometers
610             // Sun distance: 150,000,000 kilometers
611             double sun_horiz_eff, moon_horiz_eff;
612             if (fgGetBool("/sim/rendering/horizon-effect")) {
613             sun_horiz_eff = 0.67+pow(0.5+cos(cur_light_params.sun_angle*2)/2,0.33)/3;
614             moon_horiz_eff = 0.67+pow(0.5+cos(cur_light_params.moon_angle*2)/2,0.33)/3;
615             } else {
616                sun_horiz_eff = moon_horiz_eff = 1.0;
617             }
618             thesky->reposition( current__view->get_view_pos(),
619                                 current__view->get_zero_elev(),
620                                 current__view->get_world_up(),
621                                 current__view->getLongitude_deg()
622                                   * SGD_DEGREES_TO_RADIANS,
623                                 current__view->getLatitude_deg()
624                                   * SGD_DEGREES_TO_RADIANS,
625                                 current__view->getAltitudeASL_ft()
626                                   * SG_FEET_TO_METER,
627                                 cur_light_params.sun_rotation,
628                                 globals->get_time_params()->getGst(),
629                                 globals->get_ephem()->getSunRightAscension(),
630                                 globals->get_ephem()->getSunDeclination(),
631                                 50000.0 * sun_horiz_eff,
632                                 globals->get_ephem()->getMoonRightAscension(),
633                                 globals->get_ephem()->getMoonDeclination(),
634                                 40000.0 * moon_horiz_eff );
635         }
636
637         glEnable( GL_DEPTH_TEST );
638         if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
639             glEnable( GL_FOG );
640             glFogi( GL_FOG_MODE, GL_EXP2 );
641             glFogfv( GL_FOG_COLOR, l->adj_fog_color );
642         }
643
644         // set sun/lighting parameters
645         ssgGetLight( 0 ) -> setPosition( l->sun_vec );
646
647         // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
648         // we only update GL_AMBIENT for our lights we will never get
649         // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
650         // explicitely to black.
651         glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
652
653         ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
654         ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
655         ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular );
656
657         // texture parameters
658         // glEnable( GL_TEXTURE_2D );
659         glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
660         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
661
662         // glMatrixMode( GL_PROJECTION );
663         // glLoadIdentity();
664         ssgSetFOV( current__view->get_h_fov(),
665                    current__view->get_v_fov() );
666
667         double agl =
668             current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
669             - globals->get_scenery()->get_cur_elev();
670
671         if ( agl > 10.0 ) {
672             scene_nearplane = 10.0f;
673             scene_farplane = 120000.0f;
674         } else {
675             scene_nearplane = groundlevel_nearplane->getDoubleValue();
676             scene_farplane = 120000.0f;
677         }
678
679         ssgSetNearFar( scene_nearplane, scene_farplane );
680
681         // $$$ begin - added VS Renganthan 17 Oct 2K
682         if(objc)
683           fgUpdateDCS();
684         // $$$ end - added VS Renganthan 17 Oct 2K
685
686 # ifdef FG_NETWORK_OLK
687         if ( fgGetBool("/sim/networking/network-olk") ) {
688             sgCoord fgdpos;
689             other = head->next;             /* put listpointer to start  */
690             while ( other != tail) {        /* display all except myself */
691             if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
692                 other->fgd_sel->select(1);
693                 sgSetCoord( &fgdpos, other->sgFGD_COORD );
694                 other->fgd_pos->setTransform( &fgdpos );
695             }
696             other = other->next;
697             }
698
699             // fgd_sel->select(1);
700             // sgCopyMat4( sgTUX, current_view.sgVIEW);
701             // sgCoord fgdpos;
702             // sgSetCoord( &fgdpos, sgFGD_VIEW );
703             // fgd_pos->setTransform( &fgdpos);
704         }
705 # endif
706
707 #ifdef FG_MPLAYER_AS
708         // Update any multiplayer models
709         globals->get_multiplayer_rx_mgr()->Update();
710 #endif
711
712         if ( fgGetBool("/sim/rendering/skyblend") &&
713              fgGetBool("/sim/rendering/draw-otw") )
714         {
715             // draw the sky backdrop
716
717             // we need a white diffuse light for the phase of the moon
718             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
719
720             thesky->preDraw();
721
722             // return to the desired diffuse color
723             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
724         }
725
726         // draw the ssg scene
727         glEnable( GL_DEPTH_TEST );
728
729         ssgSetNearFar( scene_nearplane, scene_farplane );
730
731         if ( fgGetBool("/sim/rendering/wireframe") ) {
732             // draw wire frame
733             glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
734         }
735         if ( fgGetBool("/sim/rendering/draw-otw") ) {
736             ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
737         }
738
739         // This is a bit kludgy.  Every 200 frames, do an extra
740         // traversal of the scene graph without drawing anything, but
741         // with the field-of-view set to 360x360 degrees.  This
742         // ensures that out-of-range random objects that are not in
743         // the current view frustum will still be freed properly.
744         static int counter = 0;
745         counter++;
746         if (counter == 200) {
747           sgFrustum f;
748           f.setFOV(360, 360);
749                             // No need to put the near plane too close;
750                             // this way, at least the aircraft can be
751                             // culled.
752           f.setNearFar(1000, 1000000);
753           sgMat4 m;
754           ssgGetModelviewMatrix(m);
755           globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
756           counter = 0;
757         }
758
759         // change state for lighting here
760
761         // draw runway lighting
762         glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
763         ssgSetNearFar( scene_nearplane, scene_farplane );
764
765         if (fgGetBool("/sim/rendering/enhanced-lighting")) {
766
767             // Enable states for drawing points with GL_extension
768             glEnable(GL_POINT_SMOOTH);
769
770             if ( fgGetBool("/sim/rendering/distance-attenuation") &&
771                  ( SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ||
772                    SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) )
773             {
774                 // Enable states for drawing points with GL_extension
775                 glEnable(GL_POINT_SMOOTH);
776
777                 float quadratic[3] = {1.0, 0.001, 0.0000001};
778                 // makes the points fade as they move away
779                 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT, quadratic);
780                 glPointParameterfPtr(GL_POINT_SIZE_MIN_EXT, 1.0); 
781             }
782
783             glPointSize(4.0);
784
785             // blending function for runway lights
786             glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
787         }
788
789         glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
790         glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
791         glEnable(GL_TEXTURE_GEN_S);
792         glEnable(GL_TEXTURE_GEN_T);
793         glPolygonMode(GL_FRONT, GL_POINT);
794
795         // draw runway lighting
796         if ( fgGetBool("/sim/rendering/draw-otw") ) {
797             ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
798         }
799
800         // change punch through and then draw taxi lighting
801         glFogf ( GL_FOG_DENSITY, fog_exp2_density );
802         // sgVec3 taxi_fog;
803         // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
804         // glFogfv ( GL_FOG_COLOR, taxi_fog );
805         if ( fgGetBool("/sim/rendering/draw-otw") ) {
806             ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
807         }
808
809         // clean up lighting
810         glPolygonMode(GL_FRONT, GL_FILL);
811         glDisable(GL_TEXTURE_GEN_S);
812         glDisable(GL_TEXTURE_GEN_T);
813
814         //static int _frame_count = 0;
815         //if (_frame_count % 30 == 0) {
816         //  printf("SSG: %s\n", ssgShowStats());
817         //}
818         //else {
819         //  ssgShowStats();
820         //}
821         //_frame_count++;
822
823
824         if (fgGetBool("/sim/rendering/enhanced-lighting")) {
825             if ( fgGetBool("/sim/rendering/distance-attenuation") &&
826                  ( SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ||
827                    SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) )
828             {
829                 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT,
830                                       default_attenuation);
831             }
832
833             glPointSize(1.0);
834             glDisable(GL_POINT_SMOOTH);
835         }
836
837         // draw ground lighting
838         glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
839         if ( fgGetBool("/sim/rendering/draw-otw") ) {
840             ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
841         }
842
843         if ( fgGetBool("/sim/rendering/skyblend") ) {
844             // draw the sky cloud layers
845             if ( fgGetBool("/environment/clouds/status") &&
846                  fgGetBool("/sim/rendering/draw-otw") )
847             {
848                 thesky->postDraw( cur_fdm_state->get_Altitude()
849                                   * SG_FEET_TO_METER );
850             }
851         }
852
853         if ( fgGetBool("/sim/rendering/clouds3d") &&
854              fgGetBool("/sim/rendering/draw-otw") )
855         {
856             glDisable( GL_FOG );
857             glDisable( GL_LIGHTING );
858             // cout << "drawing new clouds" << endl;
859
860             glEnable(GL_DEPTH_TEST);
861             glEnable(GL_BLEND);
862             glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
863
864             /*
865             glEnable( GL_TEXTURE_2D );
866             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
867             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
868             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
869             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
870             */
871
872 #ifdef FG_USE_CLOUDS_3D
873             sgClouds3d->Draw((sgVec4 *)current__view->get_VIEW());
874 #endif
875             glEnable( GL_FOG );
876             glEnable( GL_LIGHTING );
877             glEnable( GL_DEPTH_TEST );
878             glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
879         }
880
881         if ( fgGetBool("/sim/rendering/draw-otw") ) {
882             globals->get_model_mgr()->draw();
883             globals->get_aircraft_model()->draw();
884         }
885
886         // display HUD && Panel
887         glDisable( GL_FOG );
888         glDisable( GL_DEPTH_TEST );
889         // glDisable( GL_CULL_FACE );
890         // glDisable( GL_TEXTURE_2D );
891
892         // update the controls subsystem
893         globals->get_controls()->update(delta_time_sec);
894
895         hud_and_panel->apply();
896         fgCockpitUpdate();
897
898         // Use the hud_and_panel ssgSimpleState for rendering the ATC output
899         // This only works properly if called before the panel call
900         if((fgGetBool("/sim/ATC/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
901             globals->get_ATC_display()->update(delta_time_sec);
902
903         // update the panel subsystem
904         if ( globals->get_current_panel() != NULL ) {
905             globals->get_current_panel()->update(delta_time_sec);
906         }
907         fgUpdate3DPanels();
908
909         // We can do translucent menus, so why not. :-)
910         menus->apply();
911         glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
912         puDisplay();
913         // glDisable ( GL_BLEND ) ;
914
915         glEnable( GL_DEPTH_TEST );
916         glEnable( GL_FOG );
917
918         // Fade out the splash screen over the first three seconds.
919         double t = globals->get_sim_time_sec();
920         if ( t <= 1.0 ) {
921             fgSplashUpdate(0.0, 1.0);
922         } else if ( t <= 3.0) {
923             fgSplashUpdate(0.0, (3.0 - t) / 2.0);
924         }
925     }
926
927     glutSwapBuffers();
928 }
929
930
931 // Update internal time dependent calculations (i.e. flight model)
932 // FIXME: this distinction is obsolete; all subsystems now get delta
933 // time on update.
934 void fgUpdateTimeDepCalcs() {
935     static bool inited = false;
936
937     //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
938
939     fgLIGHT *l = &cur_light_params;
940
941     // Initialize the FDM here if it hasn't been and if we have a
942     // scenery elevation hit.
943
944     // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited() 
945     //      << " cur_elev = " << scenery.get_cur_elev() << endl;
946
947     if ( !cur_fdm_state->get_inited() &&
948          globals->get_scenery()->get_cur_elev() > -9990 )
949     {
950         SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");  
951         cur_fdm_state->init();
952         if ( cur_fdm_state->get_bound() ) {
953             cur_fdm_state->unbind();
954         }
955         cur_fdm_state->bind();
956     }
957
958     // conceptually, the following block could be done for each fdm
959     // instance ...
960     if ( !cur_fdm_state->get_inited() ) {
961         // do nothing, fdm isn't inited yet
962     } else {
963         // we have been inited, and  we are good to go ...
964
965         if ( !inited ) {
966             inited = true;
967         }
968
969         globals->get_autopilot()->update(delta_time_sec);
970         cur_fdm_state->update(delta_time_sec);
971     }
972
973     globals->get_model_mgr()->update(delta_time_sec);
974     globals->get_aircraft_model()->update(delta_time_sec);
975
976     // update the view angle
977     globals->get_viewmgr()->update(delta_time_sec);
978
979     l->UpdateAdjFog();
980
981     // Update solar system
982     globals->get_ephem()->update( globals->get_time_params()->getMjd(),
983                               globals->get_time_params()->getLst(),
984                               cur_fdm_state->get_Latitude() );
985
986     // Update radio stack model
987     current_radiostack->update(delta_time_sec);
988 }
989
990
991 void fgInitTimeDepCalcs( void ) {
992     // noop for now
993 }
994
995
996 static const double alt_adjust_ft = 3.758099;
997 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
998
999
1000 // What should we do when we have nothing else to do?  Let's get ready
1001 // for the next move and update the display?
1002 static void fgMainLoop( void ) {
1003
1004     static const SGPropertyNode *longitude
1005         = fgGetNode("/position/longitude-deg");
1006     static const SGPropertyNode *latitude
1007         = fgGetNode("/position/latitude-deg");
1008     static const SGPropertyNode *altitude
1009         = fgGetNode("/position/altitude-ft");
1010     static const SGPropertyNode *clock_freeze
1011         = fgGetNode("/sim/freeze/clock", true);
1012     static const SGPropertyNode *cur_time_override
1013         = fgGetNode("/sim/time/cur-time-override", true);
1014
1015     // Update the elapsed time.
1016     static bool first_time = true;
1017     if ( first_time ) {
1018         last_time_stamp.stamp();
1019         first_time = false;
1020     }
1021
1022     double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
1023     if ( throttle_hz > 0.0 ) {
1024         // simple frame rate throttle
1025         double dt = 1000000.0 / throttle_hz;
1026         current_time_stamp.stamp();
1027         while ( current_time_stamp - last_time_stamp < dt ) {
1028             current_time_stamp.stamp();
1029         }
1030     } else {
1031         // run as fast as the app will go
1032         current_time_stamp.stamp();
1033     }
1034
1035     delta_time_sec = double(current_time_stamp - last_time_stamp) / 1000000.0;
1036     if ( clock_freeze->getBoolValue() ) {
1037         delta_time_sec = 0;
1038     }
1039     last_time_stamp = current_time_stamp;
1040     globals->inc_sim_time_sec( delta_time_sec );
1041     SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
1042
1043     static long remainder = 0;
1044     long elapsed;
1045 #ifdef FANCY_FRAME_COUNTER
1046     int i;
1047     double accum;
1048 #else
1049     static time_t last_time = 0;
1050     static int frames = 0;
1051 #endif // FANCY_FRAME_COUNTER
1052
1053     SGTime *t = globals->get_time_params();
1054
1055     sglog().setLogLevels( SG_ALL, (sgDebugPriority)fgGetInt("/sim/log-level") );
1056     sglog().setLogLevels( SG_ALL, SG_INFO );
1057
1058     SGLocation * acmodel_location = 0;
1059     if(cur_fdm_state->getACModel() != 0) {
1060       acmodel_location = (SGLocation *)  cur_fdm_state->getACModel()->get3DModel()->getSGLocation();
1061     }
1062
1063     SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
1064     SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
1065
1066 #ifdef FG_NETWORK_OLK
1067     if ( fgGetBool("/sim/networking/network-olk") ) {
1068         if ( net_is_registered == 0 ) {      // We first have to reg. to fgd
1069             // printf("FGD: Netupdate\n");
1070             fgd_send_com( "A", FGFS_host);   // Send Mat4 data
1071             fgd_send_com( "B", FGFS_host);   // Recv Mat4 data
1072         }
1073     }
1074 #endif
1075
1076 #if defined( ENABLE_PLIB_JOYSTICK )
1077     // Read joystick and update control settings
1078     // if ( fgGetString("/sim/control-mode") == "joystick" )
1079     // {
1080     //    fgJoystickRead();
1081     // }
1082 #elif defined( ENABLE_GLUT_JOYSTICK )
1083     // Glut joystick support works by feeding a joystick handler
1084     // function to glut.  This is taken care of once in the joystick
1085     // init routine and we don't have to worry about it again.
1086 #endif
1087
1088     // Fix elevation.  I'm just sticking this here for now, it should
1089     // probably move eventually
1090
1091     /* printf("Before - 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 // Curt is this code used?  I don't see any problems when I comment it out.
1097     if ( acmodel_location != 0 ) {
1098       if ( acmodel_location->get_cur_elev_m() > -9990 && cur_fdm_state->get_inited() ) {
1099         if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER < 
1100              (acmodel_location->get_cur_elev_m() + alt_adjust_m - 3.0) ) {
1101             // now set aircraft altitude above ground
1102             printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n", 
1103                cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
1104                acmodel_location->get_cur_elev_m() + alt_adjust_m - 3.0,
1105                acmodel_location->get_cur_elev_m() + alt_adjust_m );
1106             cur_fdm_state->set_Altitude( (acmodel_location->get_cur_elev_m() 
1107                                                 + alt_adjust_m) * SG_METER_TO_FEET );
1108             SG_LOG( SG_ALL, SG_DEBUG, 
1109                 "<*> resetting altitude to " 
1110                 << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
1111                 << " meters" );
1112         }
1113       }
1114     }
1115 // End of code in question. (see Curt is this code used? above)
1116
1117     /* printf("Adjustment - ground = %.2f  runway = %.2f  alt = %.2f\n",
1118            scenery.get_cur_elev(),
1119            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1120            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1121
1122     // cout << "Warp = " << globals->get_warp() << endl;
1123
1124     // update "time"
1125     static bool last_clock_freeze = false;
1126
1127     if ( clock_freeze->getBoolValue() ) {
1128         // clock freeze requested
1129         if ( cur_time_override->getLongValue() == 0 ) {
1130             fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
1131             globals->set_warp( 0 );
1132         }
1133     } else {
1134         // no clock freeze requested
1135         if ( last_clock_freeze == true ) {
1136             // clock just unfroze, let's set warp as the difference
1137             // between frozen time and current time so we don't get a
1138             // time jump (and corresponding sky object and lighting
1139             // jump.)
1140             globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
1141             fgSetLong( "/sim/time/cur-time-override", 0 );
1142         }
1143         if ( globals->get_warp_delta() != 0 ) {
1144             globals->inc_warp( globals->get_warp_delta() );
1145         }
1146     }
1147
1148     last_clock_freeze = clock_freeze->getBoolValue();
1149
1150     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1151                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1152                cur_time_override->getLongValue(),
1153                globals->get_warp() );
1154
1155     if ( globals->get_warp_delta() != 0 ) {
1156         fgUpdateSkyAndLightingParams();
1157     }
1158
1159     // update magvar model
1160     globals->get_mag()->update( longitude->getDoubleValue()
1161                               * SGD_DEGREES_TO_RADIANS,
1162                             latitude->getDoubleValue()
1163                               * SGD_DEGREES_TO_RADIANS,
1164                             altitude->getDoubleValue() * SG_FEET_TO_METER,
1165                             globals->get_time_params()->getJD() );
1166
1167     // Get elapsed time (in usec) for this past frame
1168     elapsed = fgGetTimeInterval();
1169     SG_LOG( SG_ALL, SG_DEBUG, 
1170             "Elapsed time interval is = " << elapsed 
1171             << ", previous remainder is = " << remainder );
1172
1173     // Calculate frame rate average
1174 #ifdef FANCY_FRAME_COUNTER
1175     /* old fps calculation */
1176     if ( elapsed > 0 ) {
1177         double tmp;
1178         accum = 0.0;
1179         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1180             tmp = general.get_frame(i);
1181             accum += tmp;
1182             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1183             general.set_frame(i+1,tmp);
1184         }
1185         tmp = 1000000.0 / (float)elapsed;
1186         general.set_frame(0,tmp);
1187         // printf("frame[0] = %.2f\n", general.frames[0]);
1188         accum += tmp;
1189         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1190         // printf("ave = %.2f\n", general.frame_rate);
1191     }
1192 #else
1193     if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1194         general.set_frame_rate( frames );
1195         fgSetInt("/sim/frame-rate", frames);
1196         SG_LOG( SG_ALL, SG_DEBUG, 
1197             "--> Frame rate is = " << general.get_frame_rate() );
1198         frames = 0;
1199     }
1200     last_time = t->get_cur_time();
1201     ++frames;
1202 #endif
1203
1204     // Run ATC subsystem
1205     if (fgGetBool("/sim/ATC/enabled"))
1206         globals->get_ATC_mgr()->update(delta_time_sec);
1207
1208     // Run the AI subsystem
1209     if (fgGetBool("/sim/ai-traffic/enabled"))
1210         globals->get_AI_mgr()->update(delta_time_sec);
1211
1212     // Run flight model
1213
1214     // Calculate model iterations needed for next frame
1215     elapsed += remainder;
1216
1217     global_multi_loop = (long)(((double)elapsed * 0.000001) * 
1218                           fgGetInt("/sim/model-hz"));
1219     remainder = elapsed - ( (global_multi_loop*1000000) / 
1220                         fgGetInt("/sim/model-hz") );
1221     SG_LOG( SG_ALL, SG_DEBUG, 
1222             "Model iterations needed = " << global_multi_loop
1223             << ", new remainder = " << remainder );
1224         
1225     // chop max interations to something reasonable if the sim was
1226     // delayed for an excesive amount of time
1227     if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1228         global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1229         remainder = 0;
1230     }
1231
1232     // flight model
1233     if ( global_multi_loop > 0 ) {
1234         fgUpdateTimeDepCalcs();
1235     } else {
1236         SG_LOG( SG_ALL, SG_DEBUG, 
1237             "Elapsed time is zero ... we're zinging" );
1238     }
1239
1240     // Do any I/O channel work that might need to be done
1241     globals->get_io()->update( delta_time_sec );
1242
1243     // see if we need to load any deferred-load textures
1244     globals->get_matlib()->load_next_deferred();
1245
1246     // Run audio scheduler
1247 #ifdef ENABLE_AUDIO_SUPPORT
1248     if ( fgGetBool("/sim/sound/audible")
1249            && globals->get_soundmgr()->is_working() ) {
1250         globals->get_soundmgr()->update( delta_time_sec );
1251     }
1252 #endif
1253
1254     globals->get_subsystem_mgr()->update(delta_time_sec);
1255
1256     //
1257     // Tile Manager updates - see if we need to load any new scenery tiles.
1258     //   this code ties together the fdm, viewer and scenery classes...
1259     //   we may want to move this to it's own class at some point
1260     //
1261     double visibility_meters = fgGetDouble("/environment/visibility-m");
1262     FGViewer *current_view = globals->get_current_view();
1263
1264     // update tile manager for FDM...
1265     // ...only if location is different than the viewer (to avoid duplicating effort)
1266     if( acmodel_location != current_view->getSGLocation() ) {
1267       if( acmodel_location != 0 ) {
1268         globals->get_tile_mgr()->prep_ssg_nodes( acmodel_location,
1269                                                  visibility_meters );
1270         globals->get_tile_mgr()->
1271             update( acmodel_location, visibility_meters,
1272                     acmodel_location->get_absolute_view_pos(globals->get_scenery()->get_center()) );
1273         // save results of update in SGLocation for fdm...
1274         if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1275           acmodel_location->
1276               set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1277         }
1278         acmodel_location->
1279             set_tile_center( globals->get_scenery()->get_next_center() );
1280       }
1281     }
1282
1283     globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
1284                                              visibility_meters );
1285     // update tile manager for view...
1286     // IMPORTANT!!! the tilemgr update for view location _must_ be done last 
1287     // after the FDM's until all of Flight Gear code references the viewer's location
1288     // for elevation instead of the "scenery's" current elevation.
1289     SGLocation *view_location = globals->get_current_view()->getSGLocation();
1290     globals->get_tile_mgr()->update( view_location, visibility_meters,
1291                                      current_view->get_absolute_view_pos() );
1292     // save results of update in SGLocation for fdm...
1293     if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1294       current_view->getSGLocation()->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1295     }
1296     current_view->getSGLocation()->set_tile_center( globals->get_scenery()->get_next_center() );
1297
1298     // If fdm location is same as viewer's then we didn't do the update for fdm location 
1299     //   above so we need to save the viewer results in the fdm SGLocation as well...
1300     if( acmodel_location == current_view->getSGLocation() ) {
1301       if( acmodel_location != 0 ) {
1302         if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1303           acmodel_location->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1304         }
1305         acmodel_location->set_tile_center( globals->get_scenery()->get_next_center() );
1306       }
1307     }
1308
1309     // END Tile Manager udpates
1310
1311     // redraw display
1312     fgRenderFrame();
1313
1314     SG_LOG( SG_ALL, SG_DEBUG, "" );
1315 }
1316
1317
1318 // This is the top level master main function that is registered as
1319 // our idle funciton
1320
1321 // The first few passes take care of initialization things (a couple
1322 // per pass) and once everything has been initialized fgMainLoop from
1323 // then on.
1324
1325 static void fgIdleFunction ( void ) {
1326     // printf("idle state == %d\n", idle_state);
1327
1328     if ( idle_state == 0 ) {
1329         // Initialize the splash screen right away
1330         if ( fgGetBool("/sim/startup/splash-screen") ) {
1331             fgSplashInit();
1332         }
1333         
1334         idle_state++;
1335     } else if ( idle_state == 1 ) {
1336         // Initialize audio support
1337 #ifdef ENABLE_AUDIO_SUPPORT
1338
1339         // Start the intro music
1340         if ( fgGetBool("/sim/startup/intro-music") ) {
1341             SGPath mp3file( globals->get_fg_root() );
1342             mp3file.append( "Sounds/intro.mp3" );
1343
1344             SG_LOG( SG_GENERAL, SG_INFO, 
1345                 "Starting intro music: " << mp3file.str() );
1346
1347 #if defined( __CYGWIN__ )
1348             string command = "start /m `cygpath -w " + mp3file.str() + "`";
1349 #elif defined( WIN32 )
1350             string command = "start /m " + mp3file.str();
1351 #else
1352             string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1353 #endif
1354
1355             system ( command.c_str() );
1356         }
1357 #endif
1358
1359         idle_state++;
1360     } else if ( idle_state == 2 ) {
1361         // These are a few miscellaneous things that aren't really
1362         // "subsystems" but still need to be initialized.
1363
1364 #ifdef USE_GLIDE
1365         if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1366             grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1367         }
1368 #endif
1369
1370         idle_state++;
1371     } else if ( idle_state == 3 ) {
1372         // This is the top level init routine which calls all the
1373         // other subsystem initialization routines.  If you are adding
1374         // a subsystem to flightgear, its initialization call should
1375         // located in this routine.
1376         if( !fgInitSubsystems()) {
1377             SG_LOG( SG_GENERAL, SG_ALERT,
1378                 "Subsystem initializations failed ..." );
1379             exit(-1);
1380         }
1381
1382         idle_state++;
1383     } else if ( idle_state == 4 ) {
1384         // setup OpenGL view parameters
1385         fgInitVisuals();
1386
1387         // Read the list of available aircrafts
1388         fgReadAircraft();
1389
1390         idle_state++;
1391     } else if ( idle_state == 5 ) {
1392
1393         idle_state++;
1394     } else if ( idle_state == 6 ) {
1395         // sleep(1);
1396         idle_state = 1000;
1397
1398         SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
1399         fgReshape( fgGetInt("/sim/startup/xsize"),
1400                fgGetInt("/sim/startup/ysize") );
1401     } 
1402
1403     if ( idle_state == 1000 ) {
1404         // We've finished all our initialization steps, from now on we
1405         // run the main loop.
1406
1407         glutIdleFunc(fgMainLoop);
1408     } else {
1409         if ( fgGetBool("/sim/startup/splash-screen") ) {
1410             fgSplashUpdate(0.0, 1.0);
1411         }
1412     }
1413 }
1414
1415 // options.cxx needs to see this for toggle_panel()
1416 // Handle new window size or exposure
1417 void fgReshape( int width, int height ) {
1418     int view_h;
1419
1420     if ( (!fgGetBool("/sim/virtual-cockpit"))
1421          && fgPanelVisible() && idle_state == 1000 ) {
1422         view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
1423                              globals->get_current_panel()->getYOffset()) / 768.0);
1424     } else {
1425         view_h = height;
1426     }
1427
1428     // for all views
1429     FGViewMgr *viewmgr = globals->get_viewmgr();
1430     for ( int i = 0; i < viewmgr->size(); ++i ) {
1431       viewmgr->get_view(i)->
1432         set_aspect_ratio((float)view_h / (float)width);
1433     }
1434
1435     glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1436
1437     fgSetInt("/sim/startup/xsize", width);
1438     fgSetInt("/sim/startup/ysize", height);
1439     guiInitMouse(width, height);
1440
1441     ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1442                viewmgr->get_current_view()->get_v_fov() );
1443
1444     fgHUDReshape();
1445
1446 #ifdef FG_USE_CLOUDS_3D
1447     sgClouds3d->Resize( viewmgr->get_current_view()->get_h_fov(),
1448                         viewmgr->get_current_view()->get_v_fov() );
1449 #endif
1450
1451 }
1452
1453 // Initialize GLUT and define a main window
1454 static bool fgGlutInit( int *argc, char **argv ) {
1455
1456 #if !defined( macintosh )
1457     // GLUT will extract all glut specific options so later on we only
1458     // need wory about our own.
1459     glutInit(argc, argv);
1460 #endif
1461
1462     // Define Display Parameters. Clouds3d works best with --bpp32 option
1463     if ( fgGetBool("/sim/rendering/clouds3d") ) {
1464         glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE | GLUT_ALPHA );
1465     } else {
1466         glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1467     }
1468
1469     SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1470             fgGetInt("/sim/startup/xsize") << "x"
1471             << fgGetInt("/sim/startup/ysize") );
1472
1473     // Define initial window size
1474     glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1475                     fgGetInt("/sim/startup/ysize") );
1476
1477     // Initialize windows
1478     if ( !fgGetBool("/sim/startup/game-mode")) {
1479         // Open the regular window
1480         glutCreateWindow("FlightGear");
1481 #ifndef GLUT_WRONG_VERSION
1482     } else {
1483         // Open the cool new 'game mode' window
1484         char game_mode_str[256];
1485 //#define SYNC_OPENGL_WITH_DESKTOP_SETTINGS
1486 #if defined(WIN32) && defined(SYNC_OPENGL_WITH_DESKTOP_SETTINGS)
1487 #ifndef ENUM_CURRENT_SETTINGS
1488 #define ENUM_CURRENT_SETTINGS       ((DWORD)-1)
1489 #define ENUM_REGISTRY_SETTINGS      ((DWORD)-2)
1490 #endif
1491
1492         DEVMODE dm;
1493         dm.dmSize = sizeof(DEVMODE);
1494         EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm);
1495         fgSetInt("/sim/startup/xsize", dm.dmPelsWidth);
1496         fgSetInt("/sim/startup/ysize", dm.dmPelsHeight);
1497         glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1498                             fgGetInt("/sim/startup/ysize") );
1499         sprintf( game_mode_str, "%dx%d:%d@%d",
1500                      dm.dmPelsWidth,
1501                      dm.dmPelsHeight,
1502                      dm.dmBitsPerPel,
1503                      dm.dmDisplayFrequency );
1504 #else
1505         // Open the cool new 'game mode' window
1506         sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1507              fgGetInt("/sim/startup/xsize"),
1508              fgGetInt("/sim/startup/ysize"),
1509              fgGetInt("/sim/rendering/bits-per-pixel"));
1510
1511 #endif // HAVE_WINDOWS_H
1512         SG_LOG( SG_GENERAL, SG_INFO, 
1513             "game mode params = " << game_mode_str );
1514         glutGameModeString( game_mode_str );
1515         glutEnterGameMode();
1516 #endif // GLUT_WRONG_VERSION
1517     }
1518
1519     // This seems to be the absolute earliest in the init sequence
1520     // that these calls will return valid info.  Too bad it's after
1521     // we've already created and sized out window. :-(
1522     general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1523     general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1524     general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1525     SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1526
1527     GLint tmp;
1528     glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1529     general.set_glMaxTexSize( tmp );
1530     SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1531
1532     glGetIntegerv( GL_DEPTH_BITS, &tmp );
1533     general.set_glDepthBits( tmp );
1534     SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1535
1536     return true;
1537 }
1538
1539
1540 // Initialize GLUT event handlers
1541 static bool fgGlutInitEvents( void ) {
1542     // call fgReshape() on window resizes
1543     glutReshapeFunc( fgReshape );
1544
1545     // keyboard and mouse callbacks are set in FGInput::init
1546
1547     // call fgMainLoop() whenever there is
1548     // nothing else to do
1549     glutIdleFunc( fgIdleFunction );
1550
1551     // draw the scene
1552     glutDisplayFunc( fgRenderFrame );
1553
1554     return true;
1555 }
1556
1557 // Main top level initialization
1558 static bool fgMainInit( int argc, char **argv ) {
1559
1560 #if defined( macintosh )
1561     freopen ("stdout.txt", "w", stdout );
1562     freopen ("stderr.txt", "w", stderr );
1563     argc = ccommand( &argv );
1564 #endif
1565
1566     // set default log levels
1567     sglog().setLogLevels( SG_ALL, SG_INFO );
1568
1569     string version;
1570 #ifdef FLIGHTGEAR_VERSION
1571     version = FLIGHTGEAR_VERSION;
1572 #else
1573     version = "unknown version";
1574 #endif
1575     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
1576             << version );
1577     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
1578
1579     // Allocate global data structures.  This needs to happen before
1580     // we parse command line options
1581
1582     globals = new FGGlobals;
1583
1584     // seed the random number generater
1585     sg_srandom_time();
1586
1587     SGRoute *route = new SGRoute;
1588     globals->set_route( route );
1589
1590     FGControls *controls = new FGControls;
1591     globals->set_controls( controls );
1592
1593     string_list *col = new string_list;
1594     globals->set_channel_options_list( col );
1595
1596     // Scan the config file(s) and command line options to see if
1597     // fg_root was specified (ignore all other options for now)
1598     fgInitFGRoot(argc, argv);
1599
1600     // Check for the correct base package version
1601     static char required_version[] = "0.9.2";
1602     string base_version = fgBasePackageVersion();
1603     if ( !(base_version == required_version) ) {
1604         // tell the operator how to use this application
1605
1606         cerr << endl << "Base package check failed ... " \
1607              << "Found version " << base_version << " at: " \
1608              << globals->get_fg_root() << endl;
1609         cerr << "Please upgrade to version: " << required_version << endl;
1610         exit(-1);
1611     }
1612
1613     // Initialize the Aircraft directory to "" (UIUC)
1614     aircraft_dir = "";
1615
1616     // Load the configuration parameters.  (Command line options
1617     // overrides config file options.  Config file options override
1618     // defaults.)
1619     if ( !fgInitConfig(argc, argv) ) {
1620         SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1621         exit(-1);
1622     }
1623
1624     // Initialize the Window/Graphics environment.
1625     if( !fgGlutInit(&argc, argv) ) {
1626         SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1627         exit(-1);
1628     }
1629
1630     // Initialize the various GLUT Event Handlers.
1631     if( !fgGlutInitEvents() ) {
1632  SG_LOG( SG_GENERAL, SG_ALERT, 
1633                 "GLUT event handler initialization failed ..." );
1634         exit(-1);
1635     }
1636
1637     // Initialize plib net interface
1638     netInit( &argc, argv );
1639
1640     // Initialize ssg (from plib).  Needs to come before we do any
1641     // other ssg stuff, but after opengl/glut has been initialized.
1642     ssgInit();
1643
1644     // Initialize the user interface (we need to do this before
1645     // passing off control to glut and before fgInitGeneral to get our
1646     // fonts !!!
1647     guiInit();
1648
1649     // Read the list of available aircrafts
1650     fgReadAircraft();
1651
1652 #ifdef GL_EXT_texture_lod_bias
1653     glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1654 #endif
1655
1656             // get the address of our OpenGL extensions
1657     if ( fgGetBool("/sim/rendering/distance-attenuation") )
1658     {
1659         if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
1660             glPointParameterfPtr = (glPointParameterfProc)
1661                                    SGLookupFunction("glPointParameterfEXT");
1662             glPointParameterfvPtr = (glPointParameterfvProc)
1663                                     SGLookupFunction("glPointParameterfvEXT");
1664
1665         } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
1666             glPointParameterfPtr = (glPointParameterfProc)
1667                                    SGLookupFunction("glPointParameterfARB");
1668             glPointParameterfvPtr = (glPointParameterfvProc)
1669                                     SGLookupFunction("glPointParameterfvARB");
1670         } 
1671    }
1672
1673     // based on the requested presets, calculate the true starting
1674     // lon, lat
1675     fgInitNav();
1676     fgInitPosition();
1677
1678     SGTime *t = fgInitTime();
1679     globals->set_time_params( t );
1680
1681     // Do some quick general initializations
1682     if( !fgInitGeneral()) {
1683         SG_LOG( SG_GENERAL, SG_ALERT, 
1684             "General initializations failed ..." );
1685         exit(-1);
1686     }
1687
1688     SGPath modelpath( globals->get_fg_root() );
1689     ssgModelPath( (char *)modelpath.c_str() );
1690
1691     ////////////////////////////////////////////////////////////////////
1692     // Initialize the property-based built-in commands
1693     ////////////////////////////////////////////////////////////////////
1694     fgInitCommands();
1695
1696     ////////////////////////////////////////////////////////////////////
1697     // Initialize the material manager
1698     ////////////////////////////////////////////////////////////////////
1699     globals->set_matlib( new SGMaterialLib );
1700
1701     globals->set_model_lib(new SGModelLib);
1702
1703     ////////////////////////////////////////////////////////////////////
1704     // Initialize the TG scenery subsystem.
1705     ////////////////////////////////////////////////////////////////////
1706     globals->set_scenery( new FGScenery );
1707     globals->get_scenery()->init();
1708     globals->get_scenery()->bind();
1709     globals->set_tile_mgr( new FGTileMgr );
1710
1711     ////////////////////////////////////////////////////////////////////
1712     // Initialize the general model subsystem.
1713     ////////////////////////////////////////////////////////////////////
1714     globals->set_model_mgr(new FGModelMgr);
1715     globals->get_model_mgr()->init();
1716     globals->get_model_mgr()->bind();
1717
1718     ////////////////////////////////////////////////////////////////////
1719     // Initialize the 3D aircraft model subsystem (has a dependency on
1720     // the scenery subsystem.)
1721     ////////////////////////////////////////////////////////////////////
1722     globals->set_aircraft_model(new FGAircraftModel);
1723     globals->get_aircraft_model()->init();
1724     globals->get_aircraft_model()->bind();
1725
1726     ////////////////////////////////////////////////////////////////////
1727     // Initialize the view manager subsystem.
1728     ////////////////////////////////////////////////////////////////////
1729
1730     FGViewMgr *viewmgr = new FGViewMgr;
1731     globals->set_viewmgr( viewmgr );
1732     viewmgr->init();
1733     viewmgr->bind();
1734
1735
1736     // Initialize the sky
1737     SGPath ephem_data_path( globals->get_fg_root() );
1738     ephem_data_path.append( "Astro" );
1739     SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1740     ephem->update( globals->get_time_params()->getMjd(),
1741                globals->get_time_params()->getLst(),
1742                0.0 );
1743     globals->set_ephem( ephem );
1744
1745                             // TODO: move to environment mgr
1746     thesky = new SGSky;
1747     SGPath texture_path(globals->get_fg_root());
1748     texture_path.append("Textures");
1749     texture_path.append("Sky");
1750     for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
1751         SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
1752         thesky->add_cloud_layer(layer);
1753     }
1754
1755
1756     SGPath sky_tex_path( globals->get_fg_root() );
1757     sky_tex_path.append( "Textures" );
1758     sky_tex_path.append( "Sky" );
1759     thesky->texture_path( sky_tex_path.str() );
1760
1761     // The sun and moon diameters are scaled down numbers of the
1762     // actual diameters. This was needed to fit bot the sun and the
1763     // moon within the distance to the far clip plane.
1764     // Moon diameter:    3,476 kilometers
1765     // Sun diameter: 1,390,000 kilometers
1766     thesky->build( 80000.0, 80000.0,
1767                    463.3, 361.8,
1768                    globals->get_ephem()->getNumPlanets(), 
1769                    globals->get_ephem()->getPlanets(),
1770                    globals->get_ephem()->getNumStars(),
1771                    globals->get_ephem()->getStars() );
1772
1773     // Initialize MagVar model
1774     SGMagVar *magvar = new SGMagVar();
1775     globals->set_mag( magvar );
1776
1777     // airport = new ssgBranch;
1778     // airport->setName( "Airport Lighting" );
1779     // lighting->addKid( airport );
1780
1781     // ADA
1782     fgLoadDCS();
1783     // ADA
1784
1785 #ifdef FG_NETWORK_OLK
1786     // Do the network intialization
1787     if ( fgGetBool("/sim/networking/network-olk") ) {
1788         printf("Multipilot mode %s\n",
1789                fg_net_init( globals->get_scenery()->get_scene_graph() ) );
1790     }
1791 #endif
1792
1793     // build our custom render states
1794     fgBuildRenderStates();
1795     
1796     // pass control off to the master GLUT event handler
1797     glutMainLoop();
1798
1799     // we never actually get here ... but to avoid compiler warnings,
1800     // etc.
1801     return false;
1802 }
1803
1804
1805 // $$$ end - added VS Renganathan, 15 Oct 2K
1806 //         - added Venky         , 12 Nov 2K
1807
1808 #if defined(__linux__) && defined(__i386__)
1809
1810 static void handleFPE (int);
1811
1812 static void
1813 initFPE ()
1814 {
1815     fpu_control_t fpe_flags = 0;
1816     _FPU_GETCW(fpe_flags);
1817 //     fpe_flags &= ~_FPU_MASK_IM;      // invalid operation
1818 //     fpe_flags &= ~_FPU_MASK_DM;      // denormalized operand
1819 //     fpe_flags &= ~_FPU_MASK_ZM;      // zero-divide
1820 //     fpe_flags &= ~_FPU_MASK_OM;      // overflow
1821 //     fpe_flags &= ~_FPU_MASK_UM;      // underflow
1822 //     fpe_flags &= ~_FPU_MASK_PM;      // precision (inexact result)
1823     _FPU_SETCW(fpe_flags);
1824     signal(SIGFPE, handleFPE);
1825 }
1826
1827 static void
1828 handleFPE (int num)
1829 {
1830   initFPE();
1831   SG_LOG(SG_GENERAL, SG_ALERT, "Floating point interrupt (SIGFPE)");
1832 }
1833 #endif
1834
1835 #ifdef __APPLE__
1836
1837 typedef struct
1838 {
1839   int  lo;
1840   int  hi;
1841 } PSN;
1842
1843 extern "C" {
1844   short CPSGetCurrentProcess(PSN *psn);
1845   short CPSSetProcessName (PSN *psn, char *processname);
1846   short CPSEnableForegroundOperation(PSN *psn, int _arg2, int _arg3, int _arg4, int _arg5);
1847   short CPSSetFrontProcess(PSN *psn);
1848 };
1849
1850 #define CPSEnableFG(psn) CPSEnableForegroundOperation(psn,0x03,0x3C,0x2C,0x1103)
1851
1852 #endif
1853
1854 // Main entry point; catch any exceptions that have made it this far.
1855 int main ( int argc, char **argv ) {
1856
1857     // Enable floating-point exceptions for Linux/x86
1858 #if defined(__linux__) && defined(__i386__)
1859     initFPE();
1860 #endif
1861
1862     // Enable floating-point exceptions for Windows
1863 #if defined( _MSC_VER ) && defined( DEBUG )
1864     // Christian, we should document what this does
1865     _control87( _EM_INEXACT, _MCW_EM );
1866 #endif
1867
1868 #if defined( HAVE_BC5PLUS )
1869     _control87(MCW_EM, MCW_EM);  /* defined in float.h */
1870 #endif
1871
1872     // Keyboard focus hack
1873 #ifdef __APPLE__
1874     {
1875       PSN psn;
1876
1877       glutInit (&argc, argv);
1878
1879       CPSGetCurrentProcess(&psn);
1880       CPSSetProcessName(&psn, "FlightGear");
1881       CPSEnableFG(&psn);
1882       CPSSetFrontProcess(&psn);
1883     }
1884 #endif
1885
1886     // FIXME: add other, more specific
1887     // exceptions.
1888     try {
1889         fgMainInit(argc, argv);
1890     } catch (sg_throwable &t) {
1891                             // We must use cerr rather than
1892                             // logging, since logging may be
1893                             // disabled.
1894         cerr << "Fatal error: " << t.getFormattedMessage()
1895              << "\n (received from " << t.getOrigin() << ')' << endl;
1896         exit(1);
1897     }
1898
1899     return 0;
1900 }
1901
1902
1903 void fgLoadDCS(void) {
1904
1905     ssgEntity *ship_obj = NULL;
1906
1907     char obj_filename[25];
1908
1909     for ( int k = 0; k < 32; k++ ) {
1910         ship_pos[k]=NULL;
1911     }
1912
1913     SGPath tile_path( globals->get_fg_root());
1914     tile_path.append( "Scenery" );
1915     tile_path.append( "Objects.txt" );
1916     sg_gzifstream in( tile_path.str() );
1917     if ( ! in.is_open() ) {
1918         SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1919     } else {
1920
1921         SGPath modelpath( globals->get_fg_root() );
1922         modelpath.append( "Models" );
1923         modelpath.append( "Geometry" );
1924   
1925         SGPath texturepath( globals->get_fg_root() );
1926         texturepath.append( "Models" );
1927         texturepath.append( "Textures" );
1928  
1929         ssgModelPath( (char *)modelpath.c_str() );
1930         ssgTexturePath( (char *)texturepath.c_str() );
1931
1932         ship_sel = new ssgSelector;
1933
1934         char c;
1935         while ( ! in.eof() ) {
1936             in >> ::skipws;
1937             if ( in.get( c ) && c == '#' ) { 
1938                 in >> skipeol;
1939             } else { 
1940                 in.putback(c);
1941                 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1942                 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] <<  " " << obj_alt[objc] << endl;
1943                    int chj=getchar();*/
1944                 
1945                 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1946                 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1947                 
1948                 ship_pos[objc] = new ssgTransform;
1949        
1950                 // type "repeat" in objects.txt to load one more
1951                 // instance of the last object.
1952
1953                 if ( strcmp(obj_filename,"repeat") != 0) {
1954                     ship_obj =
1955                       globals->get_model_lib()->load_model( globals->get_fg_root(), obj_filename, globals->get_props(), globals->get_sim_time_sec() );
1956                 }
1957       
1958                 if ( ship_obj != NULL ) {
1959                                 ship_obj->setName(obj_filename);
1960                             if (objc == 0)
1961                                         ship_obj->clrTraversalMaskBits( SSGTRAV_HOT );
1962                                 else
1963                                         ship_obj->setTraversalMaskBits( SSGTRAV_HOT );
1964                     ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1965                     ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1966                     SG_LOG( SG_TERRAIN, SG_ALERT, "Loaded file: "
1967                             << obj_filename );
1968                 } else {
1969                     SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1970                             << obj_filename );
1971                 }
1972             
1973                             // temporary hack for deck lights - ultimately should move to PLib (when??)
1974                             //const char *extn = file_extension ( obj_filename ) ;
1975                             if ( objc == 1 ){
1976                                 // ssgVertexArray *lights = new ssgVertexArray( 100 );
1977                                 ssgVertexArray *lightpoints = new ssgVertexArray( 100 );
1978                                 ssgVertexArray *lightnormals = new ssgVertexArray( 100 );
1979                                 ssgVertexArray *lightdir = new ssgVertexArray( 100 );
1980                                 int ltype[500], light_type = 0;
1981                                 static int ltcount = 0;
1982                                 string token;
1983                                 sgVec3 rway_dir,rway_normal,lightpt;
1984                                 Point3D node;
1985                                 modelpath.append(obj_filename);
1986                                 sg_gzifstream in1( modelpath.str() );
1987                                 if ( ! in1.is_open() ) {
1988                                         SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << modelpath.str() );
1989                                 } else {
1990                                         while ( ! in1.eof() ) {
1991                                                         in1 >> ::skipws;
1992                                                 if ( in1.get( c ) && c == '#' ) { 
1993                                                         in1 >> skipeol;
1994                                                 } else { 
1995                                                         in1.putback(c);
1996                                                         in1 >> token;
1997                                                         //cout << token << endl;
1998                                                         if ( token == "runway" ) {
1999                                                                 in1 >> node;
2000                                                                 sgSetVec3 (rway_dir, node[0], node[1], node[2] );                        
2001                                                         } else if ( token == "edgelight" ) {
2002                                                                 in1 >> node;
2003                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2004                                                                 light_type = 1;
2005                                                         } else if ( token == "taxi" ) {
2006                                                                 in1 >> node;
2007                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );                     
2008                                                                 light_type = 2;
2009                                                         } else if ( token == "vasi" ) {
2010                                                                 in1 >> node;
2011                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );                     
2012                                                                 light_type = 3;
2013                                                         } else if ( token == "threshold" ) {
2014                                                                 in1 >> node;
2015                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );                     
2016                                                                 light_type = 4;
2017                                                         } else if ( token == "rabbit" ) {
2018                                                                 in1 >> node;
2019                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2020                                                                 light_type = 5;
2021                                                         } else if ( token == "ols" ) {
2022                                                                 in1 >> node;
2023                                                                 sgSetVec3 (rway_ols, node[0], node[1], node[2] );
2024                                                                 light_type = 6;
2025                                                         } else if ( token == "red" ) {
2026                                                                 in1 >> node;
2027                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2028                                                                 light_type = 7;
2029                                                         } else if ( token == "green" ) {
2030                                                                 in1 >> node;
2031                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2032                                                                 light_type = 8;
2033                                                         } else if ( token == "lp" ) {
2034                                                                 in1 >> node;
2035                                                                 sgSetVec3 (lightpt, node[0], node[1], node[2] );
2036                                                                 lightpoints->add( lightpt );
2037                                                                 lightnormals->add( rway_normal );
2038                                                                 lightdir->add( rway_dir );
2039                                                                 ltype[ltcount]= light_type;
2040                                                                 ltcount++;
2041                                                         }
2042                                                         if (in1.eof()) break;
2043                                                 } 
2044                                         }  //while
2045
2046 #if 0        
2047                                         if ( lightpoints->getNum() ) {
2048                                                 ssgBranch *lightpoints_branch;
2049                                                 long int dummy = -999;
2050                                                 dummy_tile = new FGTileEntry((SGBucket)dummy);
2051                                                 dummy_tile->lightmaps_sequence = new ssgSelector;
2052                                                 dummy_tile->ols_transform = new ssgTransform;
2053
2054                                                 // call function to generate the runway lights
2055                                                 lightpoints_branch = 
2056                                                 dummy_tile->gen_runway_lights( lightpoints, lightnormals,
2057                                                                                                                         lightdir, ltype);
2058                                                 lightpoints_brightness->addKid(lightpoints_branch);
2059                                                 lightpoints_transform->addKid(lightpoints_brightness);
2060                                             //dummy_tile->lightmaps_sequence->setTraversalMaskBits( SSGTRAV_HOT );
2061                                                 lightpoints_transform->addKid( dummy_tile->lightmaps_sequence );
2062                                                 lightpoints_transform->ref();
2063                                                 globals->get_scenery()->get_gnd_lights_root()->addKid( lightpoints_transform );
2064                                         } 
2065 #endif
2066                                 } //if in1 
2067                 } //if objc
2068                             // end hack for deck lights
2069
2070                 objc++;
2071
2072                 if (in.eof()) break;
2073             }
2074         } // while
2075
2076         SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
2077
2078         globals->get_scenery()->get_terrain_branch()->addKid( ship_sel ); //add selector node to root node 
2079     }
2080
2081     return;
2082  }
2083
2084
2085 void fgUpdateDCS (void) {
2086
2087     // double eye_lat,eye_lon,eye_alt;
2088     // static double obj_head;
2089     double sl_radius,obj_latgc;
2090     // float nresultmat[4][4];
2091     // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
2092     double bz[3];
2093
2094     // Instantaneous Geodetic Lat/Lon/Alt of moving object
2095     FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
2096     
2097     // Deck should be the first object in objects.txt in case of fdm=ada
2098
2099     if (!strcmp(fgGetString("/sim/flight-model"), "ada")) {
2100             if ((fdm->get_iaux(1))==1)
2101             {
2102                     obj_lat[1] = fdm->get_daux(1)*SGD_DEGREES_TO_RADIANS;
2103                     obj_lon[1] = fdm->get_daux(2)*SGD_DEGREES_TO_RADIANS;
2104                     obj_alt[1] = fdm->get_daux(3);
2105                     obj_pitch[1] = fdm->get_faux(1);
2106                     obj_roll[1] = fdm->get_faux(2);
2107             }
2108     }
2109     
2110     for ( int m = 0; m < objc; m++ ) {
2111         //cout << endl <<  obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
2112         //int v=getchar();
2113
2114         //Geodetic to Geocentric angles for rotation
2115         sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
2116
2117         //moving object gbs-posn in cartesian coords
2118         Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
2119         Point3D obj_pos = sgGeodToCart( obj_posn );
2120
2121         // Translate moving object w.r.t eye
2122         Point3D Objtrans = obj_pos - globals->get_scenery()->get_center();
2123         bz[0]=Objtrans.x();
2124         bz[1]=Objtrans.y();
2125         bz[2]=Objtrans.z();
2126
2127        // rotate dynamic objects for lat,lon & alt and other motion about its axes
2128         
2129         sgMat4 sgTRANS;
2130         sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
2131
2132         sgVec3 ship_fwd,ship_rt,ship_up;
2133         sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
2134         sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
2135         sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
2136
2137         sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg, sgROT_pitch, sgROT_roll;
2138         sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
2139         sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
2140         sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
2141         sgMakeRotMat4( sgROT_pitch, obj_pitch[m], ship_rt );
2142         sgMakeRotMat4( sgROT_roll, obj_roll[m], ship_fwd );
2143         
2144         sgMat4 sgTUX;
2145         sgCopyMat4( sgTUX, sgROT_hdg );
2146         sgPostMultMat4( sgTUX, sgROT_pitch );
2147         sgPostMultMat4( sgTUX, sgROT_roll );
2148         sgPostMultMat4( sgTUX, sgROT_lat );
2149         sgPostMultMat4( sgTUX, sgROT_lon );
2150         sgPostMultMat4( sgTUX, sgTRANS );
2151
2152         sgCoord shippos;
2153         sgSetCoord(&shippos, sgTUX );
2154         ship_pos[m]->setTransform( &shippos );
2155         // temporary hack for deck lights - ultimately should move to PLib (when ??)
2156         if (m == 1) {
2157             if (lightpoints_transform) {
2158                     lightpoints_transform->setTransform( &shippos );
2159                     float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
2160                     if ( sun_angle > 89 ) {
2161                             lightpoints_brightness->select(0x01);
2162                     } else {
2163                             lightpoints_brightness->select(0x00);
2164                     }
2165             }
2166
2167             float elev;
2168             sgVec3 rp,to;
2169             float *vp;
2170             float alt;
2171             float ref_elev;
2172             sgXformPnt3( rp, rway_ols, sgTUX );
2173             vp = globals->get_current_view()->get_view_pos();
2174             to[0] = rp[0]-vp[0];
2175             to[1] = rp[1]-vp[1];
2176             to[2] = rp[2]-vp[2];
2177             float dist = sgLengthVec3( to );
2178             alt = (current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER)-rway_ols[2];
2179
2180             elev = asin(alt/dist)*SGD_RADIANS_TO_DEGREES;
2181
2182             ref_elev = elev - 3.75; // +ve above, -ve below
2183         
2184             unsigned int sel;
2185             sel = 0xFF;
2186 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
2187 //              if (ref_elev > 0.51) sel = 0x21;
2188 //              if ((ref_elev <= 0.51) & (ref_elev > 0.17)) sel = 0x22;
2189 //              if ((ref_elev <= 0.17) & (ref_elev >= -0.17)) sel = 0x24;
2190 //              if ((ref_elev < -0.17) & (ref_elev >= -0.51)) sel = 0x28;
2191 //              if (ref_elev < -0.51) sel = 0x30;
2192 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
2193             // dummy_tile->lightmaps_sequence->select(sel);
2194
2195             sgVec3 up;
2196             sgCopyVec3 (up, ship_up);
2197             if (dist > 750) 
2198                     sgScaleVec3 (up, 4.0*ref_elev*dist/750.0);
2199             else
2200                     sgScaleVec3 (up, 4.0*ref_elev);
2201             // dummy_tile->ols_transform->setTransform(up);
2202             //cout << "ref_elev  " << ref_elev << endl;
2203         }
2204     // end hack for deck lights
2205
2206     }
2207     if ( ship_sel != NULL ) {
2208         ship_sel->select(0xFFFFFFFE); // first object is ownship, added to acmodel
2209     }
2210 }
2211
2212 // $$$ end - added VS Renganathan, 15 Oct 2K
2213 //           added Venky         , 12 Nov 2K