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