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 <NetworkOLK/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"
103 #include "keyboard.hxx"
104 #include "options.hxx"
105 #include "splash.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 #ifdef FG_NETWORK_OLK
148 ssgSelector *fgd_sel = NULL;
149 ssgTransform *fgd_pos = NULL;
153 // current fdm/position used for view
154 FGInterface cur_view_fdm;
157 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
159 { 1.0f, 0.0f, 0.0f, 0.0f },
160 { 0.0f, 0.0f, -1.0f, 0.0f },
161 { 0.0f, 1.0f, 0.0f, 0.0f },
162 { 0.0f, 0.0f, 0.0f, 1.0f }
165 // The following defines flight gear options. Because glutlib will also
166 // want to parse its own options, those options must not be included here
167 // or they will get parsed by the main program option parser. Hence case
168 // is significant for any option added that might be in conflict with
171 // glutlib parses for:
173 // -direct (invalid in Win32)
177 // -indirect (invalid in Win32)
180 // Note that glutlib depends upon strings while this program's
181 // option parser wants only initial characters followed by numbers
186 // fgInitVisuals() -- Initialize various GL/view parameters
187 void fgInitVisuals( void ) {
190 l = &cur_light_params;
192 #ifndef GLUT_WRONG_VERSION
193 // Go full screen if requested ...
194 if ( current_options.get_fullscreen() ) {
199 // If enabled, normal vectors specified with glNormal are scaled
200 // to unit length after transformation. See glNormal.
201 // xglEnable( GL_NORMALIZE );
203 xglEnable( GL_LIGHTING );
204 xglEnable( GL_LIGHT0 );
205 xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
208 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
209 ssgGetLight( 0 ) -> setPosition( sunpos );
211 // xglFogi (GL_FOG_MODE, GL_LINEAR);
212 xglFogi (GL_FOG_MODE, GL_EXP2);
213 if ( (current_options.get_fog() == 1) ||
214 (current_options.get_shading() == 0) ) {
215 // if fastest fog requested, or if flat shading force fastest
216 xglHint ( GL_FOG_HINT, GL_FASTEST );
217 } else if ( current_options.get_fog() == 2 ) {
218 xglHint ( GL_FOG_HINT, GL_NICEST );
220 if ( current_options.get_wireframe() ) {
222 xglPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
225 // This is the default anyways, but it can't hurt
226 xglFrontFace ( GL_CCW );
229 // xglEnable(GL_POINT_SMOOTH);
230 // xglEnable(GL_LINE_SMOOTH);
231 // xglEnable(GL_POLYGON_SMOOTH);
235 // Update all Visuals (redraws anything graphics related)
236 void fgRenderFrame( void ) {
237 fgLIGHT *l = &cur_light_params;
238 FGTime *t = FGTime::cur_time_params;
239 // FGView *v = ¤t_view;
240 static double last_visibility = -9999;
241 static bool in_puff = false;
242 static double puff_length = 0;
243 static double puff_progression = 0;
244 const double ramp_up = 0.15;
245 const double ramp_down = 0.15;
248 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
249 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
250 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
251 // GLfloat mat_shininess[] = { 10.0 };
252 GLbitfield clear_mask;
254 if ( idle_state != 1000 ) {
255 // still initializing, draw the splash screen
256 if ( current_options.get_splash_screen() == 1 ) {
260 // idle_state is now 1000 meaning we've finished all our
261 // initializations and are running the main loop, so this will
262 // now work without seg faulting the system.
264 // printf("Ground = %.2f Altitude = %.2f\n", scenery.cur_elev,
265 // FG_Altitude * FEET_TO_METER);
267 // this is just a temporary hack, to make me understand Pui
268 // timerText -> setLabel (ctime (&t->cur_time));
271 // update view volume parameters
272 // cout << "before pilot_view update" << endl;
273 pilot_view.UpdateViewParams(*cur_fdm_state);
274 // cout << "after pilot_view update" << endl;
275 current_view.UpdateViewParams(cur_view_fdm);
277 // set the sun position
278 xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
280 clear_mask = GL_DEPTH_BUFFER_BIT;
281 if ( current_options.get_wireframe() ) {
282 clear_mask |= GL_COLOR_BUFFER_BIT;
284 if ( current_options.get_panel_status() ) {
285 // we can't clear the screen when the panel is active
286 } else if ( current_options.get_skyblend() ) {
287 if ( current_options.get_textures() ) {
288 // glClearColor(black[0], black[1], black[2], black[3]);
289 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
290 l->adj_fog_color[2], l->adj_fog_color[3]);
291 clear_mask |= GL_COLOR_BUFFER_BIT;
294 glClearColor(l->sky_color[0], l->sky_color[1],
295 l->sky_color[2], l->sky_color[3]);
296 clear_mask |= GL_COLOR_BUFFER_BIT;
298 xglClear( clear_mask );
300 // Tell GL we are switching to model view parameters
302 // I really should create a derived ssg node or use a call
303 // back or something so that I can draw the sky within the
304 // ssgCullandDraw() function, but for now I just mimic what
305 // ssg does to set up the model view matrix
306 xglMatrixMode(GL_MODELVIEW);
308 sgMat4 vm_tmp, view_mat;
309 sgTransposeNegateMat4 ( vm_tmp, current_view.VIEW ) ;
310 sgCopyMat4( view_mat, copy_of_ssgOpenGLAxisSwapMatrix ) ;
311 sgPreMultMat4( view_mat, vm_tmp ) ;
312 xglLoadMatrixf( (float *)view_mat );
315 xglDisable( GL_DEPTH_TEST );
316 xglDisable( GL_LIGHTING );
317 xglDisable( GL_CULL_FACE );
319 xglDisable( GL_FOG );
320 /* if ( current_options.get_fog() > 0 ) {
322 xglFogi( GL_FOG_MODE, GL_EXP2 );
323 xglFogfv( GL_FOG_COLOR, l->adj_fog_color );
326 xglShadeModel( GL_SMOOTH );
327 if ( current_options.get_skyblend() ) {
331 // xglDisable( GL_FOG );
333 // setup transformation for drawing astronomical objects
335 // Translate to view position
336 Point3D view_pos = current_view.get_view_pos();
337 xglTranslatef( view_pos.x(), view_pos.y(), view_pos.z() );
338 // Rotate based on gst (sidereal time)
339 // note: constant should be 15.041085, Curt thought it was 15
340 angle = t->getGst() * 15.041085;
341 // printf("Rotating astro objects by %.2f degrees\n",angle);
342 xglRotatef( angle, 0.0, 0.0, -1.0 );
344 // draw stars and planets
346 xglDisable( GL_COLOR_MATERIAL ); // just to make sure ...
347 xglEnable( GL_CULL_FACE ); // for moon
348 xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
349 //xglEnable(GL_DEPTH_TEST);
350 SolarSystem::theSolarSystem->draw();
351 // reset blending function
352 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
357 if ( current_options.get_shading() ) {
358 xglShadeModel( GL_SMOOTH );
360 xglShadeModel( GL_FLAT );
362 xglEnable( GL_DEPTH_TEST );
363 if ( current_options.get_fog() > 0 ) {
365 xglFogi( GL_FOG_MODE, GL_EXP2 );
366 xglFogfv( GL_FOG_COLOR, l->adj_fog_color );
369 // update fog params if visibility has changed
370 #ifndef FG_OLD_WEATHER
371 double cur_visibility = WeatherDatabase->getWeatherVisibility();
373 double cur_visibility = current_weather.get_visibility();
375 double actual_visibility = cur_visibility;
377 if ( current_options.get_clouds() ) {
378 double diff = fabs( cur_fdm_state->get_Altitude() * FEET_TO_METER -
379 current_options.get_clouds_asl() );
380 // cout << "altitude diff = " << diff << endl;
383 // calc chance of entering cloud puff
384 double rnd = fg_random();
385 double chance = rnd * rnd * rnd;
386 if ( chance > 0.95 /* * (diff - 25) / 50.0 */ ) {
389 puff_length = fg_random() * 2.0; // up to 2 seconds
390 } while ( puff_length <= 0.0 );
391 puff_progression = 0.0;
395 actual_visibility = cur_visibility * (diff - 25) / 50.0;
398 // modify actual_visibility based on puff envelope
400 if ( puff_progression <= ramp_up ) {
401 double x = FG_PI_2 * puff_progression / ramp_up;
402 double factor = 1.0 - sin( x );
403 actual_visibility = actual_visibility * factor;
404 } else if ( puff_progression >= ramp_up + puff_length ) {
406 (puff_progression - (ramp_up + puff_length)) /
408 double factor = sin( x );
409 actual_visibility = actual_visibility * factor;
411 actual_visibility = 0.0;
414 /* cout << "len = " << puff_length
416 << " factor = " << factor
417 << " actual_visibility = " << actual_visibility
420 puff_progression += ( global_multi_loop *
421 current_options.get_speed_up() ) /
422 (double)current_options.get_model_hz();
424 /* cout << "gml = " << global_multi_loop
425 << " speed up = " << current_options.get_speed_up()
426 << " hz = " << current_options.get_model_hz() << endl;
429 if ( puff_progression > puff_length + ramp_up + ramp_down) {
434 // never let visibility drop below zero
435 if ( actual_visibility < 0 ) {
436 actual_visibility = 0;
441 // cout << "actual visibility = " << actual_visibility << endl;
443 if ( actual_visibility != last_visibility ) {
444 last_visibility = actual_visibility;
446 // cout << "----> updating fog params" << endl;
448 GLfloat fog_exp_density;
449 GLfloat fog_exp2_density;
452 fog_exp_density = -log(0.01 / actual_visibility);
455 fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
457 // Set correct opengl fog density
458 xglFogf (GL_FOG_DENSITY, fog_exp2_density);
461 // set lighting parameters
462 xglLightfv( GL_LIGHT0, GL_AMBIENT, l->scene_ambient );
463 xglLightfv( GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
464 // xglLightfv(GL_LIGHT0, GL_SPECULAR, white );
466 // texture parameters
467 xglEnable( GL_TEXTURE_2D );
468 xglTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
469 xglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
470 // set base color (I don't think this is doing anything here)
471 // xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
472 // (GL_FRONT, GL_DIFFUSE, white);
473 // xglMaterialfv (GL_FRONT, GL_SPECULAR, white);
474 // xglMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
477 if ( current_options.get_textures() ) {
478 // texture parameters
479 xglEnable( GL_TEXTURE_2D );
480 xglTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
481 xglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
482 // set base color (I don't think this is doing anything here)
483 xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
484 xglMaterialfv (GL_FRONT, GL_DIFFUSE, white);
485 // xglMaterialfv (GL_FRONT, GL_SPECULAR, white);
486 // xglMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
488 xglDisable( GL_TEXTURE_2D );
489 xglMaterialfv (GL_FRONT, GL_AMBIENT, terrain_color);
490 xglMaterialfv (GL_FRONT, GL_DIFFUSE, terrain_color);
491 // xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
492 // xglMaterialfv (GL_FRONT, GL_DIFFUSE, white);
497 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
498 ssgGetLight( 0 ) -> setPosition( sunpos );
500 // xglMatrixMode( GL_PROJECTION );
501 // xglLoadIdentity();
502 float fov = current_options.get_fov();
503 ssgSetFOV(fov * current_view.get_win_ratio(), fov);
505 double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
508 // FG_LOG( FG_ALL, FG_INFO, "visibility is "
509 // << current_weather.get_visibility() );
512 ssgSetNearFar( 10.0f, 100000.0f );
514 ssgSetNearFar( 0.5f, 100000.0f );
517 if ( current_options.get_view_mode() ==
518 fgOPTIONS::FG_VIEW_PILOT )
521 penguin_sel->select(0);
522 } else if ( current_options.get_view_mode() ==
523 fgOPTIONS::FG_VIEW_FOLLOW )
525 // select view matrix from front of view matrix queue
526 // FGMat4Wrapper tmp = current_view.follow.front();
527 // sgCopyMat4( sgVIEW, tmp.m );
529 // enable TuX and set up his position and orientation
530 penguin_sel->select(1);
533 sgMakeTransMat4( sgTRANS,
534 pilot_view.view_pos.x(),
535 pilot_view.view_pos.y(),
536 pilot_view.view_pos.z() );
539 sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
542 sgMakeRotMat4( sgROT, -90.0, ownship_up );
546 sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
547 sgMultMat4( sgTUX, sgTMP, sgTRANS );
550 sgSetCoord( &tuxpos, sgTUX );
551 penguin_pos->setTransform( &tuxpos );
554 # ifdef FG_NETWORK_OLK
556 other = head->next; /* put listpointer to start */
557 while ( other != tail) { /* display all except myself */
558 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
559 other->fgd_sel->select(1);
560 sgSetCoord( &fgdpos, other->sgFGD_COORD );
561 other->fgd_pos->setTransform( &fgdpos );
566 // fgd_sel->select(1);
567 // sgCopyMat4( sgTUX, current_view.sgVIEW);
569 // sgSetCoord( &fgdpos, sgFGD_VIEW );
570 // fgd_pos->setTransform( &fgdpos);
573 ssgSetCamera( current_view.VIEW );
575 // position tile nodes and update range selectors
576 global_tile_mgr.prep_ssg_nodes();
578 // force the default state so ssg can get back on track if
579 // we've changed things elsewhere
580 FGMaterialSlot m_slot;
581 FGMaterialSlot *m_ptr = &m_slot;
582 if ( material_mgr.find( "Default", m_ptr ) ) {
583 m_ptr->get_state()->force();
586 // draw the ssg scene
587 ssgCullAndDraw( scene );
589 xglDisable( GL_TEXTURE_2D );
590 xglDisable( GL_FOG );
592 // display HUD && Panel
593 xglDisable( GL_CULL_FACE );
596 // We can do translucent menus, so why not. :-)
597 xglEnable ( GL_BLEND ) ;
598 xglBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
600 xglDisable ( GL_BLEND ) ;
609 // Update internal time dependent calculations (i.e. flight model)
610 void fgUpdateTimeDepCalcs(int multi_loop, int remainder) {
611 static fdm_state_list fdm_list;
612 // FGInterface fdm_state;
613 fgLIGHT *l = &cur_light_params;
614 FGTime *t = FGTime::cur_time_params;
615 // FGView *v = ¤t_view;
618 // update the flight model
619 if ( multi_loop < 0 ) {
623 if ( !t->getPause() ) {
624 // run Autopilot system
627 // printf("updating flight model x %d\n", multi_loop);
628 /* fgFDMUpdate( current_options.get_flight_model(),
630 multi_loop * current_options.get_speed_up(),
632 cur_fdm_state->update( multi_loop * current_options.get_speed_up() );
634 // fgFDMUpdate( current_options.get_flight_model(),
635 // fdm_state, 0, remainder );
636 cur_fdm_state->update( 0 );
639 fdm_list.push_back( *cur_fdm_state );
640 while ( fdm_list.size() > 15 ) {
641 fdm_list.pop_front();
644 if ( current_options.get_view_mode() == fgOPTIONS::FG_VIEW_PILOT ) {
645 cur_view_fdm = *cur_fdm_state;
647 } else if ( current_options.get_view_mode() == fgOPTIONS::FG_VIEW_FOLLOW ) {
648 cur_view_fdm = fdm_list.front();
651 // update the view angle
652 for ( i = 0; i < multi_loop; i++ ) {
653 if ( fabs(current_view.get_goal_view_offset() -
654 current_view.get_view_offset()) < 0.05 )
656 current_view.set_view_offset( current_view.get_goal_view_offset() );
659 // move current_view.view_offset towards current_view.goal_view_offset
660 if ( current_view.get_goal_view_offset() >
661 current_view.get_view_offset() )
663 if ( current_view.get_goal_view_offset() -
664 current_view.get_view_offset() < FG_PI )
666 current_view.inc_view_offset( 0.01 );
668 current_view.inc_view_offset( -0.01 );
671 if ( current_view.get_view_offset() -
672 current_view.get_goal_view_offset() < FG_PI )
674 current_view.inc_view_offset( -0.01 );
676 current_view.inc_view_offset( 0.01 );
679 if ( current_view.get_view_offset() > FG_2PI ) {
680 current_view.inc_view_offset( -FG_2PI );
681 } else if ( current_view.get_view_offset() < 0 ) {
682 current_view.inc_view_offset( FG_2PI );
687 double tmp = -(l->sun_rotation + FG_PI)
688 - (cur_fdm_state->get_Psi() - current_view.get_view_offset() );
689 while ( tmp < 0.0 ) {
692 while ( tmp > FG_2PI ) {
695 /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
696 FG_Psi * RAD_TO_DEG, current_view.view_offset * RAD_TO_DEG,
697 -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
702 void fgInitTimeDepCalcs( void ) {
705 // #ifdef HAVE_SETITIMER
706 // fgTimerInit( 1.0 / current_options.get_model_hz(),
707 // fgUpdateTimeDepCalcs );
708 // #endif HAVE_SETITIMER
712 static const double alt_adjust_ft = 3.758099;
713 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
716 // What should we do when we have nothing else to do? Let's get ready
717 // for the next move and update the display?
718 static void fgMainLoop( void ) {
720 static long remainder = 0;
722 #ifdef FANCY_FRAME_COUNTER
726 static time_t last_time = 0;
727 static int frames = 0;
728 #endif // FANCY_FRAME_COUNTER
730 t = FGTime::cur_time_params;
732 FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
733 FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
735 #ifdef FG_NETWORK_OLK
736 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
737 // printf("FGD: Netupdate\n");
738 fgd_send_com( "A", FGFS_host); // Send Mat4 data
739 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
743 #if defined( ENABLE_PLIB_JOYSTICK )
744 // Read joystick and update control settings
745 if ( current_options.get_control_mode() == fgOPTIONS::FG_JOYSTICK ) {
748 #elif defined( ENABLE_GLUT_JOYSTICK )
749 // Glut joystick support works by feeding a joystick handler
750 // function to glut. This is taken care of once in the joystick
751 // init routine and we don't have to worry about it again.
754 #ifdef FG_OLD_WEATHER
755 current_weather.Update();
758 // Fix elevation. I'm just sticking this here for now, it should
759 // probably move eventually
761 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
763 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
764 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
766 if ( scenery.cur_elev > -9990 ) {
767 if ( cur_fdm_state->get_Altitude() * FEET_TO_METER <
768 (scenery.cur_elev + alt_adjust_m - 3.0) ) {
769 // now set aircraft altitude above ground
770 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
771 cur_fdm_state->get_Altitude() * FEET_TO_METER,
772 scenery.cur_elev + alt_adjust_m - 3.0,
773 scenery.cur_elev + alt_adjust_m );
774 fgFDMForceAltitude( current_options.get_flight_model(),
775 scenery.cur_elev + alt_adjust_m );
777 FG_LOG( FG_ALL, FG_DEBUG,
778 "<*> resetting altitude to "
779 << cur_fdm_state->get_Altitude() * FEET_TO_METER << " meters" );
781 fgFDMSetGroundElevation( current_options.get_flight_model(),
782 scenery.cur_elev ); // meters
785 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
787 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
788 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
791 t->update(*cur_fdm_state);
793 // Get elapsed time (in usec) for this past frame
794 elapsed = fgGetTimeInterval();
795 FG_LOG( FG_ALL, FG_DEBUG,
796 "Elapsed time interval is = " << elapsed
797 << ", previous remainder is = " << remainder );
799 // Calculate frame rate average
800 #ifdef FANCY_FRAME_COUNTER
801 /* old fps calculation */
805 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
806 tmp = general.get_frame(i);
808 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
809 general.set_frame(i+1,tmp);
811 tmp = 1000000.0 / (float)elapsed;
812 general.set_frame(0,tmp);
813 // printf("frame[0] = %.2f\n", general.frames[0]);
815 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
816 // printf("ave = %.2f\n", general.frame_rate);
819 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
820 general.set_frame_rate( frames );
821 FG_LOG( FG_ALL, FG_DEBUG,
822 "--> Frame rate is = " << general.get_frame_rate() );
825 last_time = t->get_cur_time();
830 if ( ! use_signals ) {
831 // Calculate model iterations needed for next frame
832 elapsed += remainder;
834 global_multi_loop = (int)(((double)elapsed * 0.000001) *
835 current_options.get_model_hz());
836 remainder = elapsed - ( (global_multi_loop*1000000) /
837 current_options.get_model_hz() );
838 FG_LOG( FG_ALL, FG_DEBUG,
839 "Model iterations needed = " << global_multi_loop
840 << ", new remainder = " << remainder );
843 if ( global_multi_loop > 0 ) {
844 fgUpdateTimeDepCalcs(global_multi_loop, remainder);
846 FG_LOG( FG_ALL, FG_DEBUG,
847 "Elapsed time is zero ... we're zinging" );
851 #if ! defined( MACOS )
852 // Do any I/O channel work that might need to be done
856 // see if we need to load any new scenery tiles
857 global_tile_mgr.update();
859 // Process/manage pending events
860 global_events.Process();
862 // Run audio scheduler
863 #ifdef ENABLE_AUDIO_SUPPORT
864 if ( current_options.get_sound() && !audio_sched->not_working() ) {
866 # ifdef MICHAEL_JOHNSON_EXPERIMENTAL_ENGINE_AUDIO
868 // note: all these factors are relative to the sample. our
869 // sample format should really contain a conversion factor so
870 // that we can get prop speed right for arbitrary samples.
871 // Note that for normal-size props, there is a point at which
872 // the prop tips approach the speed of sound; that is a pretty
873 // strong limit to how fast the prop can go.
875 // multiplication factor is prime pitch control; add some log
876 // component for verisimilitude
878 double pitch = log((controls.get_throttle(0) * 14.0) + 1.0);
879 //fprintf(stderr, "pitch1: %f ", pitch);
880 if (controls.get_throttle(0) > 0.0 || cur_fdm_state->v_rel_wind > 40.0) {
881 //fprintf(stderr, "rel_wind: %f ", cur_fdm_state->v_rel_wind);
882 // only add relative wind and AoA if prop is moving
883 // or we're really flying at idle throttle
884 if (pitch < 5.4) { // this needs tuning
885 // prop tips not breaking sound barrier
886 pitch += log(cur_fdm_state->v_rel_wind + 0.8)/2;
888 // prop tips breaking sound barrier
889 pitch += log(cur_fdm_state->v_rel_wind + 0.8)/10;
891 //fprintf(stderr, "pitch2: %f ", pitch);
892 //fprintf(stderr, "AoA: %f ", FG_Gamma_vert_rad);
894 // Angle of Attack next... -x^3(e^x) is my best guess Just
895 // need to calculate some reasonable scaling factor and
896 // then clamp it on the positive aoa (neg adj) side
897 double aoa = cur_fdm_state->get_Gamma_vert_rad() * 2.2;
899 double aoa_adj = pow(-aoa, tmp) * pow(M_E, aoa);
900 if (aoa_adj < -0.8) aoa_adj = -0.8;
902 //fprintf(stderr, "pitch3: %f ", pitch);
904 // don't run at absurdly slow rates -- not realistic
905 // and sounds bad to boot. :-)
906 if (pitch < 0.8) pitch = 0.8;
908 //fprintf(stderr, "pitch4: %f\n", pitch);
910 double volume = controls.get_throttle(0) * 1.15 + 0.3 +
911 log(cur_fdm_state->v_rel_wind + 1.0)/14.0;
912 // fprintf(stderr, "volume: %f\n", volume);
914 pitch_envelope.setStep ( 0, 0.01, pitch );
915 volume_envelope.setStep ( 0, 0.01, volume );
919 double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
920 pitch_envelope.setStep ( 0, 0.01, param );
921 volume_envelope.setStep ( 0, 0.01, param );
923 # endif // experimental throttle patch
925 audio_sched -> update();
932 FG_LOG( FG_ALL, FG_DEBUG, "" );
936 // This is the top level master main function that is registered as
940 // The first few passes take care of initialization things (a couple
941 // per pass) and once everything has been initialized fgMainLoop from
944 static void fgIdleFunction ( void ) {
945 // printf("idle state == %d\n", idle_state);
947 if ( idle_state == 0 ) {
948 // Initialize the splash screen right away
949 if ( current_options.get_splash_screen() ) {
954 } else if ( idle_state == 1 ) {
955 // Start the intro music
957 if ( current_options.get_intro_music() ) {
958 string lockfile = "/tmp/mpg123.running";
959 FGPath mp3file( current_options.get_fg_root() );
960 mp3file.append( "Sounds/intro.mp3" );
962 string command = "(touch " + lockfile + "; mpg123 "
963 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
965 FG_LOG( FG_GENERAL, FG_INFO,
966 "Starting intro music: " << mp3file.str() );
967 system ( command.c_str() );
972 } else if ( idle_state == 2 ) {
973 // These are a few miscellaneous things that aren't really
974 // "subsystems" but still need to be initialized.
977 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
978 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
983 } else if ( idle_state == 3 ) {
984 // This is the top level init routine which calls all the
985 // other subsystem initialization routines. If you are adding
986 // a subsystem to flight gear, its initialization call should
987 // located in this routine.
988 if( !fgInitSubsystems()) {
989 FG_LOG( FG_GENERAL, FG_ALERT,
990 "Subsystem initializations failed ..." );
995 } else if ( idle_state == 4 ) {
996 // setup OpenGL view parameters
1000 // init timer routines, signals, etc. Arrange for an alarm
1001 // signal to be generated, etc.
1002 fgInitTimeDepCalcs();
1006 } else if ( idle_state == 5 ) {
1009 } else if ( idle_state == 6 ) {
1010 // Initialize audio support
1011 #ifdef ENABLE_AUDIO_SUPPORT
1014 if ( current_options.get_intro_music() ) {
1015 // Let's wait for mpg123 to finish
1016 string lockfile = "/tmp/mpg123.running";
1017 struct stat stat_buf;
1019 FG_LOG( FG_GENERAL, FG_INFO,
1020 "Waiting for mpg123 player to finish ..." );
1021 while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
1022 // file exist, wait ...
1024 FG_LOG( FG_GENERAL, FG_INFO, ".");
1026 FG_LOG( FG_GENERAL, FG_INFO, "");
1030 if ( current_options.get_sound() ) {
1031 audio_sched = new slScheduler ( 8000 );
1032 audio_mixer = new smMixer;
1033 audio_mixer -> setMasterVolume ( 80 ) ; /* 80% of max volume. */
1034 audio_sched -> setSafetyMargin ( 1.0 ) ;
1036 FGPath slfile( current_options.get_fg_root() );
1037 slfile.append( "Sounds/wasp.wav" );
1039 s1 = new slSample ( (char *)slfile.c_str() );
1040 FG_LOG( FG_GENERAL, FG_INFO,
1041 "Rate = " << s1 -> getRate()
1042 << " Bps = " << s1 -> getBps()
1043 << " Stereo = " << s1 -> getStereo() );
1044 audio_sched -> loopSample ( s1 );
1046 if ( audio_sched->not_working() ) {
1049 pitch_envelope.setStep ( 0, 0.01, 0.6 );
1050 volume_envelope.setStep ( 0, 0.01, 0.6 );
1052 audio_sched -> addSampleEnvelope( s1, 0, 0,
1054 SL_PITCH_ENVELOPE );
1055 audio_sched -> addSampleEnvelope( s1, 0, 1,
1057 SL_VOLUME_ENVELOPE );
1060 // strcpy(slfile, path);
1061 // strcat(slfile, "thunder.wav");
1062 // s2 -> loadFile ( slfile );
1063 // s2 -> adjustVolume(0.5);
1064 // audio_sched -> playSample ( s2 );
1072 if ( idle_state == 1000 ) {
1073 // We've finished all our initialization steps, from now on we
1074 // run the main loop.
1078 if ( current_options.get_splash_screen() == 1 ) {
1079 fgSplashUpdate(0.0);
1084 // options.cxx needs to see this for toggle_panel()
1085 // Handle new window size or exposure
1086 void fgReshape( int width, int height ) {
1087 if ( ! current_options.get_panel_status() ) {
1088 current_view.set_win_ratio( (GLfloat) width / (GLfloat) height );
1089 xglViewport(0, 0 , (GLint)(width), (GLint)(height) );
1091 current_view.set_win_ratio( (GLfloat) width /
1092 ((GLfloat) (height)*0.4232) );
1093 xglViewport(0, (GLint)((height)*0.5768), (GLint)(width),
1094 (GLint)((height)*0.4232) );
1097 current_view.set_winWidth( width );
1098 current_view.set_winHeight( height );
1099 current_view.force_update_fov_math();
1101 // set these fov to be the same as in fgRenderFrame()
1102 float x_fov = current_options.get_fov();
1103 float y_fov = x_fov * 1.0 / current_view.get_win_ratio();
1104 ssgSetFOV( x_fov, y_fov );
1106 glViewport ( 0, 0, width, height );
1107 float fov = current_options.get_fov();
1108 ssgSetFOV(fov * current_view.get_win_ratio(), fov);
1110 if ( idle_state == 1000 ) {
1111 // yes we've finished all our initializations and are running
1112 // the main loop, so this will now work without seg faulting
1114 solarSystemRebuild();
1115 current_view.UpdateViewParams(cur_view_fdm);
1116 if ( current_options.get_panel_status() ) {
1117 FGPanel::OurPanel->ReInit(0, 0, 1024, 768);
1123 // Initialize GLUT and define a main window
1124 int fgGlutInit( int *argc, char **argv ) {
1126 #if !defined( MACOS )
1127 // GLUT will extract all glut specific options so later on we only
1128 // need wory about our own.
1129 xglutInit(argc, argv);
1132 // Define Display Parameters
1133 xglutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1135 FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
1136 current_options.get_xsize() << "x" << current_options.get_ysize() );
1138 // Define initial window size
1139 xglutInitWindowSize( current_options.get_xsize(),
1140 current_options.get_ysize() );
1142 // Initialize windows
1143 if ( current_options.get_game_mode() == 0 ) {
1144 // Open the regular window
1145 xglutCreateWindow("Flight Gear");
1146 #ifndef GLUT_WRONG_VERSION
1148 // Open the cool new 'game mode' window
1149 char game_mode_str[256];
1150 sprintf( game_mode_str, "width=%d height=%d bpp=32",
1151 current_options.get_xsize(),
1152 current_options.get_ysize() );
1154 FG_LOG( FG_GENERAL, FG_INFO,
1155 "game mode params = " << game_mode_str );
1156 glutGameModeString( game_mode_str );
1157 glutEnterGameMode();
1161 // This seems to be the absolute earliest in the init sequence
1162 // that these calls will return valid info. Too bad it's after
1163 // we've already created and sized out window. :-(
1164 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1165 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1166 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1168 FG_LOG ( FG_GENERAL, FG_INFO, general.get_glRenderer() );
1171 // try to determine if we should adjust the initial default
1172 // display resolution. The options class defaults (is
1173 // initialized) to 640x480.
1174 string renderer = general.glRenderer;
1176 // currently we only know how to deal with Mesa/Glide/Voodoo cards
1177 if ( renderer.find( "Glide" ) != string::npos ) {
1178 FG_LOG( FG_GENERAL, FG_INFO, "Detected a Glide driver" );
1179 if ( renderer.find( "FB/8" ) != string::npos ) {
1180 // probably a voodoo-2
1181 if ( renderer.find( "TMU/SLI" ) != string::npos ) {
1182 // probably two SLI'd Voodoo-2's
1183 current_options.set_xsize( 1024 );
1184 current_options.set_ysize( 768 );
1185 FG_LOG( FG_GENERAL, FG_INFO,
1186 "It looks like you have two sli'd voodoo-2's." << endl
1187 << "upgrading your win resolution to 1024 x 768" );
1188 glutReshapeWindow(1024, 768);
1190 // probably a single non-SLI'd Voodoo-2
1191 current_options.set_xsize( 800 );
1192 current_options.set_ysize( 600 );
1193 FG_LOG( FG_GENERAL, FG_INFO,
1194 "It looks like you have a voodoo-2." << endl
1195 << "upgrading your win resolution to 800 x 600" );
1196 glutReshapeWindow(800, 600);
1198 } else if ( renderer.find( "FB/2" ) != string::npos ) {
1199 // probably a voodoo-1, stick with the default
1202 // we have no special knowledge of this card, stick with the default
1210 // Initialize GLUT event handlers
1211 int fgGlutInitEvents( void ) {
1212 // call fgReshape() on window resizes
1213 xglutReshapeFunc( fgReshape );
1215 // call GLUTkey() on keyboard event
1216 xglutKeyboardFunc( GLUTkey );
1217 glutSpecialFunc( GLUTspecialkey );
1219 // call guiMouseFunc() whenever our little rodent is used
1220 glutMouseFunc ( guiMouseFunc );
1221 glutMotionFunc (guiMotionFunc );
1222 glutPassiveMotionFunc (guiMotionFunc );
1224 // call fgMainLoop() whenever there is
1225 // nothing else to do
1226 xglutIdleFunc( fgIdleFunction );
1229 xglutDisplayFunc( fgRenderFrame );
1236 int main( int argc, char **argv ) {
1238 #if defined( MACOS )
1239 argc = ccommand( &argv );
1243 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1246 // set default log levels
1247 fglog().setLogLevels( FG_ALL, FG_INFO );
1249 FG_LOG( FG_GENERAL, FG_INFO, "Flight Gear: Version " << VERSION << endl );
1251 // seed the random number generater
1254 // Load the configuration parameters
1255 if ( !fgInitConfig(argc, argv) ) {
1256 FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1260 // Initialize the Window/Graphics environment.
1261 if( !fgGlutInit(&argc, argv) ) {
1262 FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1266 // Initialize the various GLUT Event Handlers.
1267 if( !fgGlutInitEvents() ) {
1268 FG_LOG( FG_GENERAL, FG_ALERT,
1269 "GLUT event handler initialization failed ..." );
1273 // Initialize ssg (from plib)
1276 // Initialize the user interface (we need to do this before
1277 // passing off control to glut and before fgInitGeneral to get our
1281 // Do some quick general initializations
1282 if( !fgInitGeneral()) {
1283 FG_LOG( FG_GENERAL, FG_ALERT,
1284 "General initializations failed ..." );
1289 // some ssg test stuff (requires data from the plib source
1290 // distribution) specifically from the ssg tux example
1293 FGPath modelpath( current_options.get_fg_root() );
1294 modelpath.append( "Models" );
1295 modelpath.append( "Geometry" );
1297 FGPath texturepath( current_options.get_fg_root() );
1298 texturepath.append( "Models" );
1299 texturepath.append( "Textures" );
1301 ssgModelPath( (char *)modelpath.c_str() );
1302 ssgTexturePath( (char *)texturepath.c_str() );
1304 scene = new ssgRoot;
1305 terrain = new ssgBranch;
1306 terrain->setName( "Terrain" );
1307 penguin_sel = new ssgSelector;
1308 penguin_pos = new ssgTransform;
1310 ssgEntity *tux_obj = ssgLoadAC( "glider.ac" );
1311 // ssgEntity *tux_obj = ssgLoadAC( "Tower1x.ac" );
1312 penguin_pos->addKid( tux_obj );
1313 penguin_sel->addKid( penguin_pos );
1314 ssgFlatten( tux_obj );
1315 ssgStripify( penguin_sel );
1316 penguin_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1318 #ifdef FG_NETWORK_OLK
1319 // Do the network intialization
1320 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1323 scene->addKid( terrain );
1324 scene->addKid( penguin_sel );
1326 // pass control off to the master GLUT event handler
1329 // we never actually get here ... but to avoid compiler warnings,