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