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