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