]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
59e8085bb2c311dd92c7ae8c8ea5c9a27e79e908
[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 #define MICHAEL_JOHNSON_EXPERIMENTAL_ENGINE_AUDIO
25
26
27 #ifdef HAVE_CONFIG_H
28 #  include <config.h>
29 #endif
30
31 #ifdef FG_MATH_EXCEPTION_CLASH
32 #  include <math.h>
33 #endif
34
35 #ifdef HAVE_WINDOWS_H
36 #  include <windows.h>                     
37 #  include <float.h>                    
38 #endif
39
40 #include <GL/glut.h>
41 #include <simgear/xgl/xgl.h>
42
43 #include <stdio.h>
44 #include <string.h>
45 #include <string>
46
47 #ifdef HAVE_STDLIB_H
48 #   include <stdlib.h>
49 #endif
50
51 #ifdef HAVE_SYS_STAT_H
52 #  include <sys/stat.h> /* for stat() */
53 #endif
54
55 #ifdef HAVE_UNISTD_H
56 #  include <unistd.h>    /* for stat() */
57 #endif
58
59 #include <plib/pu.h>                    // plib include
60 #include <plib/ssg.h>           // plib include
61
62 #ifdef ENABLE_AUDIO_SUPPORT
63 #  include <plib/sl.h>          // plib include
64 #  include <plib/sm.h>          // plib include
65 #endif
66
67 #include <simgear/constants.h>  // for VERSION
68 #include <simgear/debug/logstream.hxx>
69 #include <simgear/math/fg_geodesy.hxx>
70 #include <simgear/math/polar3d.hxx>
71 #include <simgear/math/fg_random.h>
72 #include <simgear/misc/fgpath.hxx>
73
74 #include <Include/general.hxx>
75
76 #include <Aircraft/aircraft.hxx>
77 #include <Ephemeris/ephemeris.hxx>
78
79 #include <Autopilot/newauto.hxx>
80 #include <Cockpit/cockpit.hxx>
81 #include <Cockpit/radiostack.hxx>
82 #include <Cockpit/steam.hxx>
83
84 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
85 #include <GUI/gui.h>
86 #include <Joystick/joystick.hxx>
87 #ifdef FG_NETWORK_OLK
88 #include <NetworkOLK/network.h>
89 #endif
90 #include <Objects/materialmgr.hxx>
91 #include <Scenery/scenery.hxx>
92 #include <Scenery/tilemgr.hxx>
93 #include <Sky/sky.hxx>
94 #include <Time/event.hxx>
95 #include <Time/fg_time.hxx>
96 #include <Time/fg_timer.hxx>
97 #include <Time/sunpos.hxx>
98
99 #ifndef FG_OLD_WEATHER
100 #  include <WeatherCM/FGLocalWeatherDatabase.h>
101 #else
102 #  include <Weather/weather.hxx>
103 #endif
104
105 #include "bfi.hxx"
106 #include "fg_init.hxx"
107 #include "fg_io.hxx"
108 #include "keyboard.hxx"
109 #include "options.hxx"
110 #include "splash.hxx"
111 #include "views.hxx"
112
113
114 // -dw- use custom sioux settings so I can see output window
115 #ifdef MACOS
116 #  ifndef FG_NDEBUG
117 #    include <sioux.h> // settings for output window
118 #  endif
119 #  include <console.h>
120 #endif
121
122
123 // This is a record containing a bit of global housekeeping information
124 FGGeneral general;
125
126 // Specify our current idle function state.  This is used to run all
127 // our initializations out of the glutIdleLoop() so that we can get a
128 // splash screen up and running right away.
129 static int idle_state = 0;
130 static int global_multi_loop;
131
132 // Another hack
133 int use_signals = 0;
134
135 // Global structures for the Audio library
136 #ifdef ENABLE_AUDIO_SUPPORT
137 slEnvelope pitch_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
138 slEnvelope volume_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
139 slScheduler *audio_sched;
140 smMixer *audio_mixer;
141 slSample *s1;
142 slSample *s2;
143 #endif
144
145
146 // ssg variables
147 ssgRoot *scene = NULL;
148 ssgBranch *terrain = NULL;
149 ssgSelector *penguin_sel = NULL;
150 ssgTransform *penguin_pos = NULL;
151
152 #ifdef FG_NETWORK_OLK
153 ssgSelector *fgd_sel = NULL;
154 ssgTransform *fgd_pos = NULL;
155 //sgMat4 sgTUX;
156 #endif
157
158 // current fdm/position used for view
159 FGInterface cur_view_fdm;
160
161 // Sky structures
162 FGEphemeris *ephem;
163 SGSky *thesky;
164
165 // hack
166 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
167 {
168   {  1.0f,  0.0f,  0.0f,  0.0f },
169   {  0.0f,  0.0f, -1.0f,  0.0f },
170   {  0.0f,  1.0f,  0.0f,  0.0f },
171   {  0.0f,  0.0f,  0.0f,  1.0f }
172 } ;
173
174 // The following defines flight gear options. Because glutlib will also
175 // want to parse its own options, those options must not be included here
176 // or they will get parsed by the main program option parser. Hence case
177 // is significant for any option added that might be in conflict with
178 // glutlib's parser.
179 //
180 // glutlib parses for:
181 //    -display
182 //    -direct   (invalid in Win32)
183 //    -geometry
184 //    -gldebug
185 //    -iconized
186 //    -indirect (invalid in Win32)
187 //    -synce
188 //
189 // Note that glutlib depends upon strings while this program's
190 // option parser wants only initial characters followed by numbers
191 // or pathnames.
192 //
193
194
195 ssgSimpleState *default_state;
196 ssgSimpleState *hud_and_panel;
197 ssgSimpleState *menus;
198
199 void fgBuildRenderStates( void ) {
200     default_state = new ssgSimpleState;
201     default_state->disable( GL_TEXTURE_2D );
202     default_state->enable( GL_CULL_FACE );
203     default_state->disable( GL_COLOR_MATERIAL );
204     default_state->disable( GL_BLEND );
205     default_state->disable( GL_ALPHA_TEST );
206     default_state->disable( GL_LIGHTING );
207     default_state->setMaterial( GL_AMBIENT_AND_DIFFUSE, 1.0, 1.0, 1.0, 1.0 );
208
209     hud_and_panel = new ssgSimpleState;
210     hud_and_panel->disable( GL_CULL_FACE );
211     hud_and_panel->disable( GL_TEXTURE_2D );
212     hud_and_panel->disable( GL_LIGHTING );
213     hud_and_panel->enable( GL_BLEND );
214
215     menus = new ssgSimpleState;
216     menus->disable( GL_CULL_FACE );
217     menus->disable( GL_TEXTURE_2D );
218     menus->enable( GL_BLEND );
219 }
220
221
222 // fgInitVisuals() -- Initialize various GL/view parameters
223 void fgInitVisuals( void ) {
224     fgLIGHT *l;
225
226     l = &cur_light_params;
227
228 #ifndef GLUT_WRONG_VERSION
229     // Go full screen if requested ...
230     if ( current_options.get_fullscreen() ) {
231         glutFullScreen();
232     }
233 #endif
234
235     // If enabled, normal vectors specified with glNormal are scaled
236     // to unit length after transformation.  See glNormal.
237     // glEnable( GL_NORMALIZE );
238
239     glEnable( GL_LIGHTING );
240     glEnable( GL_LIGHT0 );
241     glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
242
243     sgVec3 sunpos;
244     sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
245     ssgGetLight( 0 ) -> setPosition( sunpos );
246
247     // glFogi (GL_FOG_MODE, GL_LINEAR);
248     glFogi (GL_FOG_MODE, GL_EXP2);
249     if ( (current_options.get_fog() == 1) || 
250          (current_options.get_shading() == 0) ) {
251         // if fastest fog requested, or if flat shading force fastest
252         glHint ( GL_FOG_HINT, GL_FASTEST );
253     } else if ( current_options.get_fog() == 2 ) {
254         glHint ( GL_FOG_HINT, GL_NICEST );
255     }
256     if ( current_options.get_wireframe() ) {
257         // draw wire frame
258         glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
259     }
260
261     // This is the default anyways, but it can't hurt
262     glFrontFace ( GL_CCW );
263
264     // Just testing ...
265     // glEnable(GL_POINT_SMOOTH);
266     // glEnable(GL_LINE_SMOOTH);
267     // glEnable(GL_POLYGON_SMOOTH);      
268 }
269
270
271 // Update all Visuals (redraws anything graphics related)
272 void fgRenderFrame( void ) {
273     // Update the BFI.
274     FGBFI::update();
275
276     fgLIGHT *l = &cur_light_params;
277     FGTime *t = FGTime::cur_time_params;
278     // FGView *v = &current_view;
279     static double last_visibility = -9999;
280     static bool in_puff = false;
281     static double puff_length = 0;
282     static double puff_progression = 0;
283     const double ramp_up = 0.15;
284     const double ramp_down = 0.15;
285
286     double angle;
287     // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
288     // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
289     // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
290     // GLfloat mat_shininess[] = { 10.0 };
291     GLbitfield clear_mask;
292     
293     if ( idle_state != 1000 ) {
294         // still initializing, draw the splash screen
295         if ( current_options.get_splash_screen() == 1 ) {
296             fgSplashUpdate(0.0);
297         }
298     } else {
299         // idle_state is now 1000 meaning we've finished all our
300         // initializations and are running the main loop, so this will
301         // now work without seg faulting the system.
302
303         // printf("Ground = %.2f  Altitude = %.2f\n", scenery.cur_elev, 
304         //        FG_Altitude * FEET_TO_METER);
305     
306         // this is just a temporary hack, to make me understand Pui
307         // timerText -> setLabel (ctime (&t->cur_time));
308         // end of hack
309
310         // update view volume parameters
311         // cout << "before pilot_view update" << endl;
312         pilot_view.UpdateViewParams(*cur_fdm_state);
313         // cout << "after pilot_view update" << endl;
314         current_view.UpdateViewParams(cur_view_fdm);
315
316         // set the sun position
317         glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
318
319         clear_mask = GL_DEPTH_BUFFER_BIT;
320         if ( current_options.get_wireframe() ) {
321             clear_mask |= GL_COLOR_BUFFER_BIT;
322         }
323         if ( current_options.get_panel_status() ) {
324             // we can't clear the screen when the panel is active
325         } else if ( current_options.get_skyblend() ) {
326             if ( current_options.get_textures() ) {
327                 // glClearColor(black[0], black[1], black[2], black[3]);
328                 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1], 
329                              l->adj_fog_color[2], l->adj_fog_color[3]);
330                 clear_mask |= GL_COLOR_BUFFER_BIT;
331             }
332         } else {
333             glClearColor(l->sky_color[0], l->sky_color[1], 
334                          l->sky_color[2], l->sky_color[3]);
335             clear_mask |= GL_COLOR_BUFFER_BIT;
336         }
337         glClear( clear_mask );
338
339         // Tell GL we are switching to model view parameters
340
341         // I really should create a derived ssg node or use a call
342         // back or something so that I can draw the sky within the
343         // ssgCullandDraw() function, but for now I just mimic what
344         // ssg does to set up the model view matrix
345         glMatrixMode(GL_MODELVIEW);
346         glLoadIdentity();
347         ssgSetCamera( current_view.VIEW );
348
349         /*
350         sgMat4 vm_tmp, view_mat;
351         sgTransposeNegateMat4 ( vm_tmp, current_view.VIEW ) ;
352         sgCopyMat4( view_mat, copy_of_ssgOpenGLAxisSwapMatrix ) ;
353         sgPreMultMat4( view_mat, vm_tmp ) ;
354         glLoadMatrixf( (float *)view_mat );
355         */
356
357         // set the opengl state to known default values
358         default_state->force();
359
360         // draw sky dome
361         if ( current_options.get_skyblend() ) {
362             sgVec3 view_pos;
363             sgSetVec3( view_pos,
364                        current_view.get_view_pos().x(),
365                        current_view.get_view_pos().y(),
366                        current_view.get_view_pos().z() );
367
368             sgVec3 zero_elev;
369             sgSetVec3( zero_elev,
370                        current_view.get_cur_zero_elev().x(),
371                        current_view.get_cur_zero_elev().y(),
372                        current_view.get_cur_zero_elev().z() );
373
374             /* cout << "thesky->repaint() sky_color = "
375                  << cur_light_params.sky_color[0] << " "
376                  << cur_light_params.sky_color[1] << " "
377                  << cur_light_params.sky_color[2] << " "
378                  << cur_light_params.sky_color[3] << endl;
379             cout << "    fog = "
380                  << cur_light_params.fog_color[0] << " "
381                  << cur_light_params.fog_color[1] << " "
382                  << cur_light_params.fog_color[2] << " "
383                  << cur_light_params.fog_color[3] << endl;
384             cout << "    sun_angle = " << cur_light_params.sun_angle
385                  << "    moon_angle = " << cur_light_params.moon_angle
386                  << endl; */
387             thesky->repaint( cur_light_params.sky_color,
388                              cur_light_params.adj_fog_color,
389                              cur_light_params.sun_angle,
390                              cur_light_params.moon_angle,
391                              ephem->getNumPlanets(), ephem->getPlanets(),
392                              ephem->getNumStars(), ephem->getStars() );
393  
394             /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
395                  << view_pos[1] << " " << view_pos[2] << endl;
396             cout << "    zero_elev = " << zero_elev[0] << " "
397                  << zero_elev[1] << " " << zero_elev[2]
398                  << " lon = " << cur_fdm_state->get_Longitude()
399                  << " lat = " << cur_fdm_state->get_Latitude() << endl;
400             cout << "    sun_rot = " << cur_light_params.sun_rotation
401                  << " gst = " << FGTime::cur_time_params->getGst() << endl;
402             cout << "    sun ra = " << ephem->getSunRightAscension()
403                  << " sun dec = " << ephem->getSunDeclination() 
404                  << " moon ra = " << ephem->getMoonRightAscension()
405                  << " moon dec = " << ephem->getMoonDeclination() << endl; */
406
407             thesky->reposition( view_pos, zero_elev, 
408                                 cur_fdm_state->get_Longitude(),
409                                 cur_fdm_state->get_Latitude(),
410                                 cur_light_params.sun_rotation,
411                                 FGTime::cur_time_params->getGst(),
412                                 ephem->getSunRightAscension(),
413                                 ephem->getSunDeclination(), 50000.0,
414                                 ephem->getMoonRightAscension(),
415                                 ephem->getMoonDeclination(), 50000.0 );
416         }
417
418         glEnable( GL_DEPTH_TEST );
419         if ( current_options.get_fog() > 0 ) {
420             glEnable( GL_FOG );
421             glFogi( GL_FOG_MODE, GL_EXP2 );
422             glFogfv( GL_FOG_COLOR, l->adj_fog_color );
423         }
424
425         // update fog params if visibility has changed
426 #ifndef FG_OLD_WEATHER
427         double cur_visibility = WeatherDatabase->getWeatherVisibility();
428 #else
429         double cur_visibility = current_weather.get_visibility();
430 #endif
431         double actual_visibility = cur_visibility;
432
433         if ( current_options.get_clouds() ) {
434             double diff = fabs( cur_fdm_state->get_Altitude() * FEET_TO_METER -
435                                 current_options.get_clouds_asl() );
436             // cout << "altitude diff = " << diff << endl;
437             if ( diff < 75 ) {
438                 if ( ! in_puff ) {
439                     // calc chance of entering cloud puff
440                     double rnd = fg_random();
441                     double chance = rnd * rnd * rnd;
442                     if ( chance > 0.95 /* * (diff - 25) / 50.0 */ ) {
443                         in_puff = true;
444                         do {
445                             puff_length = fg_random() * 2.0; // up to 2 seconds
446                         } while ( puff_length <= 0.0 );
447                         puff_progression = 0.0;
448                     }
449                 }
450
451                 actual_visibility = cur_visibility * (diff - 25) / 50.0;
452
453                 if ( in_puff ) {
454                     // modify actual_visibility based on puff envelope
455
456                     if ( puff_progression <= ramp_up ) {
457                         double x = FG_PI_2 * puff_progression / ramp_up;
458                         double factor = 1.0 - sin( x );
459                         actual_visibility = actual_visibility * factor;
460                     } else if ( puff_progression >= ramp_up + puff_length ) {
461                         double x = FG_PI_2 * 
462                             (puff_progression - (ramp_up + puff_length)) /
463                             ramp_down;
464                         double factor = sin( x );
465                         actual_visibility = actual_visibility * factor;
466                     } else {
467                         actual_visibility = 0.0;
468                     }
469
470                     /* cout << "len = " << puff_length
471                          << "  x = " << x 
472                          << "  factor = " << factor
473                          << "  actual_visibility = " << actual_visibility 
474                          << endl; */
475
476                     puff_progression += ( global_multi_loop * 
477                                           current_options.get_speed_up() ) /
478                         (double)current_options.get_model_hz();
479
480                     /* cout << "gml = " << global_multi_loop 
481                          << "  speed up = " << current_options.get_speed_up()
482                          << "  hz = " << current_options.get_model_hz() << endl;
483                          */ 
484
485                     if ( puff_progression > puff_length + ramp_up + ramp_down) {
486                         in_puff = false; 
487                     }
488                 }
489
490                 // never let visibility drop below zero
491                 if ( actual_visibility < 0 ) {
492                     actual_visibility = 0;
493                 }
494             }
495         }
496
497         // cout << "actual visibility = " << actual_visibility << endl;
498
499         if ( actual_visibility != last_visibility ) {
500             last_visibility = actual_visibility;
501
502             // cout << "----> updating fog params" << endl;
503                 
504             GLfloat fog_exp_density;
505             GLfloat fog_exp2_density;
506     
507             // for GL_FOG_EXP
508             fog_exp_density = -log(0.01 / actual_visibility);
509     
510             // for GL_FOG_EXP2
511             fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
512     
513             // Set correct opengl fog density
514             glFogf (GL_FOG_DENSITY, fog_exp2_density);
515         }
516  
517         // set lighting parameters
518         glLightfv( GL_LIGHT0, GL_AMBIENT, l->scene_ambient );
519         glLightfv( GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
520         // glLightfv(GL_LIGHT0, GL_SPECULAR, white );
521
522         // texture parameters
523         // glEnable( GL_TEXTURE_2D );
524         glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
525         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
526         // set base color (I don't think this is doing anything here)
527         // glMaterialfv (GL_FRONT, GL_AMBIENT, white);
528         //  (GL_FRONT, GL_DIFFUSE, white);
529         // glMaterialfv (GL_FRONT, GL_SPECULAR, white);
530         // glMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
531
532         sgVec3 sunpos;
533         sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
534         ssgGetLight( 0 ) -> setPosition( sunpos );
535
536         // glMatrixMode( GL_PROJECTION );
537         // glLoadIdentity();
538         float fov = current_options.get_fov();
539         ssgSetFOV(fov * current_view.get_win_ratio(), fov);
540
541         double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
542             - scenery.cur_elev;
543
544         // FG_LOG( FG_ALL, FG_INFO, "visibility is " 
545         //         << current_weather.get_visibility() );
546             
547         if ( agl > 10.0 ) {
548             ssgSetNearFar( 10.0f, 120000.0f );
549         } else {
550             ssgSetNearFar( 0.5f, 120000.0f );
551         }
552
553         if ( current_options.get_view_mode() == 
554              fgOPTIONS::FG_VIEW_PILOT )
555         {
556             // disable TuX
557             penguin_sel->select(0);
558         } else if ( current_options.get_view_mode() == 
559                     fgOPTIONS::FG_VIEW_FOLLOW )
560         {
561             // select view matrix from front of view matrix queue
562             // FGMat4Wrapper tmp = current_view.follow.front();
563             // sgCopyMat4( sgVIEW, tmp.m );
564
565             // enable TuX and set up his position and orientation
566             penguin_sel->select(1);
567
568             sgMat4 sgTRANS;
569             sgMakeTransMat4( sgTRANS, 
570                              pilot_view.view_pos.x(),
571                              pilot_view.view_pos.y(),
572                              pilot_view.view_pos.z() );
573
574             sgVec3 ownship_up;
575             sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
576
577             sgMat4 sgROT;
578             sgMakeRotMat4( sgROT, -90.0, ownship_up );
579
580             // sgMat4 sgTMP;
581             // sgMat4 sgTUX;
582             // sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
583             // sgMultMat4( sgTUX, sgTMP, sgTRANS );
584
585             // sgTUX = ( sgROT * pilot_view.VIEW_ROT ) * sgTRANS
586             sgMat4 sgTUX;
587             sgCopyMat4( sgTUX, sgROT );
588             sgPostMultMat4( sgTUX, pilot_view.VIEW_ROT );
589             sgPostMultMat4( sgTUX, sgTRANS );
590         
591             sgCoord tuxpos;
592             sgSetCoord( &tuxpos, sgTUX );
593             penguin_pos->setTransform( &tuxpos );
594         }
595
596 # ifdef FG_NETWORK_OLK
597         if ( current_options.get_network_olk() ) {
598             sgCoord fgdpos;
599             other = head->next;             /* put listpointer to start  */
600             while ( other != tail) {        /* display all except myself */
601                 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
602                     other->fgd_sel->select(1);
603                     sgSetCoord( &fgdpos, other->sgFGD_COORD );
604                     other->fgd_pos->setTransform( &fgdpos );
605                 }
606                 other = other->next;
607             }
608
609             // fgd_sel->select(1);
610             // sgCopyMat4( sgTUX, current_view.sgVIEW);
611             // sgCoord fgdpos;
612             // sgSetCoord( &fgdpos, sgFGD_VIEW );
613             // fgd_pos->setTransform( &fgdpos);
614         }
615 # endif
616
617         // ssgSetCamera( current_view.VIEW );
618
619         // position tile nodes and update range selectors
620         global_tile_mgr.prep_ssg_nodes();
621
622         // force the default state so ssg can get back on track if
623         // we've changed things elsewhere
624         FGMaterialSlot m_slot;
625         FGMaterialSlot *m_ptr = &m_slot;
626         if ( material_mgr.find( "Default", m_ptr ) ) {
627             m_ptr->get_state()->force();
628         }
629
630         // draw the ssg scene
631         ssgCullAndDraw( scene );
632
633
634         // display HUD && Panel
635         glDisable( GL_FOG );
636         glDisable( GL_DEPTH_TEST );
637         // glDisable( GL_CULL_FACE );
638         // glDisable( GL_TEXTURE_2D );
639         hud_and_panel->apply();
640         fgCockpitUpdate();
641
642         // We can do translucent menus, so why not. :-)
643         // glEnable ( GL_BLEND ) ;
644         menus->apply();
645         glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
646         puDisplay();
647         // glDisable ( GL_BLEND ) ;
648
649         // glEnable( GL_FOG );
650     }
651
652     glutSwapBuffers();
653 }
654
655
656 // Update internal time dependent calculations (i.e. flight model)
657 void fgUpdateTimeDepCalcs(int multi_loop, int remainder) {
658     static fdm_state_list fdm_list;
659     // FGInterface fdm_state;
660     fgLIGHT *l = &cur_light_params;
661     FGTime *t = FGTime::cur_time_params;
662     // FGView *v = &current_view;
663     int i;
664
665     // update the flight model
666     if ( multi_loop < 0 ) {
667         multi_loop = 1;
668     }
669
670     if ( !t->getPause() ) {
671         // run Autopilot system
672         current_autopilot->run();
673
674         // printf("updating flight model x %d\n", multi_loop);
675         /* fgFDMUpdate( current_options.get_flight_model(), 
676                      fdm_state, 
677                      multi_loop * current_options.get_speed_up(),
678                      remainder ); */
679         cur_fdm_state->update( multi_loop * current_options.get_speed_up() );
680         FGSteam::update( multi_loop * current_options.get_speed_up() );
681     } else {
682         // fgFDMUpdate( current_options.get_flight_model(), 
683         //              fdm_state, 0, remainder );
684         cur_fdm_state->update( 0 );
685         FGSteam::update( 0 );
686     }
687
688     fdm_list.push_back( *cur_fdm_state );
689     while ( fdm_list.size() > 15 ) {
690         fdm_list.pop_front();
691     }
692
693     if ( current_options.get_view_mode() == fgOPTIONS::FG_VIEW_PILOT ) {
694         cur_view_fdm = *cur_fdm_state;
695         // do nothing
696     } else if ( current_options.get_view_mode() == fgOPTIONS::FG_VIEW_FOLLOW ) {
697         cur_view_fdm = fdm_list.front();
698     }
699
700     // update the view angle
701     for ( i = 0; i < multi_loop; i++ ) {
702         if ( fabs(current_view.get_goal_view_offset() - 
703                   current_view.get_view_offset()) < 0.05 )
704         {
705             current_view.set_view_offset( current_view.get_goal_view_offset() );
706             break;
707         } else {
708             // move current_view.view_offset towards current_view.goal_view_offset
709             if ( current_view.get_goal_view_offset() > 
710                  current_view.get_view_offset() )
711             {
712                 if ( current_view.get_goal_view_offset() - 
713                      current_view.get_view_offset() < FG_PI )
714                 {
715                     current_view.inc_view_offset( 0.01 );
716                 } else {
717                     current_view.inc_view_offset( -0.01 );
718                 }
719             } else {
720                 if ( current_view.get_view_offset() - 
721                      current_view.get_goal_view_offset() < FG_PI )
722                 {
723                     current_view.inc_view_offset( -0.01 );
724                 } else {
725                     current_view.inc_view_offset( 0.01 );
726                 }
727             }
728             if ( current_view.get_view_offset() > FG_2PI ) {
729                 current_view.inc_view_offset( -FG_2PI );
730             } else if ( current_view.get_view_offset() < 0 ) {
731                 current_view.inc_view_offset( FG_2PI );
732             }
733         }
734     }
735
736     double tmp = -(l->sun_rotation + FG_PI) 
737         - (cur_fdm_state->get_Psi() - current_view.get_view_offset() );
738     while ( tmp < 0.0 ) {
739         tmp += FG_2PI;
740     }
741     while ( tmp > FG_2PI ) {
742         tmp -= FG_2PI;
743     }
744     /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
745            FG_Psi * RAD_TO_DEG, current_view.view_offset * RAD_TO_DEG, 
746            -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
747     l->UpdateAdjFog();
748
749     // Update solar system
750     ephem->update( t, cur_fdm_state->get_Latitude() );
751
752     // Update radio stack model
753     current_radiostack->update( cur_fdm_state->get_Longitude(),
754                                 cur_fdm_state->get_Latitude(),
755                                 cur_fdm_state->get_Altitude() * FEET_TO_METER );
756 }
757
758
759 void fgInitTimeDepCalcs( void ) {
760     // initialize timer
761
762     // #ifdef HAVE_SETITIMER
763     //   fgTimerInit( 1.0 / current_options.get_model_hz(), 
764     //                fgUpdateTimeDepCalcs );
765     // #endif HAVE_SETITIMER
766 }
767
768
769 static const double alt_adjust_ft = 3.758099;
770 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
771
772
773 // What should we do when we have nothing else to do?  Let's get ready
774 // for the next move and update the display?
775 static void fgMainLoop( void ) {
776     FGTime *t;
777     static long remainder = 0;
778     long elapsed;
779 #ifdef FANCY_FRAME_COUNTER
780     int i;
781     double accum;
782 #else
783     static time_t last_time = 0;
784     static int frames = 0;
785 #endif // FANCY_FRAME_COUNTER
786
787     t = FGTime::cur_time_params;
788
789     FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
790     FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
791
792 #ifdef FG_NETWORK_OLK
793     if ( current_options.get_network_olk() ) {
794         if ( net_is_registered == 0 ) {      // We first have to reg. to fgd
795             // printf("FGD: Netupdate\n");
796             fgd_send_com( "A", FGFS_host);   // Send Mat4 data
797             fgd_send_com( "B", FGFS_host);   // Recv Mat4 data
798         }
799     }
800 #endif
801
802 #if defined( ENABLE_PLIB_JOYSTICK )
803     // Read joystick and update control settings
804     if ( current_options.get_control_mode() == fgOPTIONS::FG_JOYSTICK ) {
805         fgJoystickRead();
806     }
807 #elif defined( ENABLE_GLUT_JOYSTICK )
808     // Glut joystick support works by feeding a joystick handler
809     // function to glut.  This is taken care of once in the joystick
810     // init routine and we don't have to worry about it again.
811 #endif
812
813 #ifdef FG_OLD_WEATHER
814     current_weather.Update();
815 #endif
816
817     // Fix elevation.  I'm just sticking this here for now, it should
818     // probably move eventually
819
820     /* printf("Before - ground = %.2f  runway = %.2f  alt = %.2f\n",
821            scenery.cur_elev,
822            cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
823            cur_fdm_state->get_Altitude() * FEET_TO_METER); */
824
825     if ( scenery.cur_elev > -9990 ) {
826         if ( cur_fdm_state->get_Altitude() * FEET_TO_METER < 
827              (scenery.cur_elev + alt_adjust_m - 3.0) ) {
828             // now set aircraft altitude above ground
829             printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n", 
830                    cur_fdm_state->get_Altitude() * FEET_TO_METER,
831                    scenery.cur_elev + alt_adjust_m - 3.0,
832                    scenery.cur_elev + alt_adjust_m );
833             fgFDMForceAltitude( current_options.get_flight_model(), 
834                                 scenery.cur_elev + alt_adjust_m );
835
836             FG_LOG( FG_ALL, FG_DEBUG, 
837                     "<*> resetting altitude to " 
838                     << cur_fdm_state->get_Altitude() * FEET_TO_METER << " meters" );
839         }
840         fgFDMSetGroundElevation( current_options.get_flight_model(),
841                                  scenery.cur_elev );  // meters
842     }
843
844     /* printf("Adjustment - ground = %.2f  runway = %.2f  alt = %.2f\n",
845            scenery.cur_elev,
846            cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
847            cur_fdm_state->get_Altitude() * FEET_TO_METER); */
848
849     // update "time"
850     t->update( cur_fdm_state->get_Longitude(),
851                cur_fdm_state->get_Latitude(),
852                cur_fdm_state->get_Altitude()* FEET_TO_METER );
853
854     // Get elapsed time (in usec) for this past frame
855     elapsed = fgGetTimeInterval();
856     FG_LOG( FG_ALL, FG_DEBUG, 
857             "Elapsed time interval is = " << elapsed 
858             << ", previous remainder is = " << remainder );
859
860     // Calculate frame rate average
861 #ifdef FANCY_FRAME_COUNTER
862     /* old fps calculation */
863     if ( elapsed > 0 ) {
864         double tmp;
865         accum = 0.0;
866         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
867             tmp = general.get_frame(i);
868             accum += tmp;
869             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
870             general.set_frame(i+1,tmp);
871         }
872         tmp = 1000000.0 / (float)elapsed;
873         general.set_frame(0,tmp);
874         // printf("frame[0] = %.2f\n", general.frames[0]);
875         accum += tmp;
876         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
877         // printf("ave = %.2f\n", general.frame_rate);
878     }
879 #else
880     if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
881         general.set_frame_rate( frames );
882         FG_LOG( FG_ALL, FG_DEBUG, 
883                 "--> Frame rate is = " << general.get_frame_rate() );
884         frames = 0;
885     }
886     last_time = t->get_cur_time();
887     ++frames;
888 #endif
889
890     // Run flight model
891     if ( ! use_signals ) {
892         // Calculate model iterations needed for next frame
893         elapsed += remainder;
894
895         global_multi_loop = (int)(((double)elapsed * 0.000001) * 
896                            current_options.get_model_hz());
897         remainder = elapsed - ( (global_multi_loop*1000000) / 
898                                 current_options.get_model_hz() );
899         FG_LOG( FG_ALL, FG_DEBUG, 
900                 "Model iterations needed = " << global_multi_loop
901                 << ", new remainder = " << remainder );
902         
903         // flight model
904         if ( global_multi_loop > 0 ) {
905             fgUpdateTimeDepCalcs(global_multi_loop, remainder);
906         } else {
907             FG_LOG( FG_ALL, FG_DEBUG, 
908                     "Elapsed time is zero ... we're zinging" );
909         }
910     }
911
912 #if ! defined( MACOS )
913     // Do any I/O channel work that might need to be done
914     fgIOProcess();
915 #endif
916
917     // see if we need to load any new scenery tiles
918     global_tile_mgr.update();
919
920     // Process/manage pending events
921     global_events.Process();
922
923     // Run audio scheduler
924 #ifdef ENABLE_AUDIO_SUPPORT
925     if ( current_options.get_sound() && !audio_sched->not_working() ) {
926
927 #   ifdef MICHAEL_JOHNSON_EXPERIMENTAL_ENGINE_AUDIO
928
929         // note: all these factors are relative to the sample.  our
930         // sample format should really contain a conversion factor so
931         // that we can get prop speed right for arbitrary samples.
932         // Note that for normal-size props, there is a point at which
933         // the prop tips approach the speed of sound; that is a pretty
934         // strong limit to how fast the prop can go.
935
936         // multiplication factor is prime pitch control; add some log
937         // component for verisimilitude
938
939         double pitch = log((controls.get_throttle(0) * 14.0) + 1.0);
940         //fprintf(stderr, "pitch1: %f ", pitch);
941         if (controls.get_throttle(0) > 0.0 || cur_fdm_state->v_rel_wind > 40.0) {
942             //fprintf(stderr, "rel_wind: %f ", cur_fdm_state->v_rel_wind);
943             // only add relative wind and AoA if prop is moving
944             // or we're really flying at idle throttle
945             if (pitch < 5.4) {  // this needs tuning
946                 // prop tips not breaking sound barrier
947                 pitch += log(cur_fdm_state->v_rel_wind + 0.8)/2;
948             } else {
949                 // prop tips breaking sound barrier
950                 pitch += log(cur_fdm_state->v_rel_wind + 0.8)/10;
951             }
952             //fprintf(stderr, "pitch2: %f ", pitch);
953             //fprintf(stderr, "AoA: %f ", FG_Gamma_vert_rad);
954
955             // Angle of Attack next... -x^3(e^x) is my best guess Just
956             // need to calculate some reasonable scaling factor and
957             // then clamp it on the positive aoa (neg adj) side
958             double aoa = cur_fdm_state->get_Gamma_vert_rad() * 2.2;
959             double tmp = 3.0;
960             double aoa_adj = pow(-aoa, tmp) * pow(M_E, aoa);
961             if (aoa_adj < -0.8) aoa_adj = -0.8;
962             pitch += aoa_adj;
963             //fprintf(stderr, "pitch3: %f ", pitch);
964
965             // don't run at absurdly slow rates -- not realistic
966             // and sounds bad to boot.  :-)
967             if (pitch < 0.8) pitch = 0.8;
968         }
969         //fprintf(stderr, "pitch4: %f\n", pitch);
970
971         double volume = controls.get_throttle(0) * 1.15 + 0.3 +
972             log(cur_fdm_state->v_rel_wind + 1.0)/14.0;
973         // fprintf(stderr, "volume: %f\n", volume);
974
975         pitch_envelope.setStep  ( 0, 0.01, pitch );
976         volume_envelope.setStep ( 0, 0.01, volume );
977
978 #   else
979
980        double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
981        pitch_envelope.setStep  ( 0, 0.01, param );
982        volume_envelope.setStep ( 0, 0.01, param );
983
984 #   endif // experimental throttle patch
985
986         audio_sched -> update();
987     }
988 #endif
989
990     // redraw display
991     fgRenderFrame();
992
993     FG_LOG( FG_ALL, FG_DEBUG, "" );
994 }
995
996
997 // This is the top level master main function that is registered as
998 // our idle funciton
999 //
1000
1001 // The first few passes take care of initialization things (a couple
1002 // per pass) and once everything has been initialized fgMainLoop from
1003 // then on.
1004
1005 static void fgIdleFunction ( void ) {
1006     // printf("idle state == %d\n", idle_state);
1007
1008     if ( idle_state == 0 ) {
1009         // Initialize the splash screen right away
1010         if ( current_options.get_splash_screen() ) {
1011             fgSplashInit();
1012         }
1013         
1014         idle_state++;
1015     } else if ( idle_state == 1 ) {
1016         // Start the intro music
1017 #if !defined(WIN32)
1018         if ( current_options.get_intro_music() ) {
1019             string lockfile = "/tmp/mpg123.running";
1020             FGPath mp3file( current_options.get_fg_root() );
1021             mp3file.append( "Sounds/intro.mp3" );
1022
1023             string command = "(touch " + lockfile + "; mpg123 "
1024                 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
1025                 + lockfile + ") &";
1026             FG_LOG( FG_GENERAL, FG_INFO, 
1027                     "Starting intro music: " << mp3file.str() );
1028             system ( command.c_str() );
1029         }
1030 #endif
1031
1032         idle_state++;
1033     } else if ( idle_state == 2 ) {
1034         // These are a few miscellaneous things that aren't really
1035         // "subsystems" but still need to be initialized.
1036
1037 #ifdef USE_GLIDE
1038         if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1039             grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1040         }
1041 #endif
1042
1043         idle_state++;
1044     } else if ( idle_state == 3 ) {
1045         // This is the top level init routine which calls all the
1046         // other subsystem initialization routines.  If you are adding
1047         // a subsystem to flight gear, its initialization call should
1048         // located in this routine.
1049         if( !fgInitSubsystems()) {
1050             FG_LOG( FG_GENERAL, FG_ALERT,
1051                     "Subsystem initializations failed ..." );
1052             exit(-1);
1053         }
1054
1055         idle_state++;
1056     } else if ( idle_state == 4 ) {
1057         // setup OpenGL view parameters
1058         fgInitVisuals();
1059
1060         if ( use_signals ) {
1061             // init timer routines, signals, etc.  Arrange for an alarm
1062             // signal to be generated, etc.
1063             fgInitTimeDepCalcs();
1064         }
1065
1066         idle_state++;
1067     } else if ( idle_state == 5 ) {
1068
1069         idle_state++;
1070     } else if ( idle_state == 6 ) {
1071         // Initialize audio support
1072 #ifdef ENABLE_AUDIO_SUPPORT
1073
1074 #if !defined(WIN32)
1075         if ( current_options.get_intro_music() ) {
1076             // Let's wait for mpg123 to finish
1077             string lockfile = "/tmp/mpg123.running";
1078             struct stat stat_buf;
1079
1080             FG_LOG( FG_GENERAL, FG_INFO, 
1081                     "Waiting for mpg123 player to finish ..." );
1082             while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
1083                 // file exist, wait ...
1084                 sleep(1);
1085                 FG_LOG( FG_GENERAL, FG_INFO, ".");
1086             }
1087             FG_LOG( FG_GENERAL, FG_INFO, "");
1088         }
1089 #endif // WIN32
1090
1091         if ( current_options.get_sound() ) {
1092             audio_sched = new slScheduler ( 8000 );
1093             audio_mixer = new smMixer;
1094             audio_mixer -> setMasterVolume ( 80 ) ;  /* 80% of max volume. */
1095             audio_sched -> setSafetyMargin ( 1.0 ) ;
1096
1097             FGPath slfile( current_options.get_fg_root() );
1098             slfile.append( "Sounds/wasp.wav" );
1099
1100             s1 = new slSample ( (char *)slfile.c_str() );
1101             FG_LOG( FG_GENERAL, FG_INFO,
1102                     "Rate = " << s1 -> getRate()
1103                     << "  Bps = " << s1 -> getBps()
1104                     << "  Stereo = " << s1 -> getStereo() );
1105             audio_sched -> loopSample ( s1 );
1106
1107             if ( audio_sched->not_working() ) {
1108                 // skip
1109             } else {
1110                 pitch_envelope.setStep  ( 0, 0.01, 0.6 );
1111                 volume_envelope.setStep ( 0, 0.01, 0.6 );
1112
1113                 audio_sched -> addSampleEnvelope( s1, 0, 0, 
1114                                                   &pitch_envelope,
1115                                                   SL_PITCH_ENVELOPE );
1116                 audio_sched -> addSampleEnvelope( s1, 0, 1, 
1117                                                   &volume_envelope,
1118                                                   SL_VOLUME_ENVELOPE );
1119             }
1120
1121             // strcpy(slfile, path);
1122             // strcat(slfile, "thunder.wav");
1123             // s2 -> loadFile ( slfile );
1124             // s2 -> adjustVolume(0.5);
1125             // audio_sched -> playSample ( s2 );
1126         }
1127 #endif
1128
1129         // sleep(1);
1130         idle_state = 1000;
1131     } 
1132
1133     if ( idle_state == 1000 ) {
1134         // We've finished all our initialization steps, from now on we
1135         // run the main loop.
1136
1137         fgMainLoop();
1138     } else {
1139         if ( current_options.get_splash_screen() == 1 ) {
1140             fgSplashUpdate(0.0);
1141         }
1142     }
1143 }
1144
1145 // options.cxx needs to see this for toggle_panel()
1146 // Handle new window size or exposure
1147 void fgReshape( int width, int height ) {
1148     if ( ! current_options.get_panel_status() ) {
1149         current_view.set_win_ratio( (GLfloat) width / (GLfloat) height );
1150         glViewport(0, 0 , (GLint)(width), (GLint)(height) );
1151     } else {
1152         current_view.set_win_ratio( (GLfloat) width / 
1153                                     ((GLfloat) (height)*0.4232) );
1154         glViewport(0, (GLint)((height)*0.5768),
1155                    (GLint)(width), (GLint)((height)*0.4232) );
1156     }
1157
1158     current_view.set_winWidth( width );
1159     current_view.set_winHeight( height );
1160     current_view.force_update_fov_math();
1161
1162     // set these fov to be the same as in fgRenderFrame()
1163     // float x_fov = current_options.get_fov();
1164     // float y_fov = x_fov * 1.0 / current_view.get_win_ratio();
1165     // ssgSetFOV( x_fov, y_fov );
1166
1167     // glViewport ( 0, 0, width, height );
1168     float fov = current_options.get_fov();
1169     ssgSetFOV(fov * current_view.get_win_ratio(), fov);
1170
1171     fgHUDReshape();
1172
1173     if ( idle_state == 1000 ) {
1174         // yes we've finished all our initializations and are running
1175         // the main loop, so this will now work without seg faulting
1176         // the system.
1177         current_view.UpdateViewParams(cur_view_fdm);
1178     }
1179 }
1180
1181
1182 // Initialize GLUT and define a main window
1183 int fgGlutInit( int *argc, char **argv ) {
1184
1185 #if !defined( MACOS )
1186     // GLUT will extract all glut specific options so later on we only
1187     // need wory about our own.
1188     glutInit(argc, argv);
1189 #endif
1190
1191     // Define Display Parameters
1192     glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1193
1194     FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
1195             current_options.get_xsize() << "x" << current_options.get_ysize() );
1196
1197     // Define initial window size
1198     glutInitWindowSize( current_options.get_xsize(),
1199                          current_options.get_ysize() );
1200
1201     // Initialize windows
1202     if ( current_options.get_game_mode() == 0 ) {
1203         // Open the regular window
1204         glutCreateWindow("Flight Gear");
1205 #ifndef GLUT_WRONG_VERSION
1206     } else {
1207         // Open the cool new 'game mode' window
1208         char game_mode_str[256];
1209         sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1210                  current_options.get_xsize(),
1211                  current_options.get_ysize(),
1212                  current_options.get_bpp());
1213
1214         FG_LOG( FG_GENERAL, FG_INFO, 
1215                 "game mode params = " << game_mode_str );
1216         glutGameModeString( game_mode_str );
1217         glutEnterGameMode();
1218 #endif
1219     }
1220
1221     // This seems to be the absolute earliest in the init sequence
1222     // that these calls will return valid info.  Too bad it's after
1223     // we've already created and sized out window. :-(
1224     general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1225     general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1226     general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1227
1228     FG_LOG ( FG_GENERAL, FG_INFO, general.get_glRenderer() );
1229
1230 #if 0
1231     // try to determine if we should adjust the initial default
1232     // display resolution.  The options class defaults (is
1233     // initialized) to 640x480.
1234     string renderer = general.glRenderer;
1235
1236     // currently we only know how to deal with Mesa/Glide/Voodoo cards
1237     if ( renderer.find( "Glide" ) != string::npos ) {
1238         FG_LOG( FG_GENERAL, FG_INFO, "Detected a Glide driver" );
1239         if ( renderer.find( "FB/8" ) != string::npos ) {
1240             // probably a voodoo-2
1241             if ( renderer.find( "TMU/SLI" ) != string::npos ) {
1242                 // probably two SLI'd Voodoo-2's
1243                 current_options.set_xsize( 1024 );
1244                 current_options.set_ysize( 768 );
1245                 FG_LOG( FG_GENERAL, FG_INFO,
1246                         "It looks like you have two sli'd voodoo-2's." << endl
1247                         << "upgrading your win resolution to 1024 x 768" );
1248                 glutReshapeWindow(1024, 768);
1249             } else {
1250                 // probably a single non-SLI'd Voodoo-2
1251                 current_options.set_xsize( 800 );
1252                 current_options.set_ysize( 600 );
1253                 FG_LOG( FG_GENERAL, FG_INFO,
1254                         "It looks like you have a voodoo-2." << endl
1255                         << "upgrading your win resolution to 800 x 600" );
1256                 glutReshapeWindow(800, 600);
1257             }
1258         } else if ( renderer.find( "FB/2" ) != string::npos ) {
1259             // probably a voodoo-1, stick with the default
1260         }
1261     } else {
1262         // we have no special knowledge of this card, stick with the default
1263     }
1264 #endif
1265
1266     return(1);
1267 }
1268
1269
1270 // Initialize GLUT event handlers
1271 int fgGlutInitEvents( void ) {
1272     // call fgReshape() on window resizes
1273     glutReshapeFunc( fgReshape );
1274
1275     // call GLUTkey() on keyboard event
1276     glutKeyboardFunc( GLUTkey );
1277     glutSpecialFunc( GLUTspecialkey );
1278
1279     // call guiMouseFunc() whenever our little rodent is used
1280     glutMouseFunc ( guiMouseFunc );
1281     glutMotionFunc (guiMotionFunc );
1282     glutPassiveMotionFunc (guiMotionFunc );
1283
1284     // call fgMainLoop() whenever there is
1285     // nothing else to do
1286     glutIdleFunc( fgIdleFunction );
1287
1288     // draw the scene
1289     glutDisplayFunc( fgRenderFrame );
1290
1291     return(1);
1292 }
1293
1294
1295 // Main ...
1296 int main( int argc, char **argv ) {
1297
1298 #if defined( MACOS )
1299     freopen ("stdout.txt", "w", stdout );
1300     freopen ("stderr.txt", "w", stderr );
1301     argc = ccommand( &argv );
1302 #endif
1303
1304 #ifdef HAVE_BC5PLUS
1305     _control87(MCW_EM, MCW_EM);  /* defined in float.h */
1306 #endif
1307
1308     // set default log levels
1309     fglog().setLogLevels( FG_ALL, FG_INFO );
1310
1311     FG_LOG( FG_GENERAL, FG_INFO, "Flight Gear:  Version " << VERSION << endl );
1312
1313     // seed the random number generater
1314     fg_srandom();
1315
1316     aircraft_dir = ""; // Initialize the Aircraft directory to "" (UIUC)
1317
1318     // Load the configuration parameters
1319     if ( !fgInitConfig(argc, argv) ) {
1320         FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1321         exit(-1);
1322     }
1323
1324     // Initialize the Window/Graphics environment.
1325     if( !fgGlutInit(&argc, argv) ) {
1326         FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1327         exit(-1);
1328     }
1329
1330     // Initialize the various GLUT Event Handlers.
1331     if( !fgGlutInitEvents() ) {
1332         FG_LOG( FG_GENERAL, FG_ALERT, 
1333                 "GLUT event handler initialization failed ..." );
1334         exit(-1);
1335     }
1336  
1337     // Initialize ssg (from plib).  Needs to come before we do any
1338     // other ssg stuff, but after opengl/glut has been initialized.
1339     ssgInit();
1340
1341     // Initialize the user interface (we need to do this before
1342     // passing off control to glut and before fgInitGeneral to get our
1343     // fonts !!!
1344     guiInit();
1345
1346     // Initialize time
1347     FGTime::cur_time_params = new FGTime();
1348     // FGTime::cur_time_params->init( cur_fdm_state->get_Longitude(), 
1349     //                                cur_fdm_state->get_Latitude() );
1350     // FGTime::cur_time_params->update( cur_fdm_state->get_Longitude() );
1351     FGTime::cur_time_params->init( 0.0, 0.0 );
1352     FGTime::cur_time_params->update( 0.0, 0.0, 0.0 );
1353
1354     // Do some quick general initializations
1355     if( !fgInitGeneral()) {
1356         FG_LOG( FG_GENERAL, FG_ALERT, 
1357                 "General initializations failed ..." );
1358         exit(-1);
1359     }
1360
1361     //
1362     // some ssg test stuff (requires data from the plib source
1363     // distribution) specifically from the ssg tux example
1364     //
1365
1366     FGPath modelpath( current_options.get_fg_root() );
1367     modelpath.append( "Models" );
1368     modelpath.append( "Geometry" );
1369   
1370     FGPath texturepath( current_options.get_fg_root() );
1371     texturepath.append( "Models" );
1372     texturepath.append( "Textures" );
1373   
1374     ssgModelPath( (char *)modelpath.c_str() );
1375     ssgTexturePath( (char *)texturepath.c_str() );
1376
1377     // Scene graph root
1378     scene = new ssgRoot;
1379     scene->setName( "Scene" );
1380
1381     // Initialize the sky
1382     FGPath ephem_data_path( current_options.get_fg_root() );
1383     ephem_data_path.append( "Astro" );
1384     ephem = new FGEphemeris( ephem_data_path.c_str() );
1385     ephem->update( FGTime::cur_time_params, 0.0 );
1386
1387     FGPath sky_tex_path( current_options.get_fg_root() );
1388     sky_tex_path.append( "Textures" );
1389     sky_tex_path.append( "Sky" );
1390     thesky = new SGSky;
1391     thesky->texture_path( sky_tex_path.str() );
1392
1393     ssgBranch *sky = thesky->build( 550.0, 550.0,
1394                                     ephem->getNumPlanets(), 
1395                                     ephem->getPlanets(), 60000.0,
1396                                     ephem->getNumStars(),
1397                                     ephem->getStars(), 60000.0 );
1398     scene->addKid( sky );
1399
1400     // Terrain branch
1401     terrain = new ssgBranch;
1402     terrain->setName( "Terrain" );
1403     scene->addKid( terrain );
1404
1405     // temporary visible aircraft "own ship"
1406     penguin_sel = new ssgSelector;
1407     penguin_pos = new ssgTransform;
1408     // ssgBranch *tux_obj = ssgMakeSphere( 10.0, 10, 10 );
1409     ssgEntity *tux_obj = ssgLoadAC( "glider.ac" );
1410     // ssgEntity *tux_obj = ssgLoadAC( "Tower1x.ac" );
1411
1412     penguin_pos->addKid( tux_obj );
1413     penguin_sel->addKid( penguin_pos );
1414     ssgFlatten( tux_obj );
1415     ssgStripify( penguin_sel );
1416     penguin_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1417     scene->addKid( penguin_sel );
1418
1419 #ifdef FG_NETWORK_OLK
1420     // Do the network intialization
1421     if ( current_options.get_network_olk() ) {
1422         printf("Multipilot mode %s\n", fg_net_init( scene ) );
1423     }
1424 #endif
1425
1426     // build our custom render states
1427     fgBuildRenderStates();
1428
1429     // pass control off to the master GLUT event handler
1430     glutMainLoop();
1431
1432     // we never actually get here ... but to avoid compiler warnings,
1433     // etc.
1434     return 0;
1435 }