1 // fg_init.cxx -- Flight Gear top level initialization routines
3 // Written by Curtis Olson, started August 1997.
5 // Copyright (C) 1997 Curtis L. Olson - curt@infoplane.com
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.
29 // For BC 5.01 this must be included before OpenGL includes.
30 #ifdef SG_MATH_EXCEPTION_CLASH
42 #include <string.h> // strcmp()
45 #if defined( unix ) || defined( __CYGWIN__ )
46 # include <unistd.h> // for gethostname()
49 // work around a stdc++ lib bug in some versions of linux, but doesn't
50 // seem to hurt to have this here for all versions of Linux.
52 # define _G_NO_EXTERN_TEMPLATES
55 #include <simgear/compiler.h>
56 #include <simgear/misc/exception.hxx>
60 #include <simgear/constants.h>
61 #include <simgear/debug/logstream.hxx>
62 #include <simgear/math/point3d.hxx>
63 #include <simgear/math/polar3d.hxx>
64 #include <simgear/math/sg_geodesy.hxx>
65 #include <simgear/misc/sg_path.hxx>
66 #include <simgear/sky/clouds3d/SkySceneLoader.hpp>
67 #include <simgear/sky/clouds3d/SkyUtil.hpp>
68 #include <simgear/timing/sg_time.hxx>
69 #include <simgear/timing/lowleveltime.h>
71 #include <Aircraft/aircraft.hxx>
72 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
73 #include <Airports/runways.hxx>
74 #include <Airports/simple.hxx>
75 #include <ATC/ATCdisplay.hxx>
76 #include <ATC/ATCmgr.hxx>
77 #include <ATC/atislist.hxx>
78 #include <ATC/towerlist.hxx>
79 #include <ATC/approachlist.hxx>
80 #include <ATC/AIMgr.hxx>
81 #include <Autopilot/auto_gui.hxx>
82 #include <Autopilot/newauto.hxx>
83 #include <Cockpit/cockpit.hxx>
84 #include <Cockpit/radiostack.hxx>
85 #include <Cockpit/steam.hxx>
86 #include <Cockpit/panel.hxx>
87 #include <Cockpit/panel_io.hxx>
88 #include <FDM/ADA.hxx>
89 #include <FDM/Balloon.h>
90 #include <FDM/ExternalNet/ExternalNet.hxx>
91 #include <FDM/JSBSim/JSBSim.hxx>
92 #include <FDM/LaRCsim.hxx>
93 #include <FDM/MagicCarpet.hxx>
94 #include <FDM/UFO.hxx>
95 #include <FDM/NullFDM.hxx>
96 #include <FDM/YASim/YASim.hxx>
97 #include <GUI/new_gui.hxx>
98 #include <Include/general.hxx>
99 #include <Input/input.hxx>
100 #include <Instrumentation/instrument_mgr.hxx>
101 // #include <Joystick/joystick.hxx>
102 #include <Objects/matlib.hxx>
103 #include <Model/acmodel.hxx>
104 #include <Navaids/fixlist.hxx>
105 #include <Navaids/ilslist.hxx>
106 #include <Navaids/mkrbeacons.hxx>
107 #include <Navaids/navlist.hxx>
108 #include <Scenery/scenery.hxx>
109 #include <Scenery/tilemgr.hxx>
110 #include <Sound/fg_fx.hxx>
111 #include <Sound/soundmgr.hxx>
112 #include <Systems/system_mgr.hxx>
113 #include <Time/FGEventMgr.hxx>
114 #include <Time/light.hxx>
115 #include <Time/sunpos.hxx>
116 #include <Time/moonpos.hxx>
117 #include <Time/tmp.hxx>
120 # include <WeatherCM/FGLocalWeatherDatabase.h>
122 # include <Environment/environment_mgr.hxx>
125 #include "fg_init.hxx"
127 #include "fg_commands.hxx"
128 #include "fg_props.hxx"
129 #include "options.hxx"
130 #include "globals.hxx"
131 #include "logger.hxx"
132 #include "viewmgr.hxx"
134 #if defined(FX) && defined(XMESA)
135 #include <GL/xmesa.h>
138 SG_USING_STD(string);
140 extern const char *default_root;
142 SkySceneLoader *sgCloud3d;
145 // Scan the command line options for an fg_root definition and set
147 static string fgScanForRoot (int argc, char **argv) {
150 SG_LOG(SG_GENERAL, SG_INFO, "Scanning for root: command line");
153 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
155 string arg = argv[i];
156 if ( arg.find( "--fg-root=" ) == 0 ) {
157 return arg.substr( 10 );
167 // Scan the user config files for an fg_root definition and set just
169 static string fgScanForRoot (const string& path) {
170 sg_gzifstream in( path );
174 SG_LOG( SG_GENERAL, SG_INFO, "Scanning for root: " << path );
178 while ( ! in.eof() ) {
181 while ( in.get(c) && c != '\0' ) {
186 #if defined( macintosh )
187 getline( in, line, '\r' );
189 getline( in, line, '\n' );
192 // catch extraneous (DOS) line ending character
193 if ( line[line.length() - 1] < 32 ) {
194 line = line.substr( 0, line.length()-1 );
197 if ( line.find( "--fg-root=" ) == 0 ) {
198 return line.substr( 10 );
208 // Read in configuration (files and command line options) but only set
210 bool fgInitFGRoot ( int argc, char **argv ) {
214 // First parse command line options looking for fg-root, this will
215 // override anything specified in a config file
216 root = fgScanForRoot(argc, argv);
218 #if defined( unix ) || defined( __CYGWIN__ )
219 // Next check home directory for .fgfsrc.hostname file
220 if ( root.empty() ) {
221 envp = ::getenv( "HOME" );
222 if ( envp != NULL ) {
223 SGPath config( envp );
224 config.append( ".fgfsrc" );
226 gethostname( name, 256 );
227 config.concat( "." );
228 config.concat( name );
229 root = fgScanForRoot(config.str());
234 // Next check home directory for .fgfsrc file
235 if ( root.empty() ) {
236 envp = ::getenv( "HOME" );
237 if ( envp != NULL ) {
238 SGPath config( envp );
239 config.append( ".fgfsrc" );
240 root = fgScanForRoot(config.str());
244 // Next check if fg-root is set as an env variable
245 if ( root.empty() ) {
246 envp = ::getenv( "FG_ROOT" );
247 if ( envp != NULL ) {
252 // Otherwise, default to a random compiled-in location if we can't
253 // find fg-root any other way.
254 if ( root.empty() ) {
255 #if defined( __CYGWIN__ )
256 root = "/FlightGear";
257 #elif defined( WIN32 )
258 root = "\\FlightGear";
259 #elif defined( macintosh )
266 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
267 globals->set_fg_root(root);
273 // Scan the command line options for an aircraft definition and set
275 static string fgScanForAircraft (int argc, char **argv) {
278 SG_LOG(SG_GENERAL, SG_INFO, "Scanning for aircraft: command line");
281 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
283 string arg = argv[i];
284 if ( arg.find( "--aircraft=" ) == 0 ) {
285 return arg.substr( 11 );
295 // Scan the user config files for an aircrafg definition and set just
297 static string fgScanForAircraft (const string& path) {
298 sg_gzifstream in( path );
299 if ( !in.is_open() ) {
303 SG_LOG( SG_GENERAL, SG_INFO, "Scanning for aircraft: " << path );
307 while ( ! in.eof() ) {
310 while ( in.get(c) && c != '\0' ) {
315 #if defined( macintosh )
316 getline( in, line, '\r' );
318 getline( in, line, '\n' );
321 // catch extraneous (DOS) line ending character
322 if ( line[line.length() - 1] < 32 ) {
323 line = line.substr( 0, line.length()-1 );
326 if ( line.find( "--aircraft=" ) == 0 ) {
327 return line.substr( 11 );
337 // Read in configuration (files and command line options) but only set
339 bool fgInitFGAircraft ( int argc, char **argv ) {
343 // First parse command line options looking for --aircraft=, this
344 // will override anything specified in a config file
345 aircraft = fgScanForAircraft(argc, argv);
347 #if defined( unix ) || defined( __CYGWIN__ )
348 // Next check home directory for .fgfsrc.hostname file
349 if ( aircraft.empty() ) {
350 envp = ::getenv( "HOME" );
351 if ( envp != NULL ) {
352 SGPath config( envp );
353 config.append( ".fgfsrc" );
355 gethostname( name, 256 );
356 config.concat( "." );
357 config.concat( name );
358 aircraft = fgScanForRoot(config.str());
363 // Next check home directory for .fgfsrc file
364 if ( aircraft.empty() ) {
365 envp = ::getenv( "HOME" );
366 if ( envp != NULL ) {
367 SGPath config( envp );
368 config.append( ".fgfsrc" );
369 aircraft = fgScanForRoot(config.str());
373 // if an aircraft was specified, set the property name
374 if ( !aircraft.empty() ) {
375 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
376 fgSetString("/sim/aircraft", aircraft.c_str() );
378 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
385 // Return the current base package version
386 string fgBasePackageVersion() {
387 SGPath base_path( globals->get_fg_root() );
388 base_path.append("version");
390 sg_gzifstream in( base_path.str() );
391 if ( !in.is_open() ) {
392 SGPath old_path( globals->get_fg_root() );
393 old_path.append( "Thanks" );
394 sg_gzifstream old( old_path.str() );
395 if ( !old.is_open() ) {
398 return "[old version]";
409 // Initialize the localization
410 SGPropertyNode *fgInitLocale(const char *language) {
411 SGPropertyNode *c_node = NULL, *d_node = NULL;
412 SGPropertyNode *intl = fgGetNode("/sim/intl");
414 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
416 // localization not defined
421 // Select the proper language from the list
423 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
424 for (unsigned int i = 0; i < locale.size(); i++) {
426 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
427 for (unsigned int j = 0; j < lang.size(); j++) {
429 if (!strcmp(lang[j]->getStringValue(), language)) {
438 d_node = intl->getChild("locale");
442 // Check for localized font
443 SGPropertyNode *font_n = c_node->getNode("font", true);
444 if ( !strcmp(font_n->getStringValue(), "") )
445 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
449 // Load the default strings
451 SGPath d_path( globals->get_fg_root() );
453 const char *d_path_str = d_node->getStringValue("strings");
455 SG_LOG(SG_GENERAL, SG_ALERT, "Incorrect path in configuration file.");
459 d_path.append(d_path_str);
460 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from "
463 SGPropertyNode *strings = c_node->getNode("strings");
465 readProperties(d_path.str(), strings);
466 } catch (const sg_exception &e) {
467 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
472 // Load the language specific strings
474 if (c_node != d_node) {
475 SGPath c_path( globals->get_fg_root() );
477 const char *c_path_str = c_node->getStringValue("strings");
479 SG_LOG(SG_GENERAL, SG_ALERT, "Incorrect path in configuration file.");
483 c_path.append(c_path_str);
484 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from "
488 readProperties(c_path.str(), strings);
489 } catch (const sg_exception &e) {
490 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
500 // Initialize the localization routines
501 bool fgDetectLanguage() {
502 char *language = ::getenv("LANG");
504 if (language == NULL) {
505 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
509 SGPropertyNode *locale = fgInitLocale(language);
511 cerr << "No internationalization settings specified in preferences.xml"
517 globals->set_locale( locale );
522 // Attempt to locate and parse the various non-XML config files in order
523 // from least precidence to greatest precidence
525 do_options (int argc, char ** argv)
527 // Check for $fg_root/system.fgfsrc
528 SGPath config( globals->get_fg_root() );
529 config.append( "system.fgfsrc" );
530 fgParseOptions(config.str());
532 #if defined( unix ) || defined( __CYGWIN__ )
534 // Check for $fg_root/system.fgfsrc.hostname
535 gethostname( name, 256 );
536 config.concat( "." );
537 config.concat( name );
538 fgParseOptions(config.str());
541 // Check for ~/.fgfsrc
542 char* envp = ::getenv( "HOME" );
543 if ( envp != NULL ) {
545 config.append( ".fgfsrc" );
546 fgParseOptions(config.str());
549 #if defined( unix ) || defined( __CYGWIN__ )
550 // Check for ~/.fgfsrc.hostname
551 gethostname( name, 256 );
552 config.concat( "." );
553 config.concat( name );
554 fgParseOptions(config.str());
557 // Parse remaining command line options
558 // These will override anything specified in a config file
559 fgParseArgs(argc, argv);
563 // Read in configuration (file and command line)
564 bool fgInitConfig ( int argc, char **argv ) {
566 // First, set some sane default values
569 // Read global preferences from $FG_ROOT/preferences.xml
570 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
571 fgLoadProps("preferences.xml", globals->get_props());
572 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
574 // Detect the required language as early as possible
575 if ( !fgDetectLanguage() ) {
579 // Scan user config files and command line for a specified aircraft.
580 fgInitFGAircraft(argc, argv);
582 string aircraft = fgGetString("/sim/aircraft", "");
583 if ( aircraft.size() > 0 ) {
584 SGPath aircraft_path(globals->get_fg_root());
585 aircraft_path.append("Aircraft");
586 aircraft_path.append(aircraft);
587 aircraft_path.concat("-set.xml");
588 SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
589 << " from " << aircraft_path.str());
591 readProperties(aircraft_path.str(), globals->get_props());
592 } catch (const sg_exception &e) {
593 string message = "Error reading default aircraft: ";
594 message += e.getFormattedMessage();
595 SG_LOG(SG_INPUT, SG_ALERT, message);
599 SG_LOG(SG_INPUT, SG_ALERT, "No default aircraft specified");
602 // parse options after loading aircraft to ensure any user
603 // overrides of defaults are honored.
604 do_options(argc, argv);
610 // find basic airport location info from airport database
611 bool fgFindAirportID( const string& id, FGAirport *a ) {
613 SGPath path( globals->get_fg_root() );
614 path.append( "Airports" );
615 path.append( "simple.mk4" );
616 FGAirports airports( path.c_str() );
618 SG_LOG( SG_GENERAL, SG_INFO, "Searching for airport code = " << id );
620 if ( ! airports.search( id, a ) ) {
621 SG_LOG( SG_GENERAL, SG_ALERT,
622 "Failed to find " << id << " in " << path.str() );
629 SG_LOG( SG_GENERAL, SG_INFO,
630 "Position for " << id << " is ("
631 << a->longitude << ", "
632 << a->latitude << ")" );
638 // Preset lon/lat given an airport id
639 bool fgSetPosFromAirportID( const string& id ) {
643 SG_LOG( SG_GENERAL, SG_INFO,
644 "Attempting to set starting position from airport code " << id );
646 if ( fgFindAirportID( id, &a ) ) {
648 fgSetDouble("/sim/presets/longitude-deg", a.longitude );
649 fgSetDouble("/sim/presets/latitude-deg", a.latitude );
651 // other code depends on the actual postition being set so set
653 fgSetDouble("/position/longitude-deg", a.longitude );
654 fgSetDouble("/position/latitude-deg", a.latitude );
656 SG_LOG( SG_GENERAL, SG_INFO,
657 "Position for " << id << " is (" << a.longitude
658 << ", " << a.latitude << ")" );
669 // Set current tower position lon/lat given an airport id
670 bool fgSetTowerPosFromAirportID( const string& id, double hdg ) {
672 // tower height hard coded for now...
673 float towerheight=50.0f;
675 // make a little off the heading for 1 runway airports...
676 float fudge_lon = fabs(sin(hdg)) * .003f;
677 float fudge_lat = .003f - fudge_lon;
679 if ( fgFindAirportID( id, &a ) ) {
680 fgSetDouble("/sim/tower/longitude-deg", a.longitude + fudge_lon);
681 fgSetDouble("/sim/tower/latitude-deg", a.latitude + fudge_lat);
682 fgSetDouble("/sim/tower/altitude-ft", a.elevation + towerheight);
691 // Set current_options lon/lat given an airport id and heading (degrees)
692 bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
695 double found_dir = 0.0;
698 // set initial position from runway and heading
700 SGPath path( globals->get_fg_root() );
701 path.append( "Airports" );
702 path.append( "runways.mk4" );
703 FGRunways runways( path.c_str() );
705 SG_LOG( SG_GENERAL, SG_INFO,
706 "Attempting to set starting position from runway code "
707 << id << " heading " << tgt_hdg );
709 // SGPath inpath( globals->get_fg_root() );
710 // inpath.append( "Airports" );
711 // inpath.append( "apt_simple" );
712 // airports.load( inpath.c_str() );
714 // SGPath outpath( globals->get_fg_root() );
715 // outpath.append( "Airports" );
716 // outpath.append( "simple.gdbm" );
717 // airports.dump_gdbm( outpath.c_str() );
719 if ( ! runways.search( id, &r ) ) {
720 SG_LOG( SG_GENERAL, SG_ALERT,
721 "Failed to find " << id << " in database." );
726 double min_diff = 360.0;
728 while ( r.id == id ) {
730 diff = tgt_hdg - r.heading;
731 while ( diff < -180.0 ) { diff += 360.0; }
732 while ( diff > 180.0 ) { diff -= 360.0; }
734 SG_LOG( SG_GENERAL, SG_INFO,
735 "Runway " << r.rwy_no << " heading = " << r.heading <<
736 " diff = " << diff );
737 if ( diff < min_diff ) {
744 diff = tgt_hdg - r.heading - 180.0;
745 while ( diff < -180.0 ) { diff += 360.0; }
746 while ( diff > 180.0 ) { diff -= 360.0; }
748 SG_LOG( SG_GENERAL, SG_INFO,
749 "Runway -" << r.rwy_no << " heading = " <<
751 " diff = " << diff );
752 if ( diff < min_diff ) {
761 SG_LOG( SG_GENERAL, SG_INFO, "closest runway = " << found_r.rwy_no
762 << " + " << found_dir );
768 double heading = found_r.heading + found_dir;
769 while ( heading >= 360.0 ) { heading -= 360.0; }
771 double lat2, lon2, az2;
772 double azimuth = found_r.heading + found_dir + 180.0;
773 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
775 SG_LOG( SG_GENERAL, SG_INFO,
776 "runway = " << found_r.lon << ", " << found_r.lat
777 << " length = " << found_r.length * SG_FEET_TO_METER * 0.5
778 << " heading = " << azimuth );
780 geo_direct_wgs_84 ( 0, found_r.lat, found_r.lon,
781 azimuth, found_r.length * SG_FEET_TO_METER * 0.5 - 5.0,
782 &lat2, &lon2, &az2 );
784 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON ) {
786 double odist = fgGetDouble("/sim/presets/offset-distance");
787 odist *= SG_NM_TO_METER;
788 double oaz = azimuth;
789 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON ) {
790 oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
792 while ( oaz >= 360.0 ) { oaz -= 360.0; }
793 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
799 fgSetDouble("/sim/presets/longitude-deg", lon2 );
800 fgSetDouble("/sim/presets/latitude-deg", lat2 );
801 fgSetDouble("/sim/presets/heading-deg", heading );
803 // other code depends on the actual values being set ...
804 fgSetDouble("/position/longitude-deg", lon2 );
805 fgSetDouble("/position/latitude-deg", lat2 );
806 fgSetDouble("/orientation/heading-deg", heading );
808 SG_LOG( SG_GENERAL, SG_INFO,
809 "Position for " << id << " is ("
811 << lat2 << ") new heading is "
818 void fgSetPosFromGlideSlope() {
819 double gs = fgGetDouble("/sim/presets/glideslope");
820 double od = fgGetDouble("/sim/presets/offset-distance");
821 double alt = fgGetDouble("/sim/presets/altitude-ft");
823 // if glideslope and offset-distance are set and altitude is not,
824 // calculate the initial altitude
825 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
826 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
827 alt = fabs(od*tan(gs));
828 fgSetDouble("/sim/presets/altitude-ft",alt);
829 fgSetBool("/sim/presets/onground", false);
830 SG_LOG(SG_GENERAL,SG_INFO, "Calculated altitude as: " << alt << " ft");
831 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
833 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
834 fgSetDouble("/sim/presets/offset-distance",od);
835 SG_LOG(SG_GENERAL, SG_INFO, "Calculated offset distance as: "
837 } else if( fabs(gs) > 0.01 ) {
838 SG_LOG( SG_GENERAL, SG_ALERT,
839 "Glideslope given but not altitude or offset-distance." );
840 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
841 fgSetDouble("/sim/presets/glideslope",0);
846 // General house keeping initializations
847 bool fgInitGeneral( void ) {
850 #if defined(FX) && defined(XMESA)
851 char *mesa_win_state;
854 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
855 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
857 root = globals->get_fg_root();
858 if ( ! root.length() ) {
859 // No root path set? Then bail ...
860 SG_LOG( SG_GENERAL, SG_ALERT,
861 "Cannot continue without a path to the base package "
862 << "being defined." );
865 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
867 #if defined(FX) && defined(XMESA)
868 // initialize full screen flag
869 globals->set_fullscreen(false);
870 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
871 // Test for the MESA_GLX_FX env variable
872 if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
873 // test if we are fullscreen mesa/glide
874 if ( (mesa_win_state[0] == 'f') ||
875 (mesa_win_state[0] == 'F') ) {
876 globals->set_fullscreen(true);
886 // Initialize the flight model subsystem. This just creates the
887 // object. The actual fdm initialization is delayed until we get a
888 // proper scenery elevation hit. This is checked for in main.cxx
892 if ( cur_fdm_state ) {
893 delete cur_fdm_state;
897 double dt = 1.0 / fgGetInt("/sim/model-hz");
898 aircraft_dir = fgGetString("/sim/aircraft-dir");
899 const string &model = fgGetString("/sim/flight-model");
902 if ( model == "larcsim" ) {
903 cur_fdm_state = new FGLaRCsim( dt );
904 } else if ( model == "jsb" ) {
905 cur_fdm_state = new FGJSBsim( dt );
906 } else if ( model == "ada" ) {
907 cur_fdm_state = new FGADA( dt );
908 } else if ( model == "balloon" ) {
909 cur_fdm_state = new FGBalloonSim( dt );
910 } else if ( model == "magic" ) {
911 cur_fdm_state = new FGMagicCarpet( dt );
912 } else if ( model == "ufo" ) {
913 cur_fdm_state = new FGUFO( dt );
914 } else if ( model == "external" ) {
915 // external is a synonym for "--fdm=null" and is
916 // maintained here for backwards compatibility
917 cur_fdm_state = new FGNullFDM( dt );
918 } else if ( model.find("network") == 0 ) {
919 string host = "localhost";
923 string net_options = model.substr(8);
924 string::size_type begin, end;
927 end = net_options.find( ",", begin );
928 if ( end != string::npos ) {
929 host = net_options.substr(begin, end - begin);
933 end = net_options.find( ",", begin );
934 if ( end != string::npos ) {
935 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
939 end = net_options.find( ",", begin );
940 if ( end != string::npos ) {
941 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
945 end = net_options.find( ",", begin );
946 if ( end != string::npos ) {
947 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
950 cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
951 } else if ( model == "null" ) {
952 cur_fdm_state = new FGNullFDM( dt );
953 } else if ( model == "yasim" ) {
954 cur_fdm_state = new YASim( dt );
956 SG_LOG(SG_GENERAL, SG_ALERT,
957 "Unrecognized flight model '" << model
958 << "', cannot init flight dynamics model.");
962 SG_LOG(SG_GENERAL, SG_ALERT, "FlightGear aborting\n\n");
967 static void printMat(const sgVec4 *mat, char *name="")
970 cout << name << endl;
972 cout <<" "<<mat[i][0]<<" "<<mat[i][1]<<" "<<mat[i][2]<<" "<<mat[i][3]<<endl;
977 // Initialize view parameters
979 // force update of model so that viewer can get some data...
980 globals->get_aircraft_model()->update(0);
981 // run update for current view so that data is current...
982 globals->get_viewmgr()->update(0);
984 printMat(globals->get_current_view()->get_VIEW(),"VIEW");
985 printMat(globals->get_current_view()->get_UP(),"UP");
986 // printMat(globals->get_current_view()->get_LOCAL(),"LOCAL");
991 SGTime *fgInitTime() {
993 static const SGPropertyNode *longitude
994 = fgGetNode("/position/longitude-deg");
995 static const SGPropertyNode *latitude
996 = fgGetNode("/position/latitude-deg");
997 static const SGPropertyNode *cur_time_override
998 = fgGetNode("/sim/time/cur-time-override", true);
1000 SGPath zone( globals->get_fg_root() );
1001 zone.append( "Timezone" );
1002 SGTime *t = new SGTime( longitude->getDoubleValue()
1003 * SGD_DEGREES_TO_RADIANS,
1004 latitude->getDoubleValue()
1005 * SGD_DEGREES_TO_RADIANS,
1007 cur_time_override->getLongValue() );
1009 // Handle potential user specified time offsets
1010 time_t cur_time = t->get_cur_time();
1011 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1012 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1013 time_t aircraftLocalTime =
1014 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1016 // Okay, we now have six possible scenarios
1017 int offset = fgGetInt("/sim/startup/time-offset");
1018 const string &offset_type = fgGetString("/sim/startup/time-offset-type");
1019 if (offset_type == "system-offset") {
1020 globals->set_warp( offset );
1021 } else if (offset_type == "gmt-offset") {
1022 globals->set_warp( offset - (currGMT - systemLocalTime) );
1023 } else if (offset_type == "latitude-offset") {
1024 globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) );
1025 } else if (offset_type == "system") {
1026 globals->set_warp( offset - cur_time );
1027 } else if (offset_type == "gmt") {
1028 globals->set_warp( offset - currGMT );
1029 } else if (offset_type == "latitude") {
1030 globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) -
1033 SG_LOG( SG_GENERAL, SG_ALERT,
1034 "FG_TIME::Unsupported offset type " << offset_type );
1038 SG_LOG( SG_GENERAL, SG_INFO, "After time init, warp = "
1039 << globals->get_warp() );
1041 globals->set_warp_delta( 0 );
1043 t->update( 0.0, 0.0,
1044 cur_time_override->getLongValue(),
1045 globals->get_warp() );
1051 // This is the top level init routine which calls all the other
1052 // initialization routines. If you are adding a subsystem to flight
1053 // gear, its initialization call should located in this routine.
1054 // Returns non-zero if a problem encountered.
1055 bool fgInitSubsystems( void ) {
1056 static const SGPropertyNode *longitude
1057 = fgGetNode("/sim/presets/longitude-deg");
1058 static const SGPropertyNode *latitude
1059 = fgGetNode("/sim/presets/latitude-deg");
1060 static const SGPropertyNode *altitude
1061 = fgGetNode("/sim/presets/altitude-ft");
1063 fgLIGHT *l = &cur_light_params;
1065 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1066 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1069 ////////////////////////////////////////////////////////////////////
1070 // Initialize the material property subsystem.
1071 ////////////////////////////////////////////////////////////////////
1073 SGPath mpath( globals->get_fg_root() );
1074 mpath.append( "materials.xml" );
1075 if ( ! material_lib.load( mpath.str() ) ) {
1076 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1080 ////////////////////////////////////////////////////////////////////
1081 // Initialize the event manager subsystem.
1082 ////////////////////////////////////////////////////////////////////
1084 global_events.init();
1086 // Output event stats every 60 seconds
1087 global_events.Register( "FGEventMgr::print_stats()",
1088 &global_events, &FGEventMgr::print_stats,
1092 ////////////////////////////////////////////////////////////////////
1093 // Initialize the scenery management subsystem.
1094 ////////////////////////////////////////////////////////////////////
1096 if ( global_tile_mgr.init() ) {
1097 // Load the local scenery data
1098 double visibility_meters = fgGetDouble("/environment/visibility-m");
1100 global_tile_mgr.update( longitude->getDoubleValue(),
1101 latitude->getDoubleValue(),
1102 visibility_meters );
1104 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1108 // cause refresh of viewer scenery timestamps every 15 seconds...
1109 global_events.Register( "FGTileMgr::refresh_view_timestamps()",
1110 &global_tile_mgr, &FGTileMgr::refresh_view_timestamps,
1113 SG_LOG( SG_GENERAL, SG_DEBUG,
1114 "Current terrain elevation after tile mgr init " <<
1115 globals->get_scenery()->get_cur_elev() );
1118 ////////////////////////////////////////////////////////////////////
1119 // Initialize the flight model subsystem.
1120 ////////////////////////////////////////////////////////////////////
1124 // allocates structures so must happen before any of the flight
1125 // model or control parameters are set
1126 fgAircraftInit(); // In the future this might not be the case.
1129 ////////////////////////////////////////////////////////////////////
1130 // Initialize the view manager subsystem.
1131 ////////////////////////////////////////////////////////////////////
1136 ////////////////////////////////////////////////////////////////////
1137 // Initialize the lighting subsystem.
1138 ////////////////////////////////////////////////////////////////////
1140 // fgUpdateSunPos() needs a few position and view parameters set
1141 // so it can calculate local relative sun angle and a few other
1142 // things for correctly orienting the sky.
1145 global_events.Register( "fgUpdateSunPos()", &fgUpdateSunPos,
1147 global_events.Register( "fgUpdateMoonPos()", &fgUpdateMoonPos,
1150 // Initialize Lighting interpolation tables
1153 // force one lighting update to make it right to start with...
1155 // update the lighting parameters (based on sun angle)
1156 global_events.Register( "fgLight::Update()",
1157 &cur_light_params, &fgLIGHT::Update,
1161 ////////////////////////////////////////////////////////////////////
1162 // Create and register the logger.
1163 ////////////////////////////////////////////////////////////////////
1165 globals->get_subsystem_mgr()->add(FGSubsystemMgr::GENERAL,
1170 ////////////////////////////////////////////////////////////////////
1171 // Create and register the XML GUI.
1172 ////////////////////////////////////////////////////////////////////
1174 globals->get_subsystem_mgr()->add(FGSubsystemMgr::INIT,
1179 ////////////////////////////////////////////////////////////////////
1180 // Initialize the local time subsystem.
1181 ////////////////////////////////////////////////////////////////////
1183 // update the current timezone each 30 minutes
1184 global_events.Register( "fgUpdateLocalTime()", &fgUpdateLocalTime,
1188 ////////////////////////////////////////////////////////////////////
1189 // Initialize the weather subsystem.
1190 ////////////////////////////////////////////////////////////////////
1192 // Initialize the weather modeling subsystem
1194 // Initialize the WeatherDatabase
1195 SG_LOG(SG_GENERAL, SG_INFO, "Creating LocalWeatherDatabase");
1197 sgSetVec3( position, current_aircraft.fdm_state->get_Latitude(),
1198 current_aircraft.fdm_state->get_Longitude(),
1199 current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER );
1200 double init_vis = fgGetDouble("/environment/visibility-m");
1202 FGLocalWeatherDatabase::DatabaseWorkingType working_type;
1204 if (!strcmp(fgGetString("/environment/weather/working-type"), "internet"))
1206 working_type = FGLocalWeatherDatabase::use_internet;
1208 working_type = FGLocalWeatherDatabase::default_mode;
1211 if ( init_vis > 0 ) {
1212 FGLocalWeatherDatabase::theFGLocalWeatherDatabase =
1213 new FGLocalWeatherDatabase( position,
1214 globals->get_fg_root(),
1218 FGLocalWeatherDatabase::theFGLocalWeatherDatabase =
1219 new FGLocalWeatherDatabase( position,
1220 globals->get_fg_root(),
1224 // cout << theFGLocalWeatherDatabase << endl;
1225 // cout << "visibility = "
1226 // << theFGLocalWeatherDatabase->getWeatherVisibility() << endl;
1228 WeatherDatabase = FGLocalWeatherDatabase::theFGLocalWeatherDatabase;
1230 // register the periodic update of the weather
1231 global_events.Register( "weather update", &fgUpdateWeatherDatabase,
1234 globals->get_environment_mgr()->init();
1235 globals->get_environment_mgr()->bind();
1238 ////////////////////////////////////////////////////////////////////
1239 // Initialize the 3D cloud subsystem.
1240 ////////////////////////////////////////////////////////////////////
1241 if ( fgGetBool("/sim/rendering/clouds3d") ) {
1242 SGPath cloud_path(globals->get_fg_root());
1243 cloud_path.append("large.sky");
1244 SG_LOG(SG_GENERAL, SG_INFO, "Loading CLOUDS3d from: " << cloud_path.c_str());
1245 if ( !sgCloud3d->Load( cloud_path.str(),
1246 latitude->getDoubleValue(),
1247 longitude->getDoubleValue()) )
1249 fgSetBool("/sim/rendering/clouds3d", false);
1250 SG_LOG(SG_GENERAL, SG_INFO, "CLOUDS3d FAILED: ");
1252 SG_LOG(SG_GENERAL, SG_INFO, "CLOUDS3d Loaded: ");
1255 ////////////////////////////////////////////////////////////////////
1256 // Initialize vor/ndb/ils/fix list management and query systems
1257 ////////////////////////////////////////////////////////////////////
1259 SG_LOG(SG_GENERAL, SG_INFO, "Loading Navaids");
1261 SG_LOG(SG_GENERAL, SG_INFO, " VOR/NDB");
1262 current_navlist = new FGNavList;
1263 SGPath p_nav( globals->get_fg_root() );
1264 p_nav.append( "Navaids/default.nav" );
1265 current_navlist->init( p_nav );
1267 SG_LOG(SG_GENERAL, SG_INFO, " ILS and Marker Beacons");
1268 current_beacons = new FGMarkerBeacons;
1269 current_beacons->init();
1270 current_ilslist = new FGILSList;
1271 SGPath p_ils( globals->get_fg_root() );
1272 p_ils.append( "Navaids/default.ils" );
1273 current_ilslist->init( p_ils );
1275 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1276 current_fixlist = new FGFixList;
1277 SGPath p_fix( globals->get_fg_root() );
1278 p_fix.append( "Navaids/default.fix" );
1279 current_fixlist->init( p_fix );
1281 ////////////////////////////////////////////////////////////////////
1282 // Initialize ATC list management and query systems
1283 ////////////////////////////////////////////////////////////////////
1285 SG_LOG(SG_GENERAL, SG_INFO, " ATIS");
1286 current_atislist = new FGATISList;
1287 SGPath p_atis( globals->get_fg_root() );
1288 p_atis.append( "ATC/default.atis" );
1289 current_atislist->init( p_atis );
1291 SG_LOG(SG_GENERAL, SG_INFO, " Tower");
1292 current_towerlist = new FGTowerList;
1293 SGPath p_tower( globals->get_fg_root() );
1294 p_tower.append( "ATC/default.tower" );
1295 current_towerlist->init( p_tower );
1297 SG_LOG(SG_GENERAL, SG_INFO, " Approach");
1298 current_approachlist = new FGApproachList;
1299 SGPath p_approach( globals->get_fg_root() );
1300 p_approach.append( "ATC/default.approach" );
1301 current_approachlist->init( p_approach );
1303 ////////////////////////////////////////////////////////////////////
1304 // Initialise ATC display system
1305 ////////////////////////////////////////////////////////////////////
1307 SG_LOG(SG_GENERAL, SG_INFO, " ATC Display");
1308 globals->set_ATC_display(new FGATCDisplay);
1309 globals->get_ATC_display()->init();
1311 ////////////////////////////////////////////////////////////////////
1312 // Initialise the ATC Manager
1313 ////////////////////////////////////////////////////////////////////
1315 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1316 globals->set_ATC_mgr(new FGATCMgr);
1317 globals->get_ATC_mgr()->init();
1319 ////////////////////////////////////////////////////////////////////
1320 // Initialise the AI Manager
1321 ////////////////////////////////////////////////////////////////////
1323 if (fgGetBool("/sim/ai-traffic/enabled")) {
1324 SG_LOG(SG_GENERAL, SG_INFO, " AI Manager");
1325 globals->set_AI_mgr(new FGAIMgr);
1326 globals->get_AI_mgr()->init();
1329 #ifdef ENABLE_AUDIO_SUPPORT
1330 ////////////////////////////////////////////////////////////////////
1331 // Initialize the sound subsystem.
1332 ////////////////////////////////////////////////////////////////////
1334 globals->set_soundmgr(new FGSoundMgr);
1335 globals->get_soundmgr()->init();
1336 globals->get_soundmgr()->bind();
1339 ////////////////////////////////////////////////////////////////////
1340 // Initialize the sound-effects subsystem.
1341 ////////////////////////////////////////////////////////////////////
1343 globals->get_subsystem_mgr()->add(FGSubsystemMgr::GENERAL,
1350 globals->get_subsystem_mgr()->add(FGSubsystemMgr::GENERAL,
1352 new FGInstrumentMgr);
1353 globals->get_subsystem_mgr()->add(FGSubsystemMgr::GENERAL,
1357 ////////////////////////////////////////////////////////////////////
1358 // Initialize the radio stack subsystem.
1359 ////////////////////////////////////////////////////////////////////
1361 // A textbook example of how FGSubsystem
1363 current_radiostack = new FGRadioStack;
1364 current_radiostack->init();
1365 current_radiostack->bind();
1368 ////////////////////////////////////////////////////////////////////
1369 // Initialize the cockpit subsystem
1370 ////////////////////////////////////////////////////////////////////
1372 if( fgCockpitInit( ¤t_aircraft )) {
1373 // Cockpit initialized ok.
1375 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1380 ////////////////////////////////////////////////////////////////////
1381 // Initialize the autopilot subsystem.
1382 ////////////////////////////////////////////////////////////////////
1384 globals->set_autopilot(new FGAutopilot);
1385 globals->get_autopilot()->init();
1386 globals->get_autopilot()->bind();
1388 // FIXME: these should go in the
1389 // GUI initialization code, not here.
1391 NewTgtAirportInit();
1395 ////////////////////////////////////////////////////////////////////
1396 // Initialize I/O subsystem.
1397 ////////////////////////////////////////////////////////////////////
1399 globals->get_io()->init();
1400 globals->get_io()->bind();
1402 // Initialize the 2D panel.
1403 string panel_path = fgGetString("/sim/panel/path",
1404 "Panels/Default/default.xml");
1405 current_panel = fgReadPanel(panel_path);
1406 if (current_panel == 0) {
1407 SG_LOG( SG_INPUT, SG_ALERT,
1408 "Error reading new panel from " << panel_path );
1410 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1411 current_panel->init();
1412 current_panel->bind();
1416 ////////////////////////////////////////////////////////////////////
1417 // Initialize the default (kludged) properties.
1418 ////////////////////////////////////////////////////////////////////
1423 ////////////////////////////////////////////////////////////////////
1424 // Initialize the controls subsystem.
1425 ////////////////////////////////////////////////////////////////////
1427 globals->get_controls()->init();
1428 globals->get_controls()->bind();
1431 ////////////////////////////////////////////////////////////////////
1432 // Initialize the steam subsystem.
1433 ////////////////////////////////////////////////////////////////////
1435 globals->get_steam()->init();
1436 globals->get_steam()->bind();
1439 ////////////////////////////////////////////////////////////////////
1440 // Initialize the input subsystem.
1441 ////////////////////////////////////////////////////////////////////
1443 globals->get_subsystem_mgr()->add(FGSubsystemMgr::GENERAL,
1448 ////////////////////////////////////////////////////////////////////
1449 // Bind and initialize subsystems.
1450 ////////////////////////////////////////////////////////////////////
1452 globals->get_subsystem_mgr()->bind();
1453 globals->get_subsystem_mgr()->init();
1456 ////////////////////////////////////////////////////////////////////////
1457 // End of subsystem initialization.
1458 ////////////////////////////////////////////////////////////////////
1460 SG_LOG( SG_GENERAL, SG_INFO, endl);
1462 // Save the initial state for future
1464 globals->saveInitialState();
1470 void fgReInitSubsystems( void )
1472 static const SGPropertyNode *longitude
1473 = fgGetNode("/sim/presets/longitude-deg");
1474 static const SGPropertyNode *latitude
1475 = fgGetNode("/sim/presets/latitude-deg");
1476 static const SGPropertyNode *altitude
1477 = fgGetNode("/sim/presets/altitude-ft");
1478 static const SGPropertyNode *master_freeze
1479 = fgGetNode("/sim/freeze/master");
1481 SG_LOG( SG_GENERAL, SG_INFO,
1482 "fgReInitSubsystems(): /position/altitude = "
1483 << altitude->getDoubleValue() );
1485 bool freeze = master_freeze->getBoolValue();
1487 fgSetBool("/sim/freeze/master", true);
1490 // Initialize the Scenery Management subsystem
1491 // FIXME, what really needs to get initialized here, at the time
1492 // this was commented out, scenery.init() was a noop
1497 // allocates structures so must happen before any of the flight
1498 // model or control parameters are set
1499 fgAircraftInit(); // In the future this might not be the case.
1501 // copy viewer settings into current-view path
1502 globals->get_viewmgr()->copyToCurrent();
1506 globals->get_controls()->reset_all();
1507 globals->get_autopilot()->reset();
1511 cur_light_params.Update();
1512 fgUpdateLocalTime();
1515 fgSetBool("/sim/freeze/master", false);