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>
84 #include <Scenery/scenery.hxx>
85 #include <Scenery/tilemgr.hxx>
86 #include <Time/event.hxx>
87 #include <Time/fg_time.hxx>
88 #include <Time/fg_timer.hxx>
89 #include <Time/sunpos.hxx>
90 #include <Weather/weather.hxx>
92 #include "fg_init.hxx"
93 #include "keyboard.hxx"
94 #include "options.hxx"
97 #include "fg_serial.hxx"
100 // -dw- use custom sioux settings so I can see output window
103 # include <sioux.h> // settings for output window
105 # include <console.h>
109 // This is a record containing a bit of global housekeeping information
112 // Specify our current idle function state. This is used to run all
113 // our initializations out of the glutIdleLoop() so that we can get a
114 // splash screen up and running right away.
115 static int idle_state = 0;
120 // Global structures for the Audio library
121 #ifdef ENABLE_AUDIO_SUPPORT
122 slEnvelope pitch_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
123 slEnvelope volume_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
124 slScheduler *audio_sched;
125 smMixer *audio_mixer;
132 ssgRoot *scene = NULL;
133 ssgBranch *terrain = NULL;
134 ssgTransform *penguin = NULL;
137 // The following defines flight gear options. Because glutlib will also
138 // want to parse its own options, those options must not be included here
139 // or they will get parsed by the main program option parser. Hence case
140 // is significant for any option added that might be in conflict with
143 // glutlib parses for:
145 // -direct (invalid in Win32)
149 // -indirect (invalid in Win32)
152 // Note that glutlib depends upon strings while this program's
153 // option parser wants only initial characters followed by numbers
158 // fgInitVisuals() -- Initialize various GL/view parameters
159 static void fgInitVisuals( void ) {
162 l = &cur_light_params;
164 #ifndef GLUT_WRONG_VERSION
165 // Go full screen if requested ...
166 if ( current_options.get_fullscreen() ) {
171 // If enabled, normal vectors specified with glNormal are scaled
172 // to unit length after transformation. See glNormal.
173 // xglEnable( GL_NORMALIZE );
175 xglEnable( GL_LIGHTING );
176 xglEnable( GL_LIGHT0 );
177 xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
180 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
181 ssgGetLight( 0 ) -> setPosition( sunpos );
183 // xglFogi (GL_FOG_MODE, GL_LINEAR);
184 xglFogi (GL_FOG_MODE, GL_EXP2);
185 if ( (current_options.get_fog() == 1) ||
186 (current_options.get_shading() == 0) ) {
187 // if fastest fog requested, or if flat shading force fastest
188 xglHint ( GL_FOG_HINT, GL_FASTEST );
189 } else if ( current_options.get_fog() == 2 ) {
190 xglHint ( GL_FOG_HINT, GL_NICEST );
192 if ( current_options.get_wireframe() ) {
194 xglPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
197 // This is the default anyways, but it can't hurt
198 xglFrontFace ( GL_CCW );
201 // xglEnable(GL_POINT_SMOOTH);
202 // xglEnable(GL_LINE_SMOOTH);
203 // xglEnable(GL_POLYGON_SMOOTH);
208 // Draw a basic instrument panel
209 static void fgUpdateInstrViewParams( void ) {
213 fgVIEW *v = ¤t_view;
215 xglViewport(0, 0 , (GLint)(v->winWidth), (GLint)(v->winHeight) / 2);
217 xglMatrixMode(GL_PROJECTION);
221 gluOrtho2D(0, 640, 0, 480);
222 xglMatrixMode(GL_MODELVIEW);
226 xglColor3f(1.0, 1.0, 1.0);
229 xglDisable(GL_DEPTH_TEST);
230 xglDisable(GL_LIGHTING);
233 xglColor3f (0.5, 0.5, 0.5);
236 xglVertex2f(0.0, 0.00);
237 xglVertex2f(0.0, 480.0);
238 xglVertex2f(640.0,480.0);
239 xglVertex2f(640.0, 0.0);
242 xglRectf(0.0,0.0, 640, 480);
243 xglEnable(GL_DEPTH_TEST);
244 xglEnable(GL_LIGHTING);
245 xglMatrixMode(GL_PROJECTION);
247 xglMatrixMode(GL_MODELVIEW);
253 // Update all Visuals (redraws anything graphics related)
254 static void fgRenderFrame( void ) {
255 fgLIGHT *l = &cur_light_params;
256 FGTime *t = FGTime::cur_time_params;
257 FGView *v = ¤t_view;
260 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
261 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
262 GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
263 // GLfloat mat_shininess[] = { 10.0 };
264 GLbitfield clear_mask;
266 if ( idle_state != 1000 ) {
267 // still initializing, draw the splash screen
268 if ( current_options.get_splash_screen() == 1 ) {
272 // idle_state is now 1000 meaning we've finished all our
273 // initializations and are running the main loop, so this will
274 // now work without seg faulting the system.
276 // printf("Ground = %.2f Altitude = %.2f\n", scenery.cur_elev,
277 // FG_Altitude * FEET_TO_METER);
279 // this is just a temporary hack, to make me understand Pui
280 // timerText -> setLabel (ctime (&t->cur_time));
283 // update view volume parameters
284 v->UpdateViewParams();
286 // set the sun position
287 xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
290 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
291 ssgGetLight( 0 ) -> setPosition( sunpos );
293 clear_mask = GL_DEPTH_BUFFER_BIT;
294 if ( current_options.get_wireframe() ) {
295 clear_mask |= GL_COLOR_BUFFER_BIT;
297 if ( current_options.get_panel_status() ) {
298 // we can't clear the screen when the panel is active
299 } else if ( current_options.get_skyblend() ) {
300 if ( current_options.get_textures() ) {
301 // glClearColor(black[0], black[1], black[2], black[3]);
302 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
303 l->adj_fog_color[2], l->adj_fog_color[3]);
304 clear_mask |= GL_COLOR_BUFFER_BIT;
307 glClearColor(l->sky_color[0], l->sky_color[1],
308 l->sky_color[2], l->sky_color[3]);
309 clear_mask |= GL_COLOR_BUFFER_BIT;
311 xglClear( clear_mask );
313 // Tell GL we are switching to model view parameters
314 xglMatrixMode(GL_MODELVIEW);
315 // xglLoadIdentity();
318 xglDisable( GL_DEPTH_TEST );
319 xglDisable( GL_LIGHTING );
320 xglDisable( GL_CULL_FACE );
321 xglDisable( GL_FOG );
322 xglShadeModel( GL_SMOOTH );
323 if ( current_options.get_skyblend() ) {
327 // setup transformation for drawing astronomical objects
329 // Translate to view position
330 Point3D view_pos = v->get_view_pos();
331 xglTranslatef( view_pos.x(), view_pos.y(), view_pos.z() );
332 // Rotate based on gst (sidereal time)
333 // note: constant should be 15.041085, Curt thought it was 15
334 angle = t->getGst() * 15.041085;
335 // printf("Rotating astro objects by %.2f degrees\n",angle);
336 xglRotatef( angle, 0.0, 0.0, -1.0 );
338 // draw stars and planets
340 xglEnable( GL_CULL_FACE ); // for moon
341 //xglEnable(GL_DEPTH_TEST);
342 SolarSystem::theSolarSystem->draw();
347 if ( current_options.get_shading() ) {
348 xglShadeModel( GL_SMOOTH );
350 xglShadeModel( GL_FLAT );
352 xglEnable( GL_DEPTH_TEST );
353 if ( current_options.get_fog() > 0 ) {
355 xglFogi( GL_FOG_MODE, GL_EXP2 );
356 xglFogfv( GL_FOG_COLOR, l->adj_fog_color );
358 // set lighting parameters
359 xglLightfv( GL_LIGHT0, GL_AMBIENT, l->scene_ambient );
360 xglLightfv( GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
361 // xglLightfv(GL_LIGHT0, GL_SPECULAR, white );
363 if ( current_options.get_textures() ) {
364 // texture parameters
365 xglEnable( GL_TEXTURE_2D );
366 xglTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
367 xglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
368 // set base color (I don't think this is doing anything here)
369 xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
370 xglMaterialfv (GL_FRONT, GL_DIFFUSE, white);
371 // xglMaterialfv (GL_FRONT, GL_SPECULAR, white);
372 // xglMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
374 xglDisable( GL_TEXTURE_2D );
375 xglMaterialfv (GL_FRONT, GL_AMBIENT, terrain_color);
376 xglMaterialfv (GL_FRONT, GL_DIFFUSE, terrain_color);
377 // xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
378 // xglMaterialfv (GL_FRONT, GL_DIFFUSE, white);
381 // global_tile_mgr.render();
385 xglMatrixMode( GL_PROJECTION );
387 ssgSetFOV( current_options.get_fov(), 0.0f );
389 double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
392 // FG_LOG( FG_ALL, FG_INFO, "visibility is "
393 // << current_weather.get_visibility() );
396 // ssgSetNearFar( 10.0f, current_weather.get_visibility() );
397 ssgSetNearFar( 10.0f, 100000.0f );
399 // ssgSetNearFar( 0.5f, current_weather.get_visibility() );
400 ssgSetNearFar( 0.5f, 100000.0f );
404 sgMakeTransMat4( sgTRANS,
405 current_view.view_pos.x(),
406 current_view.view_pos.y(),
407 current_view.view_pos.z() );
411 // sgMultMat4( sgTMP, current_view.sgUP, sgTRANS );
412 // sgMultMat4( sgTUX, current_view.sgLARC_TO_SSG, sgTMP );
413 sgMultMat4( sgTUX, current_view.sgVIEW_ROT, sgTRANS );
416 sgSetCoord( &tuxpos, sgTUX );
417 penguin->setTransform( &tuxpos );
419 sgMakeTransMat4( sgTRANS,
420 current_view.view_pos.x(),
421 current_view.view_pos.y(),
422 current_view.view_pos.z() );
425 if ( current_view.view_mode == FGView::FG_VIEW_FIRST_PERSON ) {
426 sgCopyMat4( sgVIEW, current_view.sgVIEW );
427 } else if ( current_view.view_mode == FGView::FG_VIEW_FOLLOW ) {
428 FGMat4Wrapper tmp = current_view.follow.front();
429 sgCopyMat4( sgVIEW, tmp.m );
431 if ( current_view.follow.size() > 15 ) {
432 current_view.follow.pop_front();
435 ssgSetCamera( sgVIEW );
437 global_tile_mgr.prep_ssg_nodes();
438 ssgCullAndDraw( scene );
440 xglDisable( GL_TEXTURE_2D );
441 xglDisable( GL_FOG );
443 // display HUD && Panel
444 xglDisable( GL_CULL_FACE );
447 // We can do translucent menus, so why not. :-)
448 xglEnable ( GL_BLEND ) ;
449 xglBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
451 xglDisable ( GL_BLEND ) ;
460 // Update internal time dependent calculations (i.e. flight model)
461 void fgUpdateTimeDepCalcs(int multi_loop, int remainder) {
462 FGInterface *f = current_aircraft.fdm_state;
463 fgLIGHT *l = &cur_light_params;
464 FGTime *t = FGTime::cur_time_params;
465 FGView *v = ¤t_view;
468 // update the flight model
469 if ( multi_loop < 0 ) {
470 multi_loop = DEFAULT_MULTILOOP;
473 if ( !t->getPause() ) {
474 // run Autopilot system
477 // printf("updating flight model x %d\n", multi_loop);
478 fgFDMUpdate( current_options.get_flight_model(),
479 cur_fdm_state, multi_loop, remainder );
481 fgFDMUpdate( current_options.get_flight_model(),
482 cur_fdm_state, 0, remainder );
485 // update the view angle
486 for ( i = 0; i < multi_loop; i++ ) {
487 if ( fabs(v->get_goal_view_offset() - v->get_view_offset()) < 0.05 ) {
488 v->set_view_offset( v->get_goal_view_offset() );
491 // move v->view_offset towards v->goal_view_offset
492 if ( v->get_goal_view_offset() > v->get_view_offset() ) {
493 if ( v->get_goal_view_offset() - v->get_view_offset() < FG_PI ){
494 v->inc_view_offset( 0.01 );
496 v->inc_view_offset( -0.01 );
499 if ( v->get_view_offset() - v->get_goal_view_offset() < FG_PI ){
500 v->inc_view_offset( -0.01 );
502 v->inc_view_offset( 0.01 );
505 if ( v->get_view_offset() > FG_2PI ) {
506 v->inc_view_offset( -FG_2PI );
507 } else if ( v->get_view_offset() < 0 ) {
508 v->inc_view_offset( FG_2PI );
513 double tmp = -(l->sun_rotation + FG_PI)
514 - (f->get_Psi() - v->get_view_offset() );
515 while ( tmp < 0.0 ) {
518 while ( tmp > FG_2PI ) {
521 /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
522 FG_Psi * RAD_TO_DEG, v->view_offset * RAD_TO_DEG,
523 -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
528 void fgInitTimeDepCalcs( void ) {
531 // #ifdef HAVE_SETITIMER
532 // fgTimerInit( 1.0 / DEFAULT_TIMER_HZ, fgUpdateTimeDepCalcs );
533 // #endif HAVE_SETITIMER
536 static const double alt_adjust_ft = 3.758099;
537 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
539 // What should we do when we have nothing else to do? Let's get ready
540 // for the next move and update the display?
541 static void fgMainLoop( void ) {
544 static long remainder = 0;
545 long elapsed, multi_loop;
546 #ifdef FANCY_FRAME_COUNTER
550 static time_t last_time = 0;
551 static int frames = 0;
552 #endif // FANCY_FRAME_COUNTER
554 f = current_aircraft.fdm_state;
555 t = FGTime::cur_time_params;
557 FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
558 FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
560 #if defined( ENABLE_PLIB_JOYSTICK )
561 // Read joystick and update control settings
563 #elif defined( ENABLE_GLUT_JOYSTICK )
564 // Glut joystick support works by feeding a joystick handler
565 // function to glut. This is taken care of once in the joystick
566 // init routine and we don't have to worry about it again.
569 current_weather.Update();
571 // Fix elevation. I'm just sticking this here for now, it should
572 // probably move eventually
574 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
576 f->get_Runway_altitude() * FEET_TO_METER,
577 f->get_Altitude() * FEET_TO_METER); */
579 if ( scenery.cur_elev > -9990 ) {
580 if ( f->get_Altitude() * FEET_TO_METER <
581 (scenery.cur_elev + alt_adjust_m - 3.0) ) {
582 // now set aircraft altitude above ground
583 printf("Current Altitude = %.2f < %.2f forcing to %.2f\n",
584 f->get_Altitude() * FEET_TO_METER,
585 scenery.cur_elev + alt_adjust_m - 3.0,
586 scenery.cur_elev + alt_adjust_m );
587 fgFDMForceAltitude( current_options.get_flight_model(),
588 scenery.cur_elev + alt_adjust_m );
590 FG_LOG( FG_ALL, FG_DEBUG,
591 "<*> resetting altitude to "
592 << f->get_Altitude() * FEET_TO_METER << " meters" );
594 fgFDMSetGroundElevation( current_options.get_flight_model(),
595 scenery.cur_elev ); // meters
598 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
600 f->get_Runway_altitude() * FEET_TO_METER,
601 f->get_Altitude() * FEET_TO_METER); */
606 // Get elapsed time (in usec) for this past frame
607 elapsed = fgGetTimeInterval();
608 FG_LOG( FG_ALL, FG_DEBUG,
609 "Elapsed time interval is = " << elapsed
610 << ", previous remainder is = " << remainder );
612 // Calculate frame rate average
613 #ifdef FANCY_FRAME_COUNTER
614 /* old fps calculation */
618 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
619 tmp = general.get_frame(i);
621 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
622 general.set_frame(i+1,tmp);
624 tmp = 1000000.0 / (float)elapsed;
625 general.set_frame(0,tmp);
626 // printf("frame[0] = %.2f\n", general.frames[0]);
628 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
629 // printf("ave = %.2f\n", general.frame_rate);
632 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
633 general.set_frame_rate( frames );
634 FG_LOG( FG_ALL, FG_DEBUG,
635 "--> Frame rate is = " << general.get_frame_rate() );
638 last_time = t->get_cur_time();
643 if ( ! use_signals ) {
644 // Calculate model iterations needed for next frame
645 elapsed += remainder;
647 multi_loop = (int)(((double)elapsed * 0.000001) * DEFAULT_MODEL_HZ);
648 remainder = elapsed - ((multi_loop*1000000) / DEFAULT_MODEL_HZ);
649 FG_LOG( FG_ALL, FG_DEBUG,
650 "Model iterations needed = " << multi_loop
651 << ", new remainder = " << remainder );
654 if ( multi_loop > 0 ) {
655 fgUpdateTimeDepCalcs(multi_loop, remainder);
657 FG_LOG( FG_ALL, FG_INFO, "Elapsed time is zero ... we're zinging" );
661 #if ! defined( MACOS )
662 // Do any serial port work that might need to be done
666 // see if we need to load any new scenery tiles
667 global_tile_mgr.update();
669 // Process/manage pending events
670 global_events.Process();
672 // Run audio scheduler
673 #ifdef ENABLE_AUDIO_SUPPORT
674 if ( current_options.get_sound() && !audio_sched->not_working() ) {
676 # ifdef MICHAEL_JOHNSON_EXPERIMENTAL_ENGINE_AUDIO
678 // note: all these factors are relative to the sample. our
679 // sample format should really contain a conversion factor so
680 // that we can get prop speed right for arbitrary samples.
681 // Note that for normal-size props, there is a point at which
682 // the prop tips approach the speed of sound; that is a pretty
683 // strong limit to how fast the prop can go.
685 // multiplication factor is prime pitch control; add some log
686 // component for verisimilitude
688 double pitch = log((controls.get_throttle(0) * 14.0) + 1.0);
689 //fprintf(stderr, "pitch1: %f ", pitch);
690 if (controls.get_throttle(0) > 0.0 || f->v_rel_wind > 40.0) {
691 //fprintf(stderr, "rel_wind: %f ", f->v_rel_wind);
692 // only add relative wind and AoA if prop is moving
693 // or we're really flying at idle throttle
694 if (pitch < 5.4) { // this needs tuning
695 // prop tips not breaking sound barrier
696 pitch += log(f->v_rel_wind + 0.8)/2;
698 // prop tips breaking sound barrier
699 pitch += log(f->v_rel_wind + 0.8)/10;
701 //fprintf(stderr, "pitch2: %f ", pitch);
702 //fprintf(stderr, "AoA: %f ", FG_Gamma_vert_rad);
704 // Angle of Attack next... -x^3(e^x) is my best guess Just
705 // need to calculate some reasonable scaling factor and
706 // then clamp it on the positive aoa (neg adj) side
707 double aoa = f->get_Gamma_vert_rad() * 2.2;
709 double aoa_adj = pow(-aoa, tmp) * pow(M_E, aoa);
710 if (aoa_adj < -0.8) aoa_adj = -0.8;
712 //fprintf(stderr, "pitch3: %f ", pitch);
714 // don't run at absurdly slow rates -- not realistic
715 // and sounds bad to boot. :-)
716 if (pitch < 0.8) pitch = 0.8;
718 //fprintf(stderr, "pitch4: %f\n", pitch);
720 double volume = controls.get_throttle(0) * 1.15 + 0.3 +
721 log(f->v_rel_wind + 1.0)/14.0;
722 // fprintf(stderr, "volume: %f\n", volume);
724 pitch_envelope.setStep ( 0, 0.01, pitch );
725 volume_envelope.setStep ( 0, 0.01, volume );
729 double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
730 pitch_envelope.setStep ( 0, 0.01, param );
731 volume_envelope.setStep ( 0, 0.01, param );
733 # endif // experimental throttle patch
735 audio_sched -> update();
742 FG_LOG( FG_ALL, FG_DEBUG, "" );
746 // This is the top level master main function that is registered as
750 // The first few passes take care of initialization things (a couple
751 // per pass) and once everything has been initialized fgMainLoop from
754 static void fgIdleFunction ( void ) {
755 // printf("idle state == %d\n", idle_state);
757 if ( idle_state == 0 ) {
758 // Initialize the splash screen right away
759 if ( current_options.get_splash_screen() ) {
764 } else if ( idle_state == 1 ) {
765 // Start the intro music
767 if ( current_options.get_intro_music() ) {
768 string lockfile = "/tmp/mpg123.running";
769 FGPath mp3file( current_options.get_fg_root() );
770 mp3file.append( "Sounds/intro.mp3" );
772 string command = "(touch " + lockfile + "; mpg123 "
773 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
775 FG_LOG( FG_GENERAL, FG_INFO,
776 "Starting intro music: " << mp3file.str() );
777 system ( command.c_str() );
782 } else if ( idle_state == 2 ) {
783 // These are a few miscellaneous things that aren't really
784 // "subsystems" but still need to be initialized.
787 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
788 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
793 } else if ( idle_state == 3 ) {
794 // This is the top level init routine which calls all the
795 // other subsystem initialization routines. If you are adding
796 // a subsystem to flight gear, its initialization call should
797 // located in this routine.
798 if( !fgInitSubsystems()) {
799 FG_LOG( FG_GENERAL, FG_ALERT,
800 "Subsystem initializations failed ..." );
805 } else if ( idle_state == 4 ) {
806 // setup OpenGL view parameters
810 // init timer routines, signals, etc. Arrange for an alarm
811 // signal to be generated, etc.
812 fgInitTimeDepCalcs();
816 } else if ( idle_state == 5 ) {
819 } else if ( idle_state == 6 ) {
820 // Initialize audio support
821 #ifdef ENABLE_AUDIO_SUPPORT
824 if ( current_options.get_intro_music() ) {
825 // Let's wait for mpg123 to finish
826 string lockfile = "/tmp/mpg123.running";
827 struct stat stat_buf;
829 FG_LOG( FG_GENERAL, FG_INFO,
830 "Waiting for mpg123 player to finish ..." );
831 while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
832 // file exist, wait ...
834 FG_LOG( FG_GENERAL, FG_INFO, ".");
836 FG_LOG( FG_GENERAL, FG_INFO, "");
840 audio_sched = new slScheduler ( 8000 );
841 audio_mixer = new smMixer;
842 audio_mixer -> setMasterVolume ( 80 ) ; /* 80% of max volume. */
843 audio_sched -> setSafetyMargin ( 1.0 ) ;
845 FGPath slfile( current_options.get_fg_root() );
846 slfile.append( "Sounds/wasp.wav" );
848 s1 = new slSample ( (char *)slfile.c_str() );
849 FG_LOG( FG_GENERAL, FG_INFO,
850 "Rate = " << s1 -> getRate()
851 << " Bps = " << s1 -> getBps()
852 << " Stereo = " << s1 -> getStereo() );
853 audio_sched -> loopSample ( s1 );
855 if ( audio_sched->not_working() ) {
858 pitch_envelope.setStep ( 0, 0.01, 0.6 );
859 volume_envelope.setStep ( 0, 0.01, 0.6 );
861 audio_sched -> addSampleEnvelope( s1, 0, 0, &
864 audio_sched -> addSampleEnvelope( s1, 0, 1,
866 SL_VOLUME_ENVELOPE );
869 // strcpy(slfile, path);
870 // strcat(slfile, "thunder.wav");
871 // s2 -> loadFile ( slfile );
872 // s2 -> adjustVolume(0.5);
873 // audio_sched -> playSample ( s2 );
880 if ( idle_state == 1000 ) {
881 // We've finished all our initialization steps, from now on we
882 // run the main loop.
886 if ( current_options.get_splash_screen() == 1 ) {
892 // options.cxx needs to see this for toggle_panel()
893 // Handle new window size or exposure
894 void fgReshape( int width, int height ) {
895 if ( ! current_options.get_panel_status() ) {
896 current_view.set_win_ratio( (GLfloat) width / (GLfloat) height );
897 xglViewport(0, 0 , (GLint)(width), (GLint)(height) );
899 current_view.set_win_ratio( (GLfloat) width /
900 ((GLfloat) (height)*0.4232) );
901 xglViewport(0, (GLint)((height)*0.5768), (GLint)(width),
902 (GLint)((height)*0.4232) );
905 current_view.set_winWidth( width );
906 current_view.set_winHeight( height );
907 current_view.force_update_fov_math();
909 if ( idle_state == 1000 ) {
910 // yes we've finished all our initializations and are running
911 // the main loop, so this will now work without seg faulting
913 current_view.UpdateViewParams();
914 if ( current_options.get_panel_status() ) {
915 FGPanel::OurPanel->ReInit(0, 0, 1024, 768);
921 // Initialize GLUT and define a main window
922 int fgGlutInit( int *argc, char **argv ) {
924 #if !defined( MACOS )
925 // GLUT will extract all glut specific options so later on we only
926 // need wory about our own.
927 xglutInit(argc, argv);
930 // Define Display Parameters
931 xglutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
933 FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
934 current_options.get_xsize() << "x" << current_options.get_ysize() );
936 // Define initial window size
937 xglutInitWindowSize( current_options.get_xsize(),
938 current_options.get_ysize() );
940 // Initialize windows
941 if ( current_options.get_game_mode() == 0 ) {
942 // Open the regular window
943 xglutCreateWindow("Flight Gear");
944 #ifndef GLUT_WRONG_VERSION
946 // Open the cool new 'game mode' window
947 char game_mode_str[256];
948 sprintf( game_mode_str, "width=%d height=%d bpp=32",
949 current_options.get_xsize(),
950 current_options.get_ysize() );
952 FG_LOG( FG_GENERAL, FG_INFO,
953 "game mode params = " << game_mode_str );
954 glutGameModeString( game_mode_str );
959 // This seems to be the absolute earliest in the init sequence
960 // that these calls will return valid info. Too bad it's after
961 // we've already created and sized out window. :-(
962 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
963 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
964 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
966 FG_LOG ( FG_GENERAL, FG_INFO, general.get_glRenderer() );
969 // try to determine if we should adjust the initial default
970 // display resolution. The options class defaults (is
971 // initialized) to 640x480.
972 string renderer = general.glRenderer;
974 // currently we only know how to deal with Mesa/Glide/Voodoo cards
975 if ( renderer.find( "Glide" ) != string::npos ) {
976 FG_LOG( FG_GENERAL, FG_INFO, "Detected a Glide driver" );
977 if ( renderer.find( "FB/8" ) != string::npos ) {
978 // probably a voodoo-2
979 if ( renderer.find( "TMU/SLI" ) != string::npos ) {
980 // probably two SLI'd Voodoo-2's
981 current_options.set_xsize( 1024 );
982 current_options.set_ysize( 768 );
983 FG_LOG( FG_GENERAL, FG_INFO,
984 "It looks like you have two sli'd voodoo-2's." << endl
985 << "upgrading your win resolution to 1024 x 768" );
986 glutReshapeWindow(1024, 768);
988 // probably a single non-SLI'd Voodoo-2
989 current_options.set_xsize( 800 );
990 current_options.set_ysize( 600 );
991 FG_LOG( FG_GENERAL, FG_INFO,
992 "It looks like you have a voodoo-2." << endl
993 << "upgrading your win resolution to 800 x 600" );
994 glutReshapeWindow(800, 600);
996 } else if ( renderer.find( "FB/2" ) != string::npos ) {
997 // probably a voodoo-1, stick with the default
1000 // we have no special knowledge of this card, stick with the default
1008 // Initialize GLUT event handlers
1009 int fgGlutInitEvents( void ) {
1010 // call fgReshape() on window resizes
1011 xglutReshapeFunc( fgReshape );
1013 // call GLUTkey() on keyboard event
1014 xglutKeyboardFunc( GLUTkey );
1015 glutSpecialFunc( GLUTspecialkey );
1017 // call guiMouseFunc() whenever our little rodent is used
1018 glutMouseFunc ( guiMouseFunc );
1019 glutMotionFunc (guiMotionFunc );
1020 glutPassiveMotionFunc (guiMotionFunc );
1022 // call fgMainLoop() whenever there is
1023 // nothing else to do
1024 xglutIdleFunc( fgIdleFunction );
1027 xglutDisplayFunc( fgRenderFrame );
1034 int main( int argc, char **argv ) {
1036 #if defined( MACOS )
1037 argc = ccommand( &argv );
1041 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1044 // set default log levels
1045 fglog().setLogLevels( FG_ALL, FG_INFO );
1047 FG_LOG( FG_GENERAL, FG_INFO, "Flight Gear: Version " << VERSION << endl );
1049 // seed the random number generater
1052 // Load the configuration parameters
1053 if ( !fgInitConfig(argc, argv) ) {
1054 FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1058 // Initialize the Window/Graphics environment.
1059 if( !fgGlutInit(&argc, argv) ) {
1060 FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1064 // Initialize the various GLUT Event Handlers.
1065 if( !fgGlutInitEvents() ) {
1066 FG_LOG( FG_GENERAL, FG_ALERT,
1067 "GLUT event handler initialization failed ..." );
1071 // Initialize ssg (from plib)
1074 // Initialize the user interface (we need to do this before
1075 // passing off control to glut and before fgInitGeneral to get our
1079 // Do some quick general initializations
1080 if( !fgInitGeneral()) {
1081 FG_LOG( FG_GENERAL, FG_ALERT,
1082 "General initializations failed ..." );
1087 // some ssg test stuff (requires data from the plib source
1088 // distribution) specifically from the ssg tux example
1091 ssgModelPath( "/stage/pinky01/src/Libs/plib-1.0.12/examples/ssg/tux/data/" );
1092 ssgTexturePath( "/stage/pinky01/src/Libs/plib-1.0.12/examples/ssg/tux/data/" );
1093 // ssgModelPath( "/h/curt/src/Libs/plib-1.0.12/examples/ssg/tux/data/" );
1094 // ssgTexturePath( "/h/curt/src/Libs/plib-1.0.12/examples/ssg/tux/data/" );
1096 scene = new ssgRoot;
1097 terrain = new ssgBranch;
1098 terrain->setName( "Terrain" );
1099 penguin = new ssgTransform;
1101 ssgEntity *tux_obj = ssgLoadAC( "tuxedo.ac" );
1102 penguin->addKid( tux_obj );
1103 ssgFlatten( tux_obj );
1104 ssgStripify( penguin );
1106 scene->addKid( terrain );
1107 scene->addKid( penguin );
1109 // pass control off to the master GLUT event handler
1112 // we never actually get here ... but to avoid compiler warnings,