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