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