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