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>
60 #include <Include/general.hxx>
61 #include <Cockpit/cockpit.hxx>
62 #include <Cockpit/hud.hxx>
63 #include <Model/panelnode.hxx>
64 #include <Model/modelmgr.hxx>
65 #include <Model/acmodel.hxx>
66 #include <Scenery/scenery.hxx>
67 #include <Scenery/tilemgr.hxx>
68 #include <Sound/beacon.hxx>
69 #include <Sound/morse.hxx>
70 #include <FDM/flight.hxx>
71 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
72 // #include <FDM/ADA.hxx>
73 #include <ATC/ATCdisplay.hxx>
74 #include <ATC/ATCmgr.hxx>
75 #include <ATC/AIMgr.hxx>
76 #include <Replay/replay.hxx>
77 #include <Time/tmp.hxx>
78 #include <Time/fg_timer.hxx>
79 #include <Environment/environment_mgr.hxx>
80 #include <GUI/new_gui.hxx>
83 #include <MultiPlayer/multiplaytxmgr.hxx>
84 #include <MultiPlayer/multiplayrxmgr.hxx>
89 #include "fg_commands.hxx"
91 #include "renderer.hxx"
97 static double real_delta_time_sec = 0.0;
98 double delta_time_sec = 0.0;
99 extern float init_volume;
103 # include <console.h> // -dw- for command line dialog
106 // This is a record containing a bit of global housekeeping information
109 // Specify our current idle function state. This is used to run all
110 // our initializations out of the idle callback so that we can get a
111 // splash screen up and running right away.
113 long global_multi_loop;
115 SGTimeStamp last_time_stamp;
116 SGTimeStamp current_time_stamp;
118 // The atexit() functio handler should know when the graphical subsystem
120 extern int _bootstrap_OSInit;
124 // Update internal time dependent calculations (i.e. flight model)
125 // FIXME: this distinction is obsolete; all subsystems now get delta
127 void fgUpdateTimeDepCalcs() {
128 static bool inited = false;
130 static const SGPropertyNode *replay_state
131 = fgGetNode( "/sim/freeze/replay-state", true );
132 static SGPropertyNode *replay_time
133 = fgGetNode( "/sim/replay/time", true );
134 // static const SGPropertyNode *replay_end_time
135 // = fgGetNode( "/sim/replay/end-time", true );
137 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
139 // Initialize the FDM here if it hasn't been and if we have a
140 // scenery elevation hit.
142 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
143 // << " cur_elev = " << scenery.get_cur_elev() << endl;
145 if ( !cur_fdm_state->get_inited() &&
146 globals->get_scenery()->get_cur_elev() > -9990 )
148 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
149 cur_fdm_state->init();
150 if ( cur_fdm_state->get_bound() ) {
151 cur_fdm_state->unbind();
153 cur_fdm_state->bind();
156 // conceptually, the following block could be done for each fdm
158 if ( cur_fdm_state->get_inited() ) {
159 // we have been inited, and we are good to go ...
165 if ( replay_state->getIntValue() == 0 ) {
166 // replay off, run fdm
167 cur_fdm_state->update( delta_time_sec );
169 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
170 r->replay( replay_time->getDoubleValue() );
171 if ( replay_state->getIntValue() == 1 ) {
173 replay_time->setDoubleValue( replay_time->getDoubleValue()
175 * fgGetInt("/sim/speed-up") ) );
176 } else if ( replay_state->getIntValue() == 2 ) {
177 // paused playback (don't advance replay time)
181 // do nothing, fdm isn't inited yet
184 globals->get_model_mgr()->update(delta_time_sec);
185 globals->get_aircraft_model()->update(delta_time_sec);
187 // update the view angle
188 globals->get_viewmgr()->update(delta_time_sec);
190 // Update solar system
191 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
192 globals->get_time_params()->getLst(),
193 cur_fdm_state->get_Latitude() );
198 void fgInitTimeDepCalcs( void ) {
203 static const double alt_adjust_ft = 3.758099;
204 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
207 // What should we do when we have nothing else to do? Let's get ready
208 // for the next move and update the display?
209 static void fgMainLoop( void ) {
210 int model_hz = fgGetInt("/sim/model-hz");
212 static const SGPropertyNode *longitude
213 = fgGetNode("/position/longitude-deg");
214 static const SGPropertyNode *latitude
215 = fgGetNode("/position/latitude-deg");
216 static const SGPropertyNode *altitude
217 = fgGetNode("/position/altitude-ft");
218 static const SGPropertyNode *clock_freeze
219 = fgGetNode("/sim/freeze/clock", true);
220 static const SGPropertyNode *cur_time_override
221 = fgGetNode("/sim/time/cur-time-override", true);
223 SGCloudLayer::enable_bump_mapping = fgGetBool("/sim/rendering/bump-mapping");
225 // Update the elapsed time.
226 static bool first_time = true;
228 last_time_stamp.stamp();
232 double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
233 if ( throttle_hz > 0.0 ) {
234 // simple frame rate throttle
235 double dt = 1000000.0 / throttle_hz;
236 current_time_stamp.stamp();
237 while ( current_time_stamp - last_time_stamp < dt ) {
238 current_time_stamp.stamp();
241 // run as fast as the app will go
242 current_time_stamp.stamp();
246 = double(current_time_stamp - last_time_stamp) / 1000000.0;
247 // round the real time down to a multiple of 1/model-hz.
248 // this way all systems are updated the _same_ amount of dt.
250 static double rem = 0.0;
251 real_delta_time_sec += rem;
252 double hz = model_hz;
253 double nit = floor(real_delta_time_sec*hz);
254 rem = real_delta_time_sec - nit/hz;
255 real_delta_time_sec = nit/hz;
259 if ( clock_freeze->getBoolValue() ) {
262 delta_time_sec = real_delta_time_sec;
264 last_time_stamp = current_time_stamp;
265 globals->inc_sim_time_sec( delta_time_sec );
266 SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
268 // These are useful, especially for Nasal scripts.
269 fgSetDouble("/sim/time/delta-realtime-sec", real_delta_time_sec);
270 fgSetDouble("/sim/time/delta-sec", delta_time_sec);
272 static long remainder = 0;
274 #ifdef FANCY_FRAME_COUNTER
278 static time_t last_time = 0;
279 static int frames = 0;
280 #endif // FANCY_FRAME_COUNTER
282 SGTime *t = globals->get_time_params();
284 globals->get_event_mgr()->update(delta_time_sec);
286 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
287 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
289 #if defined( ENABLE_PLIB_JOYSTICK )
290 // Read joystick and update control settings
291 // if ( fgGetString("/sim/control-mode") == "joystick" )
297 // Fix elevation. I'm just sticking this here for now, it should
298 // probably move eventually
300 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
301 scenery.get_cur_elev(),
302 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
303 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
305 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
306 scenery.get_cur_elev(),
307 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
308 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
310 // cout << "Warp = " << globals->get_warp() << endl;
313 static bool last_clock_freeze = false;
315 if ( clock_freeze->getBoolValue() ) {
316 // clock freeze requested
317 if ( cur_time_override->getLongValue() == 0 ) {
318 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
319 globals->set_warp( 0 );
322 // no clock freeze requested
323 if ( last_clock_freeze == true ) {
324 // clock just unfroze, let's set warp as the difference
325 // between frozen time and current time so we don't get a
326 // time jump (and corresponding sky object and lighting
328 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
329 fgSetLong( "/sim/time/cur-time-override", 0 );
331 if ( globals->get_warp_delta() != 0 ) {
332 globals->inc_warp( globals->get_warp_delta() );
336 last_clock_freeze = clock_freeze->getBoolValue();
338 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
339 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
340 cur_time_override->getLongValue(),
341 globals->get_warp() );
343 if (globals->get_warp_delta() != 0) {
344 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
348 // update magvar model
349 globals->get_mag()->update( longitude->getDoubleValue()
350 * SGD_DEGREES_TO_RADIANS,
351 latitude->getDoubleValue()
352 * SGD_DEGREES_TO_RADIANS,
353 altitude->getDoubleValue() * SG_FEET_TO_METER,
354 globals->get_time_params()->getJD() );
356 // Get elapsed time (in usec) for this past frame
357 elapsed = fgGetTimeInterval();
358 SG_LOG( SG_ALL, SG_DEBUG,
359 "Elapsed time interval is = " << elapsed
360 << ", previous remainder is = " << remainder );
362 // Calculate frame rate average
363 #ifdef FANCY_FRAME_COUNTER
364 /* old fps calculation */
368 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
369 tmp = general.get_frame(i);
371 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
372 general.set_frame(i+1,tmp);
374 tmp = 1000000.0 / (float)elapsed;
375 general.set_frame(0,tmp);
376 // printf("frame[0] = %.2f\n", general.frames[0]);
378 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
379 // printf("ave = %.2f\n", general.frame_rate);
382 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
383 general.set_frame_rate( frames );
384 fgSetInt("/sim/frame-rate", frames);
385 SG_LOG( SG_ALL, SG_DEBUG,
386 "--> Frame rate is = " << general.get_frame_rate() );
389 last_time = t->get_cur_time();
394 if (fgGetBool("/sim/ATC/enabled"))
395 globals->get_ATC_mgr()->update(delta_time_sec);
397 // Run the AI subsystem
398 if (fgGetBool("/sim/ai-traffic/enabled"))
399 globals->get_AI_mgr()->update(delta_time_sec);
402 // Update any multiplayer models
403 globals->get_multiplayer_rx_mgr()->Update();
408 // Calculate model iterations needed for next frame
409 elapsed += remainder;
411 global_multi_loop = (long)(((double)elapsed * 0.000001) * model_hz );
412 remainder = elapsed - ( (global_multi_loop*1000000) / model_hz );
413 SG_LOG( SG_ALL, SG_DEBUG,
414 "Model iterations needed = " << global_multi_loop
415 << ", new remainder = " << remainder );
417 // chop max interations to something reasonable if the sim was
418 // delayed for an excesive amount of time
419 if ( global_multi_loop > 2.0 * model_hz ) {
420 global_multi_loop = (int)(2.0 * model_hz );
424 bool scenery_loaded = fgGetBool("sim/sceneryloaded") || fgGetBool("sim/sceneryloaded-override");
427 if ( global_multi_loop > 0) {
428 // first run the flight model each frame until it is intialized
429 // then continue running each frame only after initial scenery load is complete.
430 if (!cur_fdm_state->get_inited() || scenery_loaded) {
431 fgUpdateTimeDepCalcs();
434 SG_LOG( SG_ALL, SG_DEBUG,
435 "Elapsed time is zero ... we're zinging" );
438 // Do any I/O channel work that might need to be done
439 globals->get_io()->update( real_delta_time_sec );
441 // see if we need to load any deferred-load textures
442 globals->get_matlib()->load_next_deferred();
444 // Run audio scheduler
445 #ifdef ENABLE_AUDIO_SUPPORT
446 if ( globals->get_soundmgr()->is_working() ) {
447 globals->get_soundmgr()->update( delta_time_sec );
451 globals->get_subsystem_mgr()->update(delta_time_sec);
454 // Tile Manager updates - see if we need to load any new scenery tiles.
455 // this code ties together the fdm, viewer and scenery classes...
456 // we may want to move this to it's own class at some point
458 double visibility_meters = fgGetDouble("/environment/visibility-m");
459 FGViewer *current_view = globals->get_current_view();
461 // get the location data for the primary FDM (now hardcoded to ac model)...
462 SGLocation *acmodel_loc = NULL;
463 acmodel_loc = (SGLocation *)globals->
464 get_aircraft_model()->get3DModel()->getSGLocation();
466 // update tile manager for FDM...
467 // ...only if location is different than the current-view location
468 // (to avoid duplicating effort)
469 if( !fgGetBool("/sim/current-view/config/from-model") ) {
470 if( acmodel_loc != NULL ) {
471 globals->get_tile_mgr()->prep_ssg_nodes( acmodel_loc,
473 globals->get_tile_mgr()->
474 update( acmodel_loc, visibility_meters,
476 get_absolute_view_pos(globals->
477 get_scenery()->get_center()) );
478 // save results of update in SGLocation for fdm...
479 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
481 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
482 fgSetDouble("/position/ground-elev-m",
483 globals->get_scenery()->get_cur_elev());
486 set_tile_center( globals->get_scenery()->get_next_center() );
490 globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
492 // update tile manager for view...
493 // IMPORTANT!!! the tilemgr update for view location _must_ be
494 // done last after the FDM's until all of Flight Gear code
495 // references the viewer's location for elevation instead of the
496 // "scenery's" current elevation.
497 SGLocation *view_location = globals->get_current_view()->getSGLocation();
498 globals->get_tile_mgr()->update( view_location, visibility_meters,
499 current_view->get_absolute_view_pos() );
500 // save results of update in SGLocation for fdm...
501 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
502 current_view->getSGLocation()->
503 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
505 current_view->getSGLocation()->
506 set_tile_center( globals->get_scenery()->get_next_center() );
508 #ifdef ENABLE_AUDIO_SUPPORT
509 // Right now we make a simplifying assumption that the primary
510 // aircraft is the source of all sounds and that all sounds are
511 // positioned relative to the current view position.
513 static sgVec3 last_pos_offset;
515 // set positional offset for sources
516 sgVec3 source_pos_offset;
517 sgSubVec3( source_pos_offset,
518 view_location->get_view_pos(), acmodel_loc->get_view_pos() );
519 // cout << "pos all = " << source_pos_offset[0] << " " << source_pos_offset[1] << " " << source_pos_offset[2] << endl;
520 globals->get_soundmgr()->set_source_pos_all( source_pos_offset );
524 sgSubVec3( source_vel, source_pos_offset, last_pos_offset );
525 sgScaleVec3( source_vel, delta_time_sec );
526 sgCopyVec3( last_pos_offset, source_pos_offset );
527 // cout << "vel = " << source_vel[0] << " " << source_vel[1] << " " << source_vel[2] << endl;
528 globals->get_soundmgr()->set_source_vel_all( source_vel );
530 // Right now we make a simplifying assumption that the listener is
531 // always positioned at the origin.
533 sgSetVec3( listener_pos, 0.0, 0.0, 0.0 );
534 // cout << "listener = " << listener_pos[0] << " " << listener_pos[1] << " " << listener_pos[2] << endl;
535 globals->get_soundmgr()->set_listener_pos( listener_pos );
538 // If fdm location is same as viewer's then we didn't do the
539 // update for fdm location above so we need to save the viewer
540 // results in the fdm SGLocation as well...
541 if( fgGetBool("/sim/current-view/config/from-model") ) {
542 if( acmodel_loc != 0 ) {
543 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
544 acmodel_loc->set_cur_elev_m( globals->get_scenery()->
546 fgSetDouble("/position/ground-elev-m",
547 globals->get_scenery()->get_cur_elev());
549 acmodel_loc->set_tile_center( globals->get_scenery()->
554 // END Tile Manager udpates
556 if (!scenery_loaded && globals->get_tile_mgr()->all_queues_empty() && cur_fdm_state->get_inited()) {
557 fgSetBool("sim/sceneryloaded",true);
558 fgSetFloat("/sim/sound/volume", init_volume);
559 globals->get_soundmgr()->set_volume(init_volume);
562 if (fgGetBool("/sim/rendering/specular-highlight")) {
563 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
564 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
566 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
567 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
572 SG_LOG( SG_ALL, SG_DEBUG, "" );
576 // This is the top level master main function that is registered as
579 // The first few passes take care of initialization things (a couple
580 // per pass) and once everything has been initialized fgMainLoop from
583 static void fgIdleFunction ( void ) {
584 // printf("idle state == %d\n", idle_state);
586 if ( idle_state == 0 ) {
587 // Initialize the splash screen right away
588 if ( fgGetBool("/sim/startup/splash-screen") ) {
589 fgSplashInit(fgGetString("/sim/startup/splash-texture"));
593 } else if ( idle_state == 1 ) {
594 // Initialize audio support
595 #ifdef ENABLE_AUDIO_SUPPORT
597 // Start the intro music
598 if ( fgGetBool("/sim/startup/intro-music") ) {
599 SGPath mp3file( globals->get_fg_root() );
600 mp3file.append( "Sounds/intro.mp3" );
602 SG_LOG( SG_GENERAL, SG_INFO,
603 "Starting intro music: " << mp3file.str() );
605 #if defined( __CYGWIN__ )
606 string command = "start /m `cygpath -w " + mp3file.str() + "`";
607 #elif defined( WIN32 )
608 string command = "start /m " + mp3file.str();
610 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
613 system ( command.c_str() );
618 } else if ( idle_state == 2 ) {
619 // These are a few miscellaneous things that aren't really
620 // "subsystems" but still need to be initialized.
623 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
624 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
629 } else if ( idle_state == 3 ) {
630 // This is the top level init routine which calls all the
631 // other subsystem initialization routines. If you are adding
632 // a subsystem to flightgear, its initialization call should
633 // located in this routine.
634 if( !fgInitSubsystems()) {
635 SG_LOG( SG_GENERAL, SG_ALERT,
636 "Subsystem initializations failed ..." );
641 } else if ( idle_state == 4 ) {
642 // Initialize the time offset (warp) after fgInitSubsystem
643 // (which initializes the lighting interpolation tables.)
646 // setup OpenGL view parameters
647 globals->get_renderer()->init();
649 // Read the list of available aircrafts
653 } else if ( idle_state == 5 ) {
656 } else if ( idle_state == 6 ) {
661 SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
662 globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
663 fgGetInt("/sim/startup/ysize") );
667 if ( idle_state == 1000 ) {
668 // We've finished all our initialization steps, from now on we
669 // run the main loop.
670 fgSetBool("sim/sceneryloaded",false);
672 fgRegisterIdleHandler(fgMainLoop);
674 if ( fgGetBool("/sim/startup/splash-screen") ) {
675 fgSplashUpdate(0.0, 1.0);
681 // Main top level initialization
682 bool fgMainInit( int argc, char **argv ) {
684 #if defined( macintosh )
685 freopen ("stdout.txt", "w", stdout );
686 freopen ("stderr.txt", "w", stderr );
687 argc = ccommand( &argv );
690 // set default log levels
691 sglog().setLogLevels( SG_ALL, SG_ALERT );
694 #ifdef FLIGHTGEAR_VERSION
695 version = FLIGHTGEAR_VERSION;
697 version = "unknown version";
699 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
701 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
703 // Allocate global data structures. This needs to happen before
704 // we parse command line options
706 globals = new FGGlobals;
708 // seed the random number generater
711 FGControls *controls = new FGControls;
712 globals->set_controls( controls );
714 string_list *col = new string_list;
715 globals->set_channel_options_list( col );
717 // Scan the config file(s) and command line options to see if
718 // fg_root was specified (ignore all other options for now)
719 fgInitFGRoot(argc, argv);
721 // Check for the correct base package version
722 static char required_version[] = "0.9.8";
723 string base_version = fgBasePackageVersion();
724 if ( !(base_version == required_version) ) {
725 // tell the operator how to use this application
727 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
728 cerr << endl << "Base package check failed ... " \
729 << "Found version " << base_version << " at: " \
730 << globals->get_fg_root() << endl;
731 cerr << "Please upgrade to version: " << required_version << endl;
733 cerr << "Hit a key to continue..." << endl;
739 sgUseDisplayList = fgGetBool( "/sim/rendering/use-display-list", true );
741 // Initialize the Aircraft directory to "" (UIUC)
744 // Load the configuration parameters. (Command line options
745 // overrides config file options. Config file options override
747 if ( !fgInitConfig(argc, argv) ) {
748 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
752 // Initialize the Window/Graphics environment.
753 #if !defined(__APPLE__) || defined(OSX_BUNDLE)
754 // Mac OS X command line ("non-bundle") applications call this
755 // from main(), in bootstrap.cxx. Andy doesn't know why, someone
756 // feel free to add comments...
757 fgOSInit(&argc, argv);
761 fgRegisterWindowResizeHandler( &FGRenderer::resize );
762 fgRegisterIdleHandler( &fgIdleFunction );
763 fgRegisterDrawHandler( &FGRenderer::update );
765 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
766 bool get_stencil_buffer = true;
768 bool get_stencil_buffer = false;
771 // Clouds3D requires an alpha channel
772 // clouds may require stencil buffer
773 fgOSOpenWindow( fgGetInt("/sim/startup/xsize"),
774 fgGetInt("/sim/startup/ysize"),
775 fgGetInt("/sim/rendering/bits-per-pixel"),
776 fgGetBool("/sim/rendering/clouds3d"),
778 fgGetBool("/sim/startup/fullscreen") );
780 // This seems to be the absolute earliest in the init sequence
781 // that these calls will return valid info. Too bad it's after
782 // we've already created and sized out window. :-(
783 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
784 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
785 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
786 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
789 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
790 general.set_glMaxTexSize( tmp );
791 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
793 glGetIntegerv( GL_DEPTH_BITS, &tmp );
794 general.set_glDepthBits( tmp );
795 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
797 // Initialize plib net interface
798 netInit( &argc, argv );
800 // Initialize ssg (from plib). Needs to come before we do any
801 // other ssg stuff, but after opengl has been initialized.
804 // Initialize the user interface (we need to do this before
805 // passing off control to the OS main loop and before
806 // fgInitGeneral to get our fonts !!!
809 // Read the list of available aircrafts
812 #ifdef GL_EXT_texture_lod_bias
813 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
816 // get the address of our OpenGL extensions
817 if ( fgGetBool("/sim/rendering/distance-attenuation") )
819 if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
820 glPointParameterIsSupported = true;
821 glPointParameterfPtr = (glPointParameterfProc)
822 SGLookupFunction("glPointParameterfEXT");
823 glPointParameterfvPtr = (glPointParameterfvProc)
824 SGLookupFunction("glPointParameterfvEXT");
826 } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
827 glPointParameterIsSupported = true;
828 glPointParameterfPtr = (glPointParameterfProc)
829 SGLookupFunction("glPointParameterfARB");
830 glPointParameterfvPtr = (glPointParameterfvProc)
831 SGLookupFunction("glPointParameterfvARB");
833 glPointParameterIsSupported = false;
836 // based on the requested presets, calculate the true starting
841 SGTime *t = fgInitTime();
842 globals->set_time_params( t );
844 // Do some quick general initializations
845 if( !fgInitGeneral()) {
846 SG_LOG( SG_GENERAL, SG_ALERT,
847 "General initializations failed ..." );
851 ////////////////////////////////////////////////////////////////////
852 // Initialize the property-based built-in commands
853 ////////////////////////////////////////////////////////////////////
856 ////////////////////////////////////////////////////////////////////
857 // Initialize the material manager
858 ////////////////////////////////////////////////////////////////////
859 globals->set_matlib( new SGMaterialLib );
861 globals->set_model_lib(new SGModelLib);
863 ////////////////////////////////////////////////////////////////////
864 // Initialize the TG scenery subsystem.
865 ////////////////////////////////////////////////////////////////////
866 globals->set_scenery( new FGScenery );
867 globals->get_scenery()->init();
868 globals->get_scenery()->bind();
869 globals->set_tile_mgr( new FGTileMgr );
871 ////////////////////////////////////////////////////////////////////
872 // Initialize the general model subsystem.
873 ////////////////////////////////////////////////////////////////////
874 globals->set_model_mgr(new FGModelMgr);
875 globals->get_model_mgr()->init();
876 globals->get_model_mgr()->bind();
878 ////////////////////////////////////////////////////////////////////
879 // Initialize the 3D aircraft model subsystem (has a dependency on
880 // the scenery subsystem.)
881 ////////////////////////////////////////////////////////////////////
882 globals->set_aircraft_model(new FGAircraftModel);
883 globals->get_aircraft_model()->init();
884 globals->get_aircraft_model()->bind();
886 ////////////////////////////////////////////////////////////////////
887 // Initialize the view manager subsystem.
888 ////////////////////////////////////////////////////////////////////
889 FGViewMgr *viewmgr = new FGViewMgr;
890 globals->set_viewmgr( viewmgr );
895 // Initialize the sky
896 SGPath ephem_data_path( globals->get_fg_root() );
897 ephem_data_path.append( "Astro" );
898 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
899 ephem->update( globals->get_time_params()->getMjd(),
900 globals->get_time_params()->getLst(),
902 globals->set_ephem( ephem );
904 // TODO: move to environment mgr
906 SGPath texture_path(globals->get_fg_root());
907 texture_path.append("Textures");
908 texture_path.append("Sky");
909 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
910 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
911 thesky->add_cloud_layer(layer);
914 SGPath sky_tex_path( globals->get_fg_root() );
915 sky_tex_path.append( "Textures" );
916 sky_tex_path.append( "Sky" );
917 thesky->texture_path( sky_tex_path.str() );
919 // The sun and moon diameters are scaled down numbers of the
920 // actual diameters. This was needed to fit bot the sun and the
921 // moon within the distance to the far clip plane.
922 // Moon diameter: 3,476 kilometers
923 // Sun diameter: 1,390,000 kilometers
924 thesky->build( 80000.0, 80000.0,
926 globals->get_ephem()->getNumPlanets(),
927 globals->get_ephem()->getPlanets(),
928 globals->get_ephem()->getNumStars(),
929 globals->get_ephem()->getStars() );
931 // Initialize MagVar model
932 SGMagVar *magvar = new SGMagVar();
933 globals->set_mag( magvar );
936 // kludge to initialize mag compass
937 // (should only be done for in-flight
939 // update magvar model
940 globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
941 * SGD_DEGREES_TO_RADIANS,
942 fgGetDouble("/position/latitude-deg")
943 * SGD_DEGREES_TO_RADIANS,
944 fgGetDouble("/position/altitude-ft")
946 globals->get_time_params()->getJD() );
947 double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
948 fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
950 // airport = new ssgBranch;
951 // airport->setName( "Airport Lighting" );
952 // lighting->addKid( airport );
954 // build our custom render states
955 globals->get_renderer()->build_states();
957 // pass control off to the master event handler
960 // we never actually get here ... but to avoid compiler warnings,