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