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/interpolator.hxx>
62 #include <simgear/scene/material/matlib.hxx>
63 #include <simgear/scene/model/particles.hxx>
64 #include <simgear/sound/soundmgr_openal.hxx>
66 #include <Aircraft/controls.hxx>
67 #include <Aircraft/replay.hxx>
68 #include <Airports/apt_loader.hxx>
69 #include <Airports/runways.hxx>
70 #include <Airports/simple.hxx>
71 #include <Airports/dynamics.hxx>
73 #include <AIModel/AIManager.hxx>
76 # include <ATCDCL/ATCmgr.hxx>
77 # include "ATCDCL/commlist.hxx"
79 # include "ATC/atis.hxx"
80 # include "ATC/atcutils.hxx"
83 #include <Autopilot/route_mgr.hxx>
84 #include <Autopilot/autopilotgroup.hxx>
86 #include <Cockpit/cockpit.hxx>
87 #include <Cockpit/panel.hxx>
88 #include <Cockpit/panel_io.hxx>
90 #include <GUI/new_gui.hxx>
91 #include <Include/general.hxx>
92 #include <Input/input.hxx>
93 #include <Instrumentation/instrument_mgr.hxx>
94 #include <Model/acmodel.hxx>
95 #include <AIModel/submodel.hxx>
96 #include <AIModel/AIManager.hxx>
97 #include <Navaids/navdb.hxx>
98 #include <Navaids/navlist.hxx>
99 #include <Navaids/fix.hxx>
100 #include <Navaids/fixlist.hxx>
101 #include <Scenery/scenery.hxx>
102 #include <Scenery/tilemgr.hxx>
103 #include <Scripting/NasalSys.hxx>
104 #include <Sound/voice.hxx>
105 #include <Systems/system_mgr.hxx>
106 #include <Time/light.hxx>
107 #include <Traffic/TrafficMgr.hxx>
108 #include <MultiPlayer/multiplaymgr.hxx>
109 #include <FDM/fdm_shell.hxx>
111 #include <Environment/environment_mgr.hxx>
112 #include <Environment/ridge_lift.hxx>
114 #include "fg_init.hxx"
116 #include "fg_commands.hxx"
117 #include "fg_props.hxx"
118 #include "options.hxx"
119 #include "globals.hxx"
120 #include "logger.hxx"
121 #include "renderer.hxx"
122 #include "viewmgr.hxx"
127 # include <CoreFoundation/CoreFoundation.h>
131 using namespace boost::algorithm;
133 extern const char *default_root;
136 // Scan the command line options for the specified option and return
138 static string fgScanForOption( const string& option, int argc, char **argv ) {
141 if (hostname == NULL)
144 if( gethostname(_hostname, 256) >= 0 ) {
145 hostname = strdup(_hostname);
146 free_hostname = true;
150 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
152 int len = option.length();
155 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
157 string arg = argv[i];
158 if ( arg.find( option ) == 0 ) {
159 return arg.substr( len );
169 // Scan the user config files for the specified option and return
171 static string fgScanForOption( const string& option, const string& path ) {
172 sg_gzifstream in( path );
173 if ( !in.is_open() ) {
177 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
179 int len = option.length();
182 while ( ! in.eof() ) {
184 getline( in, line, '\n' );
186 // catch extraneous (DOS) line ending character
187 if ( line[line.length() - 1] < 32 ) {
188 line = line.substr( 0, line.length()-1 );
191 if ( line.find( option ) == 0 ) {
192 return line.substr( len );
201 // Scan the user config files for the specified option and return
203 static string fgScanForOption( const string& option ) {
206 #if defined( unix ) || defined( __CYGWIN__ ) || defined(_MSC_VER)
207 // Next check home directory for .fgfsrc.hostname file
209 if ( homedir != NULL && hostname != NULL && strlen(hostname) > 0) {
210 SGPath config( homedir );
211 config.append( ".fgfsrc" );
212 config.concat( "." );
213 config.concat( hostname );
214 arg = fgScanForOption( option, config.str() );
219 // Next check home directory for .fgfsrc file
221 if ( homedir != NULL ) {
222 SGPath config( homedir );
223 config.append( ".fgfsrc" );
224 arg = fgScanForOption( option, config.str() );
229 // Check for $fg_root/system.fgfsrc
230 SGPath config( globals->get_fg_root() );
231 config.append( "system.fgfsrc" );
232 arg = fgScanForOption( option, config.str() );
239 // Read in configuration (files and command line options) but only set
240 // fg_root and aircraft_paths, which are needed *before* do_options() is called
243 bool fgInitFGRoot ( int argc, char **argv ) {
246 // First parse command line options looking for --fg-root=, this
247 // will override anything specified in a config file
248 root = fgScanForOption( "--fg-root=", argc, argv);
250 // Check in one of the user configuration files.
252 root = fgScanForOption( "--fg-root=" );
254 // Next check if fg-root is set as an env variable
255 if ( root.empty() ) {
256 char *envp = ::getenv( "FG_ROOT" );
257 if ( envp != NULL ) {
262 // Otherwise, default to a random compiled-in location if we can't
263 // find fg-root any other way.
264 if ( root.empty() ) {
265 #if defined( __CYGWIN__ )
267 #elif defined( _WIN32 )
269 #elif defined(__APPLE__)
271 The following code looks for the base package inside the application
272 bundle, in the standard Contents/Resources location.
274 CFURLRef resourcesUrl = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
276 // look for a 'data' subdir
277 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, resourcesUrl, CFSTR("data"), true);
279 // now convert down to a path, and the a c-string
280 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
281 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
283 CFRelease(resourcesUrl);
291 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
292 globals->set_fg_root(root);
298 // Read in configuration (files and command line options) but only set
300 bool fgInitFGAircraft ( int argc, char **argv ) {
302 string aircraftDir = fgScanForOption("--fg-aircraft=", argc, argv);
303 if (aircraftDir.empty()) {
304 aircraftDir = fgScanForOption("--fg-aircraft=");
307 const char* envp = ::getenv("FG_AIRCRAFT");
308 if (aircraftDir.empty() && envp) {
309 globals->append_aircraft_paths(envp);
312 if (!aircraftDir.empty()) {
313 globals->append_aircraft_paths(aircraftDir);
318 // First parse command line options looking for --aircraft=, this
319 // will override anything specified in a config file
320 aircraft = fgScanForOption( "--aircraft=", argc, argv );
321 if ( aircraft.empty() ) {
322 // check synonym option
323 aircraft = fgScanForOption( "--vehicle=", argc, argv );
326 // Check in one of the user configuration files.
327 if ( aircraft.empty() ) {
328 aircraft = fgScanForOption( "--aircraft=" );
330 if ( aircraft.empty() ) {
331 aircraft = fgScanForOption( "--vehicle=" );
334 // if an aircraft was specified, set the property name
335 if ( !aircraft.empty() ) {
336 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
337 fgSetString("/sim/aircraft", aircraft.c_str() );
339 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
346 // Return the current base package version
347 string fgBasePackageVersion() {
348 SGPath base_path( globals->get_fg_root() );
349 base_path.append("version");
351 sg_gzifstream in( base_path.str() );
352 if ( !in.is_open() ) {
353 SGPath old_path( globals->get_fg_root() );
354 old_path.append( "Thanks" );
355 sg_gzifstream old( old_path.str() );
356 if ( !old.is_open() ) {
359 return "[old version]";
370 // Initialize the localization
371 SGPropertyNode *fgInitLocale(const char *language) {
372 SGPropertyNode *c_node = NULL, *d_node = NULL;
373 SGPropertyNode *intl = fgGetNode("/sim/intl");
375 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
377 // localization not defined
382 // Select the proper language from the list
384 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
385 for (unsigned int i = 0; i < locale.size(); i++) {
387 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
388 for (unsigned int j = 0; j < lang.size(); j++) {
390 if (!strcmp(lang[j]->getStringValue(), language)) {
399 d_node = intl->getChild("locale");
403 // Check for localized font
404 SGPropertyNode *font_n = c_node->getNode("font", true);
405 if ( !strcmp(font_n->getStringValue(), "") )
406 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
410 // Load the default strings
412 SGPath d_path( globals->get_fg_root() );
414 const char *d_path_str = d_node->getStringValue("strings");
416 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << d_node->getPath() << "/strings.");
420 d_path.append(d_path_str);
421 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << d_path.str());
423 SGPropertyNode *strings = c_node->getNode("strings");
425 readProperties(d_path.str(), strings);
426 } catch (const sg_exception &) {
427 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
432 // Load the language specific strings
434 if (c_node != d_node) {
435 SGPath c_path( globals->get_fg_root() );
437 const char *c_path_str = c_node->getStringValue("strings");
439 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << c_node->getPath() << "/strings");
443 c_path.append(c_path_str);
444 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << c_path.str());
447 readProperties(c_path.str(), strings);
448 } catch (const sg_exception &) {
449 SG_LOG(SG_GENERAL, SG_ALERT,
450 "Unable to read the localized strings from " << c_path.str());
460 // Initialize the localization routines
461 bool fgDetectLanguage() {
462 const char *language = ::getenv("LANG");
464 if (language == NULL) {
465 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
469 SGPropertyNode *locale = fgInitLocale(language);
471 SG_LOG(SG_GENERAL, SG_ALERT,
472 "No internationalization settings specified in preferences.xml" );
477 globals->set_locale( locale );
482 // Attempt to locate and parse the various non-XML config files in order
483 // from least precidence to greatest precidence
485 do_options (int argc, char ** argv)
487 // Check for $fg_root/system.fgfsrc
488 SGPath config( globals->get_fg_root() );
489 config.append( "system.fgfsrc" );
490 fgParseOptions(config.str());
492 #if defined( unix ) || defined( __CYGWIN__ ) || defined(_MSC_VER)
493 if( hostname != NULL && strlen(hostname) > 0 ) {
494 config.concat( "." );
495 config.concat( hostname );
496 fgParseOptions(config.str());
500 // Check for ~/.fgfsrc
501 if ( homedir != NULL ) {
502 config.set( homedir );
503 config.append( ".fgfsrc" );
504 fgParseOptions(config.str());
507 #if defined( unix ) || defined( __CYGWIN__ ) || defined(_MSC_VER)
508 if( hostname != NULL && strlen(hostname) > 0 ) {
509 // Check for ~/.fgfsrc.hostname
510 config.concat( "." );
511 config.concat( hostname );
512 fgParseOptions(config.str());
516 // Parse remaining command line options
517 // These will override anything specified in a config file
518 fgParseArgs(argc, argv);
522 bool fgFindAircraftInDir(const SGPath& dirPath, T* obj, bool (T::*pred)(const SGPath& p))
524 if (!dirPath.exists()) {
525 SG_LOG(SG_GENERAL, SG_WARN, "fgFindAircraftInDir: no such path:" << dirPath.str());
530 simgear::Dir dir(dirPath);
531 simgear::PathList setFiles(dir.children(simgear::Dir::TYPE_FILE, "-set.xml"));
532 simgear::PathList::iterator p;
533 for (p = setFiles.begin(); p != setFiles.end(); ++p) {
534 // check file name ends with -set.xml
536 // if we found a -set.xml at this level, don't recurse any deeper
539 bool done = (obj->*pred)(*p);
543 } // of -set.xml iteration
549 simgear::PathList subdirs(dir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT));
550 for (p = subdirs.begin(); p != subdirs.end(); ++p) {
551 if (p->file() == "CVS") {
555 if (fgFindAircraftInDir(*p, obj, pred)) {
558 } // of subdirs iteration
564 void fgFindAircraft(T* obj, bool (T::*pred)(const SGPath& p))
566 const string_list& paths(globals->get_aircraft_paths());
567 string_list::const_iterator it = paths.begin();
568 for (; it != paths.end(); ++it) {
569 bool done = fgFindAircraftInDir(SGPath(*it), obj, pred);
573 } // of aircraft paths iteration
575 // if we reach this point, search the default location (always last)
576 SGPath rootAircraft(globals->get_fg_root());
577 rootAircraft.append("Aircraft");
578 fgFindAircraftInDir(rootAircraft, obj, pred);
581 class FindAndCacheAircraft
584 FindAndCacheAircraft(SGPropertyNode* autoSave)
586 _cache = autoSave->getNode("sim/startup/path-cache", true);
591 std::string aircraft = fgGetString( "/sim/aircraft", "");
592 if (aircraft.empty()) {
593 SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
597 _searchAircraft = aircraft + "-set.xml";
599 // prepare cache for re-scan
600 SGPropertyNode *n = _cache->getNode("fg-root", true);
601 n->setStringValue(globals->get_fg_root().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());
633 if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
634 return false; // cache mismatch
637 vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
638 for (unsigned int i = 0; i < cache.size(); i++) {
639 const char *name = cache[i]->getStringValue("file", "");
640 if (!boost::equals(_searchAircraft, name, is_iequal())) {
644 SGPath xml(cache[i]->getStringValue("path", ""));
652 } // of aircraft in cache iteration
657 bool checkAircraft(const SGPath& p)
662 if (!_cache->getChild("aircraft", i++, false))
666 SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
668 std::string fileName(p.file());
669 n = entry->getNode("file", true);
670 n->setStringValue(fileName);
671 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
673 n = entry->getNode("path", true);
674 n->setStringValue(p.dir());
675 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
677 if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
685 std::string _searchAircraft;
687 SGPropertyNode* _cache;
690 // Read in configuration (file and command line)
691 bool fgInitConfig ( int argc, char **argv ) {
693 // First, set some sane default values
696 // Read global preferences from $FG_ROOT/preferences.xml
697 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
698 fgLoadProps("preferences.xml", globals->get_props());
699 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
701 // Detect the required language as early as possible
702 if ( !fgDetectLanguage() ) {
706 SGPropertyNode autosave;
708 char *envp = ::getenv( "APPDATA" );
710 SGPath config( envp );
711 config.append( "flightgear.org" );
713 if ( homedir != NULL ) {
714 SGPath config( homedir );
715 config.append( ".fgfs" );
717 const char *fg_home = getenv("FG_HOME");
721 SGPath home_export(config.str());
722 home_export.append("Export/dummy");
723 home_export.create_dir(0777);
725 // Set /sim/fg-home and don't allow malign code to override it until
726 // Nasal security is set up. Use FG_HOME if necessary.
727 SGPropertyNode *home = fgGetNode("/sim", true);
728 home->removeChild("fg-home", 0, false);
729 home = home->getChild("fg-home", 0, true);
730 home->setStringValue(config.c_str());
731 home->setAttribute(SGPropertyNode::WRITE, false);
733 config.append( "autosave.xml" );
734 if (config.exists()) {
735 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << config.str());
737 readProperties(config.str(), &autosave, SGPropertyNode::USERARCHIVE);
738 } catch (sg_exception& e) {
739 SG_LOG(SG_INPUT, SG_WARN, "failed to read user settings:" << e.getMessage()
740 << "(from " << e.getOrigin() << ")");
745 // Scan user config files and command line for a specified aircraft.
746 fgInitFGAircraft(argc, argv);
747 FindAndCacheAircraft f(&autosave);
748 if (!f.loadAircraft()) {
752 copyProperties(&autosave, globals->get_props());
754 // parse options after loading aircraft to ensure any user
755 // overrides of defaults are honored.
756 do_options(argc, argv);
761 // Set current tower position lon/lat given an airport id
762 static bool fgSetTowerPosFromAirportID( const string& id) {
763 const FGAirport *a = fgFindAirportID( id);
765 SGGeod tower = a->getTowerLocation();
766 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
767 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
768 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
776 struct FGTowerLocationListener : SGPropertyChangeListener {
777 void valueChanged(SGPropertyNode* node) {
778 const string id(node->getStringValue());
779 fgSetTowerPosFromAirportID(id);
783 void fgInitTowerLocationListener() {
784 fgGetNode("/sim/tower/airport-id", true)
785 ->addChangeListener( new FGTowerLocationListener(), true );
788 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
790 SGGeod startPos(aStartPos);
791 if (aTargetHeading == HUGE_VAL) {
792 aTargetHeading = aHeading;
795 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
796 double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
797 offsetDistance *= SG_NM_TO_METER;
798 double offsetAzimuth = aHeading;
799 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
800 offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
801 aHeading = aTargetHeading;
806 SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
811 fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
812 fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
813 fgSetDouble("/sim/presets/heading-deg", aHeading );
815 // other code depends on the actual values being set ...
816 fgSetDouble("/position/longitude-deg", startPos.getLongitudeDeg() );
817 fgSetDouble("/position/latitude-deg", startPos.getLatitudeDeg() );
818 fgSetDouble("/orientation/heading-deg", aHeading );
821 // Set current_options lon/lat given an airport id and heading (degrees)
822 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
826 // set initial position from runway and heading
827 SG_LOG( SG_GENERAL, SG_INFO,
828 "Attempting to set starting position from airport code "
829 << id << " heading " << tgt_hdg );
831 const FGAirport* apt = fgFindAirportID(id);
832 if (!apt) return false;
833 FGRunway* r = apt->findBestRunwayForHeading(tgt_hdg);
834 fgSetString("/sim/atc/runway", r->ident().c_str());
836 SGGeod startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
837 fgApplyStartOffset(startPos, r->headingDeg(), tgt_hdg);
841 // Set current_options lon/lat given an airport id and parkig position name
842 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
846 // can't see an easy way around this const_cast at the moment
847 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
849 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
852 FGAirportDynamics* dcs = apt->getDynamics();
854 SG_LOG( SG_GENERAL, SG_ALERT,
855 "Failed to find parking position " << parkpos <<
856 " at airport " << id );
860 int park_index = dcs->getNrOfParkings() - 1;
861 while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
862 if (park_index < 0) {
863 SG_LOG( SG_GENERAL, SG_ALERT,
864 "Failed to find parking position " << parkpos <<
865 " at airport " << id );
868 FGParking* parking = dcs->getParking(park_index);
869 parking->setAvailable(false);
871 SGGeod::fromDeg(parking->getLongitude(), parking->getLatitude()),
872 parking->getHeading());
877 // Set current_options lon/lat given an airport id and runway number
878 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
882 // set initial position from airport and runway number
883 SG_LOG( SG_GENERAL, SG_INFO,
884 "Attempting to set starting position for "
885 << id << ":" << rwy );
887 const FGAirport* apt = fgFindAirportID(id);
889 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
893 if (!apt->hasRunwayWithIdent(rwy)) {
894 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
895 "Failed to find runway " << rwy <<
896 " at airport " << id << ". Using default runway." );
900 FGRunway* r(apt->getRunwayByIdent(rwy));
901 fgSetString("/sim/atc/runway", r->ident().c_str());
902 SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
903 fgApplyStartOffset(startPos, r->headingDeg());
908 static void fgSetDistOrAltFromGlideSlope() {
909 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
910 string apt_id = fgGetString("/sim/presets/airport-id");
911 double gs = fgGetDouble("/sim/presets/glideslope-deg")
912 * SG_DEGREES_TO_RADIANS ;
913 double od = fgGetDouble("/sim/presets/offset-distance-nm");
914 double alt = fgGetDouble("/sim/presets/altitude-ft");
916 double apt_elev = 0.0;
917 if ( ! apt_id.empty() ) {
918 apt_elev = fgGetAirportElev( apt_id );
919 if ( apt_elev < -9990.0 ) {
926 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
927 // set altitude from glideslope and offset-distance
928 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
929 alt = fabs(od*tan(gs)) + apt_elev;
930 fgSetDouble("/sim/presets/altitude-ft", alt);
931 fgSetBool("/sim/presets/onground", false);
932 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
934 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
935 // set offset-distance from glideslope and altitude
936 od = (alt - apt_elev) / tan(gs);
937 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
938 fgSetDouble("/sim/presets/offset-distance-nm", od);
939 fgSetBool("/sim/presets/onground", false);
940 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
942 } else if( fabs(gs) > 0.01 ) {
943 SG_LOG( SG_GENERAL, SG_ALERT,
944 "Glideslope given but not altitude or offset-distance." );
945 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
946 fgSetDouble("/sim/presets/glideslope-deg", 0);
947 fgSetBool("/sim/presets/onground", true);
952 // Set current_options lon/lat given an airport id and heading (degrees)
953 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
955 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
958 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
959 << id << ":" << freq );
963 fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
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.getLongitudeDeg();
976 double lat = geodPos.getLatitudeDeg();
977 double alt = geodPos.getElevationFt();
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 )
1013 FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
1014 FGPositioned* fix = FGPositioned::findNextWithPartialId(NULL, id, &fixFilter);
1016 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
1020 fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
1025 * Initialize vor/ndb/ils/fix list management and query systems (as
1026 * well as simple airport db list)
1031 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
1033 SGPath aptdb( globals->get_fg_root() );
1034 aptdb.append( "Airports/apt.dat" );
1036 SGPath p_metar( globals->get_fg_root() );
1037 p_metar.append( "Airports/metar.dat" );
1039 // Initialise the frequency search map BEFORE reading
1040 // the airport database:
1044 current_commlist = new FGCommList;
1045 current_commlist->init( globals->get_fg_root() );
1046 fgAirportDBLoad( aptdb.str(), current_commlist, p_metar.str() );
1048 FGNavList *navlist = new FGNavList;
1049 FGNavList *loclist = new FGNavList;
1050 FGNavList *gslist = new FGNavList;
1051 FGNavList *dmelist = new FGNavList;
1052 FGNavList *tacanlist = new FGNavList;
1053 FGNavList *carrierlist = new FGNavList;
1054 FGTACANList *channellist = new FGTACANList;
1056 globals->set_navlist( navlist );
1057 globals->set_loclist( loclist );
1058 globals->set_gslist( gslist );
1059 globals->set_dmelist( dmelist );
1060 globals->set_tacanlist( tacanlist );
1061 globals->set_carrierlist( carrierlist );
1062 globals->set_channellist( channellist );
1064 if ( !fgNavDBInit(navlist, loclist, gslist, dmelist, tacanlist, carrierlist, channellist) ) {
1065 SG_LOG( SG_GENERAL, SG_ALERT,
1066 "Problems loading one or more navigational database" );
1069 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1070 SGPath p_fix( globals->get_fg_root() );
1071 p_fix.append( "Navaids/fix.dat" );
1073 fixlist.init( p_fix ); // adds fixes to the DB in positioned.cxx
1075 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
1076 SGPath p_awy( globals->get_fg_root() );
1077 p_awy.append( "Navaids/awy.dat" );
1078 FGAirwayNetwork *awyNet = new FGAirwayNetwork;
1079 //cerr << "Loading Airways" << endl;
1080 awyNet->load (p_awy );
1082 //cerr << "initializing airways" << endl;
1083 globals->set_airwaynet( awyNet );
1089 // Set the initial position based on presets (or defaults)
1090 bool fgInitPosition() {
1091 // cout << "fgInitPosition()" << endl;
1092 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1093 * SG_DEGREES_TO_RADIANS ;
1094 double od = fgGetDouble("/sim/presets/offset-distance-nm");
1095 double alt = fgGetDouble("/sim/presets/altitude-ft");
1097 bool set_pos = false;
1099 // If glideslope is specified, then calculate offset-distance or
1100 // altitude relative to glide slope if either of those was not
1102 if ( fabs( gs ) > 0.01 ) {
1103 fgSetDistOrAltFromGlideSlope();
1107 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1108 // If not, check for an airport-id and use that.
1109 // If not, default to the middle of the KSFO field.
1110 // The default values for lon/lat are deliberately out of range
1111 // so that the airport-id can take effect; valid lon/lat will
1112 // override airport-id, however.
1113 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1114 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1115 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1116 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1121 string apt = fgGetString("/sim/presets/airport-id");
1122 string rwy_no = fgGetString("/sim/presets/runway");
1123 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1124 string vor = fgGetString("/sim/presets/vor-id");
1125 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1126 string ndb = fgGetString("/sim/presets/ndb-id");
1127 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1128 string carrier = fgGetString("/sim/presets/carrier");
1129 string parkpos = fgGetString("/sim/presets/parkpos");
1130 string fix = fgGetString("/sim/presets/fix");
1131 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1132 double hdg = hdg_preset->getDoubleValue();
1134 // save some start parameters, so that we can later say what the
1135 // user really requested. TODO generalize that and move it to options.cxx
1136 static bool start_options_saved = false;
1137 if (!start_options_saved) {
1138 start_options_saved = true;
1139 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1141 opt->setDoubleValue("latitude-deg", lat_deg);
1142 opt->setDoubleValue("longitude-deg", lon_deg);
1143 opt->setDoubleValue("heading-deg", hdg);
1144 opt->setStringValue("airport", apt.c_str());
1145 opt->setStringValue("runway", rwy_no.c_str());
1149 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1151 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1152 // An airport + parking position is requested
1153 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1154 // set tower position
1155 fgSetString("/sim/tower/airport-id", apt.c_str());
1160 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1161 // An airport + runway is requested
1162 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1163 // set tower position (a little off the heading for single
1165 fgSetString("/sim/tower/airport-id", apt.c_str());
1170 if ( !set_pos && !apt.empty() ) {
1171 // An airport is requested (find runway closest to hdg)
1172 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1173 // set tower position (a little off the heading for single
1175 fgSetString("/sim/tower/airport-id", apt.c_str());
1180 if (hdg_preset->getDoubleValue() > 9990.0)
1181 hdg_preset->setDoubleValue(hdg);
1183 if ( !set_pos && !vor.empty() ) {
1184 // a VOR is requested
1185 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1190 if ( !set_pos && !ndb.empty() ) {
1191 // an NDB is requested
1192 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1197 if ( !set_pos && !carrier.empty() ) {
1198 // an aircraft carrier is requested
1199 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1204 if ( !set_pos && !fix.empty() ) {
1205 // a Fix is requested
1206 if ( fgSetPosFromFix( fix ) ) {
1212 // No lon/lat specified, no airport specified, default to
1213 // middle of KSFO field.
1214 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1215 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1218 fgSetDouble( "/position/longitude-deg",
1219 fgGetDouble("/sim/presets/longitude-deg") );
1220 fgSetDouble( "/position/latitude-deg",
1221 fgGetDouble("/sim/presets/latitude-deg") );
1222 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1224 // determine if this should be an on-ground or in-air start
1225 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1226 fgSetBool("/sim/presets/onground", false);
1228 fgSetBool("/sim/presets/onground", true);
1235 // General house keeping initializations
1236 bool fgInitGeneral() {
1239 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1240 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1242 root = globals->get_fg_root();
1243 if ( ! root.length() ) {
1244 // No root path set? Then bail ...
1245 SG_LOG( SG_GENERAL, SG_ALERT,
1246 "Cannot continue without a path to the base package "
1247 << "being defined." );
1250 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1252 globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1254 char buf[512], *cwd = getcwd(buf, 511);
1256 SGPropertyNode *curr = fgGetNode("/sim", true);
1257 curr->removeChild("fg-current", 0, false);
1258 curr = curr->getChild("fg-current", 0, true);
1259 curr->setStringValue(cwd ? cwd : "");
1260 curr->setAttribute(SGPropertyNode::WRITE, false);
1262 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1));
1263 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2));
1267 // Initialize view parameters
1269 // force update of model so that viewer can get some data...
1270 globals->get_aircraft_model()->update(0);
1271 // run update for current view so that data is current...
1272 globals->get_viewmgr()->update(0);
1275 // This is the top level init routine which calls all the other
1276 // initialization routines. If you are adding a subsystem to flight
1277 // gear, its initialization call should located in this routine.
1278 // Returns non-zero if a problem encountered.
1279 bool fgInitSubsystems() {
1280 // static const SGPropertyNode *longitude
1281 // = fgGetNode("/sim/presets/longitude-deg");
1282 // static const SGPropertyNode *latitude
1283 // = fgGetNode("/sim/presets/latitude-deg");
1284 // static const SGPropertyNode *altitude
1285 // = fgGetNode("/sim/presets/altitude-ft");
1287 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1288 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1290 ////////////////////////////////////////////////////////////////////
1291 // Initialize the event manager subsystem.
1292 ////////////////////////////////////////////////////////////////////
1294 globals->get_event_mgr()->init();
1295 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1297 ////////////////////////////////////////////////////////////////////
1298 // Initialize the property interpolator subsystem. Put into the INIT
1299 // group because the "nasal" subsystem may need it at GENERAL take-down.
1300 ////////////////////////////////////////////////////////////////////
1301 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1304 ////////////////////////////////////////////////////////////////////
1305 // Add the FlightGear property utilities.
1306 ////////////////////////////////////////////////////////////////////
1307 globals->add_subsystem("properties", new FGProperties);
1309 ////////////////////////////////////////////////////////////////////
1310 // Initialize the material property subsystem.
1311 ////////////////////////////////////////////////////////////////////
1313 SGPath mpath( globals->get_fg_root() );
1314 mpath.append( "materials.xml" );
1315 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
1316 globals->get_props()) ) {
1317 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1322 ////////////////////////////////////////////////////////////////////
1323 // Initialize the scenery management subsystem.
1324 ////////////////////////////////////////////////////////////////////
1326 if ( globals->get_tile_mgr()->init() ) {
1327 // Load the local scenery data
1328 double visibility_meters = fgGetDouble("/environment/visibility-m");
1329 globals->get_tile_mgr()->update( visibility_meters );
1331 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1335 globals->get_scenery()->get_scene_graph()
1336 ->addChild(simgear::Particles::getCommonRoot());
1337 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
1339 ////////////////////////////////////////////////////////////////////
1340 // Initialize the flight model subsystem.
1341 ////////////////////////////////////////////////////////////////////
1343 globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
1345 ////////////////////////////////////////////////////////////////////
1346 // Initialize the weather subsystem.
1347 ////////////////////////////////////////////////////////////////////
1349 // Initialize the weather modeling subsystem
1350 globals->add_subsystem("environment", new FGEnvironmentMgr);
1352 ////////////////////////////////////////////////////////////////////
1353 // Initialize the ridge lift simulation.
1354 ////////////////////////////////////////////////////////////////////
1356 // Initialize the ridgelift subsystem
1357 globals->add_subsystem("ridgelift", new FGRidgeLift);
1359 ////////////////////////////////////////////////////////////////////
1360 // Initialize the aircraft systems and instrumentation (before the
1362 ////////////////////////////////////////////////////////////////////
1364 globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
1365 globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
1367 ////////////////////////////////////////////////////////////////////
1368 // Initialize the XML Autopilot subsystem.
1369 ////////////////////////////////////////////////////////////////////
1371 globals->add_subsystem( "xml-autopilot", new FGXMLAutopilotGroup, SGSubsystemMgr::FDM );
1372 globals->add_subsystem( "route-manager", new FGRouteMgr );
1374 ////////////////////////////////////////////////////////////////////
1375 // Initialize the view manager subsystem.
1376 ////////////////////////////////////////////////////////////////////
1380 ////////////////////////////////////////////////////////////////////
1381 // Initialize the Input-Output subsystem
1382 ////////////////////////////////////////////////////////////////////
1383 globals->add_subsystem( "io", new FGIO );
1385 ////////////////////////////////////////////////////////////////////
1386 // Create and register the logger.
1387 ////////////////////////////////////////////////////////////////////
1389 globals->add_subsystem("logger", new FGLogger);
1391 ////////////////////////////////////////////////////////////////////
1392 // Create and register the XML GUI.
1393 ////////////////////////////////////////////////////////////////////
1395 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1397 ////////////////////////////////////////////////////////////////////
1398 // Initialize the lighting subsystem.
1399 ////////////////////////////////////////////////////////////////////
1401 globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
1403 //////////////////////////////////////////////////////////////////////
1404 // Initialize the 2D cloud subsystem.
1405 ////////////////////////////////////////////////////////////////////
1406 fgGetBool("/sim/rendering/bump-mapping", false);
1408 #ifdef ENABLE_AUDIO_SUPPORT
1409 ////////////////////////////////////////////////////////////////////
1410 // Initialize the sound-effects subsystem.
1411 ////////////////////////////////////////////////////////////////////
1412 globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
1415 ////////////////////////////////////////////////////////////////////
1416 // Initialise the ATC Manager
1417 ////////////////////////////////////////////////////////////////////
1420 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1421 globals->set_ATC_mgr(new FGATCMgr);
1422 globals->get_ATC_mgr()->init();
1424 ////////////////////////////////////////////////////////////////////
1425 // Initialise the ATIS Manager
1426 ////////////////////////////////////////////////////////////////////
1427 globals->add_subsystem("atis", new FGAtisManager, SGSubsystemMgr::POST_FDM);
1429 ////////////////////////////////////////////////////////////////////
1430 // Initialise the AI Model Manager
1431 ////////////////////////////////////////////////////////////////////
1432 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1433 globals->add_subsystem("ai_model", new FGAIManager, SGSubsystemMgr::POST_FDM);
1434 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
1437 // It's probably a good idea to initialize the top level traffic manager
1438 // After the AI and ATC systems have been initialized properly.
1439 // AI Traffic manager
1440 globals->add_subsystem("Traffic Manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
1443 if( fgCockpitInit()) {
1444 // Cockpit initialized ok.
1446 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1451 ////////////////////////////////////////////////////////////////////
1452 // Add a new 2D panel.
1453 ////////////////////////////////////////////////////////////////////
1455 string panel_path = fgGetString("/sim/panel/path",
1456 "Panels/Default/default.xml");
1458 globals->set_current_panel( fgReadPanel(panel_path) );
1459 if (globals->get_current_panel() == 0) {
1460 SG_LOG( SG_INPUT, SG_ALERT,
1461 "Error reading new panel from " << panel_path );
1463 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1464 globals->get_current_panel()->init();
1465 globals->get_current_panel()->bind();
1469 ////////////////////////////////////////////////////////////////////
1470 // Initialize the controls subsystem.
1471 ////////////////////////////////////////////////////////////////////
1473 globals->get_controls()->init();
1474 globals->get_controls()->bind();
1477 ////////////////////////////////////////////////////////////////////
1478 // Initialize the input subsystem.
1479 ////////////////////////////////////////////////////////////////////
1481 globals->add_subsystem("input", new FGInput);
1484 ////////////////////////////////////////////////////////////////////
1485 // Initialize the replay subsystem
1486 ////////////////////////////////////////////////////////////////////
1487 globals->add_subsystem("replay", new FGReplay);
1490 ////////////////////////////////////////////////////////////////////
1491 // Bind and initialize subsystems.
1492 ////////////////////////////////////////////////////////////////////
1494 globals->get_subsystem_mgr()->bind();
1495 globals->get_subsystem_mgr()->init();
1497 ////////////////////////////////////////////////////////////////////
1498 // Initialize multiplayer subsystem
1499 ////////////////////////////////////////////////////////////////////
1501 globals->set_multiplayer_mgr(new FGMultiplayMgr);
1502 globals->get_multiplayer_mgr()->init();
1504 ////////////////////////////////////////////////////////////////////////
1505 // Initialize the Nasal interpreter.
1506 // Do this last, so that the loaded scripts see initialized state
1507 ////////////////////////////////////////////////////////////////////////
1508 FGNasalSys* nasal = new FGNasalSys();
1509 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1512 // initialize methods that depend on other subsystems.
1513 globals->get_subsystem_mgr()->postinit();
1515 ////////////////////////////////////////////////////////////////////////
1516 // End of subsystem initialization.
1517 ////////////////////////////////////////////////////////////////////
1519 SG_LOG( SG_GENERAL, SG_INFO, endl);
1521 // Save the initial state for future
1523 globals->saveInitialState();
1529 void fgReInitSubsystems()
1531 // static const SGPropertyNode *longitude
1532 // = fgGetNode("/sim/presets/longitude-deg");
1533 // static const SGPropertyNode *latitude
1534 // = fgGetNode("/sim/presets/latitude-deg");
1535 static const SGPropertyNode *altitude
1536 = fgGetNode("/sim/presets/altitude-ft");
1537 static const SGPropertyNode *master_freeze
1538 = fgGetNode("/sim/freeze/master");
1540 SG_LOG( SG_GENERAL, SG_INFO,
1541 "fgReInitSubsystems(): /position/altitude = "
1542 << altitude->getDoubleValue() );
1544 bool freeze = master_freeze->getBoolValue();
1546 fgSetBool("/sim/freeze/master", true);
1548 fgSetBool("/sim/crashed", false);
1550 // Force reupdating the positions of the ai 3d models. They are used for
1551 // initializing ground level for the FDM.
1552 globals->get_subsystem("ai_model")->reinit();
1554 // Initialize the FDM
1555 globals->get_subsystem("flight")->reinit();
1557 // reload offsets from config defaults
1558 globals->get_viewmgr()->reinit();
1562 globals->get_controls()->reset_all();
1564 globals->get_subsystem("time")->reinit();
1567 fgSetBool("/sim/freeze/master", false);
1569 fgSetBool("/sim/sceneryloaded",false);
1573 void doSimulatorReset(void) // from gui_local.cxx -- TODO merge with fgReInitSubsystems()
1575 static SGPropertyNode_ptr master_freeze = fgGetNode("/sim/freeze/master", true);
1577 bool freeze = master_freeze->getBoolValue();
1579 master_freeze->setBoolValue(true);
1581 fgSetBool("/sim/signals/reinit", true);
1583 globals->get_subsystem("flight")->unbind();
1585 globals->restoreInitialState();
1587 // update our position based on current presets
1590 fgReInitSubsystems();
1592 globals->get_tile_mgr()->update(fgGetDouble("/environment/visibility-m"));
1593 fgSetBool("/sim/signals/reinit", false);
1596 master_freeze->setBoolValue(false);
1599 ///////////////////////////////////////////////////////////////////////////////
1600 // helper object to implement the --show-aircraft command.
1601 // resides here so we can share the fgFindAircraftInDir template above,
1602 // and hence ensure this command lists exectly the same aircraft as the normal
1609 _minStatus = getNumMaturity(fgGetString("/sim/aircraft-min-status", "all"));
1613 void show(const SGPath& path)
1615 fgFindAircraftInDir(path, this, &ShowAircraft::processAircraft);
1617 std::sort(_aircraft.begin(), _aircraft.end(), ciLessLibC());
1618 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on Windows
1619 cout << "Available aircraft:" << endl;
1620 for ( unsigned int i = 0; i < _aircraft.size(); i++ ) {
1621 cout << _aircraft[i] << endl;
1626 bool processAircraft(const SGPath& path)
1628 SGPropertyNode root;
1630 readProperties(path.str(), &root);
1631 } catch (sg_exception& ) {
1636 string descStr(" ");
1637 descStr += path.file();
1638 // trim common suffix from file names
1639 int nPos = descStr.rfind("-set.xml");
1640 if (nPos == (int)(descStr.size() - 8)) {
1641 descStr.resize(nPos);
1644 SGPropertyNode *node = root.getNode("sim");
1646 SGPropertyNode* desc = node->getNode("description");
1647 // if a status tag is found, read it in
1648 if (node->hasValue("status")) {
1649 maturity = getNumMaturity(node->getStringValue("status"));
1653 if (descStr.size() <= 27+3) {
1654 descStr.append(29+3-descStr.size(), ' ');
1657 descStr.append( 32, ' ');
1659 descStr += desc->getStringValue();
1661 } // of have 'sim' node
1663 if (maturity < _minStatus) {
1667 _aircraft.push_back(descStr);
1672 int getNumMaturity(const char * str)
1674 // changes should also be reflected in $FG_ROOT/data/options.xml &
1675 // $FG_ROOT/data/Translations/string-default.xml
1676 const char* levels[] = {"alpha","beta","early-production","production"};
1678 if (!strcmp(str, "all")) {
1682 for (size_t i=0; i<(sizeof(levels)/sizeof(levels[0]));i++)
1683 if (strcmp(str,levels[i])==0)
1689 // recommended in Meyers, Effective STL when internationalization and embedded
1690 // NULLs aren't an issue. Much faster than the STL or Boost lex versions.
1691 struct ciLessLibC : public std::binary_function<string, string, bool>
1693 bool operator()(const std::string &lhs, const std::string &rhs) const
1695 return strcasecmp(lhs.c_str(), rhs.c_str()) < 0 ? 1 : 0;
1700 string_list _aircraft;
1703 void fgShowAircraft(const SGPath &path)
1709 cout << "Hit a key to continue..." << endl;