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