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