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