1 // main.cxx -- top level sim routines
3 // Written by Curtis Olson for OpenGL, started May 1997.
5 // Copyright (C) 1997 - 1999 Curtis L. Olson - curt@flightgear.org
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.
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.
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.
24 #define MICHAEL_JOHNSON_EXPERIMENTAL_ENGINE_AUDIO
31 #ifdef FG_MATH_EXCEPTION_CLASH
50 #ifdef HAVE_SYS_STAT_H
51 # include <sys/stat.h> /* for stat() */
55 # include <unistd.h> /* for stat() */
58 #include <pu.h> // plib include
59 #include <ssg.h> // plib include
61 #ifdef ENABLE_AUDIO_SUPPORT
62 # include <sl.h> // plib include
63 # include <sm.h> // plib include
66 #include <Include/fg_constants.h> // for VERSION
67 #include <Include/general.hxx>
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>
75 #include <Autopilot/autopilot.hxx>
76 #include <Cockpit/cockpit.hxx>
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>
85 #include <Network/network.h>
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>
95 #ifndef FG_OLD_WEATHER
96 # include <WeatherCM/FGLocalWeatherDatabase.h>
98 # include <Weather/weather.hxx>
101 #include "fg_init.hxx"
102 #include "keyboard.hxx"
103 #include "options.hxx"
104 #include "splash.hxx"
106 #include "fg_serial.hxx"
109 // -dw- use custom sioux settings so I can see output window
112 # include <sioux.h> // settings for output window
114 # include <console.h>
118 // This is a record containing a bit of global housekeeping information
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 static int global_multi_loop;
130 // Global structures for the Audio library
131 #ifdef ENABLE_AUDIO_SUPPORT
132 slEnvelope pitch_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
133 slEnvelope volume_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
134 slScheduler *audio_sched;
135 smMixer *audio_mixer;
142 ssgRoot *scene = NULL;
143 ssgBranch *terrain = NULL;
144 ssgSelector *penguin_sel = NULL;
145 ssgTransform *penguin_pos = NULL;
147 // current fdm/position used for view
148 FGInterface cur_view_fdm;
151 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
153 { 1.0f, 0.0f, 0.0f, 0.0f },
154 { 0.0f, 0.0f, -1.0f, 0.0f },
155 { 0.0f, 1.0f, 0.0f, 0.0f },
156 { 0.0f, 0.0f, 0.0f, 1.0f }
159 // The following defines flight gear options. Because glutlib will also
160 // want to parse its own options, those options must not be included here
161 // or they will get parsed by the main program option parser. Hence case
162 // is significant for any option added that might be in conflict with
165 // glutlib parses for:
167 // -direct (invalid in Win32)
171 // -indirect (invalid in Win32)
174 // Note that glutlib depends upon strings while this program's
175 // option parser wants only initial characters followed by numbers
180 // fgInitVisuals() -- Initialize various GL/view parameters
181 void fgInitVisuals( void ) {
184 l = &cur_light_params;
186 #ifndef GLUT_WRONG_VERSION
187 // Go full screen if requested ...
188 if ( current_options.get_fullscreen() ) {
193 // If enabled, normal vectors specified with glNormal are scaled
194 // to unit length after transformation. See glNormal.
195 // xglEnable( GL_NORMALIZE );
197 xglEnable( GL_LIGHTING );
198 xglEnable( GL_LIGHT0 );
199 xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
202 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
203 ssgGetLight( 0 ) -> setPosition( sunpos );
205 // xglFogi (GL_FOG_MODE, GL_LINEAR);
206 xglFogi (GL_FOG_MODE, GL_EXP2);
207 if ( (current_options.get_fog() == 1) ||
208 (current_options.get_shading() == 0) ) {
209 // if fastest fog requested, or if flat shading force fastest
210 xglHint ( GL_FOG_HINT, GL_FASTEST );
211 } else if ( current_options.get_fog() == 2 ) {
212 xglHint ( GL_FOG_HINT, GL_NICEST );
214 if ( current_options.get_wireframe() ) {
216 xglPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
219 // This is the default anyways, but it can't hurt
220 xglFrontFace ( GL_CCW );
223 // xglEnable(GL_POINT_SMOOTH);
224 // xglEnable(GL_LINE_SMOOTH);
225 // xglEnable(GL_POLYGON_SMOOTH);
229 // Update all Visuals (redraws anything graphics related)
230 void fgRenderFrame( void ) {
231 fgLIGHT *l = &cur_light_params;
232 FGTime *t = FGTime::cur_time_params;
233 // FGView *v = ¤t_view;
234 static double last_visibility = -9999;
235 static bool in_puff = false;
236 static double puff_length = 0;
237 static double puff_progression = 0;
238 const double ramp_up = 0.15;
239 const double ramp_down = 0.15;
242 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
243 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
244 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
245 // GLfloat mat_shininess[] = { 10.0 };
246 GLbitfield clear_mask;
248 if ( idle_state != 1000 ) {
249 // still initializing, draw the splash screen
250 if ( current_options.get_splash_screen() == 1 ) {
254 // idle_state is now 1000 meaning we've finished all our
255 // initializations and are running the main loop, so this will
256 // now work without seg faulting the system.
258 // printf("Ground = %.2f Altitude = %.2f\n", scenery.cur_elev,
259 // FG_Altitude * FEET_TO_METER);
261 // this is just a temporary hack, to make me understand Pui
262 // timerText -> setLabel (ctime (&t->cur_time));
265 // update view volume parameters
266 // cout << "before pilot_view update" << endl;
267 pilot_view.UpdateViewParams(*cur_fdm_state);
268 // cout << "after pilot_view update" << endl;
269 current_view.UpdateViewParams(cur_view_fdm);
271 // set the sun position
272 xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
274 clear_mask = GL_DEPTH_BUFFER_BIT;
275 if ( current_options.get_wireframe() ) {
276 clear_mask |= GL_COLOR_BUFFER_BIT;
278 if ( current_options.get_panel_status() ) {
279 // we can't clear the screen when the panel is active
280 } else if ( current_options.get_skyblend() ) {
281 if ( current_options.get_textures() ) {
282 // glClearColor(black[0], black[1], black[2], black[3]);
283 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
284 l->adj_fog_color[2], l->adj_fog_color[3]);
285 clear_mask |= GL_COLOR_BUFFER_BIT;
288 glClearColor(l->sky_color[0], l->sky_color[1],
289 l->sky_color[2], l->sky_color[3]);
290 clear_mask |= GL_COLOR_BUFFER_BIT;
292 xglClear( clear_mask );
294 // Tell GL we are switching to model view parameters
296 // I really should create a derived ssg node or use a call
297 // back or something so that I can draw the sky within the
298 // ssgCullandDraw() function, but for now I just mimic what
299 // ssg does to set up the model view matrix
300 xglMatrixMode(GL_MODELVIEW);
302 sgMat4 vm_tmp, view_mat;
303 sgTransposeNegateMat4 ( vm_tmp, current_view.VIEW ) ;
304 sgCopyMat4( view_mat, copy_of_ssgOpenGLAxisSwapMatrix ) ;
305 sgPreMultMat4( view_mat, vm_tmp ) ;
306 xglLoadMatrixf( (float *)view_mat );
309 xglDisable( GL_DEPTH_TEST );
310 xglDisable( GL_LIGHTING );
311 xglDisable( GL_CULL_FACE );
312 xglDisable( GL_FOG );
313 xglShadeModel( GL_SMOOTH );
314 if ( current_options.get_skyblend() ) {
318 // setup transformation for drawing astronomical objects
320 // Translate to view position
321 Point3D view_pos = current_view.get_view_pos();
322 xglTranslatef( view_pos.x(), view_pos.y(), view_pos.z() );
323 // Rotate based on gst (sidereal time)
324 // note: constant should be 15.041085, Curt thought it was 15
325 angle = t->getGst() * 15.041085;
326 // printf("Rotating astro objects by %.2f degrees\n",angle);
327 xglRotatef( angle, 0.0, 0.0, -1.0 );
329 // draw stars and planets
331 xglDisable( GL_COLOR_MATERIAL ); // just to make sure ...
332 xglEnable( GL_CULL_FACE ); // for moon
333 xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
334 //xglEnable(GL_DEPTH_TEST);
335 SolarSystem::theSolarSystem->draw();
336 // reset blending function
337 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
342 if ( current_options.get_shading() ) {
343 xglShadeModel( GL_SMOOTH );
345 xglShadeModel( GL_FLAT );
347 xglEnable( GL_DEPTH_TEST );
348 if ( current_options.get_fog() > 0 ) {
350 xglFogi( GL_FOG_MODE, GL_EXP2 );
351 xglFogfv( GL_FOG_COLOR, l->adj_fog_color );
354 // update fog params if visibility has changed
355 double cur_visibility = WeatherDatabase->getWeatherVisibility();
356 double actual_visibility = cur_visibility;
358 if ( current_options.get_clouds() ) {
359 double diff = fabs( cur_fdm_state->get_Altitude() * FEET_TO_METER -
360 current_options.get_clouds_asl() );
361 // cout << "altitude diff = " << diff << endl;
364 // calc chance of entering cloud puff
365 double rnd = fg_random();
366 double chance = rnd * rnd * rnd;
367 if ( chance > 0.95 /* * (diff - 25) / 50.0 */ ) {
370 puff_length = fg_random() * 2.0; // up to 2 seconds
371 } while ( puff_length <= 0.0 );
372 puff_progression = 0.0;
376 actual_visibility = cur_visibility * (diff - 25) / 50.0;
379 // modify actual_visibility based on puff envelope
381 if ( puff_progression <= ramp_up ) {
382 double x = FG_PI_2 * puff_progression / ramp_up;
383 double factor = 1.0 - sin( x );
384 actual_visibility = actual_visibility * factor;
385 } else if ( puff_progression >= ramp_up + puff_length ) {
387 (puff_progression - (ramp_up + puff_length)) /
389 double factor = sin( x );
390 actual_visibility = actual_visibility * factor;
392 actual_visibility = 0.0;
395 /* cout << "len = " << puff_length
397 << " factor = " << factor
398 << " actual_visibility = " << actual_visibility
401 puff_progression += ( global_multi_loop *
402 current_options.get_speed_up() ) /
403 (double)current_options.get_model_hz();
405 /* cout << "gml = " << global_multi_loop
406 << " speed up = " << current_options.get_speed_up()
407 << " hz = " << current_options.get_model_hz() << endl;
410 if ( puff_progression > puff_length + ramp_up + ramp_down) {
415 // never let visibility drop below zero
416 if ( actual_visibility < 0 ) {
417 actual_visibility = 0;
422 // cout << "actual visibility = " << actual_visibility << endl;
424 if ( actual_visibility != last_visibility ) {
425 last_visibility = actual_visibility;
427 // cout << "----> updating fog params" << endl;
429 GLfloat fog_exp_density;
430 GLfloat fog_exp2_density;
433 fog_exp_density = -log(0.01 / actual_visibility);
436 fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
438 // Set correct opengl fog density
439 xglFogf (GL_FOG_DENSITY, fog_exp2_density);
442 // set lighting parameters
443 xglLightfv( GL_LIGHT0, GL_AMBIENT, l->scene_ambient );
444 xglLightfv( GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
445 // xglLightfv(GL_LIGHT0, GL_SPECULAR, white );
447 // texture parameters
448 xglEnable( GL_TEXTURE_2D );
449 xglTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
450 xglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
451 // set base color (I don't think this is doing anything here)
452 // xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
453 // (GL_FRONT, GL_DIFFUSE, white);
454 // xglMaterialfv (GL_FRONT, GL_SPECULAR, white);
455 // xglMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
458 if ( current_options.get_textures() ) {
459 // texture parameters
460 xglEnable( GL_TEXTURE_2D );
461 xglTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
462 xglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
463 // set base color (I don't think this is doing anything here)
464 xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
465 xglMaterialfv (GL_FRONT, GL_DIFFUSE, white);
466 // xglMaterialfv (GL_FRONT, GL_SPECULAR, white);
467 // xglMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
469 xglDisable( GL_TEXTURE_2D );
470 xglMaterialfv (GL_FRONT, GL_AMBIENT, terrain_color);
471 xglMaterialfv (GL_FRONT, GL_DIFFUSE, terrain_color);
472 // xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
473 // xglMaterialfv (GL_FRONT, GL_DIFFUSE, white);
478 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
479 ssgGetLight( 0 ) -> setPosition( sunpos );
481 // xglMatrixMode( GL_PROJECTION );
482 // xglLoadIdentity();
483 float fov = current_options.get_fov();
484 ssgSetFOV(fov * current_view.get_win_ratio(), fov);
486 double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
489 // FG_LOG( FG_ALL, FG_INFO, "visibility is "
490 // << current_weather.get_visibility() );
493 ssgSetNearFar( 10.0f, 100000.0f );
495 ssgSetNearFar( 0.5f, 100000.0f );
498 if ( current_options.get_view_mode() ==
499 fgOPTIONS::FG_VIEW_PILOT )
502 penguin_sel->select(0);
503 } else if ( current_options.get_view_mode() ==
504 fgOPTIONS::FG_VIEW_FOLLOW )
506 // select view matrix from front of view matrix queue
507 // FGMat4Wrapper tmp = current_view.follow.front();
508 // sgCopyMat4( sgVIEW, tmp.m );
510 // enable TuX and set up his position and orientation
511 penguin_sel->select(1);
514 sgMakeTransMat4( sgTRANS,
515 pilot_view.view_pos.x(),
516 pilot_view.view_pos.y(),
517 pilot_view.view_pos.z() );
520 sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
523 sgMakeRotMat4( sgROT, -90.0, ownship_up );
527 sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
528 sgMultMat4( sgTUX, sgTMP, sgTRANS );
531 sgSetCoord( &tuxpos, sgTUX );
532 penguin_pos->setTransform( &tuxpos );
535 ssgSetCamera( current_view.VIEW );
537 // position tile nodes and update range selectors
538 global_tile_mgr.prep_ssg_nodes();
540 // force the default state so ssg can get back on track if
541 // we've changed things elsewhere
542 FGMaterialSlot m_slot;
543 FGMaterialSlot *m_ptr = &m_slot;
544 if ( material_mgr.find( "Default", m_ptr ) ) {
545 m_ptr->get_state()->force();
548 // draw the ssg scene
549 ssgCullAndDraw( scene );
551 xglDisable( GL_TEXTURE_2D );
552 xglDisable( GL_FOG );
554 // display HUD && Panel
555 xglDisable( GL_CULL_FACE );
558 // We can do translucent menus, so why not. :-)
559 xglEnable ( GL_BLEND ) ;
560 xglBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
562 xglDisable ( GL_BLEND ) ;
571 // Update internal time dependent calculations (i.e. flight model)
572 void fgUpdateTimeDepCalcs(int multi_loop, int remainder) {
573 static fdm_state_list fdm_list;
574 // FGInterface fdm_state;
575 fgLIGHT *l = &cur_light_params;
576 FGTime *t = FGTime::cur_time_params;
577 // FGView *v = ¤t_view;
580 // update the flight model
581 if ( multi_loop < 0 ) {
585 if ( !t->getPause() ) {
586 // run Autopilot system
589 // printf("updating flight model x %d\n", multi_loop);
590 /* fgFDMUpdate( current_options.get_flight_model(),
592 multi_loop * current_options.get_speed_up(),
594 cur_fdm_state->update( multi_loop * current_options.get_speed_up() );
596 // fgFDMUpdate( current_options.get_flight_model(),
597 // fdm_state, 0, remainder );
598 cur_fdm_state->update( 0 );
601 fdm_list.push_back( *cur_fdm_state );
602 while ( fdm_list.size() > 15 ) {
603 fdm_list.pop_front();
606 if ( current_options.get_view_mode() == fgOPTIONS::FG_VIEW_PILOT ) {
607 cur_view_fdm = *cur_fdm_state;
609 } else if ( current_options.get_view_mode() == fgOPTIONS::FG_VIEW_FOLLOW ) {
610 cur_view_fdm = fdm_list.front();
613 // update the view angle
614 for ( i = 0; i < multi_loop; i++ ) {
615 if ( fabs(current_view.get_goal_view_offset() -
616 current_view.get_view_offset()) < 0.05 )
618 current_view.set_view_offset( current_view.get_goal_view_offset() );
621 // move current_view.view_offset towards current_view.goal_view_offset
622 if ( current_view.get_goal_view_offset() >
623 current_view.get_view_offset() )
625 if ( current_view.get_goal_view_offset() -
626 current_view.get_view_offset() < FG_PI )
628 current_view.inc_view_offset( 0.01 );
630 current_view.inc_view_offset( -0.01 );
633 if ( current_view.get_view_offset() -
634 current_view.get_goal_view_offset() < FG_PI )
636 current_view.inc_view_offset( -0.01 );
638 current_view.inc_view_offset( 0.01 );
641 if ( current_view.get_view_offset() > FG_2PI ) {
642 current_view.inc_view_offset( -FG_2PI );
643 } else if ( current_view.get_view_offset() < 0 ) {
644 current_view.inc_view_offset( FG_2PI );
649 double tmp = -(l->sun_rotation + FG_PI)
650 - (cur_fdm_state->get_Psi() - current_view.get_view_offset() );
651 while ( tmp < 0.0 ) {
654 while ( tmp > FG_2PI ) {
657 /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
658 FG_Psi * RAD_TO_DEG, current_view.view_offset * RAD_TO_DEG,
659 -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
664 void fgInitTimeDepCalcs( void ) {
667 // #ifdef HAVE_SETITIMER
668 // fgTimerInit( 1.0 / current_options.get_model_hz(),
669 // fgUpdateTimeDepCalcs );
670 // #endif HAVE_SETITIMER
674 static const double alt_adjust_ft = 3.758099;
675 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
678 // What should we do when we have nothing else to do? Let's get ready
679 // for the next move and update the display?
680 static void fgMainLoop( void ) {
682 static long remainder = 0;
684 #ifdef FANCY_FRAME_COUNTER
688 static time_t last_time = 0;
689 static int frames = 0;
690 #endif // FANCY_FRAME_COUNTER
692 t = FGTime::cur_time_params;
694 FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
695 FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
697 #if defined( ENABLE_PLIB_JOYSTICK )
698 // Read joystick and update control settings
699 if ( current_options.get_control_mode() == fgOPTIONS::FG_JOYSTICK ) {
702 #elif defined( ENABLE_GLUT_JOYSTICK )
703 // Glut joystick support works by feeding a joystick handler
704 // function to glut. This is taken care of once in the joystick
705 // init routine and we don't have to worry about it again.
708 #ifdef FG_OLD_WEATHER
709 current_weather.Update();
712 // Fix elevation. I'm just sticking this here for now, it should
713 // probably move eventually
715 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
717 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
718 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
720 if ( scenery.cur_elev > -9990 ) {
721 if ( cur_fdm_state->get_Altitude() * FEET_TO_METER <
722 (scenery.cur_elev + alt_adjust_m - 3.0) ) {
723 // now set aircraft altitude above ground
724 printf("Current Altitude = %.2f < %.2f forcing to %.2f\n",
725 cur_fdm_state->get_Altitude() * FEET_TO_METER,
726 scenery.cur_elev + alt_adjust_m - 3.0,
727 scenery.cur_elev + alt_adjust_m );
728 fgFDMForceAltitude( current_options.get_flight_model(),
729 scenery.cur_elev + alt_adjust_m );
731 FG_LOG( FG_ALL, FG_DEBUG,
732 "<*> resetting altitude to "
733 << cur_fdm_state->get_Altitude() * FEET_TO_METER << " meters" );
735 fgFDMSetGroundElevation( current_options.get_flight_model(),
736 scenery.cur_elev ); // meters
739 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
741 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
742 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
745 t->update(*cur_fdm_state);
747 // Get elapsed time (in usec) for this past frame
748 elapsed = fgGetTimeInterval();
749 FG_LOG( FG_ALL, FG_DEBUG,
750 "Elapsed time interval is = " << elapsed
751 << ", previous remainder is = " << remainder );
753 // Calculate frame rate average
754 #ifdef FANCY_FRAME_COUNTER
755 /* old fps calculation */
759 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
760 tmp = general.get_frame(i);
762 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
763 general.set_frame(i+1,tmp);
765 tmp = 1000000.0 / (float)elapsed;
766 general.set_frame(0,tmp);
767 // printf("frame[0] = %.2f\n", general.frames[0]);
769 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
770 // printf("ave = %.2f\n", general.frame_rate);
773 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
774 general.set_frame_rate( frames );
775 FG_LOG( FG_ALL, FG_DEBUG,
776 "--> Frame rate is = " << general.get_frame_rate() );
779 last_time = t->get_cur_time();
784 if ( ! use_signals ) {
785 // Calculate model iterations needed for next frame
786 elapsed += remainder;
788 global_multi_loop = (int)(((double)elapsed * 0.000001) *
789 current_options.get_model_hz());
790 remainder = elapsed - ( (global_multi_loop*1000000) /
791 current_options.get_model_hz() );
792 FG_LOG( FG_ALL, FG_DEBUG,
793 "Model iterations needed = " << global_multi_loop
794 << ", new remainder = " << remainder );
797 if ( global_multi_loop > 0 ) {
798 fgUpdateTimeDepCalcs(global_multi_loop, remainder);
800 FG_LOG( FG_ALL, FG_DEBUG,
801 "Elapsed time is zero ... we're zinging" );
805 #if ! defined( MACOS )
806 // Do any serial port work that might need to be done
810 // see if we need to load any new scenery tiles
811 global_tile_mgr.update();
813 // Process/manage pending events
814 global_events.Process();
816 // Run audio scheduler
817 #ifdef ENABLE_AUDIO_SUPPORT
818 if ( current_options.get_sound() && !audio_sched->not_working() ) {
820 # ifdef MICHAEL_JOHNSON_EXPERIMENTAL_ENGINE_AUDIO
822 // note: all these factors are relative to the sample. our
823 // sample format should really contain a conversion factor so
824 // that we can get prop speed right for arbitrary samples.
825 // Note that for normal-size props, there is a point at which
826 // the prop tips approach the speed of sound; that is a pretty
827 // strong limit to how fast the prop can go.
829 // multiplication factor is prime pitch control; add some log
830 // component for verisimilitude
832 double pitch = log((controls.get_throttle(0) * 14.0) + 1.0);
833 //fprintf(stderr, "pitch1: %f ", pitch);
834 if (controls.get_throttle(0) > 0.0 || cur_fdm_state->v_rel_wind > 40.0) {
835 //fprintf(stderr, "rel_wind: %f ", cur_fdm_state->v_rel_wind);
836 // only add relative wind and AoA if prop is moving
837 // or we're really flying at idle throttle
838 if (pitch < 5.4) { // this needs tuning
839 // prop tips not breaking sound barrier
840 pitch += log(cur_fdm_state->v_rel_wind + 0.8)/2;
842 // prop tips breaking sound barrier
843 pitch += log(cur_fdm_state->v_rel_wind + 0.8)/10;
845 //fprintf(stderr, "pitch2: %f ", pitch);
846 //fprintf(stderr, "AoA: %f ", FG_Gamma_vert_rad);
848 // Angle of Attack next... -x^3(e^x) is my best guess Just
849 // need to calculate some reasonable scaling factor and
850 // then clamp it on the positive aoa (neg adj) side
851 double aoa = cur_fdm_state->get_Gamma_vert_rad() * 2.2;
853 double aoa_adj = pow(-aoa, tmp) * pow(M_E, aoa);
854 if (aoa_adj < -0.8) aoa_adj = -0.8;
856 //fprintf(stderr, "pitch3: %f ", pitch);
858 // don't run at absurdly slow rates -- not realistic
859 // and sounds bad to boot. :-)
860 if (pitch < 0.8) pitch = 0.8;
862 //fprintf(stderr, "pitch4: %f\n", pitch);
864 double volume = controls.get_throttle(0) * 1.15 + 0.3 +
865 log(cur_fdm_state->v_rel_wind + 1.0)/14.0;
866 // fprintf(stderr, "volume: %f\n", volume);
868 pitch_envelope.setStep ( 0, 0.01, pitch );
869 volume_envelope.setStep ( 0, 0.01, volume );
873 double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
874 pitch_envelope.setStep ( 0, 0.01, param );
875 volume_envelope.setStep ( 0, 0.01, param );
877 # endif // experimental throttle patch
879 audio_sched -> update();
886 FG_LOG( FG_ALL, FG_DEBUG, "" );
890 // This is the top level master main function that is registered as
894 // The first few passes take care of initialization things (a couple
895 // per pass) and once everything has been initialized fgMainLoop from
898 static void fgIdleFunction ( void ) {
899 // printf("idle state == %d\n", idle_state);
901 if ( idle_state == 0 ) {
902 // Initialize the splash screen right away
903 if ( current_options.get_splash_screen() ) {
908 } else if ( idle_state == 1 ) {
909 // Start the intro music
911 if ( current_options.get_intro_music() ) {
912 string lockfile = "/tmp/mpg123.running";
913 FGPath mp3file( current_options.get_fg_root() );
914 mp3file.append( "Sounds/intro.mp3" );
916 string command = "(touch " + lockfile + "; mpg123 "
917 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
919 FG_LOG( FG_GENERAL, FG_INFO,
920 "Starting intro music: " << mp3file.str() );
921 system ( command.c_str() );
926 } else if ( idle_state == 2 ) {
927 // These are a few miscellaneous things that aren't really
928 // "subsystems" but still need to be initialized.
931 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
932 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
937 } else if ( idle_state == 3 ) {
938 // This is the top level init routine which calls all the
939 // other subsystem initialization routines. If you are adding
940 // a subsystem to flight gear, its initialization call should
941 // located in this routine.
942 if( !fgInitSubsystems()) {
943 FG_LOG( FG_GENERAL, FG_ALERT,
944 "Subsystem initializations failed ..." );
949 } else if ( idle_state == 4 ) {
950 // setup OpenGL view parameters
954 // init timer routines, signals, etc. Arrange for an alarm
955 // signal to be generated, etc.
956 fgInitTimeDepCalcs();
960 } else if ( idle_state == 5 ) {
963 } else if ( idle_state == 6 ) {
964 // Initialize audio support
965 #ifdef ENABLE_AUDIO_SUPPORT
968 if ( current_options.get_intro_music() ) {
969 // Let's wait for mpg123 to finish
970 string lockfile = "/tmp/mpg123.running";
971 struct stat stat_buf;
973 FG_LOG( FG_GENERAL, FG_INFO,
974 "Waiting for mpg123 player to finish ..." );
975 while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
976 // file exist, wait ...
978 FG_LOG( FG_GENERAL, FG_INFO, ".");
980 FG_LOG( FG_GENERAL, FG_INFO, "");
984 audio_sched = new slScheduler ( 8000 );
985 audio_mixer = new smMixer;
986 audio_mixer -> setMasterVolume ( 80 ) ; /* 80% of max volume. */
987 audio_sched -> setSafetyMargin ( 1.0 ) ;
989 FGPath slfile( current_options.get_fg_root() );
990 slfile.append( "Sounds/wasp.wav" );
992 s1 = new slSample ( (char *)slfile.c_str() );
993 FG_LOG( FG_GENERAL, FG_INFO,
994 "Rate = " << s1 -> getRate()
995 << " Bps = " << s1 -> getBps()
996 << " Stereo = " << s1 -> getStereo() );
997 audio_sched -> loopSample ( s1 );
999 if ( audio_sched->not_working() ) {
1002 pitch_envelope.setStep ( 0, 0.01, 0.6 );
1003 volume_envelope.setStep ( 0, 0.01, 0.6 );
1005 audio_sched -> addSampleEnvelope( s1, 0, 0,
1007 SL_PITCH_ENVELOPE );
1008 audio_sched -> addSampleEnvelope( s1, 0, 1,
1010 SL_VOLUME_ENVELOPE );
1013 // strcpy(slfile, path);
1014 // strcat(slfile, "thunder.wav");
1015 // s2 -> loadFile ( slfile );
1016 // s2 -> adjustVolume(0.5);
1017 // audio_sched -> playSample ( s2 );
1024 if ( idle_state == 1000 ) {
1025 // We've finished all our initialization steps, from now on we
1026 // run the main loop.
1030 if ( current_options.get_splash_screen() == 1 ) {
1031 fgSplashUpdate(0.0);
1036 // options.cxx needs to see this for toggle_panel()
1037 // Handle new window size or exposure
1038 void fgReshape( int width, int height ) {
1039 if ( ! current_options.get_panel_status() ) {
1040 current_view.set_win_ratio( (GLfloat) width / (GLfloat) height );
1041 xglViewport(0, 0 , (GLint)(width), (GLint)(height) );
1043 current_view.set_win_ratio( (GLfloat) width /
1044 ((GLfloat) (height)*0.4232) );
1045 xglViewport(0, (GLint)((height)*0.5768), (GLint)(width),
1046 (GLint)((height)*0.4232) );
1049 current_view.set_winWidth( width );
1050 current_view.set_winHeight( height );
1051 current_view.force_update_fov_math();
1053 // set these fov to be the same as in fgRenderFrame()
1054 float x_fov = current_options.get_fov();
1055 float y_fov = x_fov * 1.0 / current_view.get_win_ratio();
1056 ssgSetFOV( x_fov, y_fov );
1058 glViewport ( 0, 0, width, height );
1059 float fov = current_options.get_fov();
1060 ssgSetFOV(fov * current_view.get_win_ratio(), fov);
1062 if ( idle_state == 1000 ) {
1063 // yes we've finished all our initializations and are running
1064 // the main loop, so this will now work without seg faulting
1066 solarSystemRebuild();
1067 current_view.UpdateViewParams(cur_view_fdm);
1068 if ( current_options.get_panel_status() ) {
1069 FGPanel::OurPanel->ReInit(0, 0, 1024, 768);
1075 // Initialize GLUT and define a main window
1076 int fgGlutInit( int *argc, char **argv ) {
1078 #if !defined( MACOS )
1079 // GLUT will extract all glut specific options so later on we only
1080 // need wory about our own.
1081 xglutInit(argc, argv);
1084 // Define Display Parameters
1085 xglutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1087 FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
1088 current_options.get_xsize() << "x" << current_options.get_ysize() );
1090 // Define initial window size
1091 xglutInitWindowSize( current_options.get_xsize(),
1092 current_options.get_ysize() );
1094 // Initialize windows
1095 if ( current_options.get_game_mode() == 0 ) {
1096 // Open the regular window
1097 xglutCreateWindow("Flight Gear");
1098 #ifndef GLUT_WRONG_VERSION
1100 // Open the cool new 'game mode' window
1101 char game_mode_str[256];
1102 sprintf( game_mode_str, "width=%d height=%d bpp=32",
1103 current_options.get_xsize(),
1104 current_options.get_ysize() );
1106 FG_LOG( FG_GENERAL, FG_INFO,
1107 "game mode params = " << game_mode_str );
1108 glutGameModeString( game_mode_str );
1109 glutEnterGameMode();
1113 // This seems to be the absolute earliest in the init sequence
1114 // that these calls will return valid info. Too bad it's after
1115 // we've already created and sized out window. :-(
1116 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1117 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1118 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1120 FG_LOG ( FG_GENERAL, FG_INFO, general.get_glRenderer() );
1123 // try to determine if we should adjust the initial default
1124 // display resolution. The options class defaults (is
1125 // initialized) to 640x480.
1126 string renderer = general.glRenderer;
1128 // currently we only know how to deal with Mesa/Glide/Voodoo cards
1129 if ( renderer.find( "Glide" ) != string::npos ) {
1130 FG_LOG( FG_GENERAL, FG_INFO, "Detected a Glide driver" );
1131 if ( renderer.find( "FB/8" ) != string::npos ) {
1132 // probably a voodoo-2
1133 if ( renderer.find( "TMU/SLI" ) != string::npos ) {
1134 // probably two SLI'd Voodoo-2's
1135 current_options.set_xsize( 1024 );
1136 current_options.set_ysize( 768 );
1137 FG_LOG( FG_GENERAL, FG_INFO,
1138 "It looks like you have two sli'd voodoo-2's." << endl
1139 << "upgrading your win resolution to 1024 x 768" );
1140 glutReshapeWindow(1024, 768);
1142 // probably a single non-SLI'd Voodoo-2
1143 current_options.set_xsize( 800 );
1144 current_options.set_ysize( 600 );
1145 FG_LOG( FG_GENERAL, FG_INFO,
1146 "It looks like you have a voodoo-2." << endl
1147 << "upgrading your win resolution to 800 x 600" );
1148 glutReshapeWindow(800, 600);
1150 } else if ( renderer.find( "FB/2" ) != string::npos ) {
1151 // probably a voodoo-1, stick with the default
1154 // we have no special knowledge of this card, stick with the default
1162 // Initialize GLUT event handlers
1163 int fgGlutInitEvents( void ) {
1164 // call fgReshape() on window resizes
1165 xglutReshapeFunc( fgReshape );
1167 // call GLUTkey() on keyboard event
1168 xglutKeyboardFunc( GLUTkey );
1169 glutSpecialFunc( GLUTspecialkey );
1171 // call guiMouseFunc() whenever our little rodent is used
1172 glutMouseFunc ( guiMouseFunc );
1173 glutMotionFunc (guiMotionFunc );
1174 glutPassiveMotionFunc (guiMotionFunc );
1176 // call fgMainLoop() whenever there is
1177 // nothing else to do
1178 xglutIdleFunc( fgIdleFunction );
1181 xglutDisplayFunc( fgRenderFrame );
1188 int main( int argc, char **argv ) {
1190 #if defined( MACOS )
1191 argc = ccommand( &argv );
1195 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1198 // set default log levels
1199 fglog().setLogLevels( FG_ALL, FG_INFO );
1201 FG_LOG( FG_GENERAL, FG_INFO, "Flight Gear: Version " << VERSION << endl );
1203 // seed the random number generater
1206 // Load the configuration parameters
1207 if ( !fgInitConfig(argc, argv) ) {
1208 FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1212 // Initialize the Window/Graphics environment.
1213 if( !fgGlutInit(&argc, argv) ) {
1214 FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1218 // Initialize the various GLUT Event Handlers.
1219 if( !fgGlutInitEvents() ) {
1220 FG_LOG( FG_GENERAL, FG_ALERT,
1221 "GLUT event handler initialization failed ..." );
1225 // Initialize ssg (from plib)
1228 // Initialize the user interface (we need to do this before
1229 // passing off control to glut and before fgInitGeneral to get our
1233 // Do some quick general initializations
1234 if( !fgInitGeneral()) {
1235 FG_LOG( FG_GENERAL, FG_ALERT,
1236 "General initializations failed ..." );
1241 // some ssg test stuff (requires data from the plib source
1242 // distribution) specifically from the ssg tux example
1245 FGPath modelpath( current_options.get_fg_root() );
1246 modelpath.append( "Models" );
1247 modelpath.append( "Geometry" );
1249 FGPath texturepath( current_options.get_fg_root() );
1250 texturepath.append( "Models" );
1251 texturepath.append( "Textures" );
1253 ssgModelPath( (char *)modelpath.c_str() );
1254 ssgTexturePath( (char *)texturepath.c_str() );
1256 scene = new ssgRoot;
1257 terrain = new ssgBranch;
1258 terrain->setName( "Terrain" );
1259 penguin_sel = new ssgSelector;
1260 penguin_pos = new ssgTransform;
1262 ssgEntity *tux_obj = ssgLoadAC( "glider.ac" );
1263 // ssgEntity *tux_obj = ssgLoadAC( "Tower1x.ac" );
1264 penguin_pos->addKid( tux_obj );
1265 penguin_sel->addKid( penguin_pos );
1266 ssgFlatten( tux_obj );
1267 ssgStripify( penguin_sel );
1269 #ifdef FG_NETWORK_OLK
1270 // Do the network intialization
1271 printf("Multipilot mode %s\n", fg_net_init() );
1274 scene->addKid( terrain );
1275 scene->addKid( penguin_sel );
1277 // pass control off to the master GLUT event handler
1280 // we never actually get here ... but to avoid compiler warnings,