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
41 #include <simgear/xgl.h>
51 #ifdef HAVE_SYS_STAT_H
52 # include <sys/stat.h> /* for stat() */
56 # include <unistd.h> /* for stat() */
59 #include <plib/pu.h> // plib include
60 #include <plib/ssg.h> // plib include
62 #ifdef ENABLE_AUDIO_SUPPORT
63 # include <plib/sl.h> // plib include
64 # include <plib/sm.h> // plib include
67 #include <simgear/constants.h> // for VERSION
68 #include <simgear/logstream.hxx>
69 #include <simgear/fg_geodesy.hxx>
70 #include <simgear/mat3.h>
71 #include <simgear/polar3d.hxx>
72 #include <simgear/fg_random.h>
73 #include <simgear/fgpath.hxx>
75 #include <Include/general.hxx>
77 #include <Aircraft/aircraft.hxx>
78 #include <Astro/sky.hxx>
79 #include <Astro/stars.hxx>
80 #include <Astro/solarsystem.hxx>
82 #include <Autopilot/autopilot.hxx>
83 #include <Cockpit/cockpit.hxx>
85 #include <Joystick/joystick.hxx>
87 #include <NetworkOLK/network.h>
89 #include <Objects/materialmgr.hxx>
90 #include <Scenery/scenery.hxx>
91 #include <Scenery/tilemgr.hxx>
92 #include <Time/event.hxx>
93 #include <Time/fg_time.hxx>
94 #include <Time/fg_timer.hxx>
95 #include <Time/sunpos.hxx>
97 #ifndef FG_OLD_WEATHER
98 # include <WeatherCM/FGLocalWeatherDatabase.h>
100 # include <Weather/weather.hxx>
103 #include "fg_init.hxx"
105 #include "keyboard.hxx"
106 #include "options.hxx"
107 #include "splash.hxx"
111 // -dw- use custom sioux settings so I can see output window
114 # include <sioux.h> // settings for output window
116 # include <console.h>
120 // This is a record containing a bit of global housekeeping information
123 // Specify our current idle function state. This is used to run all
124 // our initializations out of the glutIdleLoop() so that we can get a
125 // splash screen up and running right away.
126 static int idle_state = 0;
127 static int global_multi_loop;
132 // Global structures for the Audio library
133 #ifdef ENABLE_AUDIO_SUPPORT
134 slEnvelope pitch_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
135 slEnvelope volume_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
136 slScheduler *audio_sched;
137 smMixer *audio_mixer;
144 ssgRoot *scene = NULL;
145 ssgBranch *terrain = NULL;
146 ssgSelector *penguin_sel = NULL;
147 ssgTransform *penguin_pos = NULL;
149 #ifdef FG_NETWORK_OLK
150 ssgSelector *fgd_sel = NULL;
151 ssgTransform *fgd_pos = NULL;
155 // current fdm/position used for view
156 FGInterface cur_view_fdm;
159 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
161 { 1.0f, 0.0f, 0.0f, 0.0f },
162 { 0.0f, 0.0f, -1.0f, 0.0f },
163 { 0.0f, 1.0f, 0.0f, 0.0f },
164 { 0.0f, 0.0f, 0.0f, 1.0f }
167 // The following defines flight gear options. Because glutlib will also
168 // want to parse its own options, those options must not be included here
169 // or they will get parsed by the main program option parser. Hence case
170 // is significant for any option added that might be in conflict with
173 // glutlib parses for:
175 // -direct (invalid in Win32)
179 // -indirect (invalid in Win32)
182 // Note that glutlib depends upon strings while this program's
183 // option parser wants only initial characters followed by numbers
188 // fgInitVisuals() -- Initialize various GL/view parameters
189 void fgInitVisuals( void ) {
192 l = &cur_light_params;
194 #ifndef GLUT_WRONG_VERSION
195 // Go full screen if requested ...
196 if ( current_options.get_fullscreen() ) {
201 // If enabled, normal vectors specified with glNormal are scaled
202 // to unit length after transformation. See glNormal.
203 // xglEnable( GL_NORMALIZE );
205 xglEnable( GL_LIGHTING );
206 xglEnable( GL_LIGHT0 );
207 xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
210 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
211 ssgGetLight( 0 ) -> setPosition( sunpos );
213 // xglFogi (GL_FOG_MODE, GL_LINEAR);
214 xglFogi (GL_FOG_MODE, GL_EXP2);
215 if ( (current_options.get_fog() == 1) ||
216 (current_options.get_shading() == 0) ) {
217 // if fastest fog requested, or if flat shading force fastest
218 xglHint ( GL_FOG_HINT, GL_FASTEST );
219 } else if ( current_options.get_fog() == 2 ) {
220 xglHint ( GL_FOG_HINT, GL_NICEST );
222 if ( current_options.get_wireframe() ) {
224 xglPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
227 // This is the default anyways, but it can't hurt
228 xglFrontFace ( GL_CCW );
231 // xglEnable(GL_POINT_SMOOTH);
232 // xglEnable(GL_LINE_SMOOTH);
233 // xglEnable(GL_POLYGON_SMOOTH);
237 // Update all Visuals (redraws anything graphics related)
238 void fgRenderFrame( void ) {
239 fgLIGHT *l = &cur_light_params;
240 FGTime *t = FGTime::cur_time_params;
241 // FGView *v = ¤t_view;
242 static double last_visibility = -9999;
243 static bool in_puff = false;
244 static double puff_length = 0;
245 static double puff_progression = 0;
246 const double ramp_up = 0.15;
247 const double ramp_down = 0.15;
250 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
251 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
252 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
253 // GLfloat mat_shininess[] = { 10.0 };
254 GLbitfield clear_mask;
256 if ( idle_state != 1000 ) {
257 // still initializing, draw the splash screen
258 if ( current_options.get_splash_screen() == 1 ) {
262 // idle_state is now 1000 meaning we've finished all our
263 // initializations and are running the main loop, so this will
264 // now work without seg faulting the system.
266 // printf("Ground = %.2f Altitude = %.2f\n", scenery.cur_elev,
267 // FG_Altitude * FEET_TO_METER);
269 // this is just a temporary hack, to make me understand Pui
270 // timerText -> setLabel (ctime (&t->cur_time));
273 // update view volume parameters
274 // cout << "before pilot_view update" << endl;
275 pilot_view.UpdateViewParams(*cur_fdm_state);
276 // cout << "after pilot_view update" << endl;
277 current_view.UpdateViewParams(cur_view_fdm);
279 // set the sun position
280 xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
282 clear_mask = GL_DEPTH_BUFFER_BIT;
283 if ( current_options.get_wireframe() ) {
284 clear_mask |= GL_COLOR_BUFFER_BIT;
286 if ( current_options.get_panel_status() ) {
287 // we can't clear the screen when the panel is active
288 } else if ( current_options.get_skyblend() ) {
289 if ( current_options.get_textures() ) {
290 // glClearColor(black[0], black[1], black[2], black[3]);
291 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
292 l->adj_fog_color[2], l->adj_fog_color[3]);
293 clear_mask |= GL_COLOR_BUFFER_BIT;
296 glClearColor(l->sky_color[0], l->sky_color[1],
297 l->sky_color[2], l->sky_color[3]);
298 clear_mask |= GL_COLOR_BUFFER_BIT;
300 xglClear( clear_mask );
302 // Tell GL we are switching to model view parameters
304 // I really should create a derived ssg node or use a call
305 // back or something so that I can draw the sky within the
306 // ssgCullandDraw() function, but for now I just mimic what
307 // ssg does to set up the model view matrix
308 xglMatrixMode(GL_MODELVIEW);
310 sgMat4 vm_tmp, view_mat;
311 sgTransposeNegateMat4 ( vm_tmp, current_view.VIEW ) ;
312 sgCopyMat4( view_mat, copy_of_ssgOpenGLAxisSwapMatrix ) ;
313 sgPreMultMat4( view_mat, vm_tmp ) ;
314 xglLoadMatrixf( (float *)view_mat );
317 xglDisable( GL_DEPTH_TEST );
318 xglDisable( GL_LIGHTING );
319 xglDisable( GL_CULL_FACE );
321 xglDisable( GL_FOG );
322 /* if ( current_options.get_fog() > 0 ) {
324 xglFogi( GL_FOG_MODE, GL_EXP2 );
325 xglFogfv( GL_FOG_COLOR, l->adj_fog_color );
328 xglShadeModel( GL_SMOOTH );
329 if ( current_options.get_skyblend() ) {
333 // xglDisable( GL_FOG );
335 // setup transformation for drawing astronomical objects
337 // Translate to view position
338 Point3D view_pos = current_view.get_view_pos();
339 xglTranslatef( view_pos.x(), view_pos.y(), view_pos.z() );
340 // Rotate based on gst (sidereal time)
341 // note: constant should be 15.041085, Curt thought it was 15
342 angle = t->getGst() * 15.041085;
343 // printf("Rotating astro objects by %.2f degrees\n",angle);
344 xglRotatef( angle, 0.0, 0.0, -1.0 );
346 // draw stars and planets
348 xglDisable( GL_COLOR_MATERIAL ); // just to make sure ...
349 xglEnable( GL_CULL_FACE ); // for moon
350 xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
351 //xglEnable(GL_DEPTH_TEST);
352 SolarSystem::theSolarSystem->draw();
353 // reset blending function
354 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
359 if ( current_options.get_shading() ) {
360 xglShadeModel( GL_SMOOTH );
362 xglShadeModel( GL_FLAT );
364 xglEnable( GL_DEPTH_TEST );
365 if ( current_options.get_fog() > 0 ) {
367 xglFogi( GL_FOG_MODE, GL_EXP2 );
368 xglFogfv( GL_FOG_COLOR, l->adj_fog_color );
371 // update fog params if visibility has changed
372 #ifndef FG_OLD_WEATHER
373 double cur_visibility = WeatherDatabase->getWeatherVisibility();
375 double cur_visibility = current_weather.get_visibility();
377 double actual_visibility = cur_visibility;
379 if ( current_options.get_clouds() ) {
380 double diff = fabs( cur_fdm_state->get_Altitude() * FEET_TO_METER -
381 current_options.get_clouds_asl() );
382 // cout << "altitude diff = " << diff << endl;
385 // calc chance of entering cloud puff
386 double rnd = fg_random();
387 double chance = rnd * rnd * rnd;
388 if ( chance > 0.95 /* * (diff - 25) / 50.0 */ ) {
391 puff_length = fg_random() * 2.0; // up to 2 seconds
392 } while ( puff_length <= 0.0 );
393 puff_progression = 0.0;
397 actual_visibility = cur_visibility * (diff - 25) / 50.0;
400 // modify actual_visibility based on puff envelope
402 if ( puff_progression <= ramp_up ) {
403 double x = FG_PI_2 * puff_progression / ramp_up;
404 double factor = 1.0 - sin( x );
405 actual_visibility = actual_visibility * factor;
406 } else if ( puff_progression >= ramp_up + puff_length ) {
408 (puff_progression - (ramp_up + puff_length)) /
410 double factor = sin( x );
411 actual_visibility = actual_visibility * factor;
413 actual_visibility = 0.0;
416 /* cout << "len = " << puff_length
418 << " factor = " << factor
419 << " actual_visibility = " << actual_visibility
422 puff_progression += ( global_multi_loop *
423 current_options.get_speed_up() ) /
424 (double)current_options.get_model_hz();
426 /* cout << "gml = " << global_multi_loop
427 << " speed up = " << current_options.get_speed_up()
428 << " hz = " << current_options.get_model_hz() << endl;
431 if ( puff_progression > puff_length + ramp_up + ramp_down) {
436 // never let visibility drop below zero
437 if ( actual_visibility < 0 ) {
438 actual_visibility = 0;
443 // cout << "actual visibility = " << actual_visibility << endl;
445 if ( actual_visibility != last_visibility ) {
446 last_visibility = actual_visibility;
448 // cout << "----> updating fog params" << endl;
450 GLfloat fog_exp_density;
451 GLfloat fog_exp2_density;
454 fog_exp_density = -log(0.01 / actual_visibility);
457 fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
459 // Set correct opengl fog density
460 xglFogf (GL_FOG_DENSITY, fog_exp2_density);
463 // set lighting parameters
464 xglLightfv( GL_LIGHT0, GL_AMBIENT, l->scene_ambient );
465 xglLightfv( GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
466 // xglLightfv(GL_LIGHT0, GL_SPECULAR, white );
468 // texture parameters
469 xglEnable( GL_TEXTURE_2D );
470 xglTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
471 xglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
472 // set base color (I don't think this is doing anything here)
473 // xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
474 // (GL_FRONT, GL_DIFFUSE, white);
475 // xglMaterialfv (GL_FRONT, GL_SPECULAR, white);
476 // xglMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
479 if ( current_options.get_textures() ) {
480 // texture parameters
481 xglEnable( GL_TEXTURE_2D );
482 xglTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
483 xglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
484 // set base color (I don't think this is doing anything here)
485 xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
486 xglMaterialfv (GL_FRONT, GL_DIFFUSE, white);
487 // xglMaterialfv (GL_FRONT, GL_SPECULAR, white);
488 // xglMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
490 xglDisable( GL_TEXTURE_2D );
491 xglMaterialfv (GL_FRONT, GL_AMBIENT, terrain_color);
492 xglMaterialfv (GL_FRONT, GL_DIFFUSE, terrain_color);
493 // xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
494 // xglMaterialfv (GL_FRONT, GL_DIFFUSE, white);
499 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
500 ssgGetLight( 0 ) -> setPosition( sunpos );
502 // xglMatrixMode( GL_PROJECTION );
503 // xglLoadIdentity();
504 float fov = current_options.get_fov();
505 ssgSetFOV(fov * current_view.get_win_ratio(), fov);
507 double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
510 // FG_LOG( FG_ALL, FG_INFO, "visibility is "
511 // << current_weather.get_visibility() );
514 ssgSetNearFar( 10.0f, 100000.0f );
516 ssgSetNearFar( 0.5f, 100000.0f );
519 if ( current_options.get_view_mode() ==
520 fgOPTIONS::FG_VIEW_PILOT )
523 penguin_sel->select(0);
524 } else if ( current_options.get_view_mode() ==
525 fgOPTIONS::FG_VIEW_FOLLOW )
527 // select view matrix from front of view matrix queue
528 // FGMat4Wrapper tmp = current_view.follow.front();
529 // sgCopyMat4( sgVIEW, tmp.m );
531 // enable TuX and set up his position and orientation
532 penguin_sel->select(1);
535 sgMakeTransMat4( sgTRANS,
536 pilot_view.view_pos.x(),
537 pilot_view.view_pos.y(),
538 pilot_view.view_pos.z() );
541 sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
544 sgMakeRotMat4( sgROT, -90.0, ownship_up );
548 sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
549 sgMultMat4( sgTUX, sgTMP, sgTRANS );
552 sgSetCoord( &tuxpos, sgTUX );
553 penguin_pos->setTransform( &tuxpos );
556 # ifdef FG_NETWORK_OLK
558 other = head->next; /* put listpointer to start */
559 while ( other != tail) { /* display all except myself */
560 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
561 other->fgd_sel->select(1);
562 sgSetCoord( &fgdpos, other->sgFGD_COORD );
563 other->fgd_pos->setTransform( &fgdpos );
568 // fgd_sel->select(1);
569 // sgCopyMat4( sgTUX, current_view.sgVIEW);
571 // sgSetCoord( &fgdpos, sgFGD_VIEW );
572 // fgd_pos->setTransform( &fgdpos);
575 ssgSetCamera( current_view.VIEW );
577 // position tile nodes and update range selectors
578 global_tile_mgr.prep_ssg_nodes();
580 // force the default state so ssg can get back on track if
581 // we've changed things elsewhere
582 FGMaterialSlot m_slot;
583 FGMaterialSlot *m_ptr = &m_slot;
584 if ( material_mgr.find( "Default", m_ptr ) ) {
585 m_ptr->get_state()->force();
588 // draw the ssg scene
589 ssgCullAndDraw( scene );
591 xglDisable( GL_TEXTURE_2D );
592 xglDisable( GL_FOG );
594 // display HUD && Panel
595 xglDisable( GL_CULL_FACE );
598 // We can do translucent menus, so why not. :-)
599 xglEnable ( GL_BLEND ) ;
600 xglBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
602 xglDisable ( GL_BLEND ) ;
611 // Update internal time dependent calculations (i.e. flight model)
612 void fgUpdateTimeDepCalcs(int multi_loop, int remainder) {
613 static fdm_state_list fdm_list;
614 // FGInterface fdm_state;
615 fgLIGHT *l = &cur_light_params;
616 FGTime *t = FGTime::cur_time_params;
617 // FGView *v = ¤t_view;
620 // update the flight model
621 if ( multi_loop < 0 ) {
625 if ( !t->getPause() ) {
626 // run Autopilot system
629 // printf("updating flight model x %d\n", multi_loop);
630 /* fgFDMUpdate( current_options.get_flight_model(),
632 multi_loop * current_options.get_speed_up(),
634 cur_fdm_state->update( multi_loop * current_options.get_speed_up() );
636 // fgFDMUpdate( current_options.get_flight_model(),
637 // fdm_state, 0, remainder );
638 cur_fdm_state->update( 0 );
641 fdm_list.push_back( *cur_fdm_state );
642 while ( fdm_list.size() > 15 ) {
643 fdm_list.pop_front();
646 if ( current_options.get_view_mode() == fgOPTIONS::FG_VIEW_PILOT ) {
647 cur_view_fdm = *cur_fdm_state;
649 } else if ( current_options.get_view_mode() == fgOPTIONS::FG_VIEW_FOLLOW ) {
650 cur_view_fdm = fdm_list.front();
653 // update the view angle
654 for ( i = 0; i < multi_loop; i++ ) {
655 if ( fabs(current_view.get_goal_view_offset() -
656 current_view.get_view_offset()) < 0.05 )
658 current_view.set_view_offset( current_view.get_goal_view_offset() );
661 // move current_view.view_offset towards current_view.goal_view_offset
662 if ( current_view.get_goal_view_offset() >
663 current_view.get_view_offset() )
665 if ( current_view.get_goal_view_offset() -
666 current_view.get_view_offset() < FG_PI )
668 current_view.inc_view_offset( 0.01 );
670 current_view.inc_view_offset( -0.01 );
673 if ( current_view.get_view_offset() -
674 current_view.get_goal_view_offset() < FG_PI )
676 current_view.inc_view_offset( -0.01 );
678 current_view.inc_view_offset( 0.01 );
681 if ( current_view.get_view_offset() > FG_2PI ) {
682 current_view.inc_view_offset( -FG_2PI );
683 } else if ( current_view.get_view_offset() < 0 ) {
684 current_view.inc_view_offset( FG_2PI );
689 double tmp = -(l->sun_rotation + FG_PI)
690 - (cur_fdm_state->get_Psi() - current_view.get_view_offset() );
691 while ( tmp < 0.0 ) {
694 while ( tmp > FG_2PI ) {
697 /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
698 FG_Psi * RAD_TO_DEG, current_view.view_offset * RAD_TO_DEG,
699 -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
704 void fgInitTimeDepCalcs( void ) {
707 // #ifdef HAVE_SETITIMER
708 // fgTimerInit( 1.0 / current_options.get_model_hz(),
709 // fgUpdateTimeDepCalcs );
710 // #endif HAVE_SETITIMER
714 static const double alt_adjust_ft = 3.758099;
715 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
718 // What should we do when we have nothing else to do? Let's get ready
719 // for the next move and update the display?
720 static void fgMainLoop( void ) {
722 static long remainder = 0;
724 #ifdef FANCY_FRAME_COUNTER
728 static time_t last_time = 0;
729 static int frames = 0;
730 #endif // FANCY_FRAME_COUNTER
732 t = FGTime::cur_time_params;
734 FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
735 FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
737 #ifdef FG_NETWORK_OLK
738 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
739 // printf("FGD: Netupdate\n");
740 fgd_send_com( "A", FGFS_host); // Send Mat4 data
741 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
745 #if defined( ENABLE_PLIB_JOYSTICK )
746 // Read joystick and update control settings
747 if ( current_options.get_control_mode() == fgOPTIONS::FG_JOYSTICK ) {
750 #elif defined( ENABLE_GLUT_JOYSTICK )
751 // Glut joystick support works by feeding a joystick handler
752 // function to glut. This is taken care of once in the joystick
753 // init routine and we don't have to worry about it again.
756 #ifdef FG_OLD_WEATHER
757 current_weather.Update();
760 // Fix elevation. I'm just sticking this here for now, it should
761 // probably move eventually
763 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
765 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
766 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
768 if ( scenery.cur_elev > -9990 ) {
769 if ( cur_fdm_state->get_Altitude() * FEET_TO_METER <
770 (scenery.cur_elev + alt_adjust_m - 3.0) ) {
771 // now set aircraft altitude above ground
772 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
773 cur_fdm_state->get_Altitude() * FEET_TO_METER,
774 scenery.cur_elev + alt_adjust_m - 3.0,
775 scenery.cur_elev + alt_adjust_m );
776 fgFDMForceAltitude( current_options.get_flight_model(),
777 scenery.cur_elev + alt_adjust_m );
779 FG_LOG( FG_ALL, FG_DEBUG,
780 "<*> resetting altitude to "
781 << cur_fdm_state->get_Altitude() * FEET_TO_METER << " meters" );
783 fgFDMSetGroundElevation( current_options.get_flight_model(),
784 scenery.cur_elev ); // meters
787 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
789 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
790 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
793 t->update(*cur_fdm_state);
795 // Get elapsed time (in usec) for this past frame
796 elapsed = fgGetTimeInterval();
797 FG_LOG( FG_ALL, FG_DEBUG,
798 "Elapsed time interval is = " << elapsed
799 << ", previous remainder is = " << remainder );
801 // Calculate frame rate average
802 #ifdef FANCY_FRAME_COUNTER
803 /* old fps calculation */
807 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
808 tmp = general.get_frame(i);
810 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
811 general.set_frame(i+1,tmp);
813 tmp = 1000000.0 / (float)elapsed;
814 general.set_frame(0,tmp);
815 // printf("frame[0] = %.2f\n", general.frames[0]);
817 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
818 // printf("ave = %.2f\n", general.frame_rate);
821 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
822 general.set_frame_rate( frames );
823 FG_LOG( FG_ALL, FG_DEBUG,
824 "--> Frame rate is = " << general.get_frame_rate() );
827 last_time = t->get_cur_time();
832 if ( ! use_signals ) {
833 // Calculate model iterations needed for next frame
834 elapsed += remainder;
836 global_multi_loop = (int)(((double)elapsed * 0.000001) *
837 current_options.get_model_hz());
838 remainder = elapsed - ( (global_multi_loop*1000000) /
839 current_options.get_model_hz() );
840 FG_LOG( FG_ALL, FG_DEBUG,
841 "Model iterations needed = " << global_multi_loop
842 << ", new remainder = " << remainder );
845 if ( global_multi_loop > 0 ) {
846 fgUpdateTimeDepCalcs(global_multi_loop, remainder);
848 FG_LOG( FG_ALL, FG_DEBUG,
849 "Elapsed time is zero ... we're zinging" );
853 #if ! defined( MACOS )
854 // Do any I/O channel work that might need to be done
858 // see if we need to load any new scenery tiles
859 global_tile_mgr.update();
861 // Process/manage pending events
862 global_events.Process();
864 // Run audio scheduler
865 #ifdef ENABLE_AUDIO_SUPPORT
866 if ( current_options.get_sound() && !audio_sched->not_working() ) {
868 # ifdef MICHAEL_JOHNSON_EXPERIMENTAL_ENGINE_AUDIO
870 // note: all these factors are relative to the sample. our
871 // sample format should really contain a conversion factor so
872 // that we can get prop speed right for arbitrary samples.
873 // Note that for normal-size props, there is a point at which
874 // the prop tips approach the speed of sound; that is a pretty
875 // strong limit to how fast the prop can go.
877 // multiplication factor is prime pitch control; add some log
878 // component for verisimilitude
880 double pitch = log((controls.get_throttle(0) * 14.0) + 1.0);
881 //fprintf(stderr, "pitch1: %f ", pitch);
882 if (controls.get_throttle(0) > 0.0 || cur_fdm_state->v_rel_wind > 40.0) {
883 //fprintf(stderr, "rel_wind: %f ", cur_fdm_state->v_rel_wind);
884 // only add relative wind and AoA if prop is moving
885 // or we're really flying at idle throttle
886 if (pitch < 5.4) { // this needs tuning
887 // prop tips not breaking sound barrier
888 pitch += log(cur_fdm_state->v_rel_wind + 0.8)/2;
890 // prop tips breaking sound barrier
891 pitch += log(cur_fdm_state->v_rel_wind + 0.8)/10;
893 //fprintf(stderr, "pitch2: %f ", pitch);
894 //fprintf(stderr, "AoA: %f ", FG_Gamma_vert_rad);
896 // Angle of Attack next... -x^3(e^x) is my best guess Just
897 // need to calculate some reasonable scaling factor and
898 // then clamp it on the positive aoa (neg adj) side
899 double aoa = cur_fdm_state->get_Gamma_vert_rad() * 2.2;
901 double aoa_adj = pow(-aoa, tmp) * pow(M_E, aoa);
902 if (aoa_adj < -0.8) aoa_adj = -0.8;
904 //fprintf(stderr, "pitch3: %f ", pitch);
906 // don't run at absurdly slow rates -- not realistic
907 // and sounds bad to boot. :-)
908 if (pitch < 0.8) pitch = 0.8;
910 //fprintf(stderr, "pitch4: %f\n", pitch);
912 double volume = controls.get_throttle(0) * 1.15 + 0.3 +
913 log(cur_fdm_state->v_rel_wind + 1.0)/14.0;
914 // fprintf(stderr, "volume: %f\n", volume);
916 pitch_envelope.setStep ( 0, 0.01, pitch );
917 volume_envelope.setStep ( 0, 0.01, volume );
921 double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
922 pitch_envelope.setStep ( 0, 0.01, param );
923 volume_envelope.setStep ( 0, 0.01, param );
925 # endif // experimental throttle patch
927 audio_sched -> update();
934 FG_LOG( FG_ALL, FG_DEBUG, "" );
938 // This is the top level master main function that is registered as
942 // The first few passes take care of initialization things (a couple
943 // per pass) and once everything has been initialized fgMainLoop from
946 static void fgIdleFunction ( void ) {
947 // printf("idle state == %d\n", idle_state);
949 if ( idle_state == 0 ) {
950 // Initialize the splash screen right away
951 if ( current_options.get_splash_screen() ) {
956 } else if ( idle_state == 1 ) {
957 // Start the intro music
959 if ( current_options.get_intro_music() ) {
960 string lockfile = "/tmp/mpg123.running";
961 FGPath mp3file( current_options.get_fg_root() );
962 mp3file.append( "Sounds/intro.mp3" );
964 string command = "(touch " + lockfile + "; mpg123 "
965 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
967 FG_LOG( FG_GENERAL, FG_INFO,
968 "Starting intro music: " << mp3file.str() );
969 system ( command.c_str() );
974 } else if ( idle_state == 2 ) {
975 // These are a few miscellaneous things that aren't really
976 // "subsystems" but still need to be initialized.
979 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
980 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
985 } else if ( idle_state == 3 ) {
986 // This is the top level init routine which calls all the
987 // other subsystem initialization routines. If you are adding
988 // a subsystem to flight gear, its initialization call should
989 // located in this routine.
990 if( !fgInitSubsystems()) {
991 FG_LOG( FG_GENERAL, FG_ALERT,
992 "Subsystem initializations failed ..." );
997 } else if ( idle_state == 4 ) {
998 // setup OpenGL view parameters
1001 if ( use_signals ) {
1002 // init timer routines, signals, etc. Arrange for an alarm
1003 // signal to be generated, etc.
1004 fgInitTimeDepCalcs();
1008 } else if ( idle_state == 5 ) {
1011 } else if ( idle_state == 6 ) {
1012 // Initialize audio support
1013 #ifdef ENABLE_AUDIO_SUPPORT
1016 if ( current_options.get_intro_music() ) {
1017 // Let's wait for mpg123 to finish
1018 string lockfile = "/tmp/mpg123.running";
1019 struct stat stat_buf;
1021 FG_LOG( FG_GENERAL, FG_INFO,
1022 "Waiting for mpg123 player to finish ..." );
1023 while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
1024 // file exist, wait ...
1026 FG_LOG( FG_GENERAL, FG_INFO, ".");
1028 FG_LOG( FG_GENERAL, FG_INFO, "");
1032 if ( current_options.get_sound() ) {
1033 audio_sched = new slScheduler ( 8000 );
1034 audio_mixer = new smMixer;
1035 audio_mixer -> setMasterVolume ( 80 ) ; /* 80% of max volume. */
1036 audio_sched -> setSafetyMargin ( 1.0 ) ;
1038 FGPath slfile( current_options.get_fg_root() );
1039 slfile.append( "Sounds/wasp.wav" );
1041 s1 = new slSample ( (char *)slfile.c_str() );
1042 FG_LOG( FG_GENERAL, FG_INFO,
1043 "Rate = " << s1 -> getRate()
1044 << " Bps = " << s1 -> getBps()
1045 << " Stereo = " << s1 -> getStereo() );
1046 audio_sched -> loopSample ( s1 );
1048 if ( audio_sched->not_working() ) {
1051 pitch_envelope.setStep ( 0, 0.01, 0.6 );
1052 volume_envelope.setStep ( 0, 0.01, 0.6 );
1054 audio_sched -> addSampleEnvelope( s1, 0, 0,
1056 SL_PITCH_ENVELOPE );
1057 audio_sched -> addSampleEnvelope( s1, 0, 1,
1059 SL_VOLUME_ENVELOPE );
1062 // strcpy(slfile, path);
1063 // strcat(slfile, "thunder.wav");
1064 // s2 -> loadFile ( slfile );
1065 // s2 -> adjustVolume(0.5);
1066 // audio_sched -> playSample ( s2 );
1074 if ( idle_state == 1000 ) {
1075 // We've finished all our initialization steps, from now on we
1076 // run the main loop.
1080 if ( current_options.get_splash_screen() == 1 ) {
1081 fgSplashUpdate(0.0);
1086 // options.cxx needs to see this for toggle_panel()
1087 // Handle new window size or exposure
1088 void fgReshape( int width, int height ) {
1089 if ( ! current_options.get_panel_status() ) {
1090 current_view.set_win_ratio( (GLfloat) width / (GLfloat) height );
1091 xglViewport(0, 0 , (GLint)(width), (GLint)(height) );
1093 current_view.set_win_ratio( (GLfloat) width /
1094 ((GLfloat) (height)*0.4232) );
1095 xglViewport(0, (GLint)((height)*0.5768), (GLint)(width),
1096 (GLint)((height)*0.4232) );
1099 current_view.set_winWidth( width );
1100 current_view.set_winHeight( height );
1101 current_view.force_update_fov_math();
1103 // set these fov to be the same as in fgRenderFrame()
1104 float x_fov = current_options.get_fov();
1105 float y_fov = x_fov * 1.0 / current_view.get_win_ratio();
1106 ssgSetFOV( x_fov, y_fov );
1108 glViewport ( 0, 0, width, height );
1109 float fov = current_options.get_fov();
1110 ssgSetFOV(fov * current_view.get_win_ratio(), fov);
1112 if ( idle_state == 1000 ) {
1113 // yes we've finished all our initializations and are running
1114 // the main loop, so this will now work without seg faulting
1116 solarSystemRebuild();
1117 current_view.UpdateViewParams(cur_view_fdm);
1118 if ( current_options.get_panel_status() ) {
1119 FGPanel::OurPanel->ReInit(0, 0, 1024, 768);
1125 // Initialize GLUT and define a main window
1126 int fgGlutInit( int *argc, char **argv ) {
1128 #if !defined( MACOS )
1129 // GLUT will extract all glut specific options so later on we only
1130 // need wory about our own.
1131 xglutInit(argc, argv);
1134 // Define Display Parameters
1135 xglutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1137 FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
1138 current_options.get_xsize() << "x" << current_options.get_ysize() );
1140 // Define initial window size
1141 xglutInitWindowSize( current_options.get_xsize(),
1142 current_options.get_ysize() );
1144 // Initialize windows
1145 if ( current_options.get_game_mode() == 0 ) {
1146 // Open the regular window
1147 xglutCreateWindow("Flight Gear");
1148 #ifndef GLUT_WRONG_VERSION
1150 // Open the cool new 'game mode' window
1151 char game_mode_str[256];
1152 sprintf( game_mode_str, "width=%d height=%d bpp=32",
1153 current_options.get_xsize(),
1154 current_options.get_ysize() );
1156 FG_LOG( FG_GENERAL, FG_INFO,
1157 "game mode params = " << game_mode_str );
1158 glutGameModeString( game_mode_str );
1159 glutEnterGameMode();
1163 // This seems to be the absolute earliest in the init sequence
1164 // that these calls will return valid info. Too bad it's after
1165 // we've already created and sized out window. :-(
1166 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1167 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1168 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1170 FG_LOG ( FG_GENERAL, FG_INFO, general.get_glRenderer() );
1173 // try to determine if we should adjust the initial default
1174 // display resolution. The options class defaults (is
1175 // initialized) to 640x480.
1176 string renderer = general.glRenderer;
1178 // currently we only know how to deal with Mesa/Glide/Voodoo cards
1179 if ( renderer.find( "Glide" ) != string::npos ) {
1180 FG_LOG( FG_GENERAL, FG_INFO, "Detected a Glide driver" );
1181 if ( renderer.find( "FB/8" ) != string::npos ) {
1182 // probably a voodoo-2
1183 if ( renderer.find( "TMU/SLI" ) != string::npos ) {
1184 // probably two SLI'd Voodoo-2's
1185 current_options.set_xsize( 1024 );
1186 current_options.set_ysize( 768 );
1187 FG_LOG( FG_GENERAL, FG_INFO,
1188 "It looks like you have two sli'd voodoo-2's." << endl
1189 << "upgrading your win resolution to 1024 x 768" );
1190 glutReshapeWindow(1024, 768);
1192 // probably a single non-SLI'd Voodoo-2
1193 current_options.set_xsize( 800 );
1194 current_options.set_ysize( 600 );
1195 FG_LOG( FG_GENERAL, FG_INFO,
1196 "It looks like you have a voodoo-2." << endl
1197 << "upgrading your win resolution to 800 x 600" );
1198 glutReshapeWindow(800, 600);
1200 } else if ( renderer.find( "FB/2" ) != string::npos ) {
1201 // probably a voodoo-1, stick with the default
1204 // we have no special knowledge of this card, stick with the default
1212 // Initialize GLUT event handlers
1213 int fgGlutInitEvents( void ) {
1214 // call fgReshape() on window resizes
1215 xglutReshapeFunc( fgReshape );
1217 // call GLUTkey() on keyboard event
1218 xglutKeyboardFunc( GLUTkey );
1219 glutSpecialFunc( GLUTspecialkey );
1221 // call guiMouseFunc() whenever our little rodent is used
1222 glutMouseFunc ( guiMouseFunc );
1223 glutMotionFunc (guiMotionFunc );
1224 glutPassiveMotionFunc (guiMotionFunc );
1226 // call fgMainLoop() whenever there is
1227 // nothing else to do
1228 xglutIdleFunc( fgIdleFunction );
1231 xglutDisplayFunc( fgRenderFrame );
1238 int main( int argc, char **argv ) {
1240 #if defined( MACOS )
1241 argc = ccommand( &argv );
1245 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1248 // set default log levels
1249 fglog().setLogLevels( FG_ALL, FG_INFO );
1251 FG_LOG( FG_GENERAL, FG_INFO, "Flight Gear: Version " << VERSION << endl );
1253 // seed the random number generater
1256 // Load the configuration parameters
1257 if ( !fgInitConfig(argc, argv) ) {
1258 FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1262 // Initialize the Window/Graphics environment.
1263 if( !fgGlutInit(&argc, argv) ) {
1264 FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1268 // Initialize the various GLUT Event Handlers.
1269 if( !fgGlutInitEvents() ) {
1270 FG_LOG( FG_GENERAL, FG_ALERT,
1271 "GLUT event handler initialization failed ..." );
1275 // Initialize ssg (from plib)
1278 // Initialize the user interface (we need to do this before
1279 // passing off control to glut and before fgInitGeneral to get our
1283 // Do some quick general initializations
1284 if( !fgInitGeneral()) {
1285 FG_LOG( FG_GENERAL, FG_ALERT,
1286 "General initializations failed ..." );
1291 // some ssg test stuff (requires data from the plib source
1292 // distribution) specifically from the ssg tux example
1295 FGPath modelpath( current_options.get_fg_root() );
1296 modelpath.append( "Models" );
1297 modelpath.append( "Geometry" );
1299 FGPath texturepath( current_options.get_fg_root() );
1300 texturepath.append( "Models" );
1301 texturepath.append( "Textures" );
1303 ssgModelPath( (char *)modelpath.c_str() );
1304 ssgTexturePath( (char *)texturepath.c_str() );
1306 scene = new ssgRoot;
1307 terrain = new ssgBranch;
1308 terrain->setName( "Terrain" );
1309 penguin_sel = new ssgSelector;
1310 penguin_pos = new ssgTransform;
1312 ssgEntity *tux_obj = ssgLoadAC( "glider.ac" );
1313 // ssgEntity *tux_obj = ssgLoadAC( "Tower1x.ac" );
1314 penguin_pos->addKid( tux_obj );
1315 penguin_sel->addKid( penguin_pos );
1316 ssgFlatten( tux_obj );
1317 ssgStripify( penguin_sel );
1318 penguin_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1320 #ifdef FG_NETWORK_OLK
1321 // Do the network intialization
1322 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1325 scene->addKid( terrain );
1326 scene->addKid( penguin_sel );
1328 // pass control off to the master GLUT event handler
1331 // we never actually get here ... but to avoid compiler warnings,