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