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 - 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.
29 // For BC 5.01 this must be included before OpenGL includes.
30 #ifdef SG_MATH_EXCEPTION_CLASH
36 #include <string.h> // strcmp()
39 #if defined( unix ) || defined( __CYGWIN__ )
40 # include <unistd.h> // for gethostname()
43 // work around a stdc++ lib bug in some versions of linux, but doesn't
44 // seem to hurt to have this here for all versions of Linux.
46 # define _G_NO_EXTERN_TEMPLATES
49 #include <simgear/compiler.h>
53 #include <simgear/constants.h>
54 #include <simgear/debug/logstream.hxx>
55 #include <simgear/structure/exception.hxx>
56 #include <simgear/structure/event_mgr.hxx>
57 #include <simgear/math/point3d.hxx>
58 #include <simgear/math/polar3d.hxx>
59 #include <simgear/math/sg_geodesy.hxx>
60 #include <simgear/misc/sg_path.hxx>
61 #include <simgear/misc/interpolator.hxx>
62 #include <simgear/scene/material/matlib.hxx>
63 #include <simgear/timing/sg_time.hxx>
64 #include <simgear/timing/lowleveltime.h>
66 #include <Aircraft/aircraft.hxx>
67 #include <Aircraft/replay.hxx>
68 #include <Airports/apt_loader.hxx>
69 #include <Airports/runways.hxx>
70 #include <Airports/simple.hxx>
71 #include <AIModel/AIManager.hxx>
72 #include <ATC/ATCdisplay.hxx>
73 #include <ATC/ATCmgr.hxx>
74 #include <ATC/AIMgr.hxx>
75 #include <Autopilot/auto_gui.hxx>
76 #include <Autopilot/route_mgr.hxx>
77 #include <Autopilot/xmlauto.hxx>
78 #include <Cockpit/cockpit.hxx>
79 #include <Cockpit/panel.hxx>
80 #include <Cockpit/panel_io.hxx>
82 #include <FDM/SP/ADA.hxx>
83 #include <FDM/SP/ACMS.hxx>
85 #include <FDM/Balloon.h>
86 #include <FDM/ExternalNet/ExternalNet.hxx>
87 #include <FDM/ExternalPipe/ExternalPipe.hxx>
88 #include <FDM/JSBSim/JSBSim.hxx>
89 #include <FDM/LaRCsim/LaRCsim.hxx>
90 #include <FDM/MagicCarpet.hxx>
91 #include <FDM/UFO.hxx>
92 #include <FDM/NullFDM.hxx>
93 #include <FDM/YASim/YASim.hxx>
94 #include <GUI/new_gui.hxx>
95 #include <Include/general.hxx>
96 #include <Input/input.hxx>
97 #include <Instrumentation/instrument_mgr.hxx>
98 #include <Model/acmodel.hxx>
99 #include <AIModel/submodel.hxx>
100 #include <AIModel/AIManager.hxx>
101 #include <Navaids/navdb.hxx>
102 #include <Navaids/navlist.hxx>
103 #include <Scenery/scenery.hxx>
104 #include <Scenery/tilemgr.hxx>
105 #include <Scripting/NasalSys.hxx>
106 #include <Sound/fg_fx.hxx>
107 #include <Sound/beacon.hxx>
108 #include <Sound/morse.hxx>
109 #include <Systems/system_mgr.hxx>
110 #include <Time/light.hxx>
111 #include <Time/sunpos.hxx>
112 #include <Time/sunsolver.hxx>
113 #include <Time/tmp.hxx>
114 #include <Traffic/TrafficMgr.hxx>
117 #include <MultiPlayer/multiplaymgr.hxx>
120 #include <Environment/environment_mgr.hxx>
122 #include "fg_init.hxx"
124 #include "fg_commands.hxx"
125 #include "fg_props.hxx"
126 #include "options.hxx"
127 #include "globals.hxx"
128 #include "logger.hxx"
129 #include "viewmgr.hxx"
131 #if defined(FX) && defined(XMESA)
132 #include <GL/xmesa.h>
135 SG_USING_STD(string);
139 extern const char *default_root;
143 // Scan the command line options for the specified option and return
145 static string fgScanForOption( const string& option, int argc, char **argv ) {
148 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
150 int len = option.length();
153 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
155 string arg = argv[i];
156 if ( arg.find( option ) == 0 ) {
157 return arg.substr( len );
167 // Scan the user config files for the specified option and return
169 static string fgScanForOption( const string& option, const string& path ) {
170 sg_gzifstream in( path );
171 if ( !in.is_open() ) {
175 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
177 int len = option.length();
181 while ( ! in.eof() ) {
184 while ( in.get(c) && c != '\0' ) {
189 #if defined( macintosh )
190 getline( in, line, '\r' );
192 getline( in, line, '\n' );
195 // catch extraneous (DOS) line ending character
196 if ( line[line.length() - 1] < 32 ) {
197 line = line.substr( 0, line.length()-1 );
200 if ( line.find( option ) == 0 ) {
201 return line.substr( len );
211 // Read in configuration (files and command line options) but only set
213 bool fgInitFGRoot ( int argc, char **argv ) {
217 // First parse command line options looking for --fg-root=, this
218 // will override anything specified in a config file
219 root = fgScanForOption( "--fg-root=", argc, argv);
221 #if defined( unix ) || defined( __CYGWIN__ )
222 // Next check home directory for .fgfsrc.hostname file
223 if ( root.empty() ) {
224 envp = ::getenv( "HOME" );
225 if ( envp != NULL ) {
226 SGPath config( envp );
227 config.append( ".fgfsrc" );
229 gethostname( name, 256 );
230 config.concat( "." );
231 config.concat( name );
232 root = fgScanForOption( "--fg-root=", config.str() );
237 // Next check home directory for .fgfsrc file
238 if ( root.empty() ) {
239 envp = ::getenv( "HOME" );
240 if ( envp != NULL ) {
241 SGPath config( envp );
242 config.append( ".fgfsrc" );
243 root = fgScanForOption( "--fg-root=", config.str() );
247 // Next check if fg-root is set as an env variable
248 if ( root.empty() ) {
249 envp = ::getenv( "FG_ROOT" );
250 if ( envp != NULL ) {
255 // Otherwise, default to a random compiled-in location if we can't
256 // find fg-root any other way.
257 if ( root.empty() ) {
258 #if defined( __CYGWIN__ )
259 root = "/FlightGear";
260 #elif defined( WIN32 )
261 root = "\\FlightGear";
262 #elif defined(OSX_BUNDLE)
263 /* the following code looks for the base package directly inside
264 the application bundle. This can be changed fairly easily by
265 fiddling with the code below. And yes, I know it's ugly and verbose.
267 CFBundleRef appBundle = CFBundleGetMainBundle();
268 CFURLRef appUrl = CFBundleCopyBundleURL(appBundle);
269 CFRelease(appBundle);
271 // look for a 'data' subdir directly inside the bundle : is there
272 // a better place? maybe in Resources? I don't know ...
273 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, appUrl, CFSTR("data"), true);
275 // now convert down to a path, and the a c-string
276 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
277 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
280 CFRelease(appBundle);
288 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
289 globals->set_fg_root(root);
295 // Read in configuration (files and command line options) but only set
297 bool fgInitFGAircraft ( int argc, char **argv ) {
301 // First parse command line options looking for --aircraft=, this
302 // will override anything specified in a config file
303 aircraft = fgScanForOption( "--aircraft=", argc, argv );
305 #if defined( unix ) || defined( __CYGWIN__ )
306 // Next check home directory for .fgfsrc.hostname file
307 if ( aircraft.empty() ) {
308 envp = ::getenv( "HOME" );
309 if ( envp != NULL ) {
310 SGPath config( envp );
311 config.append( ".fgfsrc" );
313 gethostname( name, 256 );
314 config.concat( "." );
315 config.concat( name );
316 aircraft = fgScanForOption( "--aircraft=", config.str() );
321 // Next check home directory for .fgfsrc file
322 if ( aircraft.empty() ) {
323 envp = ::getenv( "HOME" );
324 if ( envp != NULL ) {
325 SGPath config( envp );
326 config.append( ".fgfsrc" );
327 aircraft = fgScanForOption( "--aircraft=", config.str() );
331 if ( aircraft.empty() ) {
332 // Check for $fg_root/system.fgfsrc
333 SGPath sysconf( globals->get_fg_root() );
334 sysconf.append( "system.fgfsrc" );
335 aircraft = fgScanForOption( "--aircraft=", sysconf.str() );
337 // if an aircraft was specified, set the property name
338 if ( !aircraft.empty() ) {
339 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
340 fgSetString("/sim/aircraft", aircraft.c_str() );
342 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
349 // Return the current base package version
350 string fgBasePackageVersion() {
351 SGPath base_path( globals->get_fg_root() );
352 base_path.append("version");
354 sg_gzifstream in( base_path.str() );
355 if ( !in.is_open() ) {
356 SGPath old_path( globals->get_fg_root() );
357 old_path.append( "Thanks" );
358 sg_gzifstream old( old_path.str() );
359 if ( !old.is_open() ) {
362 return "[old version]";
373 // Initialize the localization
374 SGPropertyNode *fgInitLocale(const char *language) {
375 SGPropertyNode *c_node = NULL, *d_node = NULL;
376 SGPropertyNode *intl = fgGetNode("/sim/intl");
378 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
380 // localization not defined
385 // Select the proper language from the list
387 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
388 for (unsigned int i = 0; i < locale.size(); i++) {
390 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
391 for (unsigned int j = 0; j < lang.size(); j++) {
393 if (!strcmp(lang[j]->getStringValue(), language)) {
402 d_node = intl->getChild("locale");
406 // Check for localized font
407 SGPropertyNode *font_n = c_node->getNode("font", true);
408 if ( !strcmp(font_n->getStringValue(), "") )
409 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
413 // Load the default strings
415 SGPath d_path( globals->get_fg_root() );
417 const char *d_path_str = d_node->getStringValue("strings");
419 SG_LOG(SG_GENERAL, SG_ALERT, "Incorrect path in configuration file.");
423 d_path.append(d_path_str);
424 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from "
427 SGPropertyNode *strings = c_node->getNode("strings");
429 readProperties(d_path.str(), strings);
430 } catch (const sg_exception &e) {
431 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
436 // Load the language specific strings
438 if (c_node != d_node) {
439 SGPath c_path( globals->get_fg_root() );
441 const char *c_path_str = c_node->getStringValue("strings");
443 SG_LOG(SG_GENERAL, SG_ALERT, "Incorrect path in configuration file.");
447 c_path.append(c_path_str);
448 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from "
452 readProperties(c_path.str(), strings);
453 } catch (const sg_exception &e) {
454 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
464 // Initialize the localization routines
465 bool fgDetectLanguage() {
466 char *language = ::getenv("LANG");
468 if (language == NULL) {
469 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
473 SGPropertyNode *locale = fgInitLocale(language);
475 SG_LOG(SG_GENERAL, SG_ALERT,
476 "No internationalization settings specified in preferences.xml" );
481 globals->set_locale( locale );
486 // Attempt to locate and parse the various non-XML config files in order
487 // from least precidence to greatest precidence
489 do_options (int argc, char ** argv)
491 // Check for $fg_root/system.fgfsrc
492 SGPath config( globals->get_fg_root() );
493 config.append( "system.fgfsrc" );
494 fgParseOptions(config.str());
496 #if defined( unix ) || defined( __CYGWIN__ )
498 // Check for $fg_root/system.fgfsrc.hostname
499 gethostname( name, 256 );
500 config.concat( "." );
501 config.concat( name );
502 fgParseOptions(config.str());
505 // Check for ~/.fgfsrc
506 char* envp = ::getenv( "HOME" );
507 if ( envp != NULL ) {
509 config.append( ".fgfsrc" );
510 fgParseOptions(config.str());
513 #if defined( unix ) || defined( __CYGWIN__ )
514 // Check for ~/.fgfsrc.hostname
515 gethostname( name, 256 );
516 config.concat( "." );
517 config.concat( name );
518 fgParseOptions(config.str());
521 // Parse remaining command line options
522 // These will override anything specified in a config file
523 fgParseArgs(argc, argv);
527 static string fgFindAircraftPath( const SGPath &path, const string &aircraft ) {
529 ulDir *dirp = ulOpenDir(path.str().c_str());
531 cerr << "Unable to open aircraft directory '" << path.str() << '\'' << endl;
535 while ((dire = ulReadDir(dirp)) != NULL) {
537 if ( strcmp("CVS", dire->d_name) && strcmp(".", dire->d_name)
538 && strcmp("..", dire->d_name) )
541 next.append(dire->d_name);
543 string result = fgFindAircraftPath( next, aircraft );
544 if ( ! result.empty() ) {
548 } else if ( !strcmp(dire->d_name, aircraft.c_str()) ) {
559 // Read in configuration (file and command line)
560 bool fgInitConfig ( int argc, char **argv ) {
562 // First, set some sane default values
565 // Read global preferences from $FG_ROOT/preferences.xml
566 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
567 fgLoadProps("preferences.xml", globals->get_props());
568 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
570 // Detect the required language as early as possible
571 if ( !fgDetectLanguage() ) {
575 // Scan user config files and command line for a specified aircraft.
576 fgInitFGAircraft(argc, argv);
578 string aircraft = fgGetString( "/sim/aircraft", "" );
579 if ( aircraft.size() > 0 ) {
580 SGPath aircraft_search( globals->get_fg_root() );
581 aircraft_search.append( "Aircraft" );
583 string aircraft_set = aircraft + "-set.xml";
585 string result = fgFindAircraftPath( aircraft_search, aircraft_set );
586 if ( !result.empty() ) {
587 fgSetString( "/sim/aircraft-dir", result.c_str() );
588 SGPath full_name( result );
589 full_name.append( aircraft_set );
591 SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
592 << " from " << full_name.str());
594 readProperties( full_name.str(), globals->get_props() );
595 } catch ( const sg_exception &e ) {
596 string message = "Error reading default aircraft: ";
597 message += e.getFormattedMessage();
598 SG_LOG(SG_INPUT, SG_ALERT, message);
602 SG_LOG( SG_INPUT, SG_ALERT, "Cannot find specified aircraft: "
608 SG_LOG( SG_INPUT, SG_ALERT, "No default aircraft specified" );
611 // parse options after loading aircraft to ensure any user
612 // overrides of defaults are honored.
613 do_options(argc, argv);
619 // find basic airport location info from airport database
620 bool fgFindAirportID( const string& id, FGAirport *a ) {
621 const FGAirport* result;
623 SG_LOG( SG_GENERAL, SG_INFO, "Searching for airport code = " << id );
625 result = globals->get_airports()->search( id );
627 if ( result == NULL ) {
628 SG_LOG( SG_GENERAL, SG_ALERT,
629 "Failed to find " << id << " in apt.dat.gz" );
638 SG_LOG( SG_GENERAL, SG_INFO,
639 "Position for " << id << " is ("
640 << a->getLongitude() << ", "
641 << a->getLatitude() << ")" );
647 // get airport elevation
648 static double fgGetAirportElev( const string& id ) {
652 SG_LOG( SG_GENERAL, SG_INFO,
653 "Finding elevation for airport: " << id );
655 if ( fgFindAirportID( id, &a ) ) {
656 return a.getElevation();
665 // This function is never used, but maybe useful in the future ???
668 // Preset lon/lat given an airport id
669 static bool fgSetPosFromAirportID( const string& id ) {
673 SG_LOG( SG_GENERAL, SG_INFO,
674 "Attempting to set starting position from airport code " << id );
676 if ( fgFindAirportID( id, &a ) ) {
678 fgSetDouble("/sim/presets/longitude-deg", a.longitude );
679 fgSetDouble("/sim/presets/latitude-deg", a.latitude );
681 // other code depends on the actual postition being set so set
683 fgSetDouble("/position/longitude-deg", a.longitude );
684 fgSetDouble("/position/latitude-deg", a.latitude );
686 SG_LOG( SG_GENERAL, SG_INFO,
687 "Position for " << id << " is (" << a.longitude
688 << ", " << a.latitude << ")" );
698 // Set current tower position lon/lat given an airport id
699 static bool fgSetTowerPosFromAirportID( const string& id, double hdg ) {
701 // tower height hard coded for now...
702 float towerheight=50.0f;
704 // make a little off the heading for 1 runway airports...
705 float fudge_lon = fabs(sin(hdg)) * .003f;
706 float fudge_lat = .003f - fudge_lon;
708 if ( fgFindAirportID( id, &a ) ) {
709 fgSetDouble("/sim/tower/longitude-deg", a.getLongitude() + fudge_lon);
710 fgSetDouble("/sim/tower/latitude-deg", a.getLatitude() + fudge_lat);
711 fgSetDouble("/sim/tower/altitude-ft", a.getElevation() + towerheight);
719 struct FGTowerLocationListener : SGPropertyChangeListener {
720 void valueChanged(SGPropertyNode* node) {
721 const double hdg = fgGetDouble( "/orientation/heading-deg", 0);
722 const string id(node->getStringValue());
723 fgSetTowerPosFromAirportID(id, hdg);
727 static void fgInitTowerLocationListener() {
728 fgGetNode("/sim/tower/airport-id", true)
729 ->addChangeListener( new FGTowerLocationListener() );
732 // Set current_options lon/lat given an airport id and heading (degrees)
733 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
737 // set initial position from runway and heading
739 SG_LOG( SG_GENERAL, SG_INFO,
740 "Attempting to set starting position from airport code "
741 << id << " heading " << tgt_hdg );
743 if ( ! globals->get_runways()->search( id, (int)tgt_hdg, &r ) ) {
744 SG_LOG( SG_GENERAL, SG_ALERT,
745 "Failed to find a good runway for " << id << '\n' );
752 double lat2, lon2, az2;
753 double heading = r._heading;
754 double azimuth = heading + 180.0;
755 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
757 SG_LOG( SG_GENERAL, SG_INFO,
758 "runway = " << r._lon << ", " << r._lat
759 << " length = " << r._length * SG_FEET_TO_METER
760 << " heading = " << azimuth );
762 geo_direct_wgs_84 ( 0, r._lat, r._lon, azimuth,
763 r._length * SG_FEET_TO_METER * 0.5 - 5.0,
764 &lat2, &lon2, &az2 );
766 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON ) {
768 double odist = fgGetDouble("/sim/presets/offset-distance");
769 odist *= SG_NM_TO_METER;
770 double oaz = azimuth;
771 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON ) {
772 oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
775 while ( oaz >= 360.0 ) { oaz -= 360.0; }
776 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
782 fgSetDouble("/sim/presets/longitude-deg", lon2 );
783 fgSetDouble("/sim/presets/latitude-deg", lat2 );
784 fgSetDouble("/sim/presets/heading-deg", heading );
786 // other code depends on the actual values being set ...
787 fgSetDouble("/position/longitude-deg", lon2 );
788 fgSetDouble("/position/latitude-deg", lat2 );
789 fgSetDouble("/orientation/heading-deg", heading );
791 SG_LOG( SG_GENERAL, SG_INFO,
792 "Position for " << id << " is ("
794 << lat2 << ") new heading is "
801 // Set current_options lon/lat given an airport id and runway number
802 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy ) {
806 // set initial position from airport and runway number
808 SG_LOG( SG_GENERAL, SG_INFO,
809 "Attempting to set starting position for "
810 << id << ":" << rwy );
812 if ( ! globals->get_runways()->search( id, rwy, &r ) ) {
813 SG_LOG( SG_GENERAL, SG_ALERT,
814 "Failed to find runway " << rwy <<
815 " at airport " << id );
822 double lat2, lon2, az2;
823 double heading = r._heading;
824 double azimuth = heading + 180.0;
825 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
827 SG_LOG( SG_GENERAL, SG_INFO,
828 "runway = " << r._lon << ", " << r._lat
829 << " length = " << r._length * SG_FEET_TO_METER
830 << " heading = " << azimuth );
832 geo_direct_wgs_84 ( 0, r._lat, r._lon,
834 r._length * SG_FEET_TO_METER * 0.5 - 5.0,
835 &lat2, &lon2, &az2 );
837 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
840 double odist = fgGetDouble("/sim/presets/offset-distance");
841 odist *= SG_NM_TO_METER;
842 double oaz = azimuth;
843 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON )
845 oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
846 heading = fgGetDouble("/sim/presets/heading-deg");
848 while ( oaz >= 360.0 ) { oaz -= 360.0; }
849 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
855 fgSetDouble("/sim/presets/longitude-deg", lon2 );
856 fgSetDouble("/sim/presets/latitude-deg", lat2 );
857 fgSetDouble("/sim/presets/heading-deg", heading );
859 // other code depends on the actual values being set ...
860 fgSetDouble("/position/longitude-deg", lon2 );
861 fgSetDouble("/position/latitude-deg", lat2 );
862 fgSetDouble("/orientation/heading-deg", heading );
864 SG_LOG( SG_GENERAL, SG_INFO,
865 "Position for " << id << " is ("
867 << lat2 << ") new heading is "
874 static void fgSetDistOrAltFromGlideSlope() {
875 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
876 string apt_id = fgGetString("/sim/presets/airport-id");
877 double gs = fgGetDouble("/sim/presets/glideslope-deg")
878 * SG_DEGREES_TO_RADIANS ;
879 double od = fgGetDouble("/sim/presets/offset-distance");
880 double alt = fgGetDouble("/sim/presets/altitude-ft");
882 double apt_elev = 0.0;
883 if ( ! apt_id.empty() ) {
884 apt_elev = fgGetAirportElev( apt_id );
885 if ( apt_elev < -9990.0 ) {
892 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
893 // set altitude from glideslope and offset-distance
894 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
895 alt = fabs(od*tan(gs)) + apt_elev;
896 fgSetDouble("/sim/presets/altitude-ft", alt);
897 fgSetBool("/sim/presets/onground", false);
898 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
900 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
901 // set offset-distance from glideslope and altitude
902 od = (alt - apt_elev) / tan(gs);
903 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
904 fgSetDouble("/sim/presets/offset-distance", od);
905 fgSetBool("/sim/presets/onground", false);
906 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
908 } else if( fabs(gs) > 0.01 ) {
909 SG_LOG( SG_GENERAL, SG_ALERT,
910 "Glideslope given but not altitude or offset-distance." );
911 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
912 fgSetDouble("/sim/presets/glideslope-deg", 0);
913 fgSetBool("/sim/presets/onground", true);
918 // Set current_options lon/lat given an airport id and heading (degrees)
919 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
921 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
923 // set initial position from runway and heading
925 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
926 << id << ":" << freq );
928 double lon = nav->get_lon();
929 double lat = nav->get_lat();
931 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
933 double odist = fgGetDouble("/sim/presets/offset-distance")
935 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
937 while ( oaz >= 360.0 ) { oaz -= 360.0; }
938 double olat, olon, az2;
939 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
946 fgSetDouble("/sim/presets/longitude-deg", lon );
947 fgSetDouble("/sim/presets/latitude-deg", lat );
949 // other code depends on the actual values being set ...
950 fgSetDouble("/position/longitude-deg", lon );
951 fgSetDouble("/position/latitude-deg", lat );
952 fgSetDouble("/orientation/heading-deg",
953 fgGetDouble("/sim/presets/heading-deg") );
955 SG_LOG( SG_GENERAL, SG_INFO,
956 "Position for " << id << ":" << freq << " is ("
957 << lon << ", "<< lat << ")" );
961 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
962 << id << ":" << freq );
967 // Set current_options lon/lat given an aircraft carrier id
968 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
970 // set initial position from runway and heading
974 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
975 double lon = geodPos.lon() * SGD_RADIANS_TO_DEGREES;
976 double lat = geodPos.lat() * SGD_RADIANS_TO_DEGREES;
977 double alt = geodPos.elev() * SG_METER_TO_FEET;
979 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
980 << carrier << " at lat = " << lat << ", lon = " << lon
981 << ", alt = " << alt << ", heading = " << heading);
983 fgSetDouble("/sim/presets/longitude-deg", lon);
984 fgSetDouble("/sim/presets/latitude-deg", lat);
985 fgSetDouble("/sim/presets/altitude-ft", alt);
986 fgSetDouble("/sim/presets/heading-deg", heading);
987 fgSetDouble("/position/longitude-deg", lon);
988 fgSetDouble("/position/latitude-deg", lat);
989 fgSetDouble("/position/altitude-ft", alt);
990 fgSetDouble("/orientation/heading-deg", heading);
992 fgSetString("/sim/presets/speed-set", "UVW");
993 fgSetDouble("/velocities/uBody-fps", uvw[0]);
994 fgSetDouble("/velocities/vBody-fps", uvw[1]);
995 fgSetDouble("/velocities/wBody-fps", uvw[2]);
996 fgSetDouble("/sim/presets/uBody-fps", uvw[0]);
997 fgSetDouble("/sim/presets/vBody-fps", uvw[1]);
998 fgSetDouble("/sim/presets/wBody-fps", uvw[2]);
1000 fgSetBool("/sim/presets/onground", true);
1004 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
1010 // Set current_options lon/lat given an airport id and heading (degrees)
1011 static bool fgSetPosFromFix( const string& id ) {
1014 // set initial position from runway and heading
1015 if ( globals->get_fixlist()->query( id.c_str(), &fix ) ) {
1016 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1019 double lon = fix.get_lon();
1020 double lat = fix.get_lat();
1022 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
1024 double odist = fgGetDouble("/sim/presets/offset-distance")
1026 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
1028 while ( oaz >= 360.0 ) { oaz -= 360.0; }
1029 double olat, olon, az2;
1030 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
1037 fgSetDouble("/sim/presets/longitude-deg", lon );
1038 fgSetDouble("/sim/presets/latitude-deg", lat );
1040 // other code depends on the actual values being set ...
1041 fgSetDouble("/position/longitude-deg", lon );
1042 fgSetDouble("/position/latitude-deg", lat );
1043 fgSetDouble("/orientation/heading-deg",
1044 fgGetDouble("/sim/presets/heading-deg") );
1046 SG_LOG( SG_GENERAL, SG_INFO,
1047 "Position for " << id << " is ("
1048 << lon << ", "<< lat << ")" );
1052 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1058 static void parseWaypoints() {
1059 string_list *waypoints = globals->get_initial_waypoints();
1061 vector<string>::iterator i;
1062 for (i = waypoints->begin();
1063 i != waypoints->end();
1068 // Now were done using the way points we can deallocate the
1070 while (waypoints->begin() != waypoints->end()) {
1071 waypoints->pop_back();
1074 globals->set_initial_waypoints(0);
1083 * Initialize vor/ndb/ils/fix list management and query systems (as
1084 * well as simple airport db list)
1089 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
1091 SGPath aptdb( globals->get_fg_root() );
1092 aptdb.append( "Airports/apt.dat" );
1094 SGPath p_metar( globals->get_fg_root() );
1095 p_metar.append( "Airports/metar.dat" );
1097 FGAirportList *airports = new FGAirportList();
1098 globals->set_airports( airports );
1099 FGRunwayList *runways = new FGRunwayList();
1100 globals->set_runways( runways );
1102 fgAirportDBLoad( airports, runways, aptdb.str(), p_metar.str() );
1104 FGNavList *navlist = new FGNavList;
1105 FGNavList *loclist = new FGNavList;
1106 FGNavList *gslist = new FGNavList;
1107 FGNavList *dmelist = new FGNavList;
1108 FGNavList *mkrlist = new FGNavList;
1109 FGNavList *tacanlist = new FGNavList;
1110 FGNavList *carrierlist = new FGNavList;
1111 FGTACANList *channellist = new FGTACANList;
1113 globals->set_navlist( navlist );
1114 globals->set_loclist( loclist );
1115 globals->set_gslist( gslist );
1116 globals->set_dmelist( dmelist );
1117 globals->set_mkrlist( mkrlist );
1118 globals->set_tacanlist( tacanlist );
1119 globals->set_carrierlist( carrierlist );
1120 globals->set_channellist( channellist );
1122 if ( !fgNavDBInit(airports, navlist, loclist, gslist, dmelist, mkrlist, tacanlist, carrierlist, channellist) ) {
1123 SG_LOG( SG_GENERAL, SG_ALERT,
1124 "Problems loading one or more navigational database" );
1127 if ( fgGetBool("/sim/navdb/localizers/auto-align", true) ) {
1128 // align all the localizers with their corresponding runways
1129 // since data sources are good for cockpit navigation
1130 // purposes, but not always to the error tolerances needed to
1131 // exactly place these items.
1133 = fgGetDouble( "/sim/navdb/localizers/auto-align-threshold-deg",
1135 fgNavDBAlignLOCwithRunway( runways, loclist, threshold );
1138 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1139 SGPath p_fix( globals->get_fg_root() );
1140 p_fix.append( "Navaids/fix.dat" );
1141 FGFixList *fixlist = new FGFixList;
1142 fixlist->init( p_fix );
1143 globals->set_fixlist( fixlist );
1149 // Set the initial position based on presets (or defaults)
1150 bool fgInitPosition() {
1151 // cout << "fgInitPosition()" << endl;
1152 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1153 * SG_DEGREES_TO_RADIANS ;
1154 double od = fgGetDouble("/sim/presets/offset-distance");
1155 double alt = fgGetDouble("/sim/presets/altitude-ft");
1157 bool set_pos = false;
1159 // If glideslope is specified, then calculate offset-distance or
1160 // altitude relative to glide slope if either of those was not
1162 if ( fabs( gs ) > 0.01 ) {
1163 fgSetDistOrAltFromGlideSlope();
1167 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1168 // If not, check for an airport-id and use that.
1169 // If not, default to the middle of the KSFO field.
1170 // The default values for lon/lat are deliberately out of range
1171 // so that the airport-id can take effect; valid lon/lat will
1172 // override airport-id, however.
1173 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1174 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1175 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1176 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1181 string apt = fgGetString("/sim/presets/airport-id");
1182 string rwy_no = fgGetString("/sim/presets/runway");
1183 double hdg = fgGetDouble("/sim/presets/heading-deg");
1184 string vor = fgGetString("/sim/presets/vor-id");
1185 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1186 string ndb = fgGetString("/sim/presets/ndb-id");
1187 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1188 string carrier = fgGetString("/sim/presets/carrier");
1189 string parkpos = fgGetString("/sim/presets/parkpos");
1190 string fix = fgGetString("/sim/presets/fix");
1192 fgSetDouble( "/orientation/heading-deg", hdg );
1193 fgInitTowerLocationListener();
1195 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1196 // An airport + runway is requested
1197 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no ) ) {
1198 // set tower position (a little off the heading for single
1200 fgSetString("/sim/tower/airport-id", apt.c_str());
1205 if ( !set_pos && !apt.empty() ) {
1206 // An airport is requested (find runway closest to hdg)
1207 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1208 // set tower position (a little off the heading for single
1210 fgSetString("/sim/tower/airport-id", apt.c_str());
1215 if ( !set_pos && !vor.empty() ) {
1216 // a VOR is requested
1217 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1222 if ( !set_pos && !ndb.empty() ) {
1223 // an NDB is requested
1224 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1229 if ( !set_pos && !carrier.empty() ) {
1230 // an aircraft carrier is requested
1231 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1236 if ( !set_pos && !fix.empty() ) {
1237 // a Fix is requested
1238 if ( fgSetPosFromFix( fix ) ) {
1244 // No lon/lat specified, no airport specified, default to
1245 // middle of KSFO field.
1246 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1247 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1250 fgSetDouble( "/position/longitude-deg",
1251 fgGetDouble("/sim/presets/longitude-deg") );
1252 fgSetDouble( "/position/latitude-deg",
1253 fgGetDouble("/sim/presets/latitude-deg") );
1255 // determine if this should be an on-ground or in-air start
1256 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1257 fgSetBool("/sim/presets/onground", false);
1259 fgSetBool("/sim/presets/onground", true);
1266 // General house keeping initializations
1267 bool fgInitGeneral() {
1270 #if defined(FX) && defined(XMESA)
1271 char *mesa_win_state;
1274 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1275 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1277 root = globals->get_fg_root();
1278 if ( ! root.length() ) {
1279 // No root path set? Then bail ...
1280 SG_LOG( SG_GENERAL, SG_ALERT,
1281 "Cannot continue without a path to the base package "
1282 << "being defined." );
1285 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1287 #if defined(FX) && defined(XMESA)
1288 // initialize full screen flag
1289 globals->set_fullscreen(false);
1290 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1291 // Test for the MESA_GLX_FX env variable
1292 if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
1293 // test if we are fullscreen mesa/glide
1294 if ( (mesa_win_state[0] == 'f') ||
1295 (mesa_win_state[0] == 'F') ) {
1296 globals->set_fullscreen(true);
1306 // Initialize the flight model subsystem. This just creates the
1307 // object. The actual fdm initialization is delayed until we get a
1308 // proper scenery elevation hit. This is checked for in main.cxx
1312 if ( cur_fdm_state ) {
1313 delete cur_fdm_state;
1317 double dt = 1.0 / fgGetInt("/sim/model-hz");
1318 string model = fgGetString("/sim/flight-model");
1321 if ( model == "larcsim" ) {
1322 cur_fdm_state = new FGLaRCsim( dt );
1323 } else if ( model == "jsb" ) {
1324 cur_fdm_state = new FGJSBsim( dt );
1325 #ifdef ENABLE_SP_FMDS
1326 } else if ( model == "ada" ) {
1327 cur_fdm_state = new FGADA( dt );
1328 } else if ( model == "acms" ) {
1329 cur_fdm_state = new FGACMS( dt );
1331 } else if ( model == "balloon" ) {
1332 cur_fdm_state = new FGBalloonSim( dt );
1333 } else if ( model == "magic" ) {
1334 cur_fdm_state = new FGMagicCarpet( dt );
1335 } else if ( model == "ufo" ) {
1336 cur_fdm_state = new FGUFO( dt );
1337 } else if ( model == "external" ) {
1338 // external is a synonym for "--fdm=null" and is
1339 // maintained here for backwards compatibility
1340 cur_fdm_state = new FGNullFDM( dt );
1341 } else if ( model.find("network") == 0 ) {
1342 string host = "localhost";
1346 string net_options = model.substr(8);
1347 string::size_type begin, end;
1350 end = net_options.find( ",", begin );
1351 if ( end != string::npos ) {
1352 host = net_options.substr(begin, end - begin);
1356 end = net_options.find( ",", begin );
1357 if ( end != string::npos ) {
1358 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1362 end = net_options.find( ",", begin );
1363 if ( end != string::npos ) {
1364 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1368 end = net_options.find( ",", begin );
1369 if ( end != string::npos ) {
1370 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1373 cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1374 } else if ( model.find("pipe") == 0 ) {
1375 // /* old */ string pipe_path = model.substr(5);
1376 // /* old */ cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1377 string pipe_path = "";
1378 string pipe_protocol = "";
1379 string pipe_options = model.substr(5);
1380 string::size_type begin, end;
1383 end = pipe_options.find( ",", begin );
1384 if ( end != string::npos ) {
1385 pipe_path = pipe_options.substr(begin, end - begin);
1388 // protocol (last option)
1389 pipe_protocol = pipe_options.substr(begin);
1390 cur_fdm_state = new FGExternalPipe( dt, pipe_path, pipe_protocol );
1391 } else if ( model == "null" ) {
1392 cur_fdm_state = new FGNullFDM( dt );
1393 } else if ( model == "yasim" ) {
1394 cur_fdm_state = new YASim( dt );
1396 SG_LOG(SG_GENERAL, SG_ALERT,
1397 "Unrecognized flight model '" << model
1398 << "', cannot init flight dynamics model.");
1402 SG_LOG(SG_GENERAL, SG_ALERT, "FlightGear aborting\n\n");
1407 static void printMat(const sgVec4 *mat, char *name="")
1410 SG_LOG(SG_GENERAL, SG_BULK, name );
1411 for(i=0; i<4; i++) {
1412 SG_LOG(SG_GENERAL, SG_BULK, " " << mat[i][0] << " " << mat[i][1]
1413 << " " << mat[i][2] << " " << mat[i][3] );
1417 // Initialize view parameters
1419 // force update of model so that viewer can get some data...
1420 globals->get_aircraft_model()->update(0);
1421 // run update for current view so that data is current...
1422 globals->get_viewmgr()->update(0);
1424 printMat(globals->get_current_view()->get_VIEW(),"VIEW");
1425 printMat(globals->get_current_view()->get_UP(),"UP");
1426 // printMat(globals->get_current_view()->get_LOCAL(),"LOCAL");
1431 SGTime *fgInitTime() {
1433 static const SGPropertyNode *longitude
1434 = fgGetNode("/position/longitude-deg");
1435 static const SGPropertyNode *latitude
1436 = fgGetNode("/position/latitude-deg");
1437 static const SGPropertyNode *cur_time_override
1438 = fgGetNode("/sim/time/cur-time-override", true);
1440 SGPath zone( globals->get_fg_root() );
1441 zone.append( "Timezone" );
1442 SGTime *t = new SGTime( longitude->getDoubleValue()
1443 * SGD_DEGREES_TO_RADIANS,
1444 latitude->getDoubleValue()
1445 * SGD_DEGREES_TO_RADIANS,
1447 cur_time_override->getLongValue() );
1449 globals->set_warp_delta( 0 );
1451 t->update( 0.0, 0.0,
1452 cur_time_override->getLongValue(),
1453 globals->get_warp() );
1459 // set up a time offset (aka warp) if one is specified
1460 void fgInitTimeOffset() {
1461 static const SGPropertyNode *longitude
1462 = fgGetNode("/position/longitude-deg");
1463 static const SGPropertyNode *latitude
1464 = fgGetNode("/position/latitude-deg");
1465 static const SGPropertyNode *cur_time_override
1466 = fgGetNode("/sim/time/cur-time-override", true);
1468 // Handle potential user specified time offsets
1469 int orig_warp = globals->get_warp();
1470 SGTime *t = globals->get_time_params();
1471 time_t cur_time = t->get_cur_time();
1472 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1473 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1474 time_t aircraftLocalTime =
1475 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1477 // Okay, we now have several possible scenarios
1478 int offset = fgGetInt("/sim/startup/time-offset");
1479 string offset_type = fgGetString("/sim/startup/time-offset-type");
1482 if ( offset_type == "real" ) {
1484 } else if ( offset_type == "dawn" ) {
1485 warp = fgTimeSecondsUntilSunAngle( cur_time,
1486 longitude->getDoubleValue()
1487 * SGD_DEGREES_TO_RADIANS,
1488 latitude->getDoubleValue()
1489 * SGD_DEGREES_TO_RADIANS,
1491 } else if ( offset_type == "morning" ) {
1492 warp = fgTimeSecondsUntilSunAngle( cur_time,
1493 longitude->getDoubleValue()
1494 * SGD_DEGREES_TO_RADIANS,
1495 latitude->getDoubleValue()
1496 * SGD_DEGREES_TO_RADIANS,
1498 } else if ( offset_type == "noon" ) {
1499 warp = fgTimeSecondsUntilSunAngle( cur_time,
1500 longitude->getDoubleValue()
1501 * SGD_DEGREES_TO_RADIANS,
1502 latitude->getDoubleValue()
1503 * SGD_DEGREES_TO_RADIANS,
1505 } else if ( offset_type == "afternoon" ) {
1506 warp = fgTimeSecondsUntilSunAngle( cur_time,
1507 longitude->getDoubleValue()
1508 * SGD_DEGREES_TO_RADIANS,
1509 latitude->getDoubleValue()
1510 * SGD_DEGREES_TO_RADIANS,
1512 } else if ( offset_type == "dusk" ) {
1513 warp = fgTimeSecondsUntilSunAngle( cur_time,
1514 longitude->getDoubleValue()
1515 * SGD_DEGREES_TO_RADIANS,
1516 latitude->getDoubleValue()
1517 * SGD_DEGREES_TO_RADIANS,
1519 } else if ( offset_type == "evening" ) {
1520 warp = fgTimeSecondsUntilSunAngle( cur_time,
1521 longitude->getDoubleValue()
1522 * SGD_DEGREES_TO_RADIANS,
1523 latitude->getDoubleValue()
1524 * SGD_DEGREES_TO_RADIANS,
1526 } else if ( offset_type == "midnight" ) {
1527 warp = fgTimeSecondsUntilSunAngle( cur_time,
1528 longitude->getDoubleValue()
1529 * SGD_DEGREES_TO_RADIANS,
1530 latitude->getDoubleValue()
1531 * SGD_DEGREES_TO_RADIANS,
1533 } else if ( offset_type == "system-offset" ) {
1535 } else if ( offset_type == "gmt-offset" ) {
1536 warp = offset - (currGMT - systemLocalTime);
1537 } else if ( offset_type == "latitude-offset" ) {
1538 warp = offset - (aircraftLocalTime - systemLocalTime);
1539 } else if ( offset_type == "system" ) {
1540 warp = offset - cur_time;
1541 } else if ( offset_type == "gmt" ) {
1542 warp = offset - currGMT;
1543 } else if ( offset_type == "latitude" ) {
1544 warp = offset - (aircraftLocalTime - systemLocalTime) - cur_time;
1546 SG_LOG( SG_GENERAL, SG_ALERT,
1547 "FG_TIME::Unsupported offset type " << offset_type );
1550 globals->set_warp( orig_warp + warp );
1551 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1552 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1553 cur_time_override->getLongValue(),
1554 globals->get_warp() );
1556 SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = "
1557 << globals->get_warp() );
1561 // This is the top level init routine which calls all the other
1562 // initialization routines. If you are adding a subsystem to flight
1563 // gear, its initialization call should located in this routine.
1564 // Returns non-zero if a problem encountered.
1565 bool fgInitSubsystems() {
1566 // static const SGPropertyNode *longitude
1567 // = fgGetNode("/sim/presets/longitude-deg");
1568 // static const SGPropertyNode *latitude
1569 // = fgGetNode("/sim/presets/latitude-deg");
1570 // static const SGPropertyNode *altitude
1571 // = fgGetNode("/sim/presets/altitude-ft");
1573 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1574 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1576 ////////////////////////////////////////////////////////////////////
1577 // Initialize the event manager subsystem.
1578 ////////////////////////////////////////////////////////////////////
1580 globals->get_event_mgr()->init();
1581 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1583 ////////////////////////////////////////////////////////////////////
1584 // Initialize the property interpolator subsystem
1585 ////////////////////////////////////////////////////////////////////
1586 globals->add_subsystem("interpolator", new SGInterpolator);
1589 ////////////////////////////////////////////////////////////////////
1590 // Add the FlightGear property utilities.
1591 ////////////////////////////////////////////////////////////////////
1592 globals->add_subsystem("properties", new FGProperties);
1594 ////////////////////////////////////////////////////////////////////
1595 // Initialize the material property subsystem.
1596 ////////////////////////////////////////////////////////////////////
1598 SGPath mpath( globals->get_fg_root() );
1599 mpath.append( "materials.xml" );
1600 string season = fgGetString("/sim/startup/season", "summer");
1601 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(), season.c_str()) ) {
1602 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1607 ////////////////////////////////////////////////////////////////////
1608 // Initialize the scenery management subsystem.
1609 ////////////////////////////////////////////////////////////////////
1611 if ( globals->get_tile_mgr()->init() ) {
1612 // Load the local scenery data
1613 double visibility_meters = fgGetDouble("/environment/visibility-m");
1615 globals->get_tile_mgr()->update( visibility_meters );
1617 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1621 // cause refresh of viewer scenery timestamps every 15 seconds...
1622 globals->get_event_mgr()->addTask( "FGTileMgr::refresh_view_timestamps()",
1623 globals->get_tile_mgr(),
1624 &FGTileMgr::refresh_view_timestamps,
1628 ////////////////////////////////////////////////////////////////////
1629 // Initialize the flight model subsystem.
1630 ////////////////////////////////////////////////////////////////////
1634 // allocates structures so must happen before any of the flight
1635 // model or control parameters are set
1636 fgAircraftInit(); // In the future this might not be the case.
1639 ////////////////////////////////////////////////////////////////////
1640 // Initialize the XML Autopilot subsystem.
1641 ////////////////////////////////////////////////////////////////////
1643 globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1644 globals->add_subsystem( "route-manager", new FGRouteMgr );
1647 ////////////////////////////////////////////////////////////////////
1648 // Initialize the view manager subsystem.
1649 ////////////////////////////////////////////////////////////////////
1653 ////////////////////////////////////////////////////////////////////
1654 // Create and register the logger.
1655 ////////////////////////////////////////////////////////////////////
1657 globals->add_subsystem("logger", new FGLogger);
1659 ////////////////////////////////////////////////////////////////////
1660 // Create and register the XML GUI.
1661 ////////////////////////////////////////////////////////////////////
1663 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1666 ////////////////////////////////////////////////////////////////////
1667 // Initialize the local time subsystem.
1668 ////////////////////////////////////////////////////////////////////
1670 // update the current timezone each 30 minutes
1671 globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1672 &fgUpdateLocalTime, 30*60 );
1673 fgInitTimeOffset(); // the environment subsystem needs this
1676 ////////////////////////////////////////////////////////////////////
1677 // Initialize the weather subsystem.
1678 ////////////////////////////////////////////////////////////////////
1680 // Initialize the weather modeling subsystem
1681 globals->add_subsystem("environment", new FGEnvironmentMgr);
1684 ////////////////////////////////////////////////////////////////////
1685 // Initialize the lighting subsystem.
1686 ////////////////////////////////////////////////////////////////////
1688 globals->add_subsystem("lighting", new FGLight);
1690 //////////////////////////////////////////////////////////////////////
1691 // Initialize the 2D cloud subsystem.
1692 ////////////////////////////////////////////////////////////////////
1693 fgGetBool("/sim/rendering/bump-mapping", false);
1695 #ifdef ENABLE_AUDIO_SUPPORT
1696 ////////////////////////////////////////////////////////////////////
1697 // Initialize the sound subsystem.
1698 ////////////////////////////////////////////////////////////////////
1700 init_volume = fgGetFloat("/sim/sound/volume");
1701 fgSetFloat("/sim/sound/volume", 0.0f);
1702 globals->set_soundmgr(new SGSoundMgr);
1703 globals->get_soundmgr()->init();
1704 globals->get_soundmgr()->bind();
1707 ////////////////////////////////////////////////////////////////////
1708 // Initialize the sound-effects subsystem.
1709 ////////////////////////////////////////////////////////////////////
1711 globals->add_subsystem("fx", new FGFX);
1715 ////////////////////////////////////////////////////////////////////
1716 // Initialise ATC display system
1717 ////////////////////////////////////////////////////////////////////
1719 SG_LOG(SG_GENERAL, SG_INFO, " ATC Display");
1720 globals->set_ATC_display(new FGATCDisplay);
1721 globals->get_ATC_display()->init();
1723 ////////////////////////////////////////////////////////////////////
1724 // Initialise the ATC Manager
1725 ////////////////////////////////////////////////////////////////////
1727 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1728 globals->set_ATC_mgr(new FGATCMgr);
1729 globals->get_ATC_mgr()->init();
1731 ////////////////////////////////////////////////////////////////////
1732 // Initialise the AI Manager
1733 ////////////////////////////////////////////////////////////////////
1735 SG_LOG(SG_GENERAL, SG_INFO, " AI Manager");
1736 globals->set_AI_mgr(new FGAIMgr);
1737 globals->get_AI_mgr()->init();
1739 ////////////////////////////////////////////////////////////////////
1740 // Initialise the AI Model Manager
1741 ////////////////////////////////////////////////////////////////////
1742 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1743 globals->add_subsystem("ai_model", new FGAIManager);
1744 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1747 // It's probably a good idea to initialize the top level traffic manager
1748 // After the AI and ATC systems have been initialized properly.
1749 // AI Traffic manager
1750 globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1751 FGTrafficManager *dispatcher =
1752 (FGTrafficManager*) globals->get_subsystem("Traffic Manager");
1753 SGPath path = globals->get_fg_root();
1754 path.append("/Traffic/fgtraffic.xml");
1757 //globals->get_subsystem("Traffic Manager")->init();
1759 globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1760 globals->add_subsystem("systems", new FGSystemMgr);
1764 ////////////////////////////////////////////////////////////////////
1765 // Initialize the cockpit subsystem
1766 ////////////////////////////////////////////////////////////////////
1767 if( fgCockpitInit( ¤t_aircraft )) {
1768 // Cockpit initialized ok.
1770 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1775 ////////////////////////////////////////////////////////////////////
1776 // Initialize the autopilot subsystem.
1777 ////////////////////////////////////////////////////////////////////
1779 // FIXME: these should go in the
1780 // GUI initialization code, not here.
1781 // fgAPAdjustInit();
1782 NewTgtAirportInit();
1786 ////////////////////////////////////////////////////////////////////
1787 // Initialize I/O subsystem.
1788 ////////////////////////////////////////////////////////////////////
1790 globals->get_io()->init();
1791 globals->get_io()->bind();
1794 ////////////////////////////////////////////////////////////////////
1795 // Add a new 2D panel.
1796 ////////////////////////////////////////////////////////////////////
1798 string panel_path = fgGetString("/sim/panel/path",
1799 "Panels/Default/default.xml");
1801 globals->set_current_panel( fgReadPanel(panel_path) );
1802 if (globals->get_current_panel() == 0) {
1803 SG_LOG( SG_INPUT, SG_ALERT,
1804 "Error reading new panel from " << panel_path );
1806 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1807 globals->get_current_panel()->init();
1808 globals->get_current_panel()->bind();
1812 ////////////////////////////////////////////////////////////////////
1813 // Initialize the controls subsystem.
1814 ////////////////////////////////////////////////////////////////////
1816 globals->get_controls()->init();
1817 globals->get_controls()->bind();
1820 ////////////////////////////////////////////////////////////////////
1821 // Initialize the input subsystem.
1822 ////////////////////////////////////////////////////////////////////
1824 globals->add_subsystem("input", new FGInput);
1827 ////////////////////////////////////////////////////////////////////
1828 // Initialize the replay subsystem
1829 ////////////////////////////////////////////////////////////////////
1830 globals->add_subsystem("replay", new FGReplay);
1832 ////////////////////////////////////////////////////////////////////
1833 // Bind and initialize subsystems.
1834 ////////////////////////////////////////////////////////////////////
1836 globals->get_subsystem_mgr()->bind();
1837 globals->get_subsystem_mgr()->init();
1839 #ifdef FG_MPLAYER_AS
1840 ////////////////////////////////////////////////////////////////////
1841 // Initialize multiplayer subsystem
1842 ////////////////////////////////////////////////////////////////////
1844 globals->set_multiplayer_mgr(new FGMultiplayMgr);
1845 globals->get_multiplayer_mgr()->init();
1848 ////////////////////////////////////////////////////////////////////////
1849 // Initialize the Nasal interpreter.
1850 // Do this last, so that the loaded scripts see initialized state
1851 ////////////////////////////////////////////////////////////////////////
1852 FGNasalSys* nasal = new FGNasalSys();
1853 globals->add_subsystem("nasal", nasal);
1856 ////////////////////////////////////////////////////////////////////
1857 // At this point we could try and parse the waypoint options
1858 ///////////////////////////////////////////////////////////////////
1861 // initialize methods that depend on other subsystems.
1862 globals->get_subsystem_mgr()->postinit();
1864 ////////////////////////////////////////////////////////////////////////
1865 // End of subsystem initialization.
1866 ////////////////////////////////////////////////////////////////////
1868 SG_LOG( SG_GENERAL, SG_INFO, endl);
1870 // Save the initial state for future
1872 globals->saveInitialState();
1878 void fgReInitSubsystems()
1880 // static const SGPropertyNode *longitude
1881 // = fgGetNode("/sim/presets/longitude-deg");
1882 // static const SGPropertyNode *latitude
1883 // = fgGetNode("/sim/presets/latitude-deg");
1884 static const SGPropertyNode *altitude
1885 = fgGetNode("/sim/presets/altitude-ft");
1886 static const SGPropertyNode *master_freeze
1887 = fgGetNode("/sim/freeze/master");
1889 SG_LOG( SG_GENERAL, SG_INFO,
1890 "fgReInitSubsystems(): /position/altitude = "
1891 << altitude->getDoubleValue() );
1893 bool freeze = master_freeze->getBoolValue();
1895 fgSetBool("/sim/freeze/master", true);
1897 fgSetBool("/sim/crashed", false);
1899 // Force reupdating the positions of the ai 3d models. They are used for
1900 // initializing ground level for the FDM.
1901 globals->get_subsystem("ai_model")->reinit();
1903 // Initialize the FDM
1906 // allocates structures so must happen before any of the flight
1907 // model or control parameters are set
1908 fgAircraftInit(); // In the future this might not be the case.
1910 // reload offsets from config defaults
1911 globals->get_viewmgr()->reinit();
1915 globals->get_controls()->reset_all();
1917 fgUpdateLocalTime();
1919 // re-init to proper time of day setting
1923 fgSetBool("/sim/freeze/master", false);
1925 fgSetBool("/sim/sceneryloaded",false);