1 // main.cxx -- top level sim routines
3 // Written by Curtis Olson, started May 1997.
5 // Copyright (C) 1997 - 2002 Curtis L. Olson - http://www.flightgear.org/~curt
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.
28 #include <simgear/compiler.h>
30 #if defined(__linux__) && defined(__i386__)
31 # include <fpu_control.h>
35 #ifdef SG_MATH_EXCEPTION_CLASH
44 #include <plib/netSocket.h>
46 #include <simgear/props/props.hxx>
47 #include <simgear/timing/sg_time.hxx>
48 #include <simgear/math/sg_random.h>
51 #include <simgear/ephemeris/ephemeris.hxx>
52 #include <simgear/scene/model/modellib.hxx>
53 #include <simgear/scene/material/matlib.hxx>
54 #include <simgear/scene/model/animation.hxx>
55 #include <simgear/scene/sky/sky.hxx>
56 #include <Time/light.hxx>
57 #include <Include/general.hxx>
58 #include <Cockpit/cockpit.hxx>
59 #include <Cockpit/hud.hxx>
60 #include <Model/panelnode.hxx>
61 #include <Model/modelmgr.hxx>
62 #include <Model/acmodel.hxx>
63 #include <Scenery/scenery.hxx>
64 #include <Scenery/tilemgr.hxx>
65 #include <Sound/beacon.hxx>
66 #include <Sound/morse.hxx>
67 #include <FDM/flight.hxx>
68 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
69 // #include <FDM/ADA.hxx>
70 #include <ATC/ATCdisplay.hxx>
71 #include <ATC/ATCmgr.hxx>
72 #include <ATC/AIMgr.hxx>
73 #include <Replay/replay.hxx>
74 #include <Time/tmp.hxx>
75 #include <Time/fg_timer.hxx>
76 #include <Environment/environment_mgr.hxx>
77 #include <GUI/new_gui.hxx>
80 #include <MultiPlayer/multiplaytxmgr.hxx>
81 #include <MultiPlayer/multiplayrxmgr.hxx>
86 #include "fg_commands.hxx"
88 #include "renderer.hxx"
94 static double real_delta_time_sec = 0.0;
95 double delta_time_sec = 0.0;
96 extern float init_volume;
100 # include <console.h> // -dw- for command line dialog
103 // This is a record containing a bit of global housekeeping information
106 // Specify our current idle function state. This is used to run all
107 // our initializations out of the idle callback so that we can get a
108 // splash screen up and running right away.
110 long global_multi_loop;
112 SGTimeStamp last_time_stamp;
113 SGTimeStamp current_time_stamp;
115 // The atexit() functio handler should know when the graphical subsystem
117 extern int _bootstrap_OSInit;
121 // Update internal time dependent calculations (i.e. flight model)
122 // FIXME: this distinction is obsolete; all subsystems now get delta
124 void fgUpdateTimeDepCalcs() {
125 static bool inited = false;
127 static const SGPropertyNode *replay_state
128 = fgGetNode( "/sim/freeze/replay-state", true );
129 static SGPropertyNode *replay_time
130 = fgGetNode( "/sim/replay/time", true );
131 // static const SGPropertyNode *replay_end_time
132 // = fgGetNode( "/sim/replay/end-time", true );
134 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
136 // Initialize the FDM here if it hasn't been and if we have a
137 // scenery elevation hit.
139 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
140 // << " cur_elev = " << scenery.get_cur_elev() << endl;
142 if ( !cur_fdm_state->get_inited() &&
143 globals->get_scenery()->get_cur_elev() > -9990 )
145 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
146 cur_fdm_state->init();
147 if ( cur_fdm_state->get_bound() ) {
148 cur_fdm_state->unbind();
150 cur_fdm_state->bind();
153 // conceptually, the following block could be done for each fdm
155 if ( cur_fdm_state->get_inited() ) {
156 // we have been inited, and we are good to go ...
162 if ( replay_state->getIntValue() == 0 ) {
163 // replay off, run fdm
164 cur_fdm_state->update( delta_time_sec );
166 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
167 r->replay( replay_time->getDoubleValue() );
168 if ( replay_state->getIntValue() == 1 ) {
170 replay_time->setDoubleValue( replay_time->getDoubleValue()
172 * fgGetInt("/sim/speed-up") ) );
173 } else if ( replay_state->getIntValue() == 2 ) {
174 // paused playback (don't advance replay time)
178 // do nothing, fdm isn't inited yet
181 globals->get_model_mgr()->update(delta_time_sec);
182 globals->get_aircraft_model()->update(delta_time_sec);
184 // update the view angle
185 globals->get_viewmgr()->update(delta_time_sec);
187 // Update solar system
188 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
189 globals->get_time_params()->getLst(),
190 cur_fdm_state->get_Latitude() );
195 void fgInitTimeDepCalcs( void ) {
200 static const double alt_adjust_ft = 3.758099;
201 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
204 // What should we do when we have nothing else to do? Let's get ready
205 // for the next move and update the display?
206 static void fgMainLoop( void ) {
207 int model_hz = fgGetInt("/sim/model-hz");
209 static const SGPropertyNode *longitude
210 = fgGetNode("/position/longitude-deg");
211 static const SGPropertyNode *latitude
212 = fgGetNode("/position/latitude-deg");
213 static const SGPropertyNode *altitude
214 = fgGetNode("/position/altitude-ft");
215 static const SGPropertyNode *clock_freeze
216 = fgGetNode("/sim/freeze/clock", true);
217 static const SGPropertyNode *cur_time_override
218 = fgGetNode("/sim/time/cur-time-override", true);
220 SGCloudLayer::enable_bump_mapping = fgGetBool("/sim/rendering/bump-mapping");
222 bool scenery_loaded = fgGetBool("sim/sceneryloaded") || fgGetBool("sim/sceneryloaded-override");
224 // Update the elapsed time.
225 static bool first_time = true;
227 last_time_stamp.stamp();
231 double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
232 if ( throttle_hz > 0.0 && scenery_loaded ) {
233 // optionally throttle the frame rate (to get consistant frame
234 // rates or reduce cpu usage.
236 double frame_us = 1000000.0 / throttle_hz;
238 #define FG_SLEEP_BASED_TIMING 1
239 #if defined(FG_SLEEP_BASED_TIMING)
240 // sleep based timing loop.
242 // Calling sleep, even usleep() on linux is less accurate than
243 // we like, but it does free up the cpu for other tasks during
244 // the sleep so it is desireable. Because of the way sleep()
245 // is implimented in consumer operating systems like windows
246 // and linux, you almost always sleep a little longer than the
249 // To combat the problem of sleeping to long, we calculate the
250 // desired wait time and shorten it by 2000us (2ms) to avoid
251 // [hopefully] over-sleep'ing. The 2ms value was arrived at
252 // via experimentation. We follow this up at the end with a
253 // simple busy-wait loop to get the final pause timing exactly
256 // Assuming we don't oversleep by more than 2000us, this
257 // should be a reasonable compromise between sleep based
258 // waiting, and busy waiting.
260 // sleep() will always overshoot by a bit so undersleep by
261 // 2000us in the hopes of never oversleeping.
263 if ( frame_us < 0.0 ) {
266 current_time_stamp.stamp();
268 double elapsed_us = current_time_stamp - last_time_stamp;
269 if ( elapsed_us < frame_us ) {
270 double requested_us = frame_us - elapsed_us;
271 ulMilliSecondSleep ( (int)(requested_us / 1000.0) ) ;
275 // busy wait timing loop.
277 // This yields the most accurate timing. If the previous
278 // ulMilliSecondSleep() call is ommitted this will peg the cpu
279 // (which is just fine if FG is the only app you care about.)
280 current_time_stamp.stamp();
281 while ( current_time_stamp - last_time_stamp < frame_us ) {
282 current_time_stamp.stamp();
285 // run as fast as the app will go
286 current_time_stamp.stamp();
290 = double(current_time_stamp - last_time_stamp) / 1000000.0;
291 // round the real time down to a multiple of 1/model-hz.
292 // this way all systems are updated the _same_ amount of dt.
294 static double rem = 0.0;
295 real_delta_time_sec += rem;
296 double hz = model_hz;
297 double nit = floor(real_delta_time_sec*hz);
298 rem = real_delta_time_sec - nit/hz;
299 real_delta_time_sec = nit/hz;
303 if ( clock_freeze->getBoolValue() ) {
306 delta_time_sec = real_delta_time_sec;
308 last_time_stamp = current_time_stamp;
309 globals->inc_sim_time_sec( delta_time_sec );
310 SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
312 // These are useful, especially for Nasal scripts.
313 fgSetDouble("/sim/time/delta-realtime-sec", real_delta_time_sec);
314 fgSetDouble("/sim/time/delta-sec", delta_time_sec);
316 static long remainder = 0;
318 #ifdef FANCY_FRAME_COUNTER
322 static time_t last_time = 0;
323 static int frames = 0;
324 #endif // FANCY_FRAME_COUNTER
326 SGTime *t = globals->get_time_params();
328 globals->get_event_mgr()->update(delta_time_sec);
330 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
331 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
333 #if defined( ENABLE_PLIB_JOYSTICK )
334 // Read joystick and update control settings
335 // if ( fgGetString("/sim/control-mode") == "joystick" )
341 // Fix elevation. I'm just sticking this here for now, it should
342 // probably move eventually
344 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
345 scenery.get_cur_elev(),
346 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
347 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
349 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
350 scenery.get_cur_elev(),
351 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
352 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
354 // cout << "Warp = " << globals->get_warp() << endl;
357 static bool last_clock_freeze = false;
359 if ( clock_freeze->getBoolValue() ) {
360 // clock freeze requested
361 if ( cur_time_override->getLongValue() == 0 ) {
362 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
363 globals->set_warp( 0 );
366 // no clock freeze requested
367 if ( last_clock_freeze == true ) {
368 // clock just unfroze, let's set warp as the difference
369 // between frozen time and current time so we don't get a
370 // time jump (and corresponding sky object and lighting
372 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
373 fgSetLong( "/sim/time/cur-time-override", 0 );
375 if ( globals->get_warp_delta() != 0 ) {
376 globals->inc_warp( globals->get_warp_delta() );
380 last_clock_freeze = clock_freeze->getBoolValue();
382 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
383 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
384 cur_time_override->getLongValue(),
385 globals->get_warp() );
387 if (globals->get_warp_delta() != 0) {
388 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
392 // update magvar model
393 globals->get_mag()->update( longitude->getDoubleValue()
394 * SGD_DEGREES_TO_RADIANS,
395 latitude->getDoubleValue()
396 * SGD_DEGREES_TO_RADIANS,
397 altitude->getDoubleValue() * SG_FEET_TO_METER,
398 globals->get_time_params()->getJD() );
400 // Get elapsed time (in usec) for this past frame
401 elapsed = fgGetTimeInterval();
402 SG_LOG( SG_ALL, SG_DEBUG,
403 "Elapsed time interval is = " << elapsed
404 << ", previous remainder is = " << remainder );
406 // Calculate frame rate average
407 #ifdef FANCY_FRAME_COUNTER
408 /* old fps calculation */
412 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
413 tmp = general.get_frame(i);
415 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
416 general.set_frame(i+1,tmp);
418 tmp = 1000000.0 / (float)elapsed;
419 general.set_frame(0,tmp);
420 // printf("frame[0] = %.2f\n", general.frames[0]);
422 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
423 // printf("ave = %.2f\n", general.frame_rate);
426 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
427 general.set_frame_rate( frames );
428 fgSetInt("/sim/frame-rate", frames);
429 SG_LOG( SG_ALL, SG_DEBUG,
430 "--> Frame rate is = " << general.get_frame_rate() );
433 last_time = t->get_cur_time();
438 if (fgGetBool("/sim/atc/enabled"))
439 globals->get_ATC_mgr()->update(delta_time_sec);
441 // Run the AI subsystem
442 if (fgGetBool("/sim/ai-traffic/enabled"))
443 globals->get_AI_mgr()->update(delta_time_sec);
446 // Update any multiplayer models
447 globals->get_multiplayer_rx_mgr()->Update();
452 // Calculate model iterations needed for next frame
453 elapsed += remainder;
455 global_multi_loop = (long)(((double)elapsed * 0.000001) * model_hz );
456 remainder = elapsed - ( (global_multi_loop*1000000) / model_hz );
457 SG_LOG( SG_ALL, SG_DEBUG,
458 "Model iterations needed = " << global_multi_loop
459 << ", new remainder = " << remainder );
461 // chop max interations to something reasonable if the sim was
462 // delayed for an excesive amount of time
463 if ( global_multi_loop > 2.0 * model_hz ) {
464 global_multi_loop = (int)(2.0 * model_hz );
469 if ( global_multi_loop > 0) {
470 // first run the flight model each frame until it is intialized
471 // then continue running each frame only after initial scenery load is complete.
472 if (!cur_fdm_state->get_inited() || scenery_loaded) {
473 fgUpdateTimeDepCalcs();
476 SG_LOG( SG_ALL, SG_DEBUG,
477 "Elapsed time is zero ... we're zinging" );
480 // Do any I/O channel work that might need to be done
481 globals->get_io()->update( real_delta_time_sec );
483 // see if we need to load any deferred-load textures
484 globals->get_matlib()->load_next_deferred();
486 // Run audio scheduler
487 #ifdef ENABLE_AUDIO_SUPPORT
488 if ( globals->get_soundmgr()->is_working() ) {
489 globals->get_soundmgr()->update( delta_time_sec );
493 globals->get_subsystem_mgr()->update(delta_time_sec);
496 // Tile Manager updates - see if we need to load any new scenery tiles.
497 // this code ties together the fdm, viewer and scenery classes...
498 // we may want to move this to it's own class at some point
500 double visibility_meters = fgGetDouble("/environment/visibility-m");
501 FGViewer *current_view = globals->get_current_view();
503 // Let the scenery center follow the current view position with
506 // Having the scenery center near the view position will eliminate
507 // jitter of objects which are placed very near the view position
508 // and haveing it's center near that view position.
509 // So the 3d insruments of the aircraft will not jitter with this.
511 // Following the view position exactly would introduce jitter of
512 // the scenery tiles (they would be from their center up to 10000m
513 // to the view and this will introduce roundoff too). By stepping
514 // at 30m incements the roundoff error of the scenery tiles is
515 // still present, but we will make exactly the same roundoff error
516 // at each frame until the center is switched to a new
517 // position. This roundoff is still visible but you will most
518 // propably not notice.
519 double *vp = globals->get_current_view()->get_absolute_view_pos();
520 Point3D cntr(vp[0], vp[1], vp[2]);
521 if (30.0*30.0 < cntr.distance3Dsquared(globals->get_scenery()->get_center())) {
522 globals->get_scenery()->set_next_center( cntr );
525 // get the location data for the primary FDM (now hardcoded to ac model)...
526 SGLocation *acmodel_loc = NULL;
527 acmodel_loc = (SGLocation *)globals->
528 get_aircraft_model()->get3DModel()->getSGLocation();
530 // update tile manager for FDM...
531 // ...only if location is different than the current-view location
532 // (to avoid duplicating effort)
533 if( !fgGetBool("/sim/current-view/config/from-model") ) {
534 if( acmodel_loc != NULL ) {
535 globals->get_tile_mgr()->prep_ssg_nodes( acmodel_loc,
537 globals->get_tile_mgr()->
538 update( acmodel_loc, visibility_meters,
540 get_absolute_view_pos(globals->
541 get_scenery()->get_center()) );
542 globals->get_scenery()->set_center( cntr );
544 // save results of update in SGLocation for fdm...
545 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
547 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
548 fgSetDouble("/position/ground-elev-m",
549 globals->get_scenery()->get_cur_elev());
552 set_tile_center( globals->get_scenery()->get_next_center() );
556 globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
558 // update tile manager for view...
559 // IMPORTANT!!! the tilemgr update for view location _must_ be
560 // done last after the FDM's until all of Flight Gear code
561 // references the viewer's location for elevation instead of the
562 // "scenery's" current elevation.
563 SGLocation *view_location = globals->get_current_view()->getSGLocation();
564 globals->get_tile_mgr()->update( view_location, visibility_meters,
565 current_view->get_absolute_view_pos() );
566 globals->get_scenery()->set_center( cntr );
567 // save results of update in SGLocation for fdm...
568 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
569 current_view->getSGLocation()->
570 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
572 current_view->getSGLocation()->
573 set_tile_center( globals->get_scenery()->get_next_center() );
575 #ifdef ENABLE_AUDIO_SUPPORT
576 // Right now we make a simplifying assumption that the primary
577 // aircraft is the source of all sounds and that all sounds are
578 // positioned relative to the current view position.
580 static sgVec3 last_pos_offset;
582 // set positional offset for sources
583 sgVec3 source_pos_offset;
584 sgSubVec3( source_pos_offset,
585 view_location->get_view_pos(), acmodel_loc->get_view_pos() );
586 // cout << "pos all = " << source_pos_offset[0] << " " << source_pos_offset[1] << " " << source_pos_offset[2] << endl;
587 globals->get_soundmgr()->set_source_pos_all( source_pos_offset );
591 sgSubVec3( source_vel, source_pos_offset, last_pos_offset );
592 sgScaleVec3( source_vel, delta_time_sec );
593 sgCopyVec3( last_pos_offset, source_pos_offset );
594 // cout << "vel = " << source_vel[0] << " " << source_vel[1] << " " << source_vel[2] << endl;
595 globals->get_soundmgr()->set_source_vel_all( source_vel );
597 // Right now we make a simplifying assumption that the listener is
598 // always positioned at the origin.
600 sgSetVec3( listener_pos, 0.0, 0.0, 0.0 );
601 // cout << "listener = " << listener_pos[0] << " " << listener_pos[1] << " " << listener_pos[2] << endl;
602 globals->get_soundmgr()->set_listener_pos( listener_pos );
605 // If fdm location is same as viewer's then we didn't do the
606 // update for fdm location above so we need to save the viewer
607 // results in the fdm SGLocation as well...
608 if( fgGetBool("/sim/current-view/config/from-model") ) {
609 if( acmodel_loc != 0 ) {
610 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
611 acmodel_loc->set_cur_elev_m( globals->get_scenery()->
613 fgSetDouble("/position/ground-elev-m",
614 globals->get_scenery()->get_cur_elev());
616 acmodel_loc->set_tile_center( globals->get_scenery()->
621 // END Tile Manager udpates
623 if (!scenery_loaded && globals->get_tile_mgr()->all_queues_empty() && cur_fdm_state->get_inited()) {
624 fgSetBool("sim/sceneryloaded",true);
625 fgSetFloat("/sim/sound/volume", init_volume);
626 globals->get_soundmgr()->set_volume(init_volume);
629 if (fgGetBool("/sim/rendering/specular-highlight")) {
630 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
631 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
633 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
634 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
639 SG_LOG( SG_ALL, SG_DEBUG, "" );
643 // This is the top level master main function that is registered as
646 // The first few passes take care of initialization things (a couple
647 // per pass) and once everything has been initialized fgMainLoop from
650 static void fgIdleFunction ( void ) {
651 if ( idle_state == 0 ) {
653 fgSplashProgress("setting up scenegraph & user interface");
656 } else if ( idle_state == 1 ) {
658 // This seems to be the absolute earliest in the init sequence
659 // that these calls will return valid info. Too bad it's after
660 // we've already created and sized out window. :-(
661 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
662 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
663 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
664 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
667 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
668 general.set_glMaxTexSize( tmp );
669 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
671 glGetIntegerv( GL_DEPTH_BITS, &tmp );
672 general.set_glDepthBits( tmp );
673 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
675 // Initialize ssg (from plib). Needs to come before we do any
676 // other ssg stuff, but after opengl has been initialized.
679 // Initialize the user interface (we need to do this before
680 // passing off control to the OS main loop and before
681 // fgInitGeneral to get our fonts !!!
683 fgSplashProgress("reading aircraft list");
686 } else if ( idle_state == 2 ) {
688 // Read the list of available aircrafts
691 #ifdef GL_EXT_texture_lod_bias
692 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
695 // get the address of our OpenGL extensions
696 if ( fgGetBool("/sim/rendering/distance-attenuation") ) {
697 if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
698 glPointParameterIsSupported = true;
699 glPointParameterfPtr = (glPointParameterfProc)
700 SGLookupFunction("glPointParameterfEXT");
701 glPointParameterfvPtr = (glPointParameterfvProc)
702 SGLookupFunction("glPointParameterfvEXT");
704 } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
705 glPointParameterIsSupported = true;
706 glPointParameterfPtr = (glPointParameterfProc)
707 SGLookupFunction("glPointParameterfARB");
708 glPointParameterfvPtr = (glPointParameterfvProc)
709 SGLookupFunction("glPointParameterfvARB");
711 glPointParameterIsSupported = false;
713 fgSplashProgress("reading airport & navigation data");
716 } else if ( idle_state == 3 ) {
719 fgSplashProgress("setting up scenery");
722 } else if ( idle_state == 4 ) {
724 // based on the requested presets, calculate the true starting
728 SGTime *t = fgInitTime();
729 globals->set_time_params( t );
731 // Do some quick general initializations
732 if( !fgInitGeneral()) {
733 SG_LOG( SG_GENERAL, SG_ALERT,
734 "General initializations failed ..." );
738 ////////////////////////////////////////////////////////////////////
739 // Initialize the property-based built-in commands
740 ////////////////////////////////////////////////////////////////////
744 ////////////////////////////////////////////////////////////////////
745 // Initialize the material manager
746 ////////////////////////////////////////////////////////////////////
747 globals->set_matlib( new SGMaterialLib );
748 globals->set_model_lib(new SGModelLib);
751 ////////////////////////////////////////////////////////////////////
752 // Initialize the TG scenery subsystem.
753 ////////////////////////////////////////////////////////////////////
754 globals->set_scenery( new FGScenery );
755 globals->get_scenery()->init();
756 globals->get_scenery()->bind();
757 globals->set_tile_mgr( new FGTileMgr );
760 ////////////////////////////////////////////////////////////////////
761 // Initialize the general model subsystem.
762 ////////////////////////////////////////////////////////////////////
763 globals->set_model_mgr(new FGModelMgr);
764 globals->get_model_mgr()->init();
765 globals->get_model_mgr()->bind();
766 fgSplashProgress("loading aircraft");
769 } else if ( idle_state == 5 ) {
771 ////////////////////////////////////////////////////////////////////
772 // Initialize the 3D aircraft model subsystem (has a dependency on
773 // the scenery subsystem.)
774 ////////////////////////////////////////////////////////////////////
775 globals->set_aircraft_model(new FGAircraftModel);
776 globals->get_aircraft_model()->init();
777 globals->get_aircraft_model()->bind();
779 ////////////////////////////////////////////////////////////////////
780 // Initialize the view manager subsystem.
781 ////////////////////////////////////////////////////////////////////
782 FGViewMgr *viewmgr = new FGViewMgr;
783 globals->set_viewmgr( viewmgr );
786 fgSplashProgress("generating sky elements");
789 } else if ( idle_state == 6 ) {
791 // Initialize the sky
792 SGPath ephem_data_path( globals->get_fg_root() );
793 ephem_data_path.append( "Astro" );
794 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
795 ephem->update( globals->get_time_params()->getMjd(),
796 globals->get_time_params()->getLst(),
798 globals->set_ephem( ephem );
800 // TODO: move to environment mgr
802 SGPath texture_path(globals->get_fg_root());
803 texture_path.append("Textures");
804 texture_path.append("Sky");
805 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
806 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
807 thesky->add_cloud_layer(layer);
810 SGPath sky_tex_path( globals->get_fg_root() );
811 sky_tex_path.append( "Textures" );
812 sky_tex_path.append( "Sky" );
813 thesky->texture_path( sky_tex_path.str() );
815 // The sun and moon diameters are scaled down numbers of the
816 // actual diameters. This was needed to fit bot the sun and the
817 // moon within the distance to the far clip plane.
818 // Moon diameter: 3,476 kilometers
819 // Sun diameter: 1,390,000 kilometers
820 thesky->build( 80000.0, 80000.0,
822 globals->get_ephem()->getNumPlanets(),
823 globals->get_ephem()->getPlanets(),
824 globals->get_ephem()->getNumStars(),
825 globals->get_ephem()->getStars() );
827 // Initialize MagVar model
828 SGMagVar *magvar = new SGMagVar();
829 globals->set_mag( magvar );
832 // kludge to initialize mag compass
833 // (should only be done for in-flight
835 // update magvar model
836 globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
837 * SGD_DEGREES_TO_RADIANS,
838 fgGetDouble("/position/latitude-deg")
839 * SGD_DEGREES_TO_RADIANS,
840 fgGetDouble("/position/altitude-ft")
842 globals->get_time_params()->getJD() );
843 double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
844 fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
846 // airport = new ssgBranch;
847 // airport->setName( "Airport Lighting" );
848 // lighting->addKid( airport );
850 // build our custom render states
851 globals->get_renderer()->build_states();
852 fgSplashProgress("initializing subsystems");
855 } else if ( idle_state == 7 ) {
857 // Initialize audio support
858 #ifdef ENABLE_AUDIO_SUPPORT
860 // Start the intro music
861 if ( fgGetBool("/sim/startup/intro-music") ) {
862 SGPath mp3file( globals->get_fg_root() );
863 mp3file.append( "Sounds/intro.mp3" );
865 SG_LOG( SG_GENERAL, SG_INFO,
866 "Starting intro music: " << mp3file.str() );
868 #if defined( __CYGWIN__ )
869 string command = "start /m `cygpath -w " + mp3file.str() + "`";
870 #elif defined( WIN32 )
871 string command = "start /m " + mp3file.str();
873 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
876 system ( command.c_str() );
880 // These are a few miscellaneous things that aren't really
881 // "subsystems" but still need to be initialized.
884 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
885 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
889 // This is the top level init routine which calls all the
890 // other subsystem initialization routines. If you are adding
891 // a subsystem to flightgear, its initialization call should
892 // located in this routine.
893 if( !fgInitSubsystems()) {
894 SG_LOG( SG_GENERAL, SG_ALERT,
895 "Subsystem initializations failed ..." );
898 fgSplashProgress("setting up time & renderer");
901 } else if ( idle_state == 8 ) {
903 // Initialize the time offset (warp) after fgInitSubsystem
904 // (which initializes the lighting interpolation tables.)
907 // setup OpenGL view parameters
908 globals->get_renderer()->init();
910 SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
911 globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
912 fgGetInt("/sim/startup/ysize") );
914 fgSplashProgress("loading scenery objects");
918 if ( idle_state == 1000 ) {
919 // We've finished all our initialization steps, from now on we
920 // run the main loop.
921 fgSetBool("sim/sceneryloaded", false);
922 fgRegisterIdleHandler( fgMainLoop );
927 // Main top level initialization
928 bool fgMainInit( int argc, char **argv ) {
930 #if defined( macintosh )
931 freopen ("stdout.txt", "w", stdout );
932 freopen ("stderr.txt", "w", stderr );
933 argc = ccommand( &argv );
936 // set default log levels
937 sglog().setLogLevels( SG_ALL, SG_ALERT );
940 #ifdef FLIGHTGEAR_VERSION
941 version = FLIGHTGEAR_VERSION;
943 version = "unknown version";
945 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
947 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
949 // Allocate global data structures. This needs to happen before
950 // we parse command line options
952 globals = new FGGlobals;
954 // seed the random number generater
957 FGControls *controls = new FGControls;
958 globals->set_controls( controls );
960 string_list *col = new string_list;
961 globals->set_channel_options_list( col );
963 // Scan the config file(s) and command line options to see if
964 // fg_root was specified (ignore all other options for now)
965 fgInitFGRoot(argc, argv);
967 // Check for the correct base package version
968 static char required_version[] = "0.9.8";
969 string base_version = fgBasePackageVersion();
970 if ( !(base_version == required_version) ) {
971 // tell the operator how to use this application
973 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
974 cerr << endl << "Base package check failed ... " \
975 << "Found version " << base_version << " at: " \
976 << globals->get_fg_root() << endl;
977 cerr << "Please upgrade to version: " << required_version << endl;
979 cerr << "Hit a key to continue..." << endl;
985 sgUseDisplayList = fgGetBool( "/sim/rendering/use-display-list", true );
987 // Initialize the Aircraft directory to "" (UIUC)
990 // Load the configuration parameters. (Command line options
991 // overrides config file options. Config file options override
993 if ( !fgInitConfig(argc, argv) ) {
994 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
998 // Initialize the Window/Graphics environment.
999 #if !defined(__APPLE__) || defined(OSX_BUNDLE)
1000 // Mac OS X command line ("non-bundle") applications call this
1001 // from main(), in bootstrap.cxx. Andy doesn't know why, someone
1002 // feel free to add comments...
1003 fgOSInit(&argc, argv);
1004 _bootstrap_OSInit++;
1007 fgRegisterWindowResizeHandler( &FGRenderer::resize );
1008 fgRegisterIdleHandler( &fgIdleFunction );
1009 fgRegisterDrawHandler( &FGRenderer::update );
1011 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
1012 bool get_stencil_buffer = true;
1014 bool get_stencil_buffer = false;
1017 // Initialize plib net interface
1018 netInit( &argc, argv );
1020 // Clouds3D requires an alpha channel
1021 // clouds may require stencil buffer
1022 fgOSOpenWindow( fgGetInt("/sim/startup/xsize"),
1023 fgGetInt("/sim/startup/ysize"),
1024 fgGetInt("/sim/rendering/bits-per-pixel"),
1025 fgGetBool("/sim/rendering/clouds3d"),
1027 fgGetBool("/sim/startup/fullscreen") );
1029 // Initialize the splash screen right away
1031 fgSplashInit(fgGetString("/sim/startup/splash-texture"));
1033 // pass control off to the master event handler
1036 // we never actually get here ... but to avoid compiler warnings,