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/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/debug/logstream.hxx>
69 #include <simgear/math/fg_geodesy.hxx>
70 #include <simgear/math/polar3d.hxx>
71 #include <simgear/math/fg_random.h>
72 #include <simgear/misc/fgpath.hxx>
74 #include <Include/general.hxx>
76 #include <Aircraft/aircraft.hxx>
77 #include <Ephemeris/ephemeris.hxx>
79 #include <Autopilot/newauto.hxx>
80 #include <Cockpit/cockpit.hxx>
81 #include <Cockpit/radiostack.hxx>
82 #include <Cockpit/steam.hxx>
84 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
86 #include <Joystick/joystick.hxx>
88 #include <NetworkOLK/network.h>
90 #include <Objects/materialmgr.hxx>
91 #include <Scenery/scenery.hxx>
92 #include <Scenery/tilemgr.hxx>
93 #include <Sky/sky.hxx>
94 #include <Time/event.hxx>
95 #include <Time/fg_time.hxx>
96 #include <Time/fg_timer.hxx>
97 #include <Time/sunpos.hxx>
99 #ifndef FG_OLD_WEATHER
100 # include <WeatherCM/FGLocalWeatherDatabase.h>
102 # include <Weather/weather.hxx>
106 #include "fg_init.hxx"
108 #include "keyboard.hxx"
109 #include "options.hxx"
110 #include "splash.hxx"
114 // -dw- use custom sioux settings so I can see output window
117 # include <sioux.h> // settings for output window
119 # include <console.h>
123 // This is a record containing a bit of global housekeeping information
126 // Specify our current idle function state. This is used to run all
127 // our initializations out of the glutIdleLoop() so that we can get a
128 // splash screen up and running right away.
129 static int idle_state = 0;
130 static int global_multi_loop;
135 // Global structures for the Audio library
136 #ifdef ENABLE_AUDIO_SUPPORT
137 slEnvelope pitch_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
138 slEnvelope volume_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
139 slScheduler *audio_sched;
140 smMixer *audio_mixer;
147 ssgRoot *scene = NULL;
148 ssgBranch *terrain = NULL;
149 ssgSelector *penguin_sel = NULL;
150 ssgTransform *penguin_pos = NULL;
152 #ifdef FG_NETWORK_OLK
153 ssgSelector *fgd_sel = NULL;
154 ssgTransform *fgd_pos = NULL;
158 // current fdm/position used for view
159 FGInterface cur_view_fdm;
166 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
168 { 1.0f, 0.0f, 0.0f, 0.0f },
169 { 0.0f, 0.0f, -1.0f, 0.0f },
170 { 0.0f, 1.0f, 0.0f, 0.0f },
171 { 0.0f, 0.0f, 0.0f, 1.0f }
174 // The following defines flight gear options. Because glutlib will also
175 // want to parse its own options, those options must not be included here
176 // or they will get parsed by the main program option parser. Hence case
177 // is significant for any option added that might be in conflict with
180 // glutlib parses for:
182 // -direct (invalid in Win32)
186 // -indirect (invalid in Win32)
189 // Note that glutlib depends upon strings while this program's
190 // option parser wants only initial characters followed by numbers
195 ssgSimpleState *default_state;
196 ssgSimpleState *hud_and_panel;
197 ssgSimpleState *menus;
199 void fgBuildRenderStates( void ) {
200 default_state = new ssgSimpleState;
201 default_state->disable( GL_TEXTURE_2D );
202 default_state->enable( GL_CULL_FACE );
203 default_state->enable( GL_COLOR_MATERIAL );
204 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
205 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
206 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
207 default_state->disable( GL_BLEND );
208 default_state->disable( GL_ALPHA_TEST );
209 default_state->disable( GL_LIGHTING );
211 hud_and_panel = new ssgSimpleState;
212 hud_and_panel->disable( GL_CULL_FACE );
213 hud_and_panel->disable( GL_TEXTURE_2D );
214 hud_and_panel->disable( GL_LIGHTING );
215 hud_and_panel->enable( GL_BLEND );
217 menus = new ssgSimpleState;
218 menus->disable( GL_CULL_FACE );
219 menus->disable( GL_TEXTURE_2D );
220 menus->enable( GL_BLEND );
224 // fgInitVisuals() -- Initialize various GL/view parameters
225 void fgInitVisuals( void ) {
228 l = &cur_light_params;
230 #ifndef GLUT_WRONG_VERSION
231 // Go full screen if requested ...
232 if ( current_options.get_fullscreen() ) {
237 // If enabled, normal vectors specified with glNormal are scaled
238 // to unit length after transformation. See glNormal.
239 // glEnable( GL_NORMALIZE );
241 glEnable( GL_LIGHTING );
242 glEnable( GL_LIGHT0 );
243 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
246 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
247 ssgGetLight( 0 ) -> setPosition( sunpos );
249 // glFogi (GL_FOG_MODE, GL_LINEAR);
250 glFogi (GL_FOG_MODE, GL_EXP2);
251 if ( (current_options.get_fog() == 1) ||
252 (current_options.get_shading() == 0) ) {
253 // if fastest fog requested, or if flat shading force fastest
254 glHint ( GL_FOG_HINT, GL_FASTEST );
255 } else if ( current_options.get_fog() == 2 ) {
256 glHint ( GL_FOG_HINT, GL_NICEST );
258 if ( current_options.get_wireframe() ) {
260 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
263 // This is the default anyways, but it can't hurt
264 glFrontFace ( GL_CCW );
267 // glEnable(GL_POINT_SMOOTH);
268 // glEnable(GL_LINE_SMOOTH);
269 // glEnable(GL_POLYGON_SMOOTH);
273 // Update all Visuals (redraws anything graphics related)
274 void fgRenderFrame( void ) {
278 fgLIGHT *l = &cur_light_params;
279 FGTime *t = FGTime::cur_time_params;
280 // FGView *v = ¤t_view;
281 static double last_visibility = -9999;
282 static bool in_puff = false;
283 static double puff_length = 0;
284 static double puff_progression = 0;
285 const double ramp_up = 0.15;
286 const double ramp_down = 0.15;
289 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
290 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
291 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
292 // GLfloat mat_shininess[] = { 10.0 };
293 GLbitfield clear_mask;
295 if ( idle_state != 1000 ) {
296 // still initializing, draw the splash screen
297 if ( current_options.get_splash_screen() == 1 ) {
301 // idle_state is now 1000 meaning we've finished all our
302 // initializations and are running the main loop, so this will
303 // now work without seg faulting the system.
305 // printf("Ground = %.2f Altitude = %.2f\n", scenery.cur_elev,
306 // FG_Altitude * FEET_TO_METER);
308 // this is just a temporary hack, to make me understand Pui
309 // timerText -> setLabel (ctime (&t->cur_time));
312 // update view volume parameters
313 // cout << "before pilot_view update" << endl;
314 pilot_view.UpdateViewParams(*cur_fdm_state);
315 // cout << "after pilot_view update" << endl;
316 current_view.UpdateViewParams(cur_view_fdm);
318 // set the sun position
319 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
321 clear_mask = GL_DEPTH_BUFFER_BIT;
322 if ( current_options.get_wireframe() ) {
323 clear_mask |= GL_COLOR_BUFFER_BIT;
325 if ( current_options.get_panel_status() ) {
326 // we can't clear the screen when the panel is active
327 } else if ( current_options.get_skyblend() ) {
328 if ( current_options.get_textures() ) {
329 // glClearColor(black[0], black[1], black[2], black[3]);
330 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
331 l->adj_fog_color[2], l->adj_fog_color[3]);
332 clear_mask |= GL_COLOR_BUFFER_BIT;
335 glClearColor(l->sky_color[0], l->sky_color[1],
336 l->sky_color[2], l->sky_color[3]);
337 clear_mask |= GL_COLOR_BUFFER_BIT;
339 glClear( clear_mask );
341 // Tell GL we are switching to model view parameters
343 // I really should create a derived ssg node or use a call
344 // back or something so that I can draw the sky within the
345 // ssgCullAndDraw() function, but for now I just mimic what
346 // ssg does to set up the model view matrix
347 glMatrixMode(GL_MODELVIEW);
349 ssgSetCamera( current_view.VIEW );
352 sgMat4 vm_tmp, view_mat;
353 sgTransposeNegateMat4 ( vm_tmp, current_view.VIEW ) ;
354 sgCopyMat4( view_mat, copy_of_ssgOpenGLAxisSwapMatrix ) ;
355 sgPreMultMat4( view_mat, vm_tmp ) ;
356 glLoadMatrixf( (float *)view_mat );
359 // set the opengl state to known default values
360 default_state->force();
363 if ( current_options.get_skyblend() ) {
366 current_view.get_view_pos().x(),
367 current_view.get_view_pos().y(),
368 current_view.get_view_pos().z() );
371 sgSetVec3( zero_elev,
372 current_view.get_cur_zero_elev().x(),
373 current_view.get_cur_zero_elev().y(),
374 current_view.get_cur_zero_elev().z() );
376 /* cout << "thesky->repaint() sky_color = "
377 << cur_light_params.sky_color[0] << " "
378 << cur_light_params.sky_color[1] << " "
379 << cur_light_params.sky_color[2] << " "
380 << cur_light_params.sky_color[3] << endl;
382 << cur_light_params.fog_color[0] << " "
383 << cur_light_params.fog_color[1] << " "
384 << cur_light_params.fog_color[2] << " "
385 << cur_light_params.fog_color[3] << endl;
386 cout << " sun_angle = " << cur_light_params.sun_angle
387 << " moon_angle = " << cur_light_params.moon_angle
389 thesky->repaint( cur_light_params.sky_color,
390 cur_light_params.adj_fog_color,
391 cur_light_params.sun_angle,
392 cur_light_params.moon_angle,
393 ephem->getNumPlanets(), ephem->getPlanets(),
394 ephem->getNumStars(), ephem->getStars() );
396 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
397 << view_pos[1] << " " << view_pos[2] << endl;
398 cout << " zero_elev = " << zero_elev[0] << " "
399 << zero_elev[1] << " " << zero_elev[2]
400 << " lon = " << cur_fdm_state->get_Longitude()
401 << " lat = " << cur_fdm_state->get_Latitude() << endl;
402 cout << " sun_rot = " << cur_light_params.sun_rotation
403 << " gst = " << FGTime::cur_time_params->getGst() << endl;
404 cout << " sun ra = " << ephem->getSunRightAscension()
405 << " sun dec = " << ephem->getSunDeclination()
406 << " moon ra = " << ephem->getMoonRightAscension()
407 << " moon dec = " << ephem->getMoonDeclination() << endl; */
409 thesky->reposition( view_pos, zero_elev,
410 current_view.get_local_up(),
411 cur_fdm_state->get_Longitude(),
412 cur_fdm_state->get_Latitude(),
413 cur_light_params.sun_rotation,
414 FGTime::cur_time_params->getGst(),
415 ephem->getSunRightAscension(),
416 ephem->getSunDeclination(), 50000.0,
417 ephem->getMoonRightAscension(),
418 ephem->getMoonDeclination(), 50000.0 );
421 glEnable( GL_DEPTH_TEST );
422 if ( current_options.get_fog() > 0 ) {
424 glFogi( GL_FOG_MODE, GL_EXP2 );
425 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
428 // update fog params if visibility has changed
429 #ifndef FG_OLD_WEATHER
430 double cur_visibility = WeatherDatabase->getWeatherVisibility();
432 double cur_visibility = current_weather.get_visibility();
434 double actual_visibility = cur_visibility;
436 if ( current_options.get_clouds() ) {
437 double diff = fabs( cur_fdm_state->get_Altitude() * FEET_TO_METER -
438 current_options.get_clouds_asl() );
439 // cout << "altitude diff = " << diff << endl;
442 // calc chance of entering cloud puff
443 double rnd = fg_random();
444 double chance = rnd * rnd * rnd;
445 if ( chance > 0.95 /* * (diff - 25) / 50.0 */ ) {
448 puff_length = fg_random() * 2.0; // up to 2 seconds
449 } while ( puff_length <= 0.0 );
450 puff_progression = 0.0;
454 actual_visibility = cur_visibility * (diff - 25) / 50.0;
457 // modify actual_visibility based on puff envelope
459 if ( puff_progression <= ramp_up ) {
460 double x = FG_PI_2 * puff_progression / ramp_up;
461 double factor = 1.0 - sin( x );
462 actual_visibility = actual_visibility * factor;
463 } else if ( puff_progression >= ramp_up + puff_length ) {
465 (puff_progression - (ramp_up + puff_length)) /
467 double factor = sin( x );
468 actual_visibility = actual_visibility * factor;
470 actual_visibility = 0.0;
473 /* cout << "len = " << puff_length
475 << " factor = " << factor
476 << " actual_visibility = " << actual_visibility
479 puff_progression += ( global_multi_loop *
480 current_options.get_speed_up() ) /
481 (double)current_options.get_model_hz();
483 /* cout << "gml = " << global_multi_loop
484 << " speed up = " << current_options.get_speed_up()
485 << " hz = " << current_options.get_model_hz() << endl;
488 if ( puff_progression > puff_length + ramp_up + ramp_down) {
493 // never let visibility drop below zero
494 if ( actual_visibility < 0 ) {
495 actual_visibility = 0;
500 // cout << "actual visibility = " << actual_visibility << endl;
502 if ( actual_visibility != last_visibility ) {
503 last_visibility = actual_visibility;
505 // cout << "----> updating fog params" << endl;
507 GLfloat fog_exp_density;
508 GLfloat fog_exp2_density;
511 fog_exp_density = -log(0.01 / actual_visibility);
514 fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
516 // Set correct opengl fog density
517 glFogf (GL_FOG_DENSITY, fog_exp2_density);
520 // set lighting parameters
521 glLightfv( GL_LIGHT0, GL_AMBIENT, l->scene_ambient );
522 glLightfv( GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
523 // glLightfv(GL_LIGHT0, GL_SPECULAR, white );
525 // texture parameters
526 // glEnable( GL_TEXTURE_2D );
527 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
528 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
529 // set base color (I don't think this is doing anything here)
530 // glMaterialfv (GL_FRONT, GL_AMBIENT, white);
531 // (GL_FRONT, GL_DIFFUSE, white);
532 // glMaterialfv (GL_FRONT, GL_SPECULAR, white);
533 // glMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
536 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
537 ssgGetLight( 0 ) -> setPosition( sunpos );
539 // glMatrixMode( GL_PROJECTION );
541 float fov = current_options.get_fov();
542 ssgSetFOV(fov * current_view.get_win_ratio(), fov);
544 double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
547 // FG_LOG( FG_ALL, FG_INFO, "visibility is "
548 // << current_weather.get_visibility() );
551 ssgSetNearFar( 10.0f, 120000.0f );
553 ssgSetNearFar( 0.5f, 120000.0f );
556 if ( current_options.get_view_mode() ==
557 fgOPTIONS::FG_VIEW_PILOT )
560 penguin_sel->select(0);
561 } else if ( current_options.get_view_mode() ==
562 fgOPTIONS::FG_VIEW_FOLLOW )
564 // select view matrix from front of view matrix queue
565 // FGMat4Wrapper tmp = current_view.follow.front();
566 // sgCopyMat4( sgVIEW, tmp.m );
568 // enable TuX and set up his position and orientation
569 penguin_sel->select(1);
572 sgMakeTransMat4( sgTRANS,
573 pilot_view.view_pos.x(),
574 pilot_view.view_pos.y(),
575 pilot_view.view_pos.z() );
578 sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
581 sgMakeRotMat4( sgROT, -90.0, ownship_up );
585 // sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
586 // sgMultMat4( sgTUX, sgTMP, sgTRANS );
588 // sgTUX = ( sgROT * pilot_view.VIEW_ROT ) * sgTRANS
590 sgCopyMat4( sgTUX, sgROT );
591 sgPostMultMat4( sgTUX, pilot_view.VIEW_ROT );
592 sgPostMultMat4( sgTUX, sgTRANS );
595 sgSetCoord( &tuxpos, sgTUX );
596 penguin_pos->setTransform( &tuxpos );
599 # ifdef FG_NETWORK_OLK
600 if ( current_options.get_network_olk() ) {
602 other = head->next; /* put listpointer to start */
603 while ( other != tail) { /* display all except myself */
604 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
605 other->fgd_sel->select(1);
606 sgSetCoord( &fgdpos, other->sgFGD_COORD );
607 other->fgd_pos->setTransform( &fgdpos );
612 // fgd_sel->select(1);
613 // sgCopyMat4( sgTUX, current_view.sgVIEW);
615 // sgSetCoord( &fgdpos, sgFGD_VIEW );
616 // fgd_pos->setTransform( &fgdpos);
620 // ssgSetCamera( current_view.VIEW );
622 // position tile nodes and update range selectors
623 global_tile_mgr.prep_ssg_nodes();
625 // force the default state so ssg can get back on track if
626 // we've changed things elsewhere (this is now handled
629 // FGMaterialSlot m_slot;
630 // FGMaterialSlot *m_ptr = &m_slot;
631 // if ( material_mgr.find( "Default", m_ptr ) ) {
632 // m_ptr->get_state()->force();
635 // draw the sky backdrop
636 thesky->draw_background();
638 // draw the ssg scene
639 ssgCullAndDraw( scene );
641 // draw the sky cloud layers
642 thesky->draw_scene();
644 // display HUD && Panel
646 glDisable( GL_DEPTH_TEST );
647 // glDisable( GL_CULL_FACE );
648 // glDisable( GL_TEXTURE_2D );
649 hud_and_panel->apply();
652 // We can do translucent menus, so why not. :-)
653 // glEnable ( GL_BLEND ) ;
655 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
657 // glDisable ( GL_BLEND ) ;
659 // glEnable( GL_FOG );
666 // Update internal time dependent calculations (i.e. flight model)
667 void fgUpdateTimeDepCalcs(int multi_loop, int remainder) {
668 static fdm_state_list fdm_list;
669 // FGInterface fdm_state;
670 fgLIGHT *l = &cur_light_params;
671 FGTime *t = FGTime::cur_time_params;
672 // FGView *v = ¤t_view;
675 // update the flight model
676 if ( multi_loop < 0 ) {
680 if ( !t->getPause() ) {
681 // run Autopilot system
682 current_autopilot->run();
684 // printf("updating flight model x %d\n", multi_loop);
685 /* fgFDMUpdate( current_options.get_flight_model(),
687 multi_loop * current_options.get_speed_up(),
689 cur_fdm_state->update( multi_loop * current_options.get_speed_up() );
690 FGSteam::update( multi_loop * current_options.get_speed_up() );
692 // fgFDMUpdate( current_options.get_flight_model(),
693 // fdm_state, 0, remainder );
694 cur_fdm_state->update( 0 );
695 FGSteam::update( 0 );
698 fdm_list.push_back( *cur_fdm_state );
699 while ( fdm_list.size() > 15 ) {
700 fdm_list.pop_front();
703 if ( current_options.get_view_mode() == fgOPTIONS::FG_VIEW_PILOT ) {
704 cur_view_fdm = *cur_fdm_state;
706 } else if ( current_options.get_view_mode() == fgOPTIONS::FG_VIEW_FOLLOW ) {
707 cur_view_fdm = fdm_list.front();
710 // update the view angle
711 for ( i = 0; i < multi_loop; i++ ) {
712 if ( fabs(current_view.get_goal_view_offset() -
713 current_view.get_view_offset()) < 0.05 )
715 current_view.set_view_offset( current_view.get_goal_view_offset() );
718 // move current_view.view_offset towards current_view.goal_view_offset
719 if ( current_view.get_goal_view_offset() >
720 current_view.get_view_offset() )
722 if ( current_view.get_goal_view_offset() -
723 current_view.get_view_offset() < FG_PI )
725 current_view.inc_view_offset( 0.01 );
727 current_view.inc_view_offset( -0.01 );
730 if ( current_view.get_view_offset() -
731 current_view.get_goal_view_offset() < FG_PI )
733 current_view.inc_view_offset( -0.01 );
735 current_view.inc_view_offset( 0.01 );
738 if ( current_view.get_view_offset() > FG_2PI ) {
739 current_view.inc_view_offset( -FG_2PI );
740 } else if ( current_view.get_view_offset() < 0 ) {
741 current_view.inc_view_offset( FG_2PI );
746 double tmp = -(l->sun_rotation + FG_PI)
747 - (cur_fdm_state->get_Psi() - current_view.get_view_offset() );
748 while ( tmp < 0.0 ) {
751 while ( tmp > FG_2PI ) {
754 /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
755 FG_Psi * RAD_TO_DEG, current_view.view_offset * RAD_TO_DEG,
756 -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
759 // Update solar system
760 ephem->update( t, cur_fdm_state->get_Latitude() );
762 // Update radio stack model
763 current_radiostack->update( cur_fdm_state->get_Longitude(),
764 cur_fdm_state->get_Latitude(),
765 cur_fdm_state->get_Altitude() * FEET_TO_METER );
769 void fgInitTimeDepCalcs( void ) {
772 // #ifdef HAVE_SETITIMER
773 // fgTimerInit( 1.0 / current_options.get_model_hz(),
774 // fgUpdateTimeDepCalcs );
775 // #endif HAVE_SETITIMER
779 static const double alt_adjust_ft = 3.758099;
780 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
783 // What should we do when we have nothing else to do? Let's get ready
784 // for the next move and update the display?
785 static void fgMainLoop( void ) {
787 static long remainder = 0;
789 #ifdef FANCY_FRAME_COUNTER
793 static time_t last_time = 0;
794 static int frames = 0;
795 #endif // FANCY_FRAME_COUNTER
797 t = FGTime::cur_time_params;
799 FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
800 FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
802 #ifdef FG_NETWORK_OLK
803 if ( current_options.get_network_olk() ) {
804 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
805 // printf("FGD: Netupdate\n");
806 fgd_send_com( "A", FGFS_host); // Send Mat4 data
807 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
812 #if defined( ENABLE_PLIB_JOYSTICK )
813 // Read joystick and update control settings
814 if ( current_options.get_control_mode() == fgOPTIONS::FG_JOYSTICK ) {
817 #elif defined( ENABLE_GLUT_JOYSTICK )
818 // Glut joystick support works by feeding a joystick handler
819 // function to glut. This is taken care of once in the joystick
820 // init routine and we don't have to worry about it again.
823 #ifdef FG_OLD_WEATHER
824 current_weather.Update();
827 // Fix elevation. I'm just sticking this here for now, it should
828 // probably move eventually
830 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
832 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
833 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
835 if ( scenery.cur_elev > -9990 ) {
836 if ( cur_fdm_state->get_Altitude() * FEET_TO_METER <
837 (scenery.cur_elev + alt_adjust_m - 3.0) ) {
838 // now set aircraft altitude above ground
839 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
840 cur_fdm_state->get_Altitude() * FEET_TO_METER,
841 scenery.cur_elev + alt_adjust_m - 3.0,
842 scenery.cur_elev + alt_adjust_m );
843 fgFDMForceAltitude( current_options.get_flight_model(),
844 scenery.cur_elev + alt_adjust_m );
846 FG_LOG( FG_ALL, FG_DEBUG,
847 "<*> resetting altitude to "
848 << cur_fdm_state->get_Altitude() * FEET_TO_METER << " meters" );
850 fgFDMSetGroundElevation( current_options.get_flight_model(),
851 scenery.cur_elev ); // meters
854 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
856 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
857 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
860 t->update( cur_fdm_state->get_Longitude(),
861 cur_fdm_state->get_Latitude(),
862 cur_fdm_state->get_Altitude()* FEET_TO_METER );
864 // Get elapsed time (in usec) for this past frame
865 elapsed = fgGetTimeInterval();
866 FG_LOG( FG_ALL, FG_DEBUG,
867 "Elapsed time interval is = " << elapsed
868 << ", previous remainder is = " << remainder );
870 // Calculate frame rate average
871 #ifdef FANCY_FRAME_COUNTER
872 /* old fps calculation */
876 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
877 tmp = general.get_frame(i);
879 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
880 general.set_frame(i+1,tmp);
882 tmp = 1000000.0 / (float)elapsed;
883 general.set_frame(0,tmp);
884 // printf("frame[0] = %.2f\n", general.frames[0]);
886 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
887 // printf("ave = %.2f\n", general.frame_rate);
890 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
891 general.set_frame_rate( frames );
892 FG_LOG( FG_ALL, FG_DEBUG,
893 "--> Frame rate is = " << general.get_frame_rate() );
896 last_time = t->get_cur_time();
901 if ( ! use_signals ) {
902 // Calculate model iterations needed for next frame
903 elapsed += remainder;
905 global_multi_loop = (int)(((double)elapsed * 0.000001) *
906 current_options.get_model_hz());
907 remainder = elapsed - ( (global_multi_loop*1000000) /
908 current_options.get_model_hz() );
909 FG_LOG( FG_ALL, FG_DEBUG,
910 "Model iterations needed = " << global_multi_loop
911 << ", new remainder = " << remainder );
914 if ( global_multi_loop > 0 ) {
915 fgUpdateTimeDepCalcs(global_multi_loop, remainder);
917 FG_LOG( FG_ALL, FG_DEBUG,
918 "Elapsed time is zero ... we're zinging" );
922 #if ! defined( MACOS )
923 // Do any I/O channel work that might need to be done
927 // see if we need to load any new scenery tiles
928 global_tile_mgr.update();
930 // Process/manage pending events
931 global_events.Process();
933 // Run audio scheduler
934 #ifdef ENABLE_AUDIO_SUPPORT
935 if ( current_options.get_sound() && !audio_sched->not_working() ) {
937 # ifdef MICHAEL_JOHNSON_EXPERIMENTAL_ENGINE_AUDIO
939 // note: all these factors are relative to the sample. our
940 // sample format should really contain a conversion factor so
941 // that we can get prop speed right for arbitrary samples.
942 // Note that for normal-size props, there is a point at which
943 // the prop tips approach the speed of sound; that is a pretty
944 // strong limit to how fast the prop can go.
946 // multiplication factor is prime pitch control; add some log
947 // component for verisimilitude
949 double pitch = log((controls.get_throttle(0) * 14.0) + 1.0);
950 //fprintf(stderr, "pitch1: %f ", pitch);
951 // if (controls.get_throttle(0) > 0.0 ||
952 // cur_fdm_state->v_rel_wind > 40.0) {
954 //fprintf(stderr, "rel_wind: %f ", cur_fdm_state->v_rel_wind);
955 // only add relative wind and AoA if prop is moving
956 // or we're really flying at idle throttle
957 if (pitch < 5.4) { // this needs tuning
958 // prop tips not breaking sound barrier
959 pitch += log(cur_fdm_state->v_rel_wind + 0.8)/2;
961 // prop tips breaking sound barrier
962 pitch += log(cur_fdm_state->v_rel_wind + 0.8)/10;
964 //fprintf(stderr, "pitch2: %f ", pitch);
965 //fprintf(stderr, "AoA: %f ", FG_Gamma_vert_rad);
967 // Angle of Attack next... -x^3(e^x) is my best guess Just
968 // need to calculate some reasonable scaling factor and
969 // then clamp it on the positive aoa (neg adj) side
970 double aoa = cur_fdm_state->get_Gamma_vert_rad() * 2.2;
972 double aoa_adj = pow(-aoa, tmp) * pow(M_E, aoa);
973 if (aoa_adj < -0.8) aoa_adj = -0.8;
975 //fprintf(stderr, "pitch3: %f ", pitch);
977 // don't run at absurdly slow rates -- not realistic
978 // and sounds bad to boot. :-)
979 if (pitch < 0.8) pitch = 0.8;
981 // fprintf(stderr, "pitch4: %f\n", pitch);
983 double volume = controls.get_throttle(0) * 1.15 + 0.3 +
984 log(cur_fdm_state->v_rel_wind + 1.0)/14.0;
985 // fprintf(stderr, "volume: %f\n", volume);
987 pitch_envelope.setStep ( 0, 0.01, pitch );
988 volume_envelope.setStep ( 0, 0.01, volume );
992 double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
993 pitch_envelope.setStep ( 0, 0.01, param );
994 volume_envelope.setStep ( 0, 0.01, param );
996 # endif // experimental throttle patch
998 audio_sched -> update();
1005 FG_LOG( FG_ALL, FG_DEBUG, "" );
1009 // This is the top level master main function that is registered as
1010 // our idle funciton
1013 // The first few passes take care of initialization things (a couple
1014 // per pass) and once everything has been initialized fgMainLoop from
1017 static void fgIdleFunction ( void ) {
1018 // printf("idle state == %d\n", idle_state);
1020 if ( idle_state == 0 ) {
1021 // Initialize the splash screen right away
1022 if ( current_options.get_splash_screen() ) {
1027 } else if ( idle_state == 1 ) {
1028 // Start the intro music
1030 if ( current_options.get_intro_music() ) {
1031 string lockfile = "/tmp/mpg123.running";
1032 FGPath mp3file( current_options.get_fg_root() );
1033 mp3file.append( "Sounds/intro.mp3" );
1035 string command = "(touch " + lockfile + "; mpg123 "
1036 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
1038 FG_LOG( FG_GENERAL, FG_INFO,
1039 "Starting intro music: " << mp3file.str() );
1040 system ( command.c_str() );
1045 } else if ( idle_state == 2 ) {
1046 // These are a few miscellaneous things that aren't really
1047 // "subsystems" but still need to be initialized.
1050 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1051 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1056 } else if ( idle_state == 3 ) {
1057 // This is the top level init routine which calls all the
1058 // other subsystem initialization routines. If you are adding
1059 // a subsystem to flight gear, its initialization call should
1060 // located in this routine.
1061 if( !fgInitSubsystems()) {
1062 FG_LOG( FG_GENERAL, FG_ALERT,
1063 "Subsystem initializations failed ..." );
1068 } else if ( idle_state == 4 ) {
1069 // setup OpenGL view parameters
1072 if ( use_signals ) {
1073 // init timer routines, signals, etc. Arrange for an alarm
1074 // signal to be generated, etc.
1075 fgInitTimeDepCalcs();
1079 } else if ( idle_state == 5 ) {
1082 } else if ( idle_state == 6 ) {
1083 // Initialize audio support
1084 #ifdef ENABLE_AUDIO_SUPPORT
1087 if ( current_options.get_intro_music() ) {
1088 // Let's wait for mpg123 to finish
1089 string lockfile = "/tmp/mpg123.running";
1090 struct stat stat_buf;
1092 FG_LOG( FG_GENERAL, FG_INFO,
1093 "Waiting for mpg123 player to finish ..." );
1094 while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
1095 // file exist, wait ...
1097 FG_LOG( FG_GENERAL, FG_INFO, ".");
1099 FG_LOG( FG_GENERAL, FG_INFO, "");
1103 if ( current_options.get_sound() ) {
1104 audio_sched = new slScheduler ( 8000 );
1105 audio_mixer = new smMixer;
1106 audio_mixer -> setMasterVolume ( 80 ) ; /* 80% of max volume. */
1107 audio_sched -> setSafetyMargin ( 1.0 ) ;
1109 FGPath slfile( current_options.get_fg_root() );
1110 slfile.append( "Sounds/wasp.wav" );
1112 s1 = new slSample ( (char *)slfile.c_str() );
1113 FG_LOG( FG_GENERAL, FG_INFO,
1114 "Rate = " << s1 -> getRate()
1115 << " Bps = " << s1 -> getBps()
1116 << " Stereo = " << s1 -> getStereo() );
1117 audio_sched -> loopSample ( s1 );
1119 if ( audio_sched->not_working() ) {
1122 pitch_envelope.setStep ( 0, 0.01, 0.6 );
1123 volume_envelope.setStep ( 0, 0.01, 0.6 );
1125 audio_sched -> addSampleEnvelope( s1, 0, 0,
1127 SL_PITCH_ENVELOPE );
1128 audio_sched -> addSampleEnvelope( s1, 0, 1,
1130 SL_VOLUME_ENVELOPE );
1133 // strcpy(slfile, path);
1134 // strcat(slfile, "thunder.wav");
1135 // s2 -> loadFile ( slfile );
1136 // s2 -> adjustVolume(0.5);
1137 // audio_sched -> playSample ( s2 );
1145 if ( idle_state == 1000 ) {
1146 // We've finished all our initialization steps, from now on we
1147 // run the main loop.
1151 if ( current_options.get_splash_screen() == 1 ) {
1152 fgSplashUpdate(0.0);
1157 // options.cxx needs to see this for toggle_panel()
1158 // Handle new window size or exposure
1159 void fgReshape( int width, int height ) {
1160 if ( ! current_options.get_panel_status() ) {
1161 current_view.set_win_ratio( (GLfloat) width / (GLfloat) height );
1162 glViewport(0, 0 , (GLint)(width), (GLint)(height) );
1164 current_view.set_win_ratio( (GLfloat) width /
1165 ((GLfloat) (height)*0.4232) );
1166 glViewport(0, (GLint)((height)*0.5768),
1167 (GLint)(width), (GLint)((height)*0.4232) );
1170 current_view.set_winWidth( width );
1171 current_view.set_winHeight( height );
1172 current_view.force_update_fov_math();
1174 // set these fov to be the same as in fgRenderFrame()
1175 // float x_fov = current_options.get_fov();
1176 // float y_fov = x_fov * 1.0 / current_view.get_win_ratio();
1177 // ssgSetFOV( x_fov, y_fov );
1179 // glViewport ( 0, 0, width, height );
1180 float fov = current_options.get_fov();
1181 ssgSetFOV(fov * current_view.get_win_ratio(), fov);
1185 if ( idle_state == 1000 ) {
1186 // yes we've finished all our initializations and are running
1187 // the main loop, so this will now work without seg faulting
1189 current_view.UpdateViewParams(cur_view_fdm);
1194 // Initialize GLUT and define a main window
1195 int fgGlutInit( int *argc, char **argv ) {
1197 #if !defined( MACOS )
1198 // GLUT will extract all glut specific options so later on we only
1199 // need wory about our own.
1200 glutInit(argc, argv);
1203 // Define Display Parameters
1204 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1206 FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
1207 current_options.get_xsize() << "x" << current_options.get_ysize() );
1209 // Define initial window size
1210 glutInitWindowSize( current_options.get_xsize(),
1211 current_options.get_ysize() );
1213 // Initialize windows
1214 if ( current_options.get_game_mode() == 0 ) {
1215 // Open the regular window
1216 glutCreateWindow("Flight Gear");
1217 #ifndef GLUT_WRONG_VERSION
1219 // Open the cool new 'game mode' window
1220 char game_mode_str[256];
1221 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1222 current_options.get_xsize(),
1223 current_options.get_ysize(),
1224 current_options.get_bpp());
1226 FG_LOG( FG_GENERAL, FG_INFO,
1227 "game mode params = " << game_mode_str );
1228 glutGameModeString( game_mode_str );
1229 glutEnterGameMode();
1233 // This seems to be the absolute earliest in the init sequence
1234 // that these calls will return valid info. Too bad it's after
1235 // we've already created and sized out window. :-(
1236 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1237 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1238 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1240 FG_LOG ( FG_GENERAL, FG_INFO, general.get_glRenderer() );
1243 // try to determine if we should adjust the initial default
1244 // display resolution. The options class defaults (is
1245 // initialized) to 640x480.
1246 string renderer = general.glRenderer;
1248 // currently we only know how to deal with Mesa/Glide/Voodoo cards
1249 if ( renderer.find( "Glide" ) != string::npos ) {
1250 FG_LOG( FG_GENERAL, FG_INFO, "Detected a Glide driver" );
1251 if ( renderer.find( "FB/8" ) != string::npos ) {
1252 // probably a voodoo-2
1253 if ( renderer.find( "TMU/SLI" ) != string::npos ) {
1254 // probably two SLI'd Voodoo-2's
1255 current_options.set_xsize( 1024 );
1256 current_options.set_ysize( 768 );
1257 FG_LOG( FG_GENERAL, FG_INFO,
1258 "It looks like you have two sli'd voodoo-2's." << endl
1259 << "upgrading your win resolution to 1024 x 768" );
1260 glutReshapeWindow(1024, 768);
1262 // probably a single non-SLI'd Voodoo-2
1263 current_options.set_xsize( 800 );
1264 current_options.set_ysize( 600 );
1265 FG_LOG( FG_GENERAL, FG_INFO,
1266 "It looks like you have a voodoo-2." << endl
1267 << "upgrading your win resolution to 800 x 600" );
1268 glutReshapeWindow(800, 600);
1270 } else if ( renderer.find( "FB/2" ) != string::npos ) {
1271 // probably a voodoo-1, stick with the default
1274 // we have no special knowledge of this card, stick with the default
1282 // Initialize GLUT event handlers
1283 int fgGlutInitEvents( void ) {
1284 // call fgReshape() on window resizes
1285 glutReshapeFunc( fgReshape );
1287 // call GLUTkey() on keyboard event
1288 glutKeyboardFunc( GLUTkey );
1289 glutSpecialFunc( GLUTspecialkey );
1291 // call guiMouseFunc() whenever our little rodent is used
1292 glutMouseFunc ( guiMouseFunc );
1293 glutMotionFunc (guiMotionFunc );
1294 glutPassiveMotionFunc (guiMotionFunc );
1296 // call fgMainLoop() whenever there is
1297 // nothing else to do
1298 glutIdleFunc( fgIdleFunction );
1301 glutDisplayFunc( fgRenderFrame );
1308 int main( int argc, char **argv ) {
1310 #if defined( MACOS )
1311 freopen ("stdout.txt", "w", stdout );
1312 freopen ("stderr.txt", "w", stderr );
1313 argc = ccommand( &argv );
1317 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1320 // set default log levels
1321 fglog().setLogLevels( FG_ALL, FG_INFO );
1323 FG_LOG( FG_GENERAL, FG_INFO, "Flight Gear: Version " << VERSION << endl );
1325 // seed the random number generater
1328 aircraft_dir = ""; // Initialize the Aircraft directory to "" (UIUC)
1330 // Load the configuration parameters
1331 if ( !fgInitConfig(argc, argv) ) {
1332 FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1336 // Initialize the Window/Graphics environment.
1337 if( !fgGlutInit(&argc, argv) ) {
1338 FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1342 // Initialize the various GLUT Event Handlers.
1343 if( !fgGlutInitEvents() ) {
1344 FG_LOG( FG_GENERAL, FG_ALERT,
1345 "GLUT event handler initialization failed ..." );
1349 // Initialize ssg (from plib). Needs to come before we do any
1350 // other ssg stuff, but after opengl/glut has been initialized.
1353 // Initialize the user interface (we need to do this before
1354 // passing off control to glut and before fgInitGeneral to get our
1359 FGTime::cur_time_params = new FGTime();
1360 // FGTime::cur_time_params->init( cur_fdm_state->get_Longitude(),
1361 // cur_fdm_state->get_Latitude() );
1362 // FGTime::cur_time_params->update( cur_fdm_state->get_Longitude() );
1363 FGTime::cur_time_params->init( 0.0, 0.0 );
1364 FGTime::cur_time_params->update( 0.0, 0.0, 0.0 );
1366 // Do some quick general initializations
1367 if( !fgInitGeneral()) {
1368 FG_LOG( FG_GENERAL, FG_ALERT,
1369 "General initializations failed ..." );
1374 // some ssg test stuff (requires data from the plib source
1375 // distribution) specifically from the ssg tux example
1378 FGPath modelpath( current_options.get_fg_root() );
1379 modelpath.append( "Models" );
1380 modelpath.append( "Geometry" );
1382 FGPath texturepath( current_options.get_fg_root() );
1383 texturepath.append( "Models" );
1384 texturepath.append( "Textures" );
1386 ssgModelPath( (char *)modelpath.c_str() );
1387 ssgTexturePath( (char *)texturepath.c_str() );
1390 scene = new ssgRoot;
1391 scene->setName( "Scene" );
1393 // Initialize the sky
1394 FGPath ephem_data_path( current_options.get_fg_root() );
1395 ephem_data_path.append( "Astro" );
1396 ephem = new FGEphemeris( ephem_data_path.c_str() );
1397 ephem->update( FGTime::cur_time_params, 0.0 );
1399 FGPath sky_tex_path( current_options.get_fg_root() );
1400 sky_tex_path.append( "Textures" );
1401 sky_tex_path.append( "Sky" );
1403 thesky->texture_path( sky_tex_path.str() );
1405 thesky->build( 550.0, 550.0,
1406 ephem->getNumPlanets(),
1407 ephem->getPlanets(), 60000.0,
1408 ephem->getNumStars(),
1409 ephem->getStars(), 60000.0 );
1410 thesky->add_cloud_layer( 1500.0 );
1411 thesky->add_cloud_layer( 2100.0 );
1414 terrain = new ssgBranch;
1415 terrain->setName( "Terrain" );
1416 scene->addKid( terrain );
1418 // temporary visible aircraft "own ship"
1419 penguin_sel = new ssgSelector;
1420 penguin_pos = new ssgTransform;
1421 // ssgBranch *tux_obj = ssgMakeSphere( 10.0, 10, 10 );
1422 ssgEntity *tux_obj = ssgLoadAC( "glider.ac" );
1423 // ssgEntity *tux_obj = ssgLoadAC( "Tower1x.ac" );
1425 penguin_pos->addKid( tux_obj );
1426 penguin_sel->addKid( penguin_pos );
1427 ssgFlatten( tux_obj );
1428 ssgStripify( penguin_sel );
1429 penguin_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1430 scene->addKid( penguin_sel );
1432 #ifdef FG_NETWORK_OLK
1433 // Do the network intialization
1434 if ( current_options.get_network_olk() ) {
1435 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1439 // build our custom render states
1440 fgBuildRenderStates();
1442 // pass control off to the master GLUT event handler
1445 // we never actually get here ... but to avoid compiler warnings,