]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Check for the proper version of the base package and exit gracefully if not
[flightgear.git] / src / Main / main.cxx
1 // main.cxx -- top level sim routines
2 //
3 // Written by Curtis Olson for OpenGL, started May 1997.
4 //
5 // Copyright (C) 1997 - 1999  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 #ifdef SG_MATH_EXCEPTION_CLASH
31 #  include <math.h>
32 #endif
33
34 #ifdef HAVE_WINDOWS_H
35 #  include <windows.h>
36 #  include <float.h>
37 #endif
38
39 #include <GL/glut.h>
40 #include <GL/gl.h>
41
42 #include <stdio.h>
43 #include <string.h>
44 #include <string>
45
46 #ifdef HAVE_STDLIB_H
47 #   include <stdlib.h>
48 #endif
49
50 #ifdef HAVE_SYS_STAT_H
51 #  include <sys/stat.h>         // for stat()
52 #endif
53
54 #ifdef HAVE_UNISTD_H
55 #  include <unistd.h>           // for stat()
56 #endif
57
58 // #ifdef HAVE_LIBX11
59 // #  include <GL/glext.h>
60 // #endif
61
62 #include <plib/pu.h>
63 #include <plib/ssg.h>
64
65 #include <simgear/constants.h>  // for VERSION
66 #include <simgear/debug/logstream.hxx>
67 #include <simgear/math/polar3d.hxx>
68 #include <simgear/math/sg_random.h>
69 #include <simgear/misc/sg_path.hxx>
70 #include <simgear/sky/sky.hxx>
71 #include <simgear/timing/sg_time.hxx>
72 #include <simgear/timing/lowleveltime.h>
73
74 #include <Include/general.hxx>
75
76 #include <Aircraft/aircraft.hxx>
77
78 #include <Autopilot/newauto.hxx>
79 #include <Cockpit/cockpit.hxx>
80 #include <Cockpit/radiostack.hxx>
81 #include <Cockpit/steam.hxx>
82
83 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
84 #include <GUI/gui.h>
85 #include <GUI/sgVec3Slider.hxx>
86 // #include <Joystick/joystick.hxx>
87 #ifdef FG_NETWORK_OLK
88 #include <NetworkOLK/network.h>
89 #endif
90 #include <Objects/matlib.hxx>
91 #include <Scenery/scenery.hxx>
92 #include <Scenery/tilemgr.hxx>
93 #ifdef ENABLE_AUDIO_SUPPORT
94 #  include <Sound/soundmgr.hxx>
95 #  include <Sound/morse.hxx>
96 #endif
97 #include <Time/event.hxx>
98 #include <Time/fg_timer.hxx>
99 #include <Time/light.hxx>
100 #include <Time/sunpos.hxx>
101 #include <Time/tmp.hxx>
102
103 #include <Input/input.hxx>
104
105 // begin - added Venky
106 //    $$$ begin - added VS Renganathan
107 #include <simgear/misc/sgstream.hxx>
108 #include <FDM/flight.hxx>
109 #include <FDM/ADA.hxx>
110 void fgLoadDCS (void);
111 void fgUpdateDCS (void);
112 ssgSelector *ship_sel=NULL;
113 // upto 32 instances of a same object can be loaded.
114 ssgTransform *ship_pos[32];
115 double obj_lat[32],obj_lon[32],obj_alt[32];
116 int objc=0;
117 //    $$$ end - added VS Renganathan
118 // end - added Venky
119
120 #ifndef FG_OLD_WEATHER
121 #  include <WeatherCM/FGLocalWeatherDatabase.h>
122 #else
123 #  include <Weather/weather.hxx>
124 #endif
125
126 #include "version.h"
127
128 #include "fg_init.hxx"
129 #include "fg_io.hxx"
130 #include "fg_props.hxx"
131 #include "globals.hxx"
132 #include "splash.hxx"
133
134 #ifdef macintosh
135 #  include <console.h>          // -dw- for command line dialog
136 #endif
137
138
139 // This is a record containing a bit of global housekeeping information
140 FGGeneral general;
141
142 // Specify our current idle function state.  This is used to run all
143 // our initializations out of the glutIdleLoop() so that we can get a
144 // splash screen up and running right away.
145 static int idle_state = 0;
146 static long global_multi_loop;
147
148 // attempt to avoid a large bounce at startup
149 static bool initial_freeze = true;
150
151 // forward declaration
152 void fgReshape( int width, int height );
153
154 // Global structures for the Audio library
155 #ifdef ENABLE_AUDIO_SUPPORT
156    static FGSimpleSound *s1;
157    static FGSimpleSound *s2;
158 #endif
159
160
161 // ssg variables
162 ssgRoot *scene = NULL;
163 ssgBranch *terrain = NULL;
164
165 // aircraft model stuff
166 ssgSelector *acmodel_selector = NULL;
167 ssgTransform *acmodel_pos = NULL;
168 ssgSelector *prop_selector = NULL;
169 ssgSelector *flaps_selector = NULL;
170 int acmodel_npropsettings;
171 int acmodel_proprpms[4][2];  // different propeller settings
172
173 ssgRoot *lighting = NULL;
174 ssgBranch *ground = NULL;
175 ssgBranch *airport = NULL;
176
177 #ifdef FG_NETWORK_OLK
178 ssgSelector *fgd_sel = NULL;
179 ssgTransform *fgd_pos = NULL;
180 #endif
181
182 // current fdm/position used for view
183 FGInterface cur_view_fdm;
184
185 // Sky structures
186 SGSky *thesky;
187
188 // hack
189 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
190 {
191   {  1.0f,  0.0f,  0.0f,  0.0f },
192   {  0.0f,  0.0f, -1.0f,  0.0f },
193   {  0.0f,  1.0f,  0.0f,  0.0f },
194   {  0.0f,  0.0f,  0.0f,  1.0f }
195 } ;
196
197 // The following defines flightgear options. Because glutlib will also
198 // want to parse its own options, those options must not be included here
199 // or they will get parsed by the main program option parser. Hence case
200 // is significant for any option added that might be in conflict with
201 // glutlib's parser.
202 //
203 // glutlib parses for:
204 //    -display
205 //    -direct   (invalid in Win32)
206 //    -geometry
207 //    -gldebug
208 //    -iconized
209 //    -indirect (invalid in Win32)
210 //    -synce
211 //
212 // Note that glutlib depends upon strings while this program's
213 // option parser wants only initial characters followed by numbers
214 // or pathnames.
215 //
216
217
218 ssgSimpleState *default_state;
219 ssgSimpleState *hud_and_panel;
220 ssgSimpleState *menus;
221
222 void fgBuildRenderStates( void ) {
223     default_state = new ssgSimpleState;
224     default_state->ref();
225     default_state->disable( GL_TEXTURE_2D );
226     default_state->enable( GL_CULL_FACE );
227     default_state->enable( GL_COLOR_MATERIAL );
228     default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
229     default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
230     default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
231     default_state->disable( GL_BLEND );
232     default_state->disable( GL_ALPHA_TEST );
233     default_state->disable( GL_LIGHTING );
234
235     hud_and_panel = new ssgSimpleState;
236     hud_and_panel->ref();
237     hud_and_panel->disable( GL_CULL_FACE );
238     hud_and_panel->disable( GL_TEXTURE_2D );
239     hud_and_panel->disable( GL_LIGHTING );
240     hud_and_panel->enable( GL_BLEND );
241
242     menus = new ssgSimpleState;
243     menus->ref();
244     menus->disable( GL_CULL_FACE );
245     menus->disable( GL_TEXTURE_2D );
246     menus->enable( GL_BLEND );
247 }
248
249 // fgFindNode -- a function that finds a named node in an ssg graph
250 ssgEntity *fgFindNode( ssgEntity *node, const char *name ) {
251   if ( node->getName() != NULL && strcmp( name, node->getName() ) == 0 ) {
252     return node;
253   } else if ( node->isAKindOf( ssgTypeBranch() ) ) {
254     ssgEntity *kid = ((ssgBranch*)node)->getKid(0);
255     while (kid != NULL) {
256       ssgEntity *n = fgFindNode(kid, name);
257       if (n != NULL)
258         return n;
259
260       kid = ((ssgBranch*)node)->getNextKid();
261     }
262   }
263
264   return NULL;
265 }
266
267 // fgInitVisuals() -- Initialize various GL/view parameters
268 void fgInitVisuals( void ) {
269     fgLIGHT *l;
270
271     l = &cur_light_params;
272
273 #ifndef GLUT_WRONG_VERSION
274     // Go full screen if requested ...
275     if ( fgGetBool("/sim/startup/fullscreen") ) {
276         glutFullScreen();
277     }
278 #endif
279
280     // If enabled, normal vectors specified with glNormal are scaled
281     // to unit length after transformation.  See glNormal.
282     // glEnable( GL_NORMALIZE );
283
284     glEnable( GL_LIGHTING );
285     glEnable( GL_LIGHT0 );
286     glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
287
288     sgVec3 sunpos;
289     sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
290     ssgGetLight( 0 ) -> setPosition( sunpos );
291
292     // glFogi (GL_FOG_MODE, GL_LINEAR);
293     glFogi (GL_FOG_MODE, GL_EXP2);
294     if ( (fgGetString("/sim/rendering/fog") == "disabled") || 
295          (!fgGetBool("/sim/rendering/shading"))) {
296         // if fastest fog requested, or if flat shading force fastest
297         glHint ( GL_FOG_HINT, GL_FASTEST );
298     } else if ( fgGetString("/sim/rendering/fog") == "nicest" ) {
299         glHint ( GL_FOG_HINT, GL_NICEST );
300     }
301     if ( fgGetBool("/sim/rendering/wireframe") ) {
302         // draw wire frame
303         glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
304     }
305
306     // This is the default anyways, but it can't hurt
307     glFrontFace ( GL_CCW );
308
309     // Just testing ...
310     // glEnable(GL_POINT_SMOOTH);
311     // glEnable(GL_LINE_SMOOTH);
312     // glEnable(GL_POLYGON_SMOOTH);      
313 }
314
315
316 // For HiRes screen Dumps using Brian Pauls TR Library
317 void trRenderFrame( void ) {
318
319     if ( fgPanelVisible() ) {
320         GLfloat height = fgGetInt("/sim/startup/ysize");
321         GLfloat view_h =
322             (current_panel->getViewHeight() - current_panel->getYOffset())
323             * (height / 768.0) + 1;
324         glTranslatef( 0.0, view_h, 0.0 );
325     }
326
327     static double m_log01      = -log( 0.01 );
328     static double sqrt_m_log01 = sqrt( m_log01 );
329
330     static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
331     static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
332
333     fgLIGHT *l = &cur_light_params;
334
335     glClearColor(l->adj_fog_color[0], l->adj_fog_color[1], 
336                  l->adj_fog_color[2], l->adj_fog_color[3]);
337
338     glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
339
340     // set the opengl state to known default values
341     default_state->force();
342
343     // update fog params
344     double actual_visibility       = thesky->get_visibility();
345     // GLfloat fog_exp_density        = m_log01 / actual_visibility;
346     GLfloat fog_exp2_density       = sqrt_m_log01 / actual_visibility;
347     GLfloat fog_exp2_punch_through = sqrt_m_log01 / ( actual_visibility * 1.5 );
348
349     glEnable( GL_FOG );
350     glFogf  ( GL_FOG_DENSITY, fog_exp2_density);
351     glFogi  ( GL_FOG_MODE,    GL_EXP2 );
352     glFogfv ( GL_FOG_COLOR,   l->adj_fog_color );
353
354     // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
355     // we only update GL_AMBIENT for our lights we will never get
356     // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
357     // explicitely to black.
358     glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
359
360     ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
361
362     // texture parameters
363     glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
364     glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
365
366     // we need a white diffuse light for the phase of the moon
367     ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
368     thesky->preDraw();
369
370     // draw the ssg scene
371     // return to the desired diffuse color
372     ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
373     glEnable( GL_DEPTH_TEST );
374     ssgCullAndDraw( scene );
375
376     // draw the lights
377     glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
378     ssgCullAndDraw( lighting );
379
380     thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
381
382     // need to do this here as hud_and_panel state is static to
383     // main.cxx  and HUD and Panel routines have to be called with
384     // knowledge of the the TR struct < see gui.cxx::HighResDump()
385     hud_and_panel->apply();
386 }
387
388
389 // Update all Visuals (redraws anything graphics related)
390 void fgRenderFrame( void ) {
391     // Update the default (kludged) properties.
392     fgUpdateProps();
393
394     fgLIGHT *l = &cur_light_params;
395     static double last_visibility = -9999;
396
397     static GLfloat fog_exp_density;
398     static GLfloat fog_exp2_density;
399     static GLfloat fog_exp2_punch_through;
400     
401     // double angle;
402     // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
403     // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
404     // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
405     // GLfloat mat_shininess[] = { 10.0 };
406     GLbitfield clear_mask;
407     
408     if ( idle_state != 1000 ) {
409         // still initializing, draw the splash screen
410         if ( fgGetBool("/sim/startup/splash-screen") ) {
411             fgSplashUpdate(0.0);
412         }
413     } else {
414         // idle_state is now 1000 meaning we've finished all our
415         // initializations and are running the main loop, so this will
416         // now work without seg faulting the system.
417
418         // printf("Ground = %.2f  Altitude = %.2f\n", scenery.cur_elev, 
419         //        FG_Altitude * SG_FEET_TO_METER);
420     
421         // this is just a temporary hack, to make me understand Pui
422         // timerText -> setLabel (ctime (&t->cur_time));
423         // end of hack
424
425         // calculate our current position in cartesian space
426         scenery.center = scenery.next_center;
427         // printf("scenery center = %.2f %.2f %.2f\n", scenery.center.x(),
428         //        scenery.center.y(), scenery.center.z());
429
430         FGViewerRPH *pilot_view =
431             (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
432
433         pilot_view->set_geod_view_pos( cur_fdm_state->get_Longitude(), 
434                                        cur_fdm_state->get_Lat_geocentric(), 
435                                        cur_fdm_state->get_Altitude() *
436                                        SG_FEET_TO_METER );
437         pilot_view->set_sea_level_radius( cur_fdm_state->
438                                           get_Sea_level_radius() *
439                                           SG_FEET_TO_METER ); 
440         pilot_view->set_rph( cur_fdm_state->get_Phi(),
441                              cur_fdm_state->get_Theta(),
442                              cur_fdm_state->get_Psi() );
443
444         FGViewerLookAt *chase_view =
445             (FGViewerLookAt *)globals->get_viewmgr()->get_view( 1 );
446
447         sgVec3 po;              // chase view pilot_offset
448         sgVec3 wup;             // chase view world up
449         sgSetVec3( po, 0.0, 0.0, 100.0 );
450         sgCopyVec3( wup, pilot_view->get_world_up() );
451         sgMat4 CXFM;            // chase view + pilot offset xform
452         sgMakeRotMat4( CXFM,
453                        chase_view->get_view_offset() * SGD_RADIANS_TO_DEGREES -
454                        cur_fdm_state->get_Psi() * SGD_RADIANS_TO_DEGREES,
455                        wup );
456         sgVec3 npo;             // new pilot offset after rotation
457         sgVec3 *pPO = PilotOffsetGet();
458         sgXformVec3( po, *pPO, pilot_view->get_UP() );
459         sgXformVec3( npo, po, CXFM );
460
461         chase_view->set_geod_view_pos( cur_fdm_state->get_Longitude(), 
462                                        cur_fdm_state->get_Lat_geocentric(), 
463                                        cur_fdm_state->get_Altitude() *
464                                        SG_FEET_TO_METER );
465         chase_view->set_sea_level_radius( cur_fdm_state->
466                                           get_Sea_level_radius() *
467                                           SG_FEET_TO_METER );
468         chase_view->set_pilot_offset( npo[0], npo[1], npo[2] );
469         chase_view->set_view_forward( pilot_view->get_view_pos() ); 
470         chase_view->set_view_up( wup );
471
472 #if 0
473         sgMat4 rph;
474         sgCopyMat4( rph, pilot_view->get_VIEW() );
475         cout << "RPH Matrix = " << endl;
476         int i, j;
477         for ( i = 0; i < 4; i++ ) {
478             for ( j = 0; j < 4; j++ ) {
479                 printf("%10.4f ", rph[i][j]);
480             }
481             cout << endl;
482         }
483
484         sgMat4 la;
485         sgCopyMat4( la, chase_view->get_VIEW() );
486         cout << "LookAt Matrix = " << endl;
487         for ( i = 0; i < 4; i++ ) {
488             for ( j = 0; j < 4; j++ ) {
489                 printf("%10.4f ", la[i][j]);
490             }
491             cout << endl;
492         }
493 #endif
494
495         // update view port
496         fgReshape( fgGetInt("/sim/startup/xsize"),
497                    fgGetInt("/sim/startup/ysize") );
498
499 #if 0
500         // swing and a miss
501
502         if ( ! fgPanelVisible() ) {
503             xglViewport( 0, 0 ,
504                          (GLint)(fgGetInt("/sim/startup/xsize")),
505                          (GLint)(fgGetInt("/sim/startup/ysize")) );
506         } else {
507             int view_h =
508                 int( (current_panel->getViewHeight() -
509                       current_panel->getYOffset())
510                      * (fgGetInt("/sim/startup/ysize") / 768.0) );
511             glViewport( 0, 
512                         (GLint)(fgGetInt("/sim/startup/ysize") - view_h),
513                         (GLint)(fgGetInt("/sim/startup/xsize")),
514                         (GLint)(view_h) );
515         }
516 #endif
517
518         // set the sun position
519         glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
520
521         clear_mask = GL_DEPTH_BUFFER_BIT;
522         if ( fgGetBool("/sim/rendering/wireframe") ) {
523             clear_mask |= GL_COLOR_BUFFER_BIT;
524         }
525
526         if ( fgGetBool("/sim/rendering/skyblend") ) {
527             if ( fgGetBool("/sim/rendering/textures") ) {
528                 // glClearColor(black[0], black[1], black[2], black[3]);
529                 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1], 
530                              l->adj_fog_color[2], l->adj_fog_color[3]);
531                 clear_mask |= GL_COLOR_BUFFER_BIT;
532             }
533         } else {
534             glClearColor(l->sky_color[0], l->sky_color[1], 
535                          l->sky_color[2], l->sky_color[3]);
536             clear_mask |= GL_COLOR_BUFFER_BIT;
537         }
538         glClear( clear_mask );
539
540         // Tell GL we are switching to model view parameters
541
542         // I really should create a derived ssg node or use a call
543         // back or something so that I can draw the sky within the
544         // ssgCullAndDraw() function, but for now I just mimic what
545         // ssg does to set up the model view matrix
546         glMatrixMode(GL_MODELVIEW);
547         glLoadIdentity();
548         ssgSetCamera( (sgVec4 *)globals->get_current_view()->get_VIEW() );
549
550         // set the opengl state to known default values
551         default_state->force();
552
553         // update fog params if visibility has changed
554 #ifndef FG_OLD_WEATHER
555         thesky->set_visibility( WeatherDatabase->getWeatherVisibility() );
556 #else
557         thesky->set_visibility( current_weather.get_visibility() );
558 #endif
559
560         thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
561                             ( global_multi_loop * 
562                               fgGetInt("/sim/speed-up") ) /
563                             (double)fgGetInt("/sim/model-hz") );
564
565         double actual_visibility = thesky->get_visibility();
566         // cout << "actual visibility = " << actual_visibility << endl;
567
568         if ( actual_visibility != last_visibility ) {
569             last_visibility = actual_visibility;
570
571             // cout << "----> updating fog params" << endl;
572                 
573             // for GL_FOG_EXP
574             fog_exp_density = -log(0.01) / actual_visibility;
575     
576             // for GL_FOG_EXP2
577             fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
578             fog_exp2_punch_through = sqrt( -log(0.01) ) / 
579                 ( actual_visibility * 1.5 );
580         }
581
582         // Set correct opengl fog density
583         glFogf (GL_FOG_DENSITY, fog_exp2_density);
584
585         // update the sky dome
586         if ( fgGetBool("/sim/rendering/skyblend") ) {
587             /* cout << "thesky->repaint() sky_color = "
588                  << cur_light_params.sky_color[0] << " "
589                  << cur_light_params.sky_color[1] << " "
590                  << cur_light_params.sky_color[2] << " "
591                  << cur_light_params.sky_color[3] << endl;
592             cout << "    fog = "
593                  << cur_light_params.fog_color[0] << " "
594                  << cur_light_params.fog_color[1] << " "
595                  << cur_light_params.fog_color[2] << " "
596                  << cur_light_params.fog_color[3] << endl;
597             cout << "    sun_angle = " << cur_light_params.sun_angle
598                  << "    moon_angle = " << cur_light_params.moon_angle
599                  << endl; */
600             thesky->repaint( cur_light_params.sky_color,
601                              cur_light_params.adj_fog_color,
602                              cur_light_params.sun_angle,
603                              cur_light_params.moon_angle,
604                              globals->get_ephem()->getNumPlanets(),
605                              globals->get_ephem()->getPlanets(),
606                              globals->get_ephem()->getNumStars(),
607                              globals->get_ephem()->getStars() );
608  
609             /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
610                  << view_pos[1] << " " << view_pos[2] << endl;
611             cout << "    zero_elev = " << zero_elev[0] << " "
612                  << zero_elev[1] << " " << zero_elev[2]
613                  << " lon = " << cur_fdm_state->get_Longitude()
614                  << " lat = " << cur_fdm_state->get_Latitude() << endl;
615             cout << "    sun_rot = " << cur_light_params.sun_rotation
616                  << " gst = " << SGTime::cur_time_params->getGst() << endl;
617             cout << "    sun ra = " << globals->get_ephem()->getSunRightAscension()
618                  << " sun dec = " << globals->get_ephem()->getSunDeclination() 
619                  << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
620                  << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
621
622             thesky->reposition( globals->get_current_view()->get_view_pos(),
623                                 globals->get_current_view()->get_zero_elev(),
624                                 globals->get_current_view()->get_world_up(),
625                                 cur_fdm_state->get_Longitude(),
626                                 cur_fdm_state->get_Latitude(),
627                                 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
628                                 cur_light_params.sun_rotation,
629                                 globals->get_time_params()->getGst(),
630                                 globals->get_ephem()->getSunRightAscension(),
631                                 globals->get_ephem()->getSunDeclination(),
632                                 50000.0,
633                                 globals->get_ephem()->getMoonRightAscension(),
634                                 globals->get_ephem()->getMoonDeclination(),
635                                 50000.0 );
636         }
637
638         glEnable( GL_DEPTH_TEST );
639         if ( fgGetString("/sim/rendering/fog") != (string)"disabled" ) {
640             glEnable( GL_FOG );
641             glFogi( GL_FOG_MODE, GL_EXP2 );
642             glFogfv( GL_FOG_COLOR, l->adj_fog_color );
643         }
644
645         // set sun/lighting parameters
646         ssgGetLight( 0 ) -> setPosition( l->sun_vec );
647
648         // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
649         // we only update GL_AMBIENT for our lights we will never get
650         // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
651         // explicitely to black.
652         GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
653         GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
654         glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
655
656         ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
657         ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
658         // ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_white );
659
660         // texture parameters
661         // glEnable( GL_TEXTURE_2D );
662         glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
663         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
664
665         // glMatrixMode( GL_PROJECTION );
666         // glLoadIdentity();
667         float fov = globals->get_current_view()->get_fov();
668         ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
669
670         double agl = current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
671             - scenery.cur_elev;
672
673         // SG_LOG( SG_ALL, SG_INFO, "visibility is " 
674         //         << current_weather.get_visibility() );
675             
676         if ( agl > 10.0 ) {
677             ssgSetNearFar( 10.0f, 120000.0f );
678         } else {
679             ssgSetNearFar( 0.5f, 120000.0f );
680         }
681
682         if ( globals->get_viewmgr()->get_current() == 0 ) {
683             // disable aircraft model
684             acmodel_selector->select(0);
685         } else { 
686             // enable aircraft model and set up its position and orientation
687             acmodel_selector->select(1);
688
689             FGViewerRPH *pilot_view =
690                 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
691
692             sgMat4 sgTRANS;
693             sgMakeTransMat4( sgTRANS, pilot_view->get_view_pos() );
694
695             sgVec3 ownship_up;
696             sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
697
698             sgMat4 sgROT;
699             sgMakeRotMat4( sgROT, -90.0, ownship_up );
700
701             // sgMat4 sgTMP;
702             // sgMat4 sgTUX;
703             // sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
704             // sgMultMat4( sgTUX, sgTMP, sgTRANS );
705
706             // sgTUX = ( sgROT * pilot_view.VIEW_ROT ) * sgTRANS
707             sgMat4 sgTUX;
708             sgCopyMat4( sgTUX, sgROT );
709             sgPostMultMat4( sgTUX, pilot_view->get_VIEW_ROT() );
710             sgPostMultMat4( sgTUX, sgTRANS );
711         
712             sgCoord tuxpos;
713             sgSetCoord( &tuxpos, sgTUX );
714             acmodel_pos->setTransform( &tuxpos );
715
716             // set up moving parts
717             if (flaps_selector != NULL) {
718               flaps_selector->select( (controls.get_flaps() > 0.5f) ? 1 : 2 );
719             }
720
721             if (prop_selector != NULL) {
722               int propsel_mask = 0;
723               double rpm = fgGetDouble("/engines/engine[0]/rpm");
724               for (int i = 0; i < acmodel_npropsettings; i++) {
725                 if (rpm >= acmodel_proprpms[i][0] &&
726                     rpm <= acmodel_proprpms[i][1]) {
727                   propsel_mask |= 1 << i;
728                 }
729               }
730               prop_selector->select(propsel_mask);
731             }
732         }
733
734         // $$$ begin - added VS Renganthan 17 Oct 2K
735         fgUpdateDCS();
736         // $$$ end - added VS Renganthan 17 Oct 2K
737
738 # ifdef FG_NETWORK_OLK
739         if ( fgGetBool("/sim/networking/network-olk") ) {
740             sgCoord fgdpos;
741             other = head->next;             /* put listpointer to start  */
742             while ( other != tail) {        /* display all except myself */
743                 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
744                     other->fgd_sel->select(1);
745                     sgSetCoord( &fgdpos, other->sgFGD_COORD );
746                     other->fgd_pos->setTransform( &fgdpos );
747                 }
748                 other = other->next;
749             }
750
751             // fgd_sel->select(1);
752             // sgCopyMat4( sgTUX, current_view.sgVIEW);
753             // sgCoord fgdpos;
754             // sgSetCoord( &fgdpos, sgFGD_VIEW );
755             // fgd_pos->setTransform( &fgdpos);
756         }
757 # endif
758
759         // position tile nodes and update range selectors
760         global_tile_mgr.prep_ssg_nodes();
761
762         if ( fgGetBool("/sim/rendering/skyblend") ) {
763             // draw the sky backdrop
764
765             // we need a white diffuse light for the phase of the moon
766             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
767
768             thesky->preDraw();
769
770             // return to the desired diffuse color
771             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
772         }
773
774         // draw the ssg scene
775         glEnable( GL_DEPTH_TEST );
776         ssgCullAndDraw( scene );
777
778         // change state for lighting here
779
780         // draw lighting
781         // Set punch through fog density
782         glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
783
784         ssgCullAndDraw( lighting );
785
786         if ( fgGetBool("/sim/rendering/skyblend") ) {
787             // draw the sky cloud layers
788             thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
789         }
790
791         // display HUD && Panel
792         glDisable( GL_FOG );
793         glDisable( GL_DEPTH_TEST );
794         // glDisable( GL_CULL_FACE );
795         // glDisable( GL_TEXTURE_2D );
796
797         // update the input subsystem
798         current_input.update();
799
800         // update the controls subsystem
801         controls.update();
802
803         hud_and_panel->apply();
804         fgCockpitUpdate();
805
806         // update the panel subsystem
807         if (current_panel != 0)
808           current_panel->update();
809
810         // We can do translucent menus, so why not. :-)
811         menus->apply();
812         glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
813         puDisplay();
814         // glDisable ( GL_BLEND ) ;
815
816         // glEnable( GL_FOG );
817     }
818
819     glutSwapBuffers();
820 }
821
822
823 // Update internal time dependent calculations (i.e. flight model)
824 void fgUpdateTimeDepCalcs() {
825     static bool inited = false;
826
827     fgLIGHT *l = &cur_light_params;
828     int i;
829
830     long multi_loop = 1;
831
832     if ( !globals->get_freeze() && !initial_freeze ) {
833         // conceptually, this could be done for each fdm instance ...
834
835         if ( !inited ) {
836             cur_fdm_state->stamp();
837             inited = true;
838         }
839
840         SGTimeStamp current;
841         current.stamp();
842         long elapsed = current - cur_fdm_state->get_time_stamp();
843         cur_fdm_state->set_time_stamp( current );
844         elapsed += cur_fdm_state->get_remainder();
845         // cout << "elapsed = " << elapsed << endl;
846         // cout << "dt = " << cur_fdm_state->get_delta_t() << endl;
847         multi_loop = (long)(((double)elapsed * 0.000001) /
848                                cur_fdm_state->get_delta_t() );
849         cur_fdm_state->set_multi_loop( multi_loop );
850         long remainder = elapsed - (long)( (multi_loop*1000000) *
851                                      cur_fdm_state->get_delta_t() );
852         cur_fdm_state->set_remainder( remainder );
853         // cout << "remainder = " << remainder << endl;
854
855         // chop max interations to something reasonable if the sim was
856         // delayed for an excesive amount of time
857         if ( multi_loop > 2.0 / cur_fdm_state->get_delta_t() ) {
858             multi_loop = (int)(2.0 / cur_fdm_state->get_delta_t());
859             cur_fdm_state->set_remainder( 0 );
860         }
861
862         // cout << "multi_loop = " << multi_loop << endl;
863         for ( i = 0; i < multi_loop * fgGetInt("/sim/speed-up"); ++i ) {
864             // run Autopilot system
865             current_autopilot->run();
866
867             // update autopilot
868             cur_fdm_state->update( 1 );
869         }
870         FGSteam::update( multi_loop * fgGetInt("/sim/speed-up") );
871     } else {
872         cur_fdm_state->update( 0 );
873         FGSteam::update( 0 );
874
875         //if ( global_tile_mgr.queue_size() == 0 ) {
876             initial_freeze = false;
877             //}
878     }
879
880     if ( fgGetString("/sim/view-mode") == "pilot" ) {
881         cur_view_fdm = *cur_fdm_state;
882         // do nothing
883     }
884
885     // update the view angle
886     FGViewer *v = globals->get_current_view();
887     for ( i = 0; i < multi_loop; i++ ) {
888         if ( fabs(v->get_goal_view_offset() - v->get_view_offset()) < 0.05 ) {
889             v->set_view_offset( v->get_goal_view_offset() );
890             break;
891         } else {
892             // move current_view.view_offset towards
893             // current_view.goal_view_offset
894             if ( v->get_goal_view_offset() > v->get_view_offset() )
895             {
896                 if ( v->get_goal_view_offset() - v->get_view_offset() < SGD_PI ){
897                     v->inc_view_offset( 0.01 );
898                 } else {
899                     v->inc_view_offset( -0.01 );
900                 }
901             } else {
902                 if ( v->get_view_offset() - v->get_goal_view_offset() < SGD_PI ){
903                     v->inc_view_offset( -0.01 );
904                 } else {
905                     v->inc_view_offset( 0.01 );
906                 }
907             }
908             if ( v->get_view_offset() > SGD_2PI ) {
909                 v->inc_view_offset( -SGD_2PI );
910             } else if ( v->get_view_offset() < 0 ) {
911                 v->inc_view_offset( SGD_2PI );
912             }
913         }
914     }
915
916     double tmp = -(l->sun_rotation + SGD_PI) 
917         - (cur_fdm_state->get_Psi() -
918            globals->get_current_view()->get_view_offset() );
919     while ( tmp < 0.0 ) {
920         tmp += SGD_2PI;
921     }
922     while ( tmp > SGD_2PI ) {
923         tmp -= SGD_2PI;
924     }
925     /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
926            FG_Psi * SGD_RADIANS_TO_DEGREES, current_view.view_offset * SGD_RADIANS_TO_DEGREES, 
927            -(l->sun_rotation+SGD_PI) * SGD_RADIANS_TO_DEGREES, tmp * SGD_RADIANS_TO_DEGREES); */
928     l->UpdateAdjFog();
929
930     // Update solar system
931     globals->get_ephem()->update( globals->get_time_params()->getMjd(),
932                                   globals->get_time_params()->getLst(),
933                                   cur_fdm_state->get_Latitude() );
934
935     // Update radio stack model
936     current_radiostack->update();
937 }
938
939
940 void fgInitTimeDepCalcs( void ) {
941     // initialize timer
942
943     // #ifdef HAVE_SETITIMER
944     //   fgTimerInit( 1.0 / fgGetInt("/sim/model-hz"), 
945     //                fgUpdateTimeDepCalcs );
946     // #endif HAVE_SETITIMER
947 }
948
949
950 static const double alt_adjust_ft = 3.758099;
951 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
952
953
954 // What should we do when we have nothing else to do?  Let's get ready
955 // for the next move and update the display?
956 static void fgMainLoop( void ) {
957     static long remainder = 0;
958     long elapsed;
959 #ifdef FANCY_FRAME_COUNTER
960     int i;
961     double accum;
962 #else
963     static time_t last_time = 0;
964     static int frames = 0;
965 #endif // FANCY_FRAME_COUNTER
966
967     SGTime *t = globals->get_time_params();
968
969     SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
970     SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
971
972 #ifdef FG_NETWORK_OLK
973     if ( fgGetBool("/sim/networking/network-olk") ) {
974         if ( net_is_registered == 0 ) {      // We first have to reg. to fgd
975             // printf("FGD: Netupdate\n");
976             fgd_send_com( "A", FGFS_host);   // Send Mat4 data
977             fgd_send_com( "B", FGFS_host);   // Recv Mat4 data
978         }
979     }
980 #endif
981
982 #if defined( ENABLE_PLIB_JOYSTICK )
983     // Read joystick and update control settings
984     // if ( fgGetString("/sim/control-mode") == "joystick" )
985     // {
986     //    fgJoystickRead();
987     // }
988 #elif defined( ENABLE_GLUT_JOYSTICK )
989     // Glut joystick support works by feeding a joystick handler
990     // function to glut.  This is taken care of once in the joystick
991     // init routine and we don't have to worry about it again.
992 #endif
993
994 #ifdef FG_OLD_WEATHER
995     current_weather.Update();
996 #endif
997
998     // Fix elevation.  I'm just sticking this here for now, it should
999     // probably move eventually
1000
1001     /* printf("Before - ground = %.2f  runway = %.2f  alt = %.2f\n",
1002            scenery.cur_elev,
1003            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1004            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1005
1006     if ( scenery.cur_elev > -9990 ) {
1007         if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER < 
1008              (scenery.cur_elev + alt_adjust_m - 3.0) ) {
1009             // now set aircraft altitude above ground
1010             printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n", 
1011                    cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
1012                    scenery.cur_elev + alt_adjust_m - 3.0,
1013                    scenery.cur_elev + alt_adjust_m );
1014             fgFDMForceAltitude( fgGetString("/sim/flight-model"), 
1015                                 scenery.cur_elev + alt_adjust_m );
1016
1017             SG_LOG( SG_ALL, SG_DEBUG, 
1018                     "<*> resetting altitude to " 
1019                     << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
1020                     << " meters" );
1021         }
1022     }
1023
1024     /* printf("Adjustment - ground = %.2f  runway = %.2f  alt = %.2f\n",
1025            scenery.cur_elev,
1026            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1027            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1028
1029     // cout << "Warp = " << globals->get_warp() << endl;
1030
1031     // update "time"
1032     if ( globals->get_warp_delta() != 0 ) {
1033         globals->inc_warp( globals->get_warp_delta() );
1034     }
1035
1036     t->update( cur_fdm_state->get_Longitude(),
1037                cur_fdm_state->get_Latitude(),
1038                globals->get_warp() );
1039
1040     if ( globals->get_warp_delta() != 0 ) {
1041         fgUpdateSkyAndLightingParams();
1042     }
1043
1044     // update magvar model
1045     globals->get_mag()->update( cur_fdm_state->get_Longitude(),
1046                                 cur_fdm_state->get_Latitude(),
1047                                 cur_fdm_state->get_Altitude()* SG_FEET_TO_METER,
1048                                 globals->get_time_params()->getJD() );
1049
1050     // Get elapsed time (in usec) for this past frame
1051     elapsed = fgGetTimeInterval();
1052     SG_LOG( SG_ALL, SG_DEBUG, 
1053             "Elapsed time interval is = " << elapsed 
1054             << ", previous remainder is = " << remainder );
1055
1056     // Calculate frame rate average
1057 #ifdef FANCY_FRAME_COUNTER
1058     /* old fps calculation */
1059     if ( elapsed > 0 ) {
1060         double tmp;
1061         accum = 0.0;
1062         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1063             tmp = general.get_frame(i);
1064             accum += tmp;
1065             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1066             general.set_frame(i+1,tmp);
1067         }
1068         tmp = 1000000.0 / (float)elapsed;
1069         general.set_frame(0,tmp);
1070         // printf("frame[0] = %.2f\n", general.frames[0]);
1071         accum += tmp;
1072         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1073         // printf("ave = %.2f\n", general.frame_rate);
1074     }
1075 #else
1076     if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1077         general.set_frame_rate( frames );
1078         SG_LOG( SG_ALL, SG_DEBUG, 
1079                 "--> Frame rate is = " << general.get_frame_rate() );
1080         frames = 0;
1081     }
1082     last_time = t->get_cur_time();
1083     ++frames;
1084 #endif
1085
1086     // Run flight model
1087
1088     // Calculate model iterations needed for next frame
1089     elapsed += remainder;
1090
1091     global_multi_loop = (long)(((double)elapsed * 0.000001) * 
1092                               fgGetInt("/sim/model-hz"));
1093     remainder = elapsed - ( (global_multi_loop*1000000) / 
1094                             fgGetInt("/sim/model-hz") );
1095     SG_LOG( SG_ALL, SG_DEBUG, 
1096             "Model iterations needed = " << global_multi_loop
1097             << ", new remainder = " << remainder );
1098         
1099     // chop max interations to something reasonable if the sim was
1100     // delayed for an excesive amount of time
1101     if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1102         global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1103         remainder = 0;
1104     }
1105
1106     // flight model
1107     if ( global_multi_loop > 0 ) {
1108         fgUpdateTimeDepCalcs();
1109     } else {
1110         SG_LOG( SG_ALL, SG_DEBUG, 
1111                 "Elapsed time is zero ... we're zinging" );
1112     }
1113
1114 #if ! defined( macintosh )
1115     // Do any I/O channel work that might need to be done
1116     fgIOProcess();
1117 #endif
1118
1119     // see if we need to load any new scenery tiles
1120     global_tile_mgr.update( cur_fdm_state->get_Longitude()
1121                             * SGD_RADIANS_TO_DEGREES,
1122                             cur_fdm_state->get_Latitude()
1123                             * SGD_RADIANS_TO_DEGREES );
1124
1125     // see if we need to load any deferred-load textures
1126     material_lib.load_next_deferred();
1127
1128     // Process/manage pending events
1129     global_events.Process();
1130
1131     // Run audio scheduler
1132 #ifdef ENABLE_AUDIO_SUPPORT
1133     if ( fgGetBool("/sim/sound") && globals->get_soundmgr()->is_working() ) {
1134         if ( fgGetString("/sim/aircraft") == "c172" ) {
1135             // pitch corresponds to rpm
1136             // volume corresponds to manifold pressure
1137
1138             // cout << "AUDIO working = "
1139             //      << globals->get_soundmgr()->is_working() << endl;
1140
1141             double rpm_factor;
1142             if ( cur_fdm_state->get_engine(0) != NULL ) {
1143                 rpm_factor = cur_fdm_state->get_engine(0)->get_RPM() / 2500.0;
1144             } else {
1145                 rpm_factor = 1.0;
1146             }
1147             // cout << "rpm = " << cur_fdm_state->get_engine(0)->get_RPM()
1148             //      << endl;
1149
1150             double pitch = 0.3 + rpm_factor * 3.0;
1151         
1152             // don't run at absurdly slow rates -- not realistic
1153             // and sounds bad to boot.  :-)
1154             if (pitch < 0.7) { pitch = 0.7; }
1155             if (pitch > 5.0) { pitch = 5.0; }
1156
1157             double mp_factor;
1158             if ( cur_fdm_state->get_engine(0) != NULL ) {
1159                 mp_factor = 
1160                     cur_fdm_state->get_engine(0)->get_Manifold_Pressure() / 100;
1161             } else {
1162                 mp_factor = 0.3;
1163             }
1164             /* cout << "mp = " 
1165                  << cur_fdm_state->get_engine(0)->get_Manifold_Pressure()
1166                  << endl; */
1167
1168             double volume = 0.15 + mp_factor / 2.0;
1169
1170             if ( volume < 0.15 ) { volume = 0.15; }
1171             if ( volume > 0.5 ) { volume = 0.5; }
1172             // cout << "volume = " << volume << endl;
1173
1174             s1->set_pitch( pitch );
1175             s1->set_volume( volume );
1176         } else {
1177             double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
1178             s1->set_pitch( param );
1179             s1->set_volume( param );
1180         }
1181
1182         globals->get_soundmgr()->update();
1183     }
1184 #endif
1185
1186     // redraw display
1187     fgRenderFrame();
1188
1189     SG_LOG( SG_ALL, SG_DEBUG, "" );
1190 }
1191
1192
1193 // This is the top level master main function that is registered as
1194 // our idle funciton
1195 //
1196
1197 // The first few passes take care of initialization things (a couple
1198 // per pass) and once everything has been initialized fgMainLoop from
1199 // then on.
1200
1201 static void fgIdleFunction ( void ) {
1202     // printf("idle state == %d\n", idle_state);
1203
1204     if ( idle_state == 0 ) {
1205         // Initialize the splash screen right away
1206         if ( fgGetBool("/sim/startup/splash-screen") ) {
1207             fgSplashInit();
1208         }
1209         
1210         idle_state++;
1211     } else if ( idle_state == 1 ) {
1212         // Initialize audio support
1213 #ifdef ENABLE_AUDIO_SUPPORT
1214
1215         // Start the intro music
1216 #if !defined(WIN32)
1217         if ( fgGetBool("/sim/startup/intro-music") ) {
1218             SGPath mp3file( globals->get_fg_root() );
1219             mp3file.append( "Sounds/intro.mp3" );
1220
1221             SG_LOG( SG_GENERAL, SG_INFO, 
1222                     "Starting intro music: " << mp3file.str() );
1223
1224             string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1225             system ( command.c_str() );
1226         }
1227 #endif // !WIN32
1228
1229         FGSoundMgr *soundmgr = new FGSoundMgr;
1230         globals->set_soundmgr( soundmgr );
1231
1232         if ( fgGetBool("/sim/sound") ) {
1233             globals->get_soundmgr()->init();
1234
1235             s1 = new FGSimpleSound( fgGetString("/sim/sounds/engine",
1236                                                 "Sounds/wasp.wav") );
1237             globals->get_soundmgr()->add( s1, "engine loop" );
1238             globals->get_soundmgr()->play_looped( "engine loop" );
1239             SG_LOG( SG_GENERAL, SG_INFO,
1240                     "Rate = " << s1->get_sample()->getRate()
1241                     << "  Bps = " << s1->get_sample()->getBps()
1242                     << "  Stereo = " << s1->get_sample()->getStereo() );
1243
1244             // s2 = new FGSimpleSound( "Sounds/corflaps.wav" );
1245             // s2->set_volume( 0.3 );
1246             // globals->get_soundmgr()->add( s2, "flaps" );
1247         }
1248 #endif
1249
1250         idle_state++;
1251     } else if ( idle_state == 2 ) {
1252         // These are a few miscellaneous things that aren't really
1253         // "subsystems" but still need to be initialized.
1254
1255 #ifdef USE_GLIDE
1256         if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1257             grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1258         }
1259 #endif
1260
1261         idle_state++;
1262     } else if ( idle_state == 3 ) {
1263         // This is the top level init routine which calls all the
1264         // other subsystem initialization routines.  If you are adding
1265         // a subsystem to flightgear, its initialization call should
1266         // located in this routine.
1267         if( !fgInitSubsystems()) {
1268             SG_LOG( SG_GENERAL, SG_ALERT,
1269                     "Subsystem initializations failed ..." );
1270             exit(-1);
1271         }
1272
1273         idle_state++;
1274     } else if ( idle_state == 4 ) {
1275         // setup OpenGL view parameters
1276         fgInitVisuals();
1277
1278         idle_state++;
1279     } else if ( idle_state == 5 ) {
1280
1281         idle_state++;
1282     } else if ( idle_state == 6 ) {
1283         // sleep(1);
1284         idle_state = 1000;
1285
1286         cout << "Panel visible = " << fgPanelVisible() << endl;
1287         fgReshape( fgGetInt("/sim/startup/xsize"),
1288                    fgGetInt("/sim/startup/ysize") );
1289     } 
1290
1291     if ( idle_state == 1000 ) {
1292         // We've finished all our initialization steps, from now on we
1293         // run the main loop.
1294
1295         fgMainLoop();
1296     } else {
1297         if ( fgGetBool("/sim/startup/splash-screen") ) {
1298             fgSplashUpdate(0.0);
1299         }
1300     }
1301 }
1302
1303 // options.cxx needs to see this for toggle_panel()
1304 // Handle new window size or exposure
1305 void fgReshape( int width, int height ) {
1306     // for all views
1307     for ( int i = 0; i < globals->get_viewmgr()->size(); ++i ) {
1308         if ( ! fgPanelVisible() || idle_state != 1000 ) {
1309             globals->get_viewmgr()->get_view(i)->
1310                 set_win_ratio( (float)height / (float)width );
1311         } else {
1312             int view_h =
1313                 int((current_panel->getViewHeight() -
1314                      current_panel->getYOffset())
1315                     * (height / 768.0)) + 1;
1316             globals->get_viewmgr()->get_view(i)->
1317                 set_win_ratio( (float)view_h / (float)width );
1318         }
1319     }
1320
1321     if ( ! fgPanelVisible() || idle_state != 1000 ) {
1322         glViewport(0, 0 , (GLint)(width), (GLint)(height) );
1323     } else {
1324         int view_h =
1325             int((current_panel->getViewHeight() - current_panel->getYOffset())
1326                 * (height / 768.0)) + 1;
1327         glViewport(0, (GLint)(height - view_h),
1328                    (GLint)(width), (GLint)(view_h) );
1329     }
1330
1331     fgSetInt("/sim/startup/xsize", width);
1332     fgSetInt("/sim/startup/ysize", height);
1333
1334     float fov = globals->get_current_view()->get_fov();
1335     ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
1336
1337     fgHUDReshape();
1338 }
1339
1340
1341 // Initialize GLUT and define a main window
1342 int fgGlutInit( int *argc, char **argv ) {
1343
1344 #if !defined( macintosh )
1345     // GLUT will extract all glut specific options so later on we only
1346     // need wory about our own.
1347     glutInit(argc, argv);
1348 #endif
1349
1350     // Define Display Parameters
1351     glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1352
1353     SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1354             fgGetInt("/sim/startup/xsize") << "x"
1355             << fgGetInt("/sim/startup/ysize") );
1356
1357     // Define initial window size
1358     glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1359                         fgGetInt("/sim/startup/ysize") );
1360
1361     // Initialize windows
1362     if ( !fgGetBool("/sim/startup/game-mode")) {
1363         // Open the regular window
1364         glutCreateWindow("FlightGear");
1365 #ifndef GLUT_WRONG_VERSION
1366     } else {
1367         // Open the cool new 'game mode' window
1368         char game_mode_str[256];
1369         sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1370                  fgGetInt("/sim/startup/xsize"),
1371                  fgGetInt("/sim/startup/ysize"),
1372                  fgGetInt("/sim/rendering/bits-per-pixel"));
1373
1374         SG_LOG( SG_GENERAL, SG_INFO, 
1375                 "game mode params = " << game_mode_str );
1376         glutGameModeString( game_mode_str );
1377         glutEnterGameMode();
1378 #endif
1379     }
1380
1381     // This seems to be the absolute earliest in the init sequence
1382     // that these calls will return valid info.  Too bad it's after
1383     // we've already created and sized out window. :-(
1384     general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1385     general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1386     general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1387     SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1388
1389     GLint tmp;
1390     glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1391     general.set_glMaxTexSize( tmp );
1392     SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1393
1394     glGetIntegerv( GL_DEPTH_BITS, &tmp );
1395     general.set_glDepthBits( tmp );
1396     SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1397
1398     return 1;
1399 }
1400
1401
1402 // Initialize GLUT event handlers
1403 int fgGlutInitEvents( void ) {
1404     // call fgReshape() on window resizes
1405     glutReshapeFunc( fgReshape );
1406
1407     // call GLUTkey() on keyboard event
1408     glutKeyboardFunc(GLUTkey);
1409     glutKeyboardUpFunc(GLUTkeyup);
1410     glutSpecialFunc(GLUTspecialkey);
1411     glutSpecialUpFunc(GLUTspecialkeyup);
1412
1413     // call guiMouseFunc() whenever our little rodent is used
1414     glutMouseFunc ( guiMouseFunc );
1415     glutMotionFunc (guiMotionFunc );
1416     glutPassiveMotionFunc (guiMotionFunc );
1417
1418     // call fgMainLoop() whenever there is
1419     // nothing else to do
1420     glutIdleFunc( fgIdleFunction );
1421
1422     // draw the scene
1423     glutDisplayFunc( fgRenderFrame );
1424
1425     return(1);
1426 }
1427
1428
1429 // Main ...
1430 int main( int argc, char **argv ) {
1431
1432 #if defined( macintosh )
1433     freopen ("stdout.txt", "w", stdout );
1434     freopen ("stderr.txt", "w", stderr );
1435     argc = ccommand( &argv );
1436 #endif
1437
1438 #ifdef HAVE_BC5PLUS
1439     _control87(MCW_EM, MCW_EM);  /* defined in float.h */
1440 #endif
1441
1442     // set default log levels
1443     sglog().setLogLevels( SG_ALL, SG_INFO );
1444
1445     string version;
1446 #ifdef FLIGHTGEAR_VERSION
1447     version = FLIGHTGEAR_VERSION;
1448 #else
1449     version = "unknown version";
1450 #endif
1451     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
1452             << version << endl );
1453
1454     // Allocate global data structures.  This needs to happen before
1455     // we parse command line options
1456
1457     globals = new FGGlobals;
1458
1459     // seed the random number generater
1460     sg_srandom_time();
1461
1462     SGRoute *route = new SGRoute;
1463     globals->set_route( route );
1464
1465     FGViewMgr *viewmgr = new FGViewMgr;
1466     globals->set_viewmgr( viewmgr );
1467
1468     FGViewerRPH *pv = new FGViewerRPH;
1469     globals->get_viewmgr()->add_view( pv );
1470
1471     FGViewerLookAt *chase = new FGViewerLookAt;
1472     globals->get_viewmgr()->add_view( chase );
1473
1474     string_list *col = new string_list;
1475     globals->set_channel_options_list( col );
1476
1477     // set current view to 0 (first) which is our main pilot view
1478     globals->set_current_view( globals->get_viewmgr()->get_view( 0 ) );
1479
1480     // Scan the config file(s) and command line options to see if
1481     // fg_root was specified (ignore all other options for now)
1482     fgInitFGRoot(argc, argv);
1483
1484     // Check for the correct base package version
1485     string base_version = fgBasePackageVersion();
1486     if ( !(base_version == "0.7.9") ) {
1487         SG_LOG( SG_GENERAL, SG_ALERT, "Base package check failed ... "
1488                 << base_version);
1489         exit(-1);
1490     }
1491
1492     // Initialize the Aircraft directory to "" (UIUC)
1493     aircraft_dir = "";
1494
1495     // Load the configuration parameters
1496     if ( !fgInitConfig(argc, argv) ) {
1497         SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1498         exit(-1);
1499     }
1500
1501     // Initialize the Window/Graphics environment.
1502     if( !fgGlutInit(&argc, argv) ) {
1503         SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1504         exit(-1);
1505     }
1506
1507     // Initialize the various GLUT Event Handlers.
1508     if( !fgGlutInitEvents() ) {
1509         SG_LOG( SG_GENERAL, SG_ALERT, 
1510                 "GLUT event handler initialization failed ..." );
1511         exit(-1);
1512     }
1513  
1514     // Initialize ssg (from plib).  Needs to come before we do any
1515     // other ssg stuff, but after opengl/glut has been initialized.
1516     ssgInit();
1517
1518     // Initialize the user interface (we need to do this before
1519     // passing off control to glut and before fgInitGeneral to get our
1520     // fonts !!!
1521     guiInit();
1522
1523 #ifdef GL_EXT_texture_lod_bias
1524     glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1525 #endif
1526
1527 #if 0
1528 #ifdef GL_EXT_texture_filter_anisotropic
1529     float max_anisotropy;
1530     glGetFloatv( GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &max_anisotropy );
1531     glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT,
1532                      max_anisotropy );
1533     cout << "Max anisotropy = " << max_anisotropy << endl;
1534 #endif
1535 #endif
1536
1537     // set current_options lon/lat if an airport id is specified
1538     // cout << "3. airport_id = " << fgGetString("/sim/startup/airport-id") << endl;
1539     if ( fgGetString("/sim/startup/airport-id").length() ) {
1540         // fgSetPosFromAirportID( fgGetString("/sim/startup/airport-id") );
1541         fgSetPosFromAirportIDandHdg( fgGetString("/sim/startup/airport-id"),
1542                                      fgGetDouble("/orientation/heading-deg") );
1543     }
1544
1545     // Initialize time
1546     SGPath zone( globals->get_fg_root() );
1547     zone.append( "Timezone" );
1548     SGTime *t = new SGTime( fgGetDouble("/position/longitude-deg") * SGD_DEGREES_TO_RADIANS,
1549                             fgGetDouble("/position/latitude-deg") * SGD_DEGREES_TO_RADIANS,
1550                             zone.str() );
1551
1552     // Handle potential user specified time offsets
1553     time_t cur_time = t->get_cur_time();
1554     time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1555     time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1556     time_t aircraftLocalTime = 
1557         sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1558
1559     // Okay, we now have six possible scenarios
1560     int offset = fgGetInt("/sim/startup/time-offset");
1561     const string &offset_type = fgGetString("/sim/startup/time-offset-type");
1562     if (offset_type == "system-offset") {
1563         globals->set_warp( offset );
1564     } else if (offset_type == "gmt-offset") {
1565         globals->set_warp( offset - (currGMT - systemLocalTime) );
1566     } else if (offset_type == "latitude-offset") {
1567         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) );
1568     } else if (offset_type == "system") {
1569         globals->set_warp( offset - cur_time );
1570     } else if (offset_type == "gmt") {
1571         globals->set_warp( offset - currGMT );
1572     } else if (offset_type == "latitude") {
1573         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) - 
1574                            cur_time ); 
1575     } else {
1576         SG_LOG( SG_GENERAL, SG_ALERT,
1577                 "Unsupported offset type " << offset_type );
1578         exit( -1 );
1579     }
1580
1581     SG_LOG( SG_GENERAL, SG_INFO, "After time init, warp = " 
1582             << globals->get_warp() );
1583
1584     globals->set_warp_delta( 0 );
1585
1586     t->update( 0.0, 0.0, globals->get_warp() );
1587
1588     globals->set_time_params( t );
1589
1590     // Do some quick general initializations
1591     if( !fgInitGeneral()) {
1592         SG_LOG( SG_GENERAL, SG_ALERT, 
1593                 "General initializations failed ..." );
1594         exit(-1);
1595     }
1596
1597     SGPath modelpath( globals->get_fg_root() );
1598     ssgModelPath( (char *)modelpath.c_str() );
1599   
1600     // Scene graph root
1601     scene = new ssgRoot;
1602     scene->setName( "Scene" );
1603
1604     lighting = new ssgRoot;
1605     lighting->setName( "Lighting" );
1606
1607     // Initialize the sky
1608     SGPath ephem_data_path( globals->get_fg_root() );
1609     ephem_data_path.append( "Astro" );
1610     SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1611     ephem->update( globals->get_time_params()->getMjd(),
1612                    globals->get_time_params()->getLst(),
1613                    0.0 );
1614     globals->set_ephem( ephem );
1615
1616     thesky = new SGSky;
1617
1618     SGPath sky_tex_path( globals->get_fg_root() );
1619     sky_tex_path.append( "Textures" );
1620     sky_tex_path.append( "Sky" );
1621     thesky->texture_path( sky_tex_path.str() );
1622
1623     thesky->build( 550.0, 550.0,
1624                    globals->get_ephem()->getNumPlanets(), 
1625                    globals->get_ephem()->getPlanets(), 60000.0,
1626                    globals->get_ephem()->getNumStars(),
1627                    globals->get_ephem()->getStars(), 60000.0 );
1628
1629     if ( fgGetBool("/environment/clouds/status") ) {
1630         // thesky->add_cloud_layer( 2000.0, 200.0, 50.0, 40000.0,
1631         //                          SG_CLOUD_OVERCAST );
1632         thesky->add_cloud_layer( 2600.0, 200.0, 50.0, 40000.0,
1633                                  SG_CLOUD_MOSTLY_CLOUDY );
1634         // thesky->add_cloud_layer( 3000.0, 200.0, 50.0, 40000.0,
1635         //                          SG_CLOUD_MOSTLY_SUNNY );
1636         thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1637                                  SG_CLOUD_CIRRUS );
1638     }
1639
1640     // Initialize MagVar model
1641     SGMagVar *magvar = new SGMagVar();
1642     globals->set_mag( magvar );
1643
1644     // Terrain branch
1645     terrain = new ssgBranch;
1646     terrain->setName( "Terrain" );
1647     scene->addKid( terrain );
1648
1649     // Lighting
1650     ground = new ssgBranch;
1651     ground->setName( "Ground Lighting" );
1652     lighting->addKid( ground );
1653
1654     airport = new ssgBranch;
1655     airport->setName( "Airport Lighting" );
1656     lighting->addKid( airport );
1657
1658     // temporary visible aircraft "own ship"
1659     acmodel_selector = new ssgSelector;
1660     acmodel_pos = new ssgTransform;
1661
1662     // Get the model location, and load textures from the same
1663     // directory.  Use an absolute path for the model to avoid
1664     // incompatibilities in different versions of PLIB.
1665     string acmodel_path =
1666         fgGetString("/sim/model/path", "Models/Geometry/glider.ac");
1667     SGPath full_model = globals->get_fg_root();
1668     full_model.append(acmodel_path);
1669
1670 #if !defined( PLIB_1_2_X )
1671     // this should be redundant ... but it breaks for relative paths
1672     // ssgModelPath( (char *)full_model.dir().c_str() );
1673 #endif
1674
1675     ssgTexturePath( (char *)full_model.dir().c_str() );
1676     ssgEntity *acmodel_obj = ssgLoad( (char *)full_model.c_str() );
1677     if( !acmodel_obj ) {
1678         // fall back to default
1679         acmodel_obj = ssgLoad( (char *)"Models/Geometry/glider.ac" );
1680         if( !acmodel_obj ) {
1681             SG_LOG( SG_GENERAL, SG_ALERT, "FAILED to LOAD an AC model! ..." );
1682             exit(-1);
1683         }
1684     }
1685
1686     // find moving parts (if this is an MDL model)
1687     flaps_selector = (ssgSelector*)fgFindNode( acmodel_obj, "FLAPS" );
1688     prop_selector  = (ssgSelector*)fgFindNode( acmodel_obj, "PROP"  );
1689
1690     acmodel_npropsettings = 0;
1691     if (prop_selector != NULL) {
1692       for (ssgEntity* kid = prop_selector->getKid(0); kid != NULL;
1693            kid = prop_selector->getNextKid()) {
1694         int prop_low, prop_high;
1695         if ( sscanf(kid->getName(), "PROP_%d_%d", 
1696                     &prop_low, &prop_high) == 2 ) {
1697           prop_low  = (int)((float)prop_low  * (5000.0f / 32767.0f));
1698           prop_high = (int)((float)prop_high * (5000.0f / 32767.0f));
1699           acmodel_proprpms[acmodel_npropsettings][0] = prop_low ;
1700           acmodel_proprpms[acmodel_npropsettings][1] = prop_high;
1701           acmodel_npropsettings++;
1702
1703           SG_LOG( SG_GENERAL, SG_INFO, "PROPELLER SETTING " << prop_low <<
1704                   " " << prop_high );
1705         }
1706       }
1707     }
1708
1709     // align the model properly for FGFS
1710     ssgTransform *acmodel_align = new ssgTransform;
1711     acmodel_align->addKid(acmodel_obj);
1712     sgMat4 rot_matrix;
1713     sgMat4 off_matrix;
1714     sgMat4 res_matrix;
1715     float h_rot = fgGetFloat("/sim/model/heading-offset-deg", 0.0);
1716     float p_rot = fgGetFloat("/sim/model/roll-offset-deg", 0.0);
1717     float r_rot = fgGetFloat("/sim/model/pitch-offset-deg", 0.0);
1718     float x_off = fgGetFloat("/sim/model/x-offset-m", 0.0);
1719     float y_off = fgGetFloat("/sim/model/y-offset-m", 0.0);
1720     float z_off = fgGetFloat("/sim/model/z-offset-m", 0.0);
1721     sgMakeRotMat4(rot_matrix, h_rot, p_rot, r_rot);
1722     sgMakeTransMat4(off_matrix, x_off, y_off, z_off);
1723     sgMultMat4(res_matrix, off_matrix, rot_matrix);
1724     acmodel_align->setTransform(res_matrix);
1725
1726     acmodel_pos->addKid( acmodel_align );
1727     acmodel_selector->addKid( acmodel_pos );
1728     //ssgFlatten( acmodel_obj );
1729     //ssgStripify( acmodel_selector );
1730     acmodel_selector->clrTraversalMaskBits( SSGTRAV_HOT );
1731     scene->addKid( acmodel_selector );
1732
1733     // $$$ begin - added VS Renganthan 17 Oct 2K
1734     fgLoadDCS();
1735     // $$$ end - added VS Renganthan 17 Oct 2K
1736
1737 #ifdef FG_NETWORK_OLK
1738     // Do the network intialization
1739     if ( fgGetBool("/sim/networking/network-olk") ) {
1740         printf("Multipilot mode %s\n", fg_net_init( scene ) );
1741     }
1742 #endif
1743
1744     // build our custom render states
1745     fgBuildRenderStates();
1746
1747     // pass control off to the master GLUT event handler
1748     glutMainLoop();
1749
1750     // we never actually get here ... but to avoid compiler warnings,
1751     // etc.
1752     return 0;
1753 }
1754
1755
1756 // $$$ end - added VS Renganathan, 15 Oct 2K
1757 //         - added Venky         , 12 Nov 2K
1758
1759 void fgLoadDCS(void) {
1760
1761     ssgEntity *ship_obj = NULL;
1762     // double bz[3];
1763     // int j=0;
1764     char obj_filename[25];
1765
1766     for ( int k = 0; k < 32; k++ ) {
1767         ship_pos[k]=NULL;
1768     }
1769
1770     SGPath tile_path( globals->get_fg_root());
1771     tile_path.append( "Scenery" );
1772     tile_path.append( "Objects.txt" );
1773     sg_gzifstream in( tile_path.str() );
1774     if ( ! in.is_open() ) {
1775         SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1776     } else {
1777
1778         SGPath modelpath( globals->get_fg_root() );
1779         modelpath.append( "Models" );
1780         modelpath.append( "Geometry" );
1781   
1782         SGPath texturepath( globals->get_fg_root() );
1783         texturepath.append( "Models" );
1784         texturepath.append( "Textures" );
1785  
1786         ssgModelPath( (char *)modelpath.c_str() );
1787         ssgTexturePath( (char *)texturepath.c_str() );
1788
1789         ship_sel = new ssgSelector;
1790
1791         char c;
1792         while ( ! in.eof() ) {
1793             in >> ::skipws;
1794             if ( in.get( c ) && c == '#' ) { 
1795                 in >> skipeol;
1796             } else { 
1797                 in.putback(c);
1798                 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1799                 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] <<  " " << obj_alt[objc] << endl;
1800                    int chj=getchar();*/
1801                 
1802                 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1803                 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1804                 
1805                 ship_pos[objc] = new ssgTransform;
1806        
1807                 // type "repeat" in objects.txt to load one more
1808                 // instance of the last object.
1809
1810                 if ( strcmp(obj_filename,"repeat") != 0) {
1811                     ship_obj = ssgLoadOBJ( obj_filename );
1812                 }
1813       
1814                 if ( ship_obj != NULL ) {
1815                     ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1816                     ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1817                 } else {
1818                     SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1819                             << obj_filename );
1820                 }
1821             
1822                 objc++;
1823
1824                 if (in.eof()) break;
1825             }
1826         } // while
1827
1828         SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
1829
1830         ship_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1831         scene->addKid( ship_sel ); //add selector node to root node 
1832     }
1833
1834     return;
1835  }
1836
1837
1838 void fgUpdateDCS (void) {
1839
1840     // double eye_lat,eye_lon,eye_alt;
1841     // static double obj_head;
1842     double sl_radius,obj_latgc;
1843     // float nresultmat[4][4];
1844     // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1845     double bz[3];
1846
1847     // Instantaneous Geodetic Lat/Lon/Alt of moving object
1848     FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1849     
1850     // Deck should be the first object in objects.txt in case of fdm=ada
1851
1852     if (fgGetString("/sim/flight-model") == "ada") {
1853         obj_lon[0] = fdm->get_aux5()*SGD_DEGREES_TO_RADIANS;
1854         obj_lat[0] = fdm->get_aux6()*SGD_DEGREES_TO_RADIANS;
1855         obj_alt[0] = fdm->get_aux7();
1856     }
1857     
1858     for ( int m = 0; m < objc; m++ ) {
1859         //cout << endl <<  obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
1860         //int v=getchar();
1861
1862         //Geodetic to Geocentric angles for rotation
1863         sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
1864
1865         //moving object gbs-posn in cartesian coords
1866         Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
1867         Point3D obj_pos = sgGeodToCart( obj_posn );
1868
1869         // Translate moving object w.r.t eye
1870         Point3D Objtrans = obj_pos-scenery.center;
1871         bz[0]=Objtrans.x();
1872         bz[1]=Objtrans.y();
1873         bz[2]=Objtrans.z();
1874
1875        // rotate dynamic objects for lat,lon & alt and other motion about its axes
1876         
1877         sgMat4 sgTRANS;
1878         sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1879
1880         sgVec3 ship_fwd,ship_rt,ship_up;
1881         sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1882         sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1883         sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1884
1885         sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg;
1886         sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
1887         sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
1888         sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1889         
1890         sgMat4 sgTUX;
1891         sgCopyMat4( sgTUX, sgROT_hdg );
1892         sgPostMultMat4( sgTUX, sgROT_lat );
1893         sgPostMultMat4( sgTUX, sgROT_lon );
1894         sgPostMultMat4( sgTUX, sgTRANS );
1895
1896         sgCoord shippos;
1897         sgSetCoord(&shippos, sgTUX );
1898         ship_pos[m]->setTransform( &shippos );
1899     }
1900     if ( ship_sel != NULL ) {
1901         ship_sel->select(0xFFFFFFFF);
1902     }
1903 }
1904
1905 // $$$ end - added VS Renganathan, 15 Oct 2K
1906 //           added Venky         , 12 Nov 2K