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