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