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