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