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