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