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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
30 #include <string.h> // strcmp()
32 #if defined( unix ) || defined( __CYGWIN__ )
33 # include <unistd.h> // for gethostname()
36 # include <direct.h> // for getcwd()
37 # define getcwd _getcwd
38 # include <io.h> // isatty()
39 # define isatty _isatty
40 # include "winsock2.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>
52 #include <boost/algorithm/string/compare.hpp>
53 #include <boost/algorithm/string/predicate.hpp>
55 #include <simgear/constants.h>
56 #include <simgear/debug/logstream.hxx>
57 #include <simgear/structure/exception.hxx>
58 #include <simgear/structure/event_mgr.hxx>
59 #include <simgear/misc/sg_path.hxx>
60 #include <simgear/misc/sg_dir.hxx>
61 #include <simgear/misc/sgstream.hxx>
62 #include <simgear/misc/strutils.hxx>
64 #include <simgear/misc/interpolator.hxx>
65 #include <simgear/scene/material/matlib.hxx>
66 #include <simgear/scene/model/particles.hxx>
67 #include <simgear/sound/soundmgr_openal.hxx>
69 #include <Aircraft/controls.hxx>
70 #include <Aircraft/replay.hxx>
71 #include <Airports/apt_loader.hxx>
72 #include <Airports/runways.hxx>
73 #include <Airports/simple.hxx>
74 #include <Airports/dynamics.hxx>
76 #include <AIModel/AIManager.hxx>
78 #include <ATCDCL/ATCmgr.hxx>
79 #include <ATC/atc_mgr.hxx>
81 #include <Autopilot/route_mgr.hxx>
82 #include <Autopilot/autopilotgroup.hxx>
84 #include <Cockpit/panel.hxx>
85 #include <Cockpit/panel_io.hxx>
87 #include <GUI/new_gui.hxx>
88 #include <Input/input.hxx>
89 #include <Instrumentation/instrument_mgr.hxx>
90 #include <Model/acmodel.hxx>
91 #include <Model/modelmgr.hxx>
92 #include <AIModel/submodel.hxx>
93 #include <AIModel/AIManager.hxx>
94 #include <Navaids/navdb.hxx>
95 #include <Navaids/navlist.hxx>
96 #include <Navaids/fix.hxx>
97 #include <Navaids/fixlist.hxx>
98 #include <Navaids/airways.hxx>
99 #include <Scenery/scenery.hxx>
100 #include <Scenery/tilemgr.hxx>
101 #include <Scripting/NasalSys.hxx>
102 #include <Sound/voice.hxx>
103 #include <Systems/system_mgr.hxx>
104 #include <Time/light.hxx>
105 #include <Traffic/TrafficMgr.hxx>
106 #include <MultiPlayer/multiplaymgr.hxx>
107 #include <FDM/fdm_shell.hxx>
109 #include <Environment/environment_mgr.hxx>
111 #include "fg_init.hxx"
113 #include "fg_commands.hxx"
114 #include "fg_props.hxx"
115 #include "options.hxx"
116 #include "globals.hxx"
117 #include "logger.hxx"
118 #include "renderer.hxx"
119 #include "viewmgr.hxx"
124 # include <CoreFoundation/CoreFoundation.h>
128 using namespace boost::algorithm;
130 extern const char *default_root;
133 // Scan the command line options for the specified option and return
135 static string fgScanForOption( const string& option, int argc, char **argv ) {
138 if (hostname == NULL)
141 if( gethostname(_hostname, 256) >= 0 ) {
142 hostname = strdup(_hostname);
143 free_hostname = true;
147 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
149 int len = option.length();
152 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
154 string arg = argv[i];
155 if ( arg.find( option ) == 0 ) {
156 return arg.substr( len );
166 // Scan the user config files for the specified option and return
168 static string fgScanForOption( const string& option, const string& path ) {
169 sg_gzifstream in( path );
170 if ( !in.is_open() ) {
174 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
176 int len = option.length();
179 while ( ! in.eof() ) {
181 getline( in, line, '\n' );
183 // catch extraneous (DOS) line ending character
184 if ( line[line.length() - 1] < 32 ) {
185 line = line.substr( 0, line.length()-1 );
188 if ( line.find( option ) == 0 ) {
189 return line.substr( len );
198 // Scan the user config files for the specified option and return
200 static string fgScanForOption( const string& option ) {
203 #if defined( unix ) || defined( __CYGWIN__ ) || defined(_MSC_VER)
204 // Next check home directory for .fgfsrc.hostname file
206 if ( homedir != NULL && hostname != NULL && strlen(hostname) > 0) {
207 SGPath config( homedir );
208 config.append( ".fgfsrc" );
209 config.concat( "." );
210 config.concat( hostname );
211 arg = fgScanForOption( option, config.str() );
216 // Next check home directory for .fgfsrc file
218 if ( homedir != NULL ) {
219 SGPath config( homedir );
220 config.append( ".fgfsrc" );
221 arg = fgScanForOption( option, config.str() );
226 // Check for $fg_root/system.fgfsrc
227 SGPath config( globals->get_fg_root() );
228 config.append( "system.fgfsrc" );
229 arg = fgScanForOption( option, config.str() );
236 // Read in configuration (files and command line options) but only set
237 // fg_root and aircraft_paths, which are needed *before* do_options() is called
240 bool fgInitFGRoot ( int argc, char **argv ) {
243 // First parse command line options looking for --fg-root=, this
244 // will override anything specified in a config file
245 root = fgScanForOption( "--fg-root=", argc, argv);
247 // Check in one of the user configuration files.
249 root = fgScanForOption( "--fg-root=" );
251 // Next check if fg-root is set as an env variable
252 if ( root.empty() ) {
253 char *envp = ::getenv( "FG_ROOT" );
254 if ( envp != NULL ) {
259 // Otherwise, default to a random compiled-in location if we can't
260 // find fg-root any other way.
261 if ( root.empty() ) {
262 #if defined( __CYGWIN__ )
264 #elif defined( _WIN32 )
266 #elif defined(__APPLE__)
268 The following code looks for the base package inside the application
269 bundle, in the standard Contents/Resources location.
271 CFURLRef resourcesUrl = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
273 // look for a 'data' subdir
274 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, resourcesUrl, CFSTR("data"), true);
276 // now convert down to a path, and the a c-string
277 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
278 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
280 CFRelease(resourcesUrl);
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 ) {
299 string aircraftDir = fgScanForOption("--fg-aircraft=", argc, argv);
300 if (aircraftDir.empty()) {
301 aircraftDir = fgScanForOption("--fg-aircraft=");
304 const char* envp = ::getenv("FG_AIRCRAFT");
305 if (aircraftDir.empty() && envp) {
306 globals->append_aircraft_paths(envp);
309 if (!aircraftDir.empty()) {
310 globals->append_aircraft_paths(aircraftDir);
315 // First parse command line options looking for --aircraft=, this
316 // will override anything specified in a config file
317 aircraft = fgScanForOption( "--aircraft=", argc, argv );
318 if ( aircraft.empty() ) {
319 // check synonym option
320 aircraft = fgScanForOption( "--vehicle=", argc, argv );
323 // Check in one of the user configuration files.
324 if ( aircraft.empty() ) {
325 aircraft = fgScanForOption( "--aircraft=" );
327 if ( aircraft.empty() ) {
328 aircraft = fgScanForOption( "--vehicle=" );
331 // if an aircraft was specified, set the property name
332 if ( !aircraft.empty() ) {
333 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
334 fgSetString("/sim/aircraft", aircraft.c_str() );
336 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
343 // Return the current base package version
344 string fgBasePackageVersion() {
345 SGPath base_path( globals->get_fg_root() );
346 base_path.append("version");
348 sg_gzifstream in( base_path.str() );
349 if ( !in.is_open() ) {
350 SGPath old_path( globals->get_fg_root() );
351 old_path.append( "Thanks" );
352 sg_gzifstream old( old_path.str() );
353 if ( !old.is_open() ) {
356 return "[old version]";
367 // Initialize the localization
368 SGPropertyNode *fgInitLocale(const char *language) {
369 SGPropertyNode *c_node = NULL, *d_node = NULL;
370 SGPropertyNode *intl = fgGetNode("/sim/intl");
372 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
374 // localization not defined
379 // Select the proper language from the list
381 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
382 for (unsigned int i = 0; i < locale.size(); i++) {
384 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
385 for (unsigned int j = 0; j < lang.size(); j++) {
387 if (!strcmp(lang[j]->getStringValue(), language)) {
396 d_node = intl->getChild("locale");
400 // Check for localized font
401 SGPropertyNode *font_n = c_node->getNode("font", true);
402 if ( !strcmp(font_n->getStringValue(), "") )
403 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
407 // Load the default strings
409 SGPath d_path( globals->get_fg_root() );
411 const char *d_path_str = d_node->getStringValue("strings");
413 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << d_node->getPath() << "/strings.");
417 d_path.append(d_path_str);
418 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << d_path.str());
420 SGPropertyNode *strings = c_node->getNode("strings");
422 readProperties(d_path.str(), strings);
423 } catch (const sg_exception &) {
424 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
429 // Load the language specific strings
431 if (c_node != d_node) {
432 SGPath c_path( globals->get_fg_root() );
434 const char *c_path_str = c_node->getStringValue("strings");
436 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << c_node->getPath() << "/strings");
440 c_path.append(c_path_str);
441 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << c_path.str());
444 readProperties(c_path.str(), strings);
445 } catch (const sg_exception &) {
446 SG_LOG(SG_GENERAL, SG_ALERT,
447 "Unable to read the localized strings from " << c_path.str());
457 // Initialize the localization routines
458 bool fgDetectLanguage() {
459 const char *language = ::getenv("LANG");
461 if (language == NULL) {
462 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
466 SGPropertyNode *locale = fgInitLocale(language);
468 SG_LOG(SG_GENERAL, SG_ALERT,
469 "No internationalization settings specified in preferences.xml" );
474 globals->set_locale( locale );
479 // Attempt to locate and parse the various non-XML config files in order
480 // from least precidence to greatest precidence
482 do_options (int argc, char ** argv)
484 // Check for $fg_root/system.fgfsrc
485 SGPath config( globals->get_fg_root() );
486 config.append( "system.fgfsrc" );
487 fgParseOptions(config.str());
489 #if defined( unix ) || defined( __CYGWIN__ ) || defined(_MSC_VER)
490 if( hostname != NULL && strlen(hostname) > 0 ) {
491 config.concat( "." );
492 config.concat( hostname );
493 fgParseOptions(config.str());
497 // Check for ~/.fgfsrc
498 if ( homedir != NULL ) {
499 config.set( homedir );
500 config.append( ".fgfsrc" );
501 fgParseOptions(config.str());
504 #if defined( unix ) || defined( __CYGWIN__ ) || defined(_MSC_VER)
505 if( hostname != NULL && strlen(hostname) > 0 ) {
506 // Check for ~/.fgfsrc.hostname
507 config.concat( "." );
508 config.concat( hostname );
509 fgParseOptions(config.str());
513 // Parse remaining command line options
514 // These will override anything specified in a config file
515 fgParseArgs(argc, argv);
519 bool fgFindAircraftInDir(const SGPath& dirPath, T* obj, bool (T::*pred)(const SGPath& p))
521 if (!dirPath.exists()) {
522 SG_LOG(SG_GENERAL, SG_WARN, "fgFindAircraftInDir: no such path:" << dirPath.str());
527 simgear::Dir dir(dirPath);
528 simgear::PathList setFiles(dir.children(simgear::Dir::TYPE_FILE, "-set.xml"));
529 simgear::PathList::iterator p;
530 for (p = setFiles.begin(); p != setFiles.end(); ++p) {
531 // check file name ends with -set.xml
533 // if we found a -set.xml at this level, don't recurse any deeper
536 bool done = (obj->*pred)(*p);
540 } // of -set.xml iteration
546 simgear::PathList subdirs(dir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT));
547 for (p = subdirs.begin(); p != subdirs.end(); ++p) {
548 if (p->file() == "CVS") {
552 if (fgFindAircraftInDir(*p, obj, pred)) {
555 } // of subdirs iteration
561 void fgFindAircraft(T* obj, bool (T::*pred)(const SGPath& p))
563 const string_list& paths(globals->get_aircraft_paths());
564 string_list::const_iterator it = paths.begin();
565 for (; it != paths.end(); ++it) {
566 bool done = fgFindAircraftInDir(SGPath(*it), obj, pred);
570 } // of aircraft paths iteration
572 // if we reach this point, search the default location (always last)
573 SGPath rootAircraft(globals->get_fg_root());
574 rootAircraft.append("Aircraft");
575 fgFindAircraftInDir(rootAircraft, obj, pred);
578 class FindAndCacheAircraft
581 FindAndCacheAircraft(SGPropertyNode* autoSave)
583 _cache = autoSave->getNode("sim/startup/path-cache", true);
588 std::string aircraft = fgGetString( "/sim/aircraft", "");
589 if (aircraft.empty()) {
590 SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
594 _searchAircraft = aircraft + "-set.xml";
596 // prepare cache for re-scan
597 SGPropertyNode *n = _cache->getNode("fg-root", true);
598 n->setStringValue(globals->get_fg_root().c_str());
599 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
600 n = _cache->getNode("fg-aircraft", true);
601 n->setStringValue(getAircraftPaths().c_str());
602 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
603 _cache->removeChildren("aircraft");
605 fgFindAircraft(this, &FindAndCacheAircraft::checkAircraft);
608 if (_foundPath.str().empty()) {
609 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
613 SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
614 fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
615 if (!_foundPath.exists()) {
616 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
621 readProperties(_foundPath.str(), globals->get_props());
622 } catch ( const sg_exception &e ) {
623 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
631 SGPath getAircraftPaths() {
632 string_list pathList = globals->get_aircraft_paths();
633 SGPath aircraftPaths;
634 string_list::const_iterator it = pathList.begin();
635 if (it != pathList.end()) {
636 aircraftPaths.set(*it);
639 for (; it != pathList.end(); ++it) {
640 aircraftPaths.add(*it);
642 return aircraftPaths;
647 if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
648 return false; // cache mismatch
651 if (getAircraftPaths().str() != _cache->getStringValue("fg-aircraft", "")) {
652 return false; // cache mismatch
655 vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
656 for (unsigned int i = 0; i < cache.size(); i++) {
657 const char *name = cache[i]->getStringValue("file", "");
658 if (!boost::equals(_searchAircraft, name, is_iequal())) {
662 SGPath xml(cache[i]->getStringValue("path", ""));
670 } // of aircraft in cache iteration
675 bool checkAircraft(const SGPath& p)
680 if (!_cache->getChild("aircraft", i++, false))
684 SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
686 std::string fileName(p.file());
687 n = entry->getNode("file", true);
688 n->setStringValue(fileName);
689 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
691 n = entry->getNode("path", true);
692 n->setStringValue(p.dir());
693 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
695 if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
703 std::string _searchAircraft;
705 SGPropertyNode* _cache;
708 // Read in configuration (file and command line)
709 bool fgInitConfig ( int argc, char **argv ) {
711 // First, set some sane default values
714 // Read global preferences from $FG_ROOT/preferences.xml
715 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
716 fgLoadProps("preferences.xml", globals->get_props());
717 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
719 // Detect the required language as early as possible
720 if ( !fgDetectLanguage() ) {
724 SGPropertyNode autosave;
726 char *envp = ::getenv( "APPDATA" );
728 SGPath config( envp );
729 config.append( "flightgear.org" );
731 if ( homedir != NULL ) {
732 SGPath config( homedir );
733 config.append( ".fgfs" );
735 const char *fg_home = getenv("FG_HOME");
739 SGPath home_export(config.str());
740 home_export.append("Export/dummy");
741 home_export.create_dir(0777);
743 // Set /sim/fg-home and don't allow malign code to override it until
744 // Nasal security is set up. Use FG_HOME if necessary.
745 SGPropertyNode *home = fgGetNode("/sim", true);
746 home->removeChild("fg-home", 0, false);
747 home = home->getChild("fg-home", 0, true);
748 home->setStringValue(config.c_str());
749 home->setAttribute(SGPropertyNode::WRITE, false);
751 config.append( "autosave.xml" );
752 if (config.exists()) {
753 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << config.str());
755 readProperties(config.str(), &autosave, SGPropertyNode::USERARCHIVE);
756 } catch (sg_exception& e) {
757 SG_LOG(SG_INPUT, SG_WARN, "failed to read user settings:" << e.getMessage()
758 << "(from " << e.getOrigin() << ")");
763 // Scan user config files and command line for a specified aircraft.
764 fgInitFGAircraft(argc, argv);
765 FindAndCacheAircraft f(&autosave);
766 if (!f.loadAircraft()) {
770 copyProperties(&autosave, globals->get_props());
772 // parse options after loading aircraft to ensure any user
773 // overrides of defaults are honored.
774 do_options(argc, argv);
779 // Set current tower position lon/lat given an airport id
780 static bool fgSetTowerPosFromAirportID( const string& id) {
781 const FGAirport *a = fgFindAirportID( id);
783 SGGeod tower = a->getTowerLocation();
784 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
785 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
786 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
794 struct FGTowerLocationListener : SGPropertyChangeListener {
795 void valueChanged(SGPropertyNode* node) {
796 string id(node->getStringValue());
797 if (fgGetBool("/sim/tower/auto-position",true))
799 // enforce using closest airport when auto-positioning is enabled
800 const char* closest_airport = fgGetString("/sim/airport/closest-airport-id", "");
801 if (closest_airport && (id != closest_airport))
803 id = closest_airport;
804 node->setStringValue(id);
807 fgSetTowerPosFromAirportID(id);
811 struct FGClosestTowerLocationListener : SGPropertyChangeListener
813 void valueChanged(SGPropertyNode* )
815 // closest airport has changed
816 if (fgGetBool("/sim/tower/auto-position",true))
818 // update tower position
819 const char* id = fgGetString("/sim/airport/closest-airport-id", "");
821 fgSetString("/sim/tower/airport-id", id);
826 void fgInitTowerLocationListener() {
827 fgGetNode("/sim/tower/airport-id", true)
828 ->addChangeListener( new FGTowerLocationListener(), true );
829 FGClosestTowerLocationListener* ntcl = new FGClosestTowerLocationListener();
830 fgGetNode("/sim/airport/closest-airport-id", true)
831 ->addChangeListener(ntcl , true );
832 fgGetNode("/sim/tower/auto-position", true)
833 ->addChangeListener(ntcl, true );
836 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
838 SGGeod startPos(aStartPos);
839 if (aTargetHeading == HUGE_VAL) {
840 aTargetHeading = aHeading;
843 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
844 double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
845 offsetDistance *= SG_NM_TO_METER;
846 double offsetAzimuth = aHeading;
847 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
848 offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
849 aHeading = aTargetHeading;
854 SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
859 fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
860 fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
861 fgSetDouble("/sim/presets/heading-deg", aHeading );
863 // other code depends on the actual values being set ...
864 fgSetDouble("/position/longitude-deg", startPos.getLongitudeDeg() );
865 fgSetDouble("/position/latitude-deg", startPos.getLatitudeDeg() );
866 fgSetDouble("/orientation/heading-deg", aHeading );
869 // Set current_options lon/lat given an airport id and heading (degrees)
870 bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
874 // set initial position from runway and heading
875 SG_LOG( SG_GENERAL, SG_INFO,
876 "Attempting to set starting position from airport code "
877 << id << " heading " << tgt_hdg );
879 const FGAirport* apt = fgFindAirportID(id);
880 if (!apt) return false;
881 FGRunway* r = apt->findBestRunwayForHeading(tgt_hdg);
882 fgSetString("/sim/atc/runway", r->ident().c_str());
884 SGGeod startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
885 fgApplyStartOffset(startPos, r->headingDeg(), tgt_hdg);
889 // Set current_options lon/lat given an airport id and parkig position name
890 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
894 // can't see an easy way around this const_cast at the moment
895 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
897 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
900 FGAirportDynamics* dcs = apt->getDynamics();
902 SG_LOG( SG_GENERAL, SG_ALERT,
903 "Failed to find parking position " << parkpos <<
904 " at airport " << id );
908 int park_index = dcs->getNrOfParkings() - 1;
909 while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
910 if (park_index < 0) {
911 SG_LOG( SG_GENERAL, SG_ALERT,
912 "Failed to find parking position " << parkpos <<
913 " at airport " << id );
916 FGParking* parking = dcs->getParking(park_index);
917 parking->setAvailable(false);
919 SGGeod::fromDeg(parking->getLongitude(), parking->getLatitude()),
920 parking->getHeading());
925 // Set current_options lon/lat given an airport id and runway number
926 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
930 // set initial position from airport and runway number
931 SG_LOG( SG_GENERAL, SG_INFO,
932 "Attempting to set starting position for "
933 << id << ":" << rwy );
935 const FGAirport* apt = fgFindAirportID(id);
937 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
941 if (!apt->hasRunwayWithIdent(rwy)) {
942 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
943 "Failed to find runway " << rwy <<
944 " at airport " << id << ". Using default runway." );
948 FGRunway* r(apt->getRunwayByIdent(rwy));
949 fgSetString("/sim/atc/runway", r->ident().c_str());
950 SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
951 fgApplyStartOffset(startPos, r->headingDeg());
956 static void fgSetDistOrAltFromGlideSlope() {
957 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
958 string apt_id = fgGetString("/sim/presets/airport-id");
959 double gs = fgGetDouble("/sim/presets/glideslope-deg")
960 * SG_DEGREES_TO_RADIANS ;
961 double od = fgGetDouble("/sim/presets/offset-distance-nm");
962 double alt = fgGetDouble("/sim/presets/altitude-ft");
964 double apt_elev = 0.0;
965 if ( ! apt_id.empty() ) {
966 apt_elev = fgGetAirportElev( apt_id );
967 if ( apt_elev < -9990.0 ) {
974 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
975 // set altitude from glideslope and offset-distance
976 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
977 alt = fabs(od*tan(gs)) + apt_elev;
978 fgSetDouble("/sim/presets/altitude-ft", alt);
979 fgSetBool("/sim/presets/onground", false);
980 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
982 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
983 // set offset-distance from glideslope and altitude
984 od = (alt - apt_elev) / tan(gs);
985 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
986 fgSetDouble("/sim/presets/offset-distance-nm", od);
987 fgSetBool("/sim/presets/onground", false);
988 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
990 } else if( fabs(gs) > 0.01 ) {
991 SG_LOG( SG_GENERAL, SG_ALERT,
992 "Glideslope given but not altitude or offset-distance." );
993 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
994 fgSetDouble("/sim/presets/glideslope-deg", 0);
995 fgSetBool("/sim/presets/onground", true);
1000 // Set current_options lon/lat given an airport id and heading (degrees)
1001 static bool fgSetPosFromNAV( const string& id, const double& freq, FGPositioned::Type type ) {
1003 const nav_list_type navlist
1004 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq, type );
1006 if (navlist.size() == 0 ) {
1007 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1008 << id << ":" << freq );
1012 if( navlist.size() > 1 ) {
1014 buf << "Ambigous NAV-ID: '" << id << "'. Specify id and frequency. Available stations:" << endl;
1015 for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
1016 // NDB stored in kHz, VOR stored in MHz * 100 :-P
1017 double factor = (*it)->type() == FGPositioned::NDB ? 1.0 : 1/100.0;
1018 string unit = (*it)->type() == FGPositioned::NDB ? "kHz" : "MHz";
1019 buf << (*it)->ident() << " "
1020 << setprecision(5) << (double)((*it)->get_freq() * factor) << " "
1021 << (*it)->get_lat() << "/" << (*it)->get_lon()
1025 SG_LOG( SG_GENERAL, SG_ALERT, buf.str() );
1029 FGNavRecord *nav = navlist[0];
1030 fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
1034 // Set current_options lon/lat given an aircraft carrier id
1035 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
1037 // set initial position from runway and heading
1041 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
1042 double lon = geodPos.getLongitudeDeg();
1043 double lat = geodPos.getLatitudeDeg();
1044 double alt = geodPos.getElevationFt();
1046 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1047 << carrier << " at lat = " << lat << ", lon = " << lon
1048 << ", alt = " << alt << ", heading = " << heading);
1050 fgSetDouble("/sim/presets/longitude-deg", lon);
1051 fgSetDouble("/sim/presets/latitude-deg", lat);
1052 fgSetDouble("/sim/presets/altitude-ft", alt);
1053 fgSetDouble("/sim/presets/heading-deg", heading);
1054 fgSetDouble("/position/longitude-deg", lon);
1055 fgSetDouble("/position/latitude-deg", lat);
1056 fgSetDouble("/position/altitude-ft", alt);
1057 fgSetDouble("/orientation/heading-deg", heading);
1059 fgSetString("/sim/presets/speed-set", "UVW");
1060 fgSetDouble("/velocities/uBody-fps", uvw(0));
1061 fgSetDouble("/velocities/vBody-fps", uvw(1));
1062 fgSetDouble("/velocities/wBody-fps", uvw(2));
1063 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
1064 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
1065 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
1067 fgSetBool("/sim/presets/onground", true);
1071 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
1077 // Set current_options lon/lat given an airport id and heading (degrees)
1078 static bool fgSetPosFromFix( const string& id )
1080 FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
1081 FGPositioned* fix = FGPositioned::findNextWithPartialId(NULL, id, &fixFilter);
1083 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
1087 fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
1092 * Initialize vor/ndb/ils/fix list management and query systems (as
1093 * well as simple airport db list)
1098 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
1100 SGPath aptdb( globals->get_fg_root() );
1101 aptdb.append( "Airports/apt.dat" );
1103 SGPath p_metar( globals->get_fg_root() );
1104 p_metar.append( "Airports/metar.dat" );
1106 fgAirportDBLoad( aptdb.str(), p_metar.str() );
1107 FGAirport::installPropertyListener();
1108 FGPositioned::installCommands();
1110 FGNavList *navlist = new FGNavList;
1111 FGNavList *loclist = new FGNavList;
1112 FGNavList *gslist = new FGNavList;
1113 FGNavList *dmelist = new FGNavList;
1114 FGNavList *tacanlist = new FGNavList;
1115 FGNavList *carrierlist = new FGNavList;
1116 FGTACANList *channellist = new FGTACANList;
1118 globals->set_navlist( navlist );
1119 globals->set_loclist( loclist );
1120 globals->set_gslist( gslist );
1121 globals->set_dmelist( dmelist );
1122 globals->set_tacanlist( tacanlist );
1123 globals->set_carrierlist( carrierlist );
1124 globals->set_channellist( channellist );
1126 if ( !fgNavDBInit(navlist, loclist, gslist, dmelist, tacanlist, carrierlist, channellist) ) {
1127 SG_LOG( SG_GENERAL, SG_ALERT,
1128 "Problems loading one or more navigational database" );
1131 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1132 SGPath p_fix( globals->get_fg_root() );
1133 p_fix.append( "Navaids/fix.dat" );
1135 fixlist.init( p_fix ); // adds fixes to the DB in positioned.cxx
1137 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
1138 flightgear::Airway::load();
1144 // Set the initial position based on presets (or defaults)
1145 bool fgInitPosition() {
1146 // cout << "fgInitPosition()" << endl;
1147 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1148 * SG_DEGREES_TO_RADIANS ;
1149 double od = fgGetDouble("/sim/presets/offset-distance-nm");
1150 double alt = fgGetDouble("/sim/presets/altitude-ft");
1152 bool set_pos = false;
1154 // If glideslope is specified, then calculate offset-distance or
1155 // altitude relative to glide slope if either of those was not
1157 if ( fabs( gs ) > 0.01 ) {
1158 fgSetDistOrAltFromGlideSlope();
1162 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1163 // If not, check for an airport-id and use that.
1164 // If not, default to the middle of the KSFO field.
1165 // The default values for lon/lat are deliberately out of range
1166 // so that the airport-id can take effect; valid lon/lat will
1167 // override airport-id, however.
1168 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1169 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1170 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1171 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1176 string apt = fgGetString("/sim/presets/airport-id");
1177 string rwy_no = fgGetString("/sim/presets/runway");
1178 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1179 string vor = fgGetString("/sim/presets/vor-id");
1180 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1181 string ndb = fgGetString("/sim/presets/ndb-id");
1182 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1183 string carrier = fgGetString("/sim/presets/carrier");
1184 string parkpos = fgGetString("/sim/presets/parkpos");
1185 string fix = fgGetString("/sim/presets/fix");
1186 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1187 double hdg = hdg_preset->getDoubleValue();
1189 // save some start parameters, so that we can later say what the
1190 // user really requested. TODO generalize that and move it to options.cxx
1191 static bool start_options_saved = false;
1192 if (!start_options_saved) {
1193 start_options_saved = true;
1194 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1196 opt->setDoubleValue("latitude-deg", lat_deg);
1197 opt->setDoubleValue("longitude-deg", lon_deg);
1198 opt->setDoubleValue("heading-deg", hdg);
1199 opt->setStringValue("airport", apt.c_str());
1200 opt->setStringValue("runway", rwy_no.c_str());
1204 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1206 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1207 // An airport + parking position is requested
1208 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1209 // set tower position
1210 fgSetString("/sim/airport/closest-airport-id", apt.c_str());
1211 fgSetString("/sim/tower/airport-id", apt.c_str());
1216 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1217 // An airport + runway is requested
1218 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1219 // set tower position (a little off the heading for single
1221 fgSetString("/sim/airport/closest-airport-id", apt.c_str());
1222 fgSetString("/sim/tower/airport-id", apt.c_str());
1227 if ( !set_pos && !apt.empty() ) {
1228 // An airport is requested (find runway closest to hdg)
1229 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1230 // set tower position (a little off the heading for single
1232 fgSetString("/sim/airport/closest-airport-id", apt.c_str());
1233 fgSetString("/sim/tower/airport-id", apt.c_str());
1238 if (hdg_preset->getDoubleValue() > 9990.0)
1239 hdg_preset->setDoubleValue(hdg);
1241 if ( !set_pos && !vor.empty() ) {
1242 // a VOR is requested
1243 if ( fgSetPosFromNAV( vor, vor_freq, FGPositioned::VOR ) ) {
1248 if ( !set_pos && !ndb.empty() ) {
1249 // an NDB is requested
1250 if ( fgSetPosFromNAV( ndb, ndb_freq, FGPositioned::NDB ) ) {
1255 if ( !set_pos && !carrier.empty() ) {
1256 // an aircraft carrier is requested
1257 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1262 if ( !set_pos && !fix.empty() ) {
1263 // a Fix is requested
1264 if ( fgSetPosFromFix( fix ) ) {
1270 // No lon/lat specified, no airport specified, default to
1271 // middle of KSFO field.
1272 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1273 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1276 fgSetDouble( "/position/longitude-deg",
1277 fgGetDouble("/sim/presets/longitude-deg") );
1278 fgSetDouble( "/position/latitude-deg",
1279 fgGetDouble("/sim/presets/latitude-deg") );
1280 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1282 // determine if this should be an on-ground or in-air start
1283 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1284 fgSetBool("/sim/presets/onground", false);
1286 fgSetBool("/sim/presets/onground", true);
1293 // General house keeping initializations
1294 bool fgInitGeneral() {
1297 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1298 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1300 root = globals->get_fg_root();
1301 if ( ! root.length() ) {
1302 // No root path set? Then bail ...
1303 SG_LOG( SG_GENERAL, SG_ALERT,
1304 "Cannot continue without a path to the base package "
1305 << "being defined." );
1308 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1310 globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1312 char buf[512], *cwd = getcwd(buf, 511);
1314 SGPropertyNode *curr = fgGetNode("/sim", true);
1315 curr->removeChild("fg-current", 0, false);
1316 curr = curr->getChild("fg-current", 0, true);
1317 curr->setStringValue(cwd ? cwd : "");
1318 curr->setAttribute(SGPropertyNode::WRITE, false);
1320 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
1321 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
1325 // This is the top level init routine which calls all the other
1326 // initialization routines. If you are adding a subsystem to flight
1327 // gear, its initialization call should located in this routine.
1328 // Returns non-zero if a problem encountered.
1329 bool fgInitSubsystems() {
1330 // static const SGPropertyNode *longitude
1331 // = fgGetNode("/sim/presets/longitude-deg");
1332 // static const SGPropertyNode *latitude
1333 // = fgGetNode("/sim/presets/latitude-deg");
1334 // static const SGPropertyNode *altitude
1335 // = fgGetNode("/sim/presets/altitude-ft");
1337 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1338 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1340 ////////////////////////////////////////////////////////////////////
1341 // Initialize the event manager subsystem.
1342 ////////////////////////////////////////////////////////////////////
1344 globals->get_event_mgr()->init();
1345 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1347 ////////////////////////////////////////////////////////////////////
1348 // Initialize the property interpolator subsystem. Put into the INIT
1349 // group because the "nasal" subsystem may need it at GENERAL take-down.
1350 ////////////////////////////////////////////////////////////////////
1351 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1354 ////////////////////////////////////////////////////////////////////
1355 // Add the FlightGear property utilities.
1356 ////////////////////////////////////////////////////////////////////
1357 globals->add_subsystem("properties", new FGProperties);
1359 ////////////////////////////////////////////////////////////////////
1360 // Initialize the material property subsystem.
1361 ////////////////////////////////////////////////////////////////////
1363 SGPath mpath( globals->get_fg_root() );
1364 mpath.append( "materials.xml" );
1365 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
1366 globals->get_props()) ) {
1367 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1372 ////////////////////////////////////////////////////////////////////
1373 // Initialize the scenery management subsystem.
1374 ////////////////////////////////////////////////////////////////////
1376 globals->get_scenery()->get_scene_graph()
1377 ->addChild(simgear::Particles::getCommonRoot());
1378 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
1380 ////////////////////////////////////////////////////////////////////
1381 // Initialize the flight model subsystem.
1382 ////////////////////////////////////////////////////////////////////
1384 globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
1386 ////////////////////////////////////////////////////////////////////
1387 // Initialize the weather subsystem.
1388 ////////////////////////////////////////////////////////////////////
1390 // Initialize the weather modeling subsystem
1391 globals->add_subsystem("environment", new FGEnvironmentMgr);
1393 ////////////////////////////////////////////////////////////////////
1394 // Initialize the aircraft systems and instrumentation (before the
1396 ////////////////////////////////////////////////////////////////////
1398 globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
1399 globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
1401 ////////////////////////////////////////////////////////////////////
1402 // Initialize the XML Autopilot subsystem.
1403 ////////////////////////////////////////////////////////////////////
1405 globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance(), SGSubsystemMgr::FDM );
1406 globals->add_subsystem( "route-manager", new FGRouteMgr );
1408 ////////////////////////////////////////////////////////////////////
1409 // Initialize the Input-Output subsystem
1410 ////////////////////////////////////////////////////////////////////
1411 globals->add_subsystem( "io", new FGIO );
1413 ////////////////////////////////////////////////////////////////////
1414 // Create and register the logger.
1415 ////////////////////////////////////////////////////////////////////
1417 globals->add_subsystem("logger", new FGLogger);
1419 ////////////////////////////////////////////////////////////////////
1420 // Create and register the XML GUI.
1421 ////////////////////////////////////////////////////////////////////
1423 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1425 //////////////////////////////////////////////////////////////////////
1426 // Initialize the 2D cloud subsystem.
1427 ////////////////////////////////////////////////////////////////////
1428 fgGetBool("/sim/rendering/bump-mapping", false);
1432 ////////////////////////////////////////////////////////////////////
1433 // Initialise the ATC Manager
1434 // Note that this is old stuff, but might be necessesary for the
1435 // current ATIS implementation. Therefore, leave it in here
1436 // until the ATIS system is ported over to make use of the ATIS
1437 // sub system infrastructure.
1438 ////////////////////////////////////////////////////////////////////
1440 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1441 globals->set_ATC_mgr(new FGATCMgr);
1442 globals->get_ATC_mgr()->init();
1444 ////////////////////////////////////////////////////////////////////
1445 // Initialize the ATC subsystem
1446 ////////////////////////////////////////////////////////////////////
1447 globals->add_subsystem("ATC", new FGATCManager, SGSubsystemMgr::POST_FDM);
1448 ////////////////////////////////////////////////////////////////////
1449 // Initialise the ATIS Subsystem
1450 ////////////////////////////////////////////////////////////////////
1451 //globals->add_subsystem("atis", new FGAtisManager, SGSubsystemMgr::POST_FDM);
1454 ////////////////////////////////////////////////////////////////////
1455 // Initialize multiplayer subsystem
1456 ////////////////////////////////////////////////////////////////////
1458 globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
1460 ////////////////////////////////////////////////////////////////////
1461 // Initialise the AI Model Manager
1462 ////////////////////////////////////////////////////////////////////
1463 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1464 globals->add_subsystem("ai_model", new FGAIManager, SGSubsystemMgr::POST_FDM);
1465 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
1468 // It's probably a good idea to initialize the top level traffic manager
1469 // After the AI and ATC systems have been initialized properly.
1470 // AI Traffic manager
1471 globals->add_subsystem("Traffic Manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
1473 ////////////////////////////////////////////////////////////////////
1474 // Add a new 2D panel.
1475 ////////////////////////////////////////////////////////////////////
1477 string panel_path(fgGetString("/sim/panel/path"));
1478 if (!panel_path.empty()) {
1479 FGPanel* p = fgReadPanel(panel_path);
1481 globals->set_current_panel(p);
1484 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1486 SG_LOG( SG_INPUT, SG_ALERT,
1487 "Error reading new panel from " << panel_path );
1491 ////////////////////////////////////////////////////////////////////
1492 // Initialize the controls subsystem.
1493 ////////////////////////////////////////////////////////////////////
1495 globals->get_controls()->init();
1496 globals->get_controls()->bind();
1499 ////////////////////////////////////////////////////////////////////
1500 // Initialize the input subsystem.
1501 ////////////////////////////////////////////////////////////////////
1503 globals->add_subsystem("input", new FGInput);
1506 ////////////////////////////////////////////////////////////////////
1507 // Initialize the replay subsystem
1508 ////////////////////////////////////////////////////////////////////
1509 globals->add_subsystem("replay", new FGReplay);
1511 #ifdef ENABLE_AUDIO_SUPPORT
1512 ////////////////////////////////////////////////////////////////////
1513 // Initialize the sound-effects subsystem.
1514 ////////////////////////////////////////////////////////////////////
1515 globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
1518 ////////////////////////////////////////////////////////////////////
1519 // Initialize the lighting subsystem.
1520 ////////////////////////////////////////////////////////////////////
1522 globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
1524 // ordering here is important : Nasal (via events), then models, then views
1525 globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
1527 FGAircraftModel* acm = new FGAircraftModel;
1528 globals->set_aircraft_model(acm);
1529 globals->add_subsystem("aircraft-model", acm, SGSubsystemMgr::DISPLAY);
1531 FGModelMgr* mm = new FGModelMgr;
1532 globals->set_model_mgr(mm);
1533 globals->add_subsystem("model-manager", mm, SGSubsystemMgr::DISPLAY);
1535 FGViewMgr *viewmgr = new FGViewMgr;
1536 globals->set_viewmgr( viewmgr );
1537 globals->add_subsystem("view-manager", viewmgr, SGSubsystemMgr::DISPLAY);
1539 globals->add_subsystem("tile-manager", globals->get_tile_mgr(),
1540 SGSubsystemMgr::DISPLAY);
1542 ////////////////////////////////////////////////////////////////////
1543 // Bind and initialize subsystems.
1544 ////////////////////////////////////////////////////////////////////
1546 globals->get_subsystem_mgr()->bind();
1547 globals->get_subsystem_mgr()->init();
1549 ////////////////////////////////////////////////////////////////////////
1550 // Initialize the Nasal interpreter.
1551 // Do this last, so that the loaded scripts see initialized state
1552 ////////////////////////////////////////////////////////////////////////
1553 FGNasalSys* nasal = new FGNasalSys();
1554 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1557 // initialize methods that depend on other subsystems.
1558 globals->get_subsystem_mgr()->postinit();
1560 ////////////////////////////////////////////////////////////////////////
1561 // End of subsystem initialization.
1562 ////////////////////////////////////////////////////////////////////
1564 fgSetBool("/sim/initialized", true);
1566 SG_LOG( SG_GENERAL, SG_INFO, endl);
1568 // Save the initial state for future
1570 globals->saveInitialState();
1575 // Reset: this is what the 'reset' command (and hence, GUI) is attached to
1576 void fgReInitSubsystems()
1578 static const SGPropertyNode *master_freeze
1579 = fgGetNode("/sim/freeze/master");
1581 SG_LOG( SG_GENERAL, SG_INFO, "fgReInitSubsystems()");
1583 // setup state to begin re-init
1584 bool freeze = master_freeze->getBoolValue();
1586 fgSetBool("/sim/freeze/master", true);
1589 fgSetBool("/sim/signals/reinit", true);
1590 fgSetBool("/sim/crashed", false);
1592 // do actual re-init steps
1593 globals->get_subsystem("flight")->unbind();
1595 // reset control state, before restoring initial state; -set or config files
1596 // may specify values for flaps, trim tabs, magnetos, etc
1597 globals->get_controls()->reset_all();
1599 globals->restoreInitialState();
1601 // update our position based on current presets
1604 // Force reupdating the positions of the ai 3d models. They are used for
1605 // initializing ground level for the FDM.
1606 globals->get_subsystem("ai_model")->reinit();
1608 // Initialize the FDM
1609 globals->get_subsystem("flight")->reinit();
1611 // reset replay buffers
1612 globals->get_subsystem("replay")->reinit();
1614 // reload offsets from config defaults
1615 globals->get_viewmgr()->reinit();
1617 globals->get_subsystem("time")->reinit();
1619 // need to bind FDMshell again, since we manually unbound it above...
1620 globals->get_subsystem("flight")->bind();
1622 // setup state to end re-init
1623 fgSetBool("/sim/signals/reinit", false);
1625 fgSetBool("/sim/freeze/master", false);
1627 fgSetBool("/sim/sceneryloaded",false);
1631 ///////////////////////////////////////////////////////////////////////////////
1632 // helper object to implement the --show-aircraft command.
1633 // resides here so we can share the fgFindAircraftInDir template above,
1634 // and hence ensure this command lists exectly the same aircraft as the normal
1641 _minStatus = getNumMaturity(fgGetString("/sim/aircraft-min-status", "all"));
1645 void show(const SGPath& path)
1647 fgFindAircraftInDir(path, this, &ShowAircraft::processAircraft);
1649 std::sort(_aircraft.begin(), _aircraft.end(), ciLessLibC());
1650 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on Windows
1651 cout << "Available aircraft:" << endl;
1652 for ( unsigned int i = 0; i < _aircraft.size(); i++ ) {
1653 cout << _aircraft[i] << endl;
1658 bool processAircraft(const SGPath& path)
1660 SGPropertyNode root;
1662 readProperties(path.str(), &root);
1663 } catch (sg_exception& ) {
1668 string descStr(" ");
1669 descStr += path.file();
1670 // trim common suffix from file names
1671 int nPos = descStr.rfind("-set.xml");
1672 if (nPos == (int)(descStr.size() - 8)) {
1673 descStr.resize(nPos);
1676 SGPropertyNode *node = root.getNode("sim");
1678 SGPropertyNode* desc = node->getNode("description");
1679 // if a status tag is found, read it in
1680 if (node->hasValue("status")) {
1681 maturity = getNumMaturity(node->getStringValue("status"));
1685 if (descStr.size() <= 27+3) {
1686 descStr.append(29+3-descStr.size(), ' ');
1689 descStr.append( 32, ' ');
1691 descStr += desc->getStringValue();
1693 } // of have 'sim' node
1695 if (maturity < _minStatus) {
1699 _aircraft.push_back(descStr);
1704 int getNumMaturity(const char * str)
1706 // changes should also be reflected in $FG_ROOT/data/options.xml &
1707 // $FG_ROOT/data/Translations/string-default.xml
1708 const char* levels[] = {"alpha","beta","early-production","production"};
1710 if (!strcmp(str, "all")) {
1714 for (size_t i=0; i<(sizeof(levels)/sizeof(levels[0]));i++)
1715 if (strcmp(str,levels[i])==0)
1721 // recommended in Meyers, Effective STL when internationalization and embedded
1722 // NULLs aren't an issue. Much faster than the STL or Boost lex versions.
1723 struct ciLessLibC : public std::binary_function<string, string, bool>
1725 bool operator()(const std::string &lhs, const std::string &rhs) const
1727 return strcasecmp(lhs.c_str(), rhs.c_str()) < 0 ? 1 : 0;
1732 string_list _aircraft;
1735 void fgShowAircraft(const SGPath &path)
1741 cout << "Hit a key to continue..." << endl;