]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
0f8b6a544af12f4e8da0af074c5bad6045583d70
[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 <XGL/xgl.h>
42 #include <stdio.h>
43 #include <string.h>
44 #include <string>
45
46 #ifdef HAVE_STDLIB_H
47 #   include <stdlib.h>
48 #endif
49
50 #ifdef HAVE_SYS_STAT_H
51 #  include <sys/stat.h> /* for stat() */
52 #endif
53
54 #ifdef HAVE_UNISTD_H
55 #  include <unistd.h>    /* for stat() */
56 #endif
57
58 #include <pu.h>                 // plib include
59 #include <ssg.h>                // plib include
60
61 #ifdef ENABLE_AUDIO_SUPPORT
62 #  include <sl.h>               // plib include
63 #  include <sm.h>               // plib include
64 #endif
65
66 #include <Include/fg_constants.h>  // for VERSION
67 #include <Include/general.hxx>
68
69 #include <Debug/logstream.hxx>
70 #include <Aircraft/aircraft.hxx>
71 #include <Astro/sky.hxx>
72 #include <Astro/stars.hxx>
73 #include <Astro/solarsystem.hxx>
74
75 #include <Autopilot/autopilot.hxx>
76 #include <Cockpit/cockpit.hxx>
77 #include <GUI/gui.h>
78 #include <Joystick/joystick.hxx>
79 #include <Math/fg_geodesy.hxx>
80 #include <Math/mat3.h>
81 #include <Math/polar3d.hxx>
82 #include <Math/fg_random.h>
83 #include <Misc/fgpath.hxx>
84 #include <Scenery/scenery.hxx>
85 #include <Scenery/tilemgr.hxx>
86 #include <Time/event.hxx>
87 #include <Time/fg_time.hxx>
88 #include <Time/fg_timer.hxx>
89 #include <Time/sunpos.hxx>
90 #include <Weather/weather.hxx>
91
92 #include "fg_init.hxx"
93 #include "keyboard.hxx"
94 #include "options.hxx"
95 #include "splash.hxx"
96 #include "views.hxx"
97 #include "fg_serial.hxx"
98
99
100 // -dw- use custom sioux settings so I can see output window
101 #ifdef MACOS
102 #  ifndef FG_NDEBUG
103 #    include <sioux.h> // settings for output window
104 #  endif
105 #  include <console.h>
106 #endif
107
108
109 // This is a record containing a bit of global housekeeping information
110 FGGeneral general;
111
112 // Specify our current idle function state.  This is used to run all
113 // our initializations out of the glutIdleLoop() so that we can get a
114 // splash screen up and running right away.
115 static int idle_state = 0;
116
117 // Another hack
118 int use_signals = 0;
119
120 // Global structures for the Audio library
121 #ifdef ENABLE_AUDIO_SUPPORT
122 slEnvelope pitch_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
123 slEnvelope volume_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
124 slScheduler *audio_sched;
125 smMixer *audio_mixer;
126 slSample *s1;
127 slSample *s2;
128 #endif
129
130
131 // ssg variables
132 ssgRoot *scene = NULL;
133 ssgBranch *terrain = NULL;
134 ssgTransform *penguin = NULL;
135
136
137 // The following defines flight gear options. Because glutlib will also
138 // want to parse its own options, those options must not be included here
139 // or they will get parsed by the main program option parser. Hence case
140 // is significant for any option added that might be in conflict with
141 // glutlib's parser.
142 //
143 // glutlib parses for:
144 //    -display
145 //    -direct   (invalid in Win32)
146 //    -geometry
147 //    -gldebug
148 //    -iconized
149 //    -indirect (invalid in Win32)
150 //    -synce
151 //
152 // Note that glutlib depends upon strings while this program's
153 // option parser wants only initial characters followed by numbers
154 // or pathnames.
155 //
156
157
158 // fgInitVisuals() -- Initialize various GL/view parameters
159 static void fgInitVisuals( void ) {
160     fgLIGHT *l;
161
162     l = &cur_light_params;
163
164 #ifndef GLUT_WRONG_VERSION
165     // Go full screen if requested ...
166     if ( current_options.get_fullscreen() ) {
167         glutFullScreen();
168     }
169 #endif
170
171     // If enabled, normal vectors specified with glNormal are scaled
172     // to unit length after transformation.  See glNormal.
173     // xglEnable( GL_NORMALIZE );
174
175     xglEnable( GL_LIGHTING );
176     xglEnable( GL_LIGHT0 );
177     xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
178
179     sgVec3 sunpos;
180     sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
181     ssgGetLight( 0 ) -> setPosition( sunpos );
182
183     // xglFogi (GL_FOG_MODE, GL_LINEAR);
184     xglFogi (GL_FOG_MODE, GL_EXP2);
185     if ( (current_options.get_fog() == 1) || 
186          (current_options.get_shading() == 0) ) {
187         // if fastest fog requested, or if flat shading force fastest
188         xglHint ( GL_FOG_HINT, GL_FASTEST );
189     } else if ( current_options.get_fog() == 2 ) {
190         xglHint ( GL_FOG_HINT, GL_NICEST );
191     }
192     if ( current_options.get_wireframe() ) {
193         // draw wire frame
194         xglPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
195     }
196
197     // This is the default anyways, but it can't hurt
198     xglFrontFace ( GL_CCW );
199
200     // Just testing ...
201     // xglEnable(GL_POINT_SMOOTH);
202     // xglEnable(GL_LINE_SMOOTH);
203     // xglEnable(GL_POLYGON_SMOOTH);      
204 }
205
206
207 #if 0
208 // Draw a basic instrument panel
209 static void fgUpdateInstrViewParams( void ) {
210
211     exit(0);
212
213     fgVIEW *v = &current_view;
214
215     xglViewport(0, 0 , (GLint)(v->winWidth), (GLint)(v->winHeight) / 2);
216   
217     xglMatrixMode(GL_PROJECTION);
218     xglPushMatrix();
219   
220     xglLoadIdentity();
221     gluOrtho2D(0, 640, 0, 480);
222     xglMatrixMode(GL_MODELVIEW);
223     xglPushMatrix();
224     xglLoadIdentity();
225
226     xglColor3f(1.0, 1.0, 1.0);
227     xglIndexi(7);
228   
229     xglDisable(GL_DEPTH_TEST);
230     xglDisable(GL_LIGHTING);
231   
232     xglLineWidth(1);
233     xglColor3f (0.5, 0.5, 0.5);
234
235     xglBegin(GL_QUADS);
236     xglVertex2f(0.0, 0.00);
237     xglVertex2f(0.0, 480.0);
238     xglVertex2f(640.0,480.0);
239     xglVertex2f(640.0, 0.0);
240     xglEnd();
241
242     xglRectf(0.0,0.0, 640, 480);
243     xglEnable(GL_DEPTH_TEST);
244     xglEnable(GL_LIGHTING);
245     xglMatrixMode(GL_PROJECTION);
246     xglPopMatrix();
247     xglMatrixMode(GL_MODELVIEW);
248     xglPopMatrix();
249 }
250 #endif
251
252
253 // Update all Visuals (redraws anything graphics related)
254 static void fgRenderFrame( void ) {
255     fgLIGHT *l = &cur_light_params;
256     FGTime *t = FGTime::cur_time_params;
257     FGView *v = &current_view;
258
259     double angle;
260     // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
261     GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
262     GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
263     // GLfloat mat_shininess[] = { 10.0 };
264     GLbitfield clear_mask;
265
266     if ( idle_state != 1000 ) {
267         // still initializing, draw the splash screen
268         if ( current_options.get_splash_screen() == 1 ) {
269             fgSplashUpdate(0.0);
270         }
271     } else {
272         // idle_state is now 1000 meaning we've finished all our
273         // initializations and are running the main loop, so this will
274         // now work without seg faulting the system.
275
276         // printf("Ground = %.2f  Altitude = %.2f\n", scenery.cur_elev, 
277         //        FG_Altitude * FEET_TO_METER);
278     
279         // this is just a temporary hack, to make me understand Pui
280         // timerText -> setLabel (ctime (&t->cur_time));
281         // end of hack
282
283         // update view volume parameters
284         v->UpdateViewParams();
285
286         // set the sun position
287         xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
288
289         sgVec3 sunpos;
290         sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
291         ssgGetLight( 0 ) -> setPosition( sunpos );
292
293         clear_mask = GL_DEPTH_BUFFER_BIT;
294         if ( current_options.get_wireframe() ) {
295             clear_mask |= GL_COLOR_BUFFER_BIT;
296         }
297         if ( current_options.get_panel_status() ) {
298             // we can't clear the screen when the panel is active
299         } else if ( current_options.get_skyblend() ) {
300             if ( current_options.get_textures() ) {
301                 // glClearColor(black[0], black[1], black[2], black[3]);
302                 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1], 
303                              l->adj_fog_color[2], l->adj_fog_color[3]);
304                 clear_mask |= GL_COLOR_BUFFER_BIT;
305             }
306         } else {
307             glClearColor(l->sky_color[0], l->sky_color[1], 
308                          l->sky_color[2], l->sky_color[3]);
309             clear_mask |= GL_COLOR_BUFFER_BIT;
310         }
311         xglClear( clear_mask );
312
313         // Tell GL we are switching to model view parameters
314         xglMatrixMode(GL_MODELVIEW);
315         // xglLoadIdentity();
316
317         // draw sky
318         xglDisable( GL_DEPTH_TEST );
319         xglDisable( GL_LIGHTING );
320         xglDisable( GL_CULL_FACE );
321         xglDisable( GL_FOG );
322         xglShadeModel( GL_SMOOTH );
323         if ( current_options.get_skyblend() ) {
324             fgSkyRender();
325         }
326
327         // setup transformation for drawing astronomical objects
328         xglPushMatrix();
329         // Translate to view position
330         Point3D view_pos = v->get_view_pos();
331         xglTranslatef( view_pos.x(), view_pos.y(), view_pos.z() );
332         // Rotate based on gst (sidereal time)
333         // note: constant should be 15.041085, Curt thought it was 15
334         angle = t->getGst() * 15.041085;
335         // printf("Rotating astro objects by %.2f degrees\n",angle);
336         xglRotatef( angle, 0.0, 0.0, -1.0 );
337
338         // draw stars and planets
339         fgStarsRender();
340         xglEnable( GL_CULL_FACE ); // for moon
341         //xglEnable(GL_DEPTH_TEST);
342         SolarSystem::theSolarSystem->draw();
343
344         xglPopMatrix();
345
346         // draw scenery
347         if ( current_options.get_shading() ) {
348             xglShadeModel( GL_SMOOTH ); 
349         } else {
350             xglShadeModel( GL_FLAT ); 
351         }
352         xglEnable( GL_DEPTH_TEST );
353         if ( current_options.get_fog() > 0 ) {
354             xglEnable( GL_FOG );
355             xglFogi( GL_FOG_MODE, GL_EXP2 );
356             xglFogfv( GL_FOG_COLOR, l->adj_fog_color );
357         }
358         // set lighting parameters
359         xglLightfv( GL_LIGHT0, GL_AMBIENT, l->scene_ambient );
360         xglLightfv( GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
361         // xglLightfv(GL_LIGHT0, GL_SPECULAR, white );
362         
363         if ( current_options.get_textures() ) {
364             // texture parameters
365             xglEnable( GL_TEXTURE_2D );
366             xglTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
367             xglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
368             // set base color (I don't think this is doing anything here)
369             xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
370             xglMaterialfv (GL_FRONT, GL_DIFFUSE, white);
371             // xglMaterialfv (GL_FRONT, GL_SPECULAR, white);
372             // xglMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
373         } else {
374             xglDisable( GL_TEXTURE_2D );
375             xglMaterialfv (GL_FRONT, GL_AMBIENT, terrain_color);
376             xglMaterialfv (GL_FRONT, GL_DIFFUSE, terrain_color);
377             // xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
378             // xglMaterialfv (GL_FRONT, GL_DIFFUSE, white);
379         }
380
381         global_tile_mgr.render();
382
383         // ssg test
384
385         xglMatrixMode( GL_PROJECTION );
386         xglLoadIdentity();
387         ssgSetFOV( current_options.get_fov(), 0.0f );
388
389         double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
390             - scenery.cur_elev;
391
392         FG_LOG( FG_ALL, FG_INFO, "visibility is " 
393                 << current_weather.get_visibility() );
394             
395         if ( agl > 10.0 ) {
396             // ssgSetNearFar( 10.0f, current_weather.get_visibility() );
397             ssgSetNearFar( 10.0f, 100000.0f );
398         } else {
399             // ssgSetNearFar( 0.5f, current_weather.get_visibility() );
400             ssgSetNearFar( 0.5f, 100000.0f );
401         }
402
403         sgMat4 sgTRANS;
404         sgMakeTransMat4( sgTRANS, 
405                          current_view.view_pos.x() 
406                          + current_view.view_forward[0] * 20,
407                          current_view.view_pos.y() 
408                          + current_view.view_forward[1] * 20,
409                          current_view.view_pos.z() 
410                          + current_view.view_forward[2] * 20 );
411
412         sgMat4 sgTMP;
413         sgMat4 sgTUX;
414         sgMultMat4( sgTMP, current_view.sgUP, sgTRANS );
415         sgMultMat4( sgTUX, current_view.sgLARC_TO_SSG, sgTMP );
416         
417         sgCoord tuxpos;
418         sgSetCoord( &tuxpos, sgTUX );
419         penguin->setTransform( &tuxpos );
420
421         sgMakeTransMat4( sgTRANS, 
422                          current_view.view_pos.x(),
423                          current_view.view_pos.y(),
424                          current_view.view_pos.z() );
425         sgMat4 sgVIEW;
426         sgMultMat4( sgVIEW, current_view.sgVIEW, sgTRANS );
427         ssgSetCamera( sgVIEW );
428         // ssgSetCamera( current_view.sgVIEW );
429         ssgCullAndDraw( scene );
430
431         xglDisable( GL_TEXTURE_2D );
432         xglDisable( GL_FOG );
433
434         // display HUD && Panel
435         xglDisable( GL_CULL_FACE );
436         fgCockpitUpdate();
437
438         // We can do translucent menus, so why not. :-)
439         xglEnable    ( GL_BLEND ) ;
440         xglBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
441         puDisplay();
442         xglDisable   ( GL_BLEND ) ;
443         xglEnable( GL_FOG );
444
445     }
446
447     xglutSwapBuffers();
448 }
449
450
451 // Update internal time dependent calculations (i.e. flight model)
452 void fgUpdateTimeDepCalcs(int multi_loop, int remainder) {
453     FGInterface *f = current_aircraft.fdm_state;
454     fgLIGHT *l = &cur_light_params;
455     FGTime *t = FGTime::cur_time_params;
456     FGView *v = &current_view;
457     int i;
458
459     // update the flight model
460     if ( multi_loop < 0 ) {
461         multi_loop = DEFAULT_MULTILOOP;
462     }
463
464     if ( !t->getPause() ) {
465         // run Autopilot system
466         fgAPRun();
467
468         // printf("updating flight model x %d\n", multi_loop);
469         fgFDMUpdate( current_options.get_flight_model(), 
470                      cur_fdm_state, multi_loop, remainder );
471     } else {
472         fgFDMUpdate( current_options.get_flight_model(), 
473                      cur_fdm_state, 0, remainder );
474     }
475
476     // update the view angle
477     for ( i = 0; i < multi_loop; i++ ) {
478         if ( fabs(v->get_goal_view_offset() - v->get_view_offset()) < 0.05 ) {
479             v->set_view_offset( v->get_goal_view_offset() );
480             break;
481         } else {
482             // move v->view_offset towards v->goal_view_offset
483             if ( v->get_goal_view_offset() > v->get_view_offset() ) {
484                 if ( v->get_goal_view_offset() - v->get_view_offset() < FG_PI ){
485                     v->inc_view_offset( 0.01 );
486                 } else {
487                     v->inc_view_offset( -0.01 );
488                 }
489             } else {
490                 if ( v->get_view_offset() - v->get_goal_view_offset() < FG_PI ){
491                     v->inc_view_offset( -0.01 );
492                 } else {
493                     v->inc_view_offset( 0.01 );
494                 }
495             }
496             if ( v->get_view_offset() > FG_2PI ) {
497                 v->inc_view_offset( -FG_2PI );
498             } else if ( v->get_view_offset() < 0 ) {
499                 v->inc_view_offset( FG_2PI );
500             }
501         }
502     }
503
504     double tmp = -(l->sun_rotation + FG_PI) 
505         - (f->get_Psi() - v->get_view_offset() );
506     while ( tmp < 0.0 ) {
507         tmp += FG_2PI;
508     }
509     while ( tmp > FG_2PI ) {
510         tmp -= FG_2PI;
511     }
512     /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
513            FG_Psi * RAD_TO_DEG, v->view_offset * RAD_TO_DEG, 
514            -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
515     l->UpdateAdjFog();
516 }
517
518
519 void fgInitTimeDepCalcs( void ) {
520     // initialize timer
521
522     // #ifdef HAVE_SETITIMER
523     //   fgTimerInit( 1.0 / DEFAULT_TIMER_HZ, fgUpdateTimeDepCalcs );
524     // #endif HAVE_SETITIMER
525 }
526
527 static const double alt_adjust_ft = 3.758099;
528 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
529
530 // What should we do when we have nothing else to do?  Let's get ready
531 // for the next move and update the display?
532 static void fgMainLoop( void ) {
533     FGInterface *f;
534     FGTime *t;
535     static long remainder = 0;
536     long elapsed, multi_loop;
537 #ifdef FANCY_FRAME_COUNTER
538     int i;
539     double accum;
540 #else
541     static time_t last_time = 0;
542     static int frames = 0;
543 #endif // FANCY_FRAME_COUNTER
544
545     f = current_aircraft.fdm_state;
546     t = FGTime::cur_time_params;
547
548     FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
549     FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
550
551 #if defined( ENABLE_PLIB_JOYSTICK )
552     // Read joystick and update control settings
553     fgJoystickRead();
554 #elif defined( ENABLE_GLUT_JOYSTICK )
555     // Glut joystick support works by feeding a joystick handler
556     // function to glut.  This is taken care of once in the joystick
557     // init routine and we don't have to worry about it again.
558 #endif
559
560     current_weather.Update();
561
562     // Fix elevation.  I'm just sticking this here for now, it should
563     // probably move eventually
564
565     /* printf("Before - ground = %.2f  runway = %.2f  alt = %.2f\n",
566            scenery.cur_elev,
567            f->get_Runway_altitude() * FEET_TO_METER,
568            f->get_Altitude() * FEET_TO_METER); */
569
570     if ( scenery.cur_elev > -9990 ) {
571         if ( f->get_Altitude() * FEET_TO_METER < 
572              (scenery.cur_elev + alt_adjust_m - 3.0) ) {
573             // now set aircraft altitude above ground
574             printf("Current Altitude = %.2f < %.2f forcing to %.2f\n", 
575                    f->get_Altitude() * FEET_TO_METER,
576                    scenery.cur_elev + alt_adjust_m - 3.0,
577                    scenery.cur_elev + alt_adjust_m );
578             fgFDMForceAltitude( current_options.get_flight_model(), 
579                                 scenery.cur_elev + alt_adjust_m );
580
581             FG_LOG( FG_ALL, FG_DEBUG, 
582                     "<*> resetting altitude to " 
583                     << f->get_Altitude() * FEET_TO_METER << " meters" );
584         }
585         fgFDMSetGroundElevation( current_options.get_flight_model(),
586                                  scenery.cur_elev );  // meters
587     }
588
589     /* printf("Adjustment - ground = %.2f  runway = %.2f  alt = %.2f\n",
590            scenery.cur_elev,
591            f->get_Runway_altitude() * FEET_TO_METER,
592            f->get_Altitude() * FEET_TO_METER); */
593
594     // update "time"
595     t->update(f);
596
597     // Get elapsed time (in usec) for this past frame
598     elapsed = fgGetTimeInterval();
599     FG_LOG( FG_ALL, FG_DEBUG, 
600             "Elapsed time interval is = " << elapsed 
601             << ", previous remainder is = " << remainder );
602
603     // Calculate frame rate average
604 #ifdef FANCY_FRAME_COUNTER
605     /* old fps calculation */
606     if ( elapsed > 0 ) {
607         double tmp;
608         accum = 0.0;
609         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
610             tmp = general.get_frame(i);
611             accum += tmp;
612             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
613             general.set_frame(i+1,tmp);
614         }
615         tmp = 1000000.0 / (float)elapsed;
616         general.set_frame(0,tmp);
617         // printf("frame[0] = %.2f\n", general.frames[0]);
618         accum += tmp;
619         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
620         // printf("ave = %.2f\n", general.frame_rate);
621     }
622 #else
623     if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
624         general.set_frame_rate( frames );
625         FG_LOG( FG_ALL, FG_DEBUG, 
626                 "--> Frame rate is = " << general.get_frame_rate() );
627         frames = 0;
628     }
629     last_time = t->get_cur_time();
630     ++frames;
631 #endif
632
633     // Run flight model
634     if ( ! use_signals ) {
635         // Calculate model iterations needed for next frame
636         elapsed += remainder;
637
638         multi_loop = (int)(((double)elapsed * 0.000001) * DEFAULT_MODEL_HZ);
639         remainder = elapsed - ((multi_loop*1000000) / DEFAULT_MODEL_HZ);
640         FG_LOG( FG_ALL, FG_DEBUG, 
641                 "Model iterations needed = " << multi_loop
642                 << ", new remainder = " << remainder );
643         
644         // flight model
645         if ( multi_loop > 0 ) {
646             fgUpdateTimeDepCalcs(multi_loop, remainder);
647         } else {
648             FG_LOG( FG_ALL, FG_INFO, "Elapsed time is zero ... we're zinging" );
649         }
650     }
651
652 #if ! defined( MACOS )
653     // Do any serial port work that might need to be done
654     fgSerialProcess();
655 #endif
656
657     // see if we need to load any new scenery tiles
658     global_tile_mgr.update();
659
660     // Process/manage pending events
661     global_events.Process();
662
663     // Run audio scheduler
664 #ifdef ENABLE_AUDIO_SUPPORT
665     if ( current_options.get_sound() && !audio_sched->not_working() ) {
666
667 #   ifdef MICHAEL_JOHNSON_EXPERIMENTAL_ENGINE_AUDIO
668
669         // note: all these factors are relative to the sample.  our
670         // sample format should really contain a conversion factor so
671         // that we can get prop speed right for arbitrary samples.
672         // Note that for normal-size props, there is a point at which
673         // the prop tips approach the speed of sound; that is a pretty
674         // strong limit to how fast the prop can go.
675
676         // multiplication factor is prime pitch control; add some log
677         // component for verisimilitude
678
679         double pitch = log((controls.get_throttle(0) * 14.0) + 1.0);
680         //fprintf(stderr, "pitch1: %f ", pitch);
681         if (controls.get_throttle(0) > 0.0 || f->v_rel_wind > 40.0) {
682             //fprintf(stderr, "rel_wind: %f ", f->v_rel_wind);
683             // only add relative wind and AoA if prop is moving
684             // or we're really flying at idle throttle
685             if (pitch < 5.4) {  // this needs tuning
686                 // prop tips not breaking sound barrier
687                 pitch += log(f->v_rel_wind + 0.8)/2;
688             } else {
689                 // prop tips breaking sound barrier
690                 pitch += log(f->v_rel_wind + 0.8)/10;
691             }
692             //fprintf(stderr, "pitch2: %f ", pitch);
693             //fprintf(stderr, "AoA: %f ", FG_Gamma_vert_rad);
694
695             // Angle of Attack next... -x^3(e^x) is my best guess Just
696             // need to calculate some reasonable scaling factor and
697             // then clamp it on the positive aoa (neg adj) side
698             double aoa = f->get_Gamma_vert_rad() * 2.2;
699             double tmp = 3.0;
700             double aoa_adj = pow(-aoa, tmp) * pow(M_E, aoa);
701             if (aoa_adj < -0.8) aoa_adj = -0.8;
702             pitch += aoa_adj;
703             //fprintf(stderr, "pitch3: %f ", pitch);
704
705             // don't run at absurdly slow rates -- not realistic
706             // and sounds bad to boot.  :-)
707             if (pitch < 0.8) pitch = 0.8;
708         }
709         //fprintf(stderr, "pitch4: %f\n", pitch);
710
711         double volume = controls.get_throttle(0) * 1.15 + 0.3 +
712             log(f->v_rel_wind + 1.0)/14.0;
713         // fprintf(stderr, "volume: %f\n", volume);
714
715         pitch_envelope.setStep  ( 0, 0.01, pitch );
716         volume_envelope.setStep ( 0, 0.01, volume );
717
718 #   else
719
720        double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
721        pitch_envelope.setStep  ( 0, 0.01, param );
722        volume_envelope.setStep ( 0, 0.01, param );
723
724 #   endif // experimental throttle patch
725
726         audio_sched -> update();
727     }
728 #endif
729
730     // redraw display
731     fgRenderFrame();
732
733     FG_LOG( FG_ALL, FG_DEBUG, "" );
734 }
735
736
737 // This is the top level master main function that is registered as
738 // our idle funciton
739 //
740
741 // The first few passes take care of initialization things (a couple
742 // per pass) and once everything has been initialized fgMainLoop from
743 // then on.
744
745 static void fgIdleFunction ( void ) {
746     // printf("idle state == %d\n", idle_state);
747
748     if ( idle_state == 0 ) {
749         // Initialize the splash screen right away
750         if ( current_options.get_splash_screen() ) {
751             fgSplashInit();
752         }
753         
754         idle_state++;
755     } else if ( idle_state == 1 ) {
756         // Start the intro music
757 #if !defined(WIN32)
758         if ( current_options.get_intro_music() ) {
759             string lockfile = "/tmp/mpg123.running";
760             FGPath mp3file( current_options.get_fg_root() );
761             mp3file.append( "Sounds/intro.mp3" );
762
763             string command = "(touch " + lockfile + "; mpg123 "
764                 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
765                 + lockfile + ") &";
766             FG_LOG( FG_GENERAL, FG_INFO, 
767                     "Starting intro music: " << mp3file.str() );
768             system ( command.c_str() );
769         }
770 #endif
771
772         idle_state++;
773     } else if ( idle_state == 2 ) {
774         // These are a few miscellaneous things that aren't really
775         // "subsystems" but still need to be initialized.
776
777 #ifdef USE_GLIDE
778         if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
779             grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
780         }
781 #endif
782
783         idle_state++;
784     } else if ( idle_state == 3 ) {
785         // This is the top level init routine which calls all the
786         // other subsystem initialization routines.  If you are adding
787         // a subsystem to flight gear, its initialization call should
788         // located in this routine.
789         if( !fgInitSubsystems()) {
790             FG_LOG( FG_GENERAL, FG_ALERT,
791                     "Subsystem initializations failed ..." );
792             exit(-1);
793         }
794
795         idle_state++;
796     } else if ( idle_state == 4 ) {
797         // setup OpenGL view parameters
798         fgInitVisuals();
799
800         if ( use_signals ) {
801             // init timer routines, signals, etc.  Arrange for an alarm
802             // signal to be generated, etc.
803             fgInitTimeDepCalcs();
804         }
805
806         idle_state++;
807     } else if ( idle_state == 5 ) {
808
809         idle_state++;
810     } else if ( idle_state == 6 ) {
811         // Initialize audio support
812 #ifdef ENABLE_AUDIO_SUPPORT
813
814 #if !defined(WIN32)
815         if ( current_options.get_intro_music() ) {
816             // Let's wait for mpg123 to finish
817             string lockfile = "/tmp/mpg123.running";
818             struct stat stat_buf;
819
820             FG_LOG( FG_GENERAL, FG_INFO, 
821                     "Waiting for mpg123 player to finish ..." );
822             while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
823                 // file exist, wait ...
824                 sleep(1);
825                 FG_LOG( FG_GENERAL, FG_INFO, ".");
826             }
827             FG_LOG( FG_GENERAL, FG_INFO, "");
828         }
829 #endif // WIN32
830
831         audio_sched = new slScheduler ( 8000 );
832         audio_mixer = new smMixer;
833         audio_mixer -> setMasterVolume ( 80 ) ;  /* 80% of max volume. */
834         audio_sched -> setSafetyMargin ( 1.0 ) ;
835
836         FGPath slfile( current_options.get_fg_root() );
837         slfile.append( "Sounds/wasp.wav" );
838
839         s1 = new slSample ( (char *)slfile.c_str() );
840         FG_LOG( FG_GENERAL, FG_INFO,
841                 "Rate = " << s1 -> getRate()
842                 << "  Bps = " << s1 -> getBps()
843                 << "  Stereo = " << s1 -> getStereo() );
844         audio_sched -> loopSample ( s1 );
845
846         if ( audio_sched->not_working() ) {
847             // skip
848         } else {
849             pitch_envelope.setStep  ( 0, 0.01, 0.6 );
850             volume_envelope.setStep ( 0, 0.01, 0.6 );
851
852             audio_sched -> addSampleEnvelope( s1, 0, 0, &
853                                               pitch_envelope,
854                                               SL_PITCH_ENVELOPE );
855             audio_sched -> addSampleEnvelope( s1, 0, 1, 
856                                               &volume_envelope,
857                                               SL_VOLUME_ENVELOPE );
858         }
859
860         // strcpy(slfile, path);
861         // strcat(slfile, "thunder.wav");
862         // s2 -> loadFile ( slfile );
863         // s2 -> adjustVolume(0.5);
864         // audio_sched -> playSample ( s2 );
865 #endif
866
867         // sleep(1);
868         idle_state = 1000;
869     } 
870
871     if ( idle_state == 1000 ) {
872         // We've finished all our initialization steps, from now on we
873         // run the main loop.
874
875         fgMainLoop();
876     } else {
877         if ( current_options.get_splash_screen() == 1 ) {
878             fgSplashUpdate(0.0);
879         }
880     }
881 }
882
883 // options.cxx needs to see this for toggle_panel()
884 // Handle new window size or exposure
885 void fgReshape( int width, int height ) {
886     if ( ! current_options.get_panel_status() ) {
887         current_view.set_win_ratio( (GLfloat) width / (GLfloat) height );
888         xglViewport(0, 0 , (GLint)(width), (GLint)(height) );
889     } else {
890         current_view.set_win_ratio( (GLfloat) width / 
891                                     ((GLfloat) (height)*0.4232) );
892         xglViewport(0, (GLint)((height)*0.5768), (GLint)(width), 
893                     (GLint)((height)*0.4232) );
894     }
895
896     current_view.set_winWidth( width );
897     current_view.set_winHeight( height );
898     current_view.force_update_fov_math();
899
900     if ( idle_state == 1000 ) {
901         // yes we've finished all our initializations and are running
902         // the main loop, so this will now work without seg faulting
903         // the system.
904         current_view.UpdateViewParams();
905         if ( current_options.get_panel_status() ) {
906             FGPanel::OurPanel->ReInit(0, 0, 1024, 768);
907         }
908     }
909 }
910
911
912 // Initialize GLUT and define a main window
913 int fgGlutInit( int *argc, char **argv ) {
914
915 #if !defined( MACOS )
916     // GLUT will extract all glut specific options so later on we only
917     // need wory about our own.
918     xglutInit(argc, argv);
919 #endif
920
921     // Define Display Parameters
922     xglutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
923
924     FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
925             current_options.get_xsize() << "x" << current_options.get_ysize() );
926
927     // Define initial window size
928     xglutInitWindowSize( current_options.get_xsize(),
929                          current_options.get_ysize() );
930
931     // Initialize windows
932     if ( current_options.get_game_mode() == 0 ) {
933         // Open the regular window
934         xglutCreateWindow("Flight Gear");
935 #ifndef GLUT_WRONG_VERSION
936     } else {
937         // Open the cool new 'game mode' window
938         char game_mode_str[256];
939         sprintf( game_mode_str, "width=%d height=%d bpp=32",
940                  current_options.get_xsize(),
941                  current_options.get_ysize() );
942
943         FG_LOG( FG_GENERAL, FG_INFO, 
944                 "game mode params = " << game_mode_str );
945         glutGameModeString( game_mode_str );
946         glutEnterGameMode();
947 #endif
948     }
949
950     // This seems to be the absolute earliest in the init sequence
951     // that these calls will return valid info.  Too bad it's after
952     // we've already created and sized out window. :-(
953     general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
954     general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
955     general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
956
957     FG_LOG ( FG_GENERAL, FG_INFO, general.get_glRenderer() );
958
959 #if 0
960     // try to determine if we should adjust the initial default
961     // display resolution.  The options class defaults (is
962     // initialized) to 640x480.
963     string renderer = general.glRenderer;
964
965     // currently we only know how to deal with Mesa/Glide/Voodoo cards
966     if ( renderer.find( "Glide" ) != string::npos ) {
967         FG_LOG( FG_GENERAL, FG_INFO, "Detected a Glide driver" );
968         if ( renderer.find( "FB/8" ) != string::npos ) {
969             // probably a voodoo-2
970             if ( renderer.find( "TMU/SLI" ) != string::npos ) {
971                 // probably two SLI'd Voodoo-2's
972                 current_options.set_xsize( 1024 );
973                 current_options.set_ysize( 768 );
974                 FG_LOG( FG_GENERAL, FG_INFO,
975                         "It looks like you have two sli'd voodoo-2's." << endl
976                         << "upgrading your win resolution to 1024 x 768" );
977                 glutReshapeWindow(1024, 768);
978             } else {
979                 // probably a single non-SLI'd Voodoo-2
980                 current_options.set_xsize( 800 );
981                 current_options.set_ysize( 600 );
982                 FG_LOG( FG_GENERAL, FG_INFO,
983                         "It looks like you have a voodoo-2." << endl
984                         << "upgrading your win resolution to 800 x 600" );
985                 glutReshapeWindow(800, 600);
986             }
987         } else if ( renderer.find( "FB/2" ) != string::npos ) {
988             // probably a voodoo-1, stick with the default
989         }
990     } else {
991         // we have no special knowledge of this card, stick with the default
992     }
993 #endif
994
995     return(1);
996 }
997
998
999 // Initialize GLUT event handlers
1000 int fgGlutInitEvents( void ) {
1001     // call fgReshape() on window resizes
1002     xglutReshapeFunc( fgReshape );
1003
1004     // call GLUTkey() on keyboard event
1005     xglutKeyboardFunc( GLUTkey );
1006     glutSpecialFunc( GLUTspecialkey );
1007
1008     // call guiMouseFunc() whenever our little rodent is used
1009     glutMouseFunc ( guiMouseFunc );
1010     glutMotionFunc (guiMotionFunc );
1011     glutPassiveMotionFunc (guiMotionFunc );
1012
1013     // call fgMainLoop() whenever there is
1014     // nothing else to do
1015     xglutIdleFunc( fgIdleFunction );
1016
1017     // draw the scene
1018     xglutDisplayFunc( fgRenderFrame );
1019
1020     return(1);
1021 }
1022
1023
1024 // Main ...
1025 int main( int argc, char **argv ) {
1026
1027 #if defined( MACOS )
1028     argc = ccommand( &argv );
1029 #endif
1030
1031 #ifdef HAVE_BC5PLUS
1032     _control87(MCW_EM, MCW_EM);  /* defined in float.h */
1033 #endif
1034
1035     // set default log levels
1036     fglog().setLogLevels( FG_ALL, FG_INFO );
1037
1038     FG_LOG( FG_GENERAL, FG_INFO, "Flight Gear:  Version " << VERSION << endl );
1039
1040     // seed the random number generater
1041     fg_srandom();
1042
1043     // Load the configuration parameters
1044     if ( !fgInitConfig(argc, argv) ) {
1045         FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1046         exit(-1);
1047     }
1048
1049     // Initialize the Window/Graphics environment.
1050     if( !fgGlutInit(&argc, argv) ) {
1051         FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1052         exit(-1);
1053     }
1054
1055     // Initialize the various GLUT Event Handlers.
1056     if( !fgGlutInitEvents() ) {
1057         FG_LOG( FG_GENERAL, FG_ALERT, 
1058                 "GLUT event handler initialization failed ..." );
1059         exit(-1);
1060     }
1061
1062     // Initialize ssg (from plib)
1063     ssgInit();
1064
1065     // Initialize the user interface (we need to do this before
1066     // passing off control to glut and before fgInitGeneral to get our
1067     // fonts !!!
1068     guiInit();
1069
1070     // Do some quick general initializations
1071     if( !fgInitGeneral()) {
1072         FG_LOG( FG_GENERAL, FG_ALERT, 
1073                 "General initializations failed ..." );
1074         exit(-1);
1075     }
1076
1077     //
1078     // some ssg test stuff (requires data from the plib source
1079     // distribution) specifically from the ssg tux example
1080     //
1081
1082     // ssgModelPath( "/stage/pinky01/src/Libs/plib-1.0.12/examples/ssg/tux/data/" );
1083     // ssgTexturePath( "/stage/pinky01/src/Libs/plib-1.0.12/examples/ssg/tux/data/" );
1084     ssgModelPath( "/h/curt/src/Libs/plib-1.0.12/examples/ssg/tux/data/" );
1085     ssgTexturePath( "/h/curt/src/Libs/plib-1.0.12/examples/ssg/tux/data/" );
1086
1087     scene = new ssgRoot;
1088     terrain = new ssgBranch;
1089     terrain->setName( "Terrain" );
1090     penguin = new ssgTransform;
1091
1092     ssgEntity *tux_obj = ssgLoadAC( "tuxedo.ac" );
1093     penguin->addKid( tux_obj );
1094     ssgFlatten( tux_obj );
1095     ssgStripify( penguin );
1096
1097     scene->addKid( terrain );
1098     scene->addKid( penguin );
1099
1100     // pass control off to the master GLUT event handler
1101     glutMainLoop();
1102
1103     // we never actually get here ... but to avoid compiler warnings,
1104     // etc.
1105     return 0;
1106 }