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