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>
63 #include <simgear/misc/interpolator.hxx>
64 #include <simgear/scene/material/matlib.hxx>
65 #include <simgear/scene/model/particles.hxx>
66 #include <simgear/sound/soundmgr_openal.hxx>
68 #include <Aircraft/controls.hxx>
69 #include <Aircraft/replay.hxx>
70 #include <Airports/apt_loader.hxx>
71 #include <Airports/runways.hxx>
72 #include <Airports/simple.hxx>
73 #include <Airports/dynamics.hxx>
75 #include <AIModel/AIManager.hxx>
77 #include <ATCDCL/ATCmgr.hxx>
79 #include <Autopilot/route_mgr.hxx>
80 #include <Autopilot/autopilotgroup.hxx>
82 #include <Cockpit/panel.hxx>
83 #include <Cockpit/panel_io.hxx>
85 #include <GUI/new_gui.hxx>
86 #include <Input/input.hxx>
87 #include <Instrumentation/instrument_mgr.hxx>
88 #include <Model/acmodel.hxx>
89 #include <Model/modelmgr.hxx>
90 #include <AIModel/submodel.hxx>
91 #include <AIModel/AIManager.hxx>
92 #include <Navaids/navdb.hxx>
93 #include <Navaids/navlist.hxx>
94 #include <Navaids/fix.hxx>
95 #include <Navaids/fixlist.hxx>
96 #include <Navaids/airways.hxx>
97 #include <Scenery/scenery.hxx>
98 #include <Scenery/tilemgr.hxx>
99 #include <Scripting/NasalSys.hxx>
100 #include <Sound/voice.hxx>
101 #include <Systems/system_mgr.hxx>
102 #include <Time/light.hxx>
103 #include <Traffic/TrafficMgr.hxx>
104 #include <MultiPlayer/multiplaymgr.hxx>
105 #include <FDM/fdm_shell.hxx>
107 #include <Environment/environment_mgr.hxx>
109 #include "fg_init.hxx"
111 #include "fg_commands.hxx"
112 #include "fg_props.hxx"
113 #include "options.hxx"
114 #include "globals.hxx"
115 #include "logger.hxx"
116 #include "renderer.hxx"
117 #include "viewmgr.hxx"
122 # include <CoreFoundation/CoreFoundation.h>
126 using namespace boost::algorithm;
128 extern const char *default_root;
131 // Scan the command line options for the specified option and return
133 static string fgScanForOption( const string& option, int argc, char **argv ) {
136 if (hostname == NULL)
139 if( gethostname(_hostname, 256) >= 0 ) {
140 hostname = strdup(_hostname);
141 free_hostname = true;
145 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
147 int len = option.length();
150 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
152 string arg = argv[i];
153 if ( arg.find( option ) == 0 ) {
154 return arg.substr( len );
164 // Scan the user config files for the specified option and return
166 static string fgScanForOption( const string& option, const string& path ) {
167 sg_gzifstream in( path );
168 if ( !in.is_open() ) {
172 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
174 int len = option.length();
177 while ( ! in.eof() ) {
179 getline( in, line, '\n' );
181 // catch extraneous (DOS) line ending character
182 if ( line[line.length() - 1] < 32 ) {
183 line = line.substr( 0, line.length()-1 );
186 if ( line.find( option ) == 0 ) {
187 return line.substr( len );
196 // Scan the user config files for the specified option and return
198 static string fgScanForOption( const string& option ) {
201 #if defined( unix ) || defined( __CYGWIN__ ) || defined(_MSC_VER)
202 // Next check home directory for .fgfsrc.hostname file
204 if ( homedir != NULL && hostname != NULL && strlen(hostname) > 0) {
205 SGPath config( homedir );
206 config.append( ".fgfsrc" );
207 config.concat( "." );
208 config.concat( hostname );
209 arg = fgScanForOption( option, config.str() );
214 // Next check home directory for .fgfsrc file
216 if ( homedir != NULL ) {
217 SGPath config( homedir );
218 config.append( ".fgfsrc" );
219 arg = fgScanForOption( option, config.str() );
224 // Check for $fg_root/system.fgfsrc
225 SGPath config( globals->get_fg_root() );
226 config.append( "system.fgfsrc" );
227 arg = fgScanForOption( option, config.str() );
234 // Read in configuration (files and command line options) but only set
235 // fg_root and aircraft_paths, which are needed *before* do_options() is called
238 bool fgInitFGRoot ( int argc, char **argv ) {
241 // First parse command line options looking for --fg-root=, this
242 // will override anything specified in a config file
243 root = fgScanForOption( "--fg-root=", argc, argv);
245 // Check in one of the user configuration files.
247 root = fgScanForOption( "--fg-root=" );
249 // Next check if fg-root is set as an env variable
250 if ( root.empty() ) {
251 char *envp = ::getenv( "FG_ROOT" );
252 if ( envp != NULL ) {
257 // Otherwise, default to a random compiled-in location if we can't
258 // find fg-root any other way.
259 if ( root.empty() ) {
260 #if defined( __CYGWIN__ )
262 #elif defined( _WIN32 )
264 #elif defined(__APPLE__)
266 The following code looks for the base package inside the application
267 bundle, in the standard Contents/Resources location.
269 CFURLRef resourcesUrl = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
271 // look for a 'data' subdir
272 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, resourcesUrl, CFSTR("data"), true);
274 // now convert down to a path, and the a c-string
275 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
276 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
278 CFRelease(resourcesUrl);
286 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
287 globals->set_fg_root(root);
293 // Read in configuration (files and command line options) but only set
295 bool fgInitFGAircraft ( int argc, char **argv ) {
297 string aircraftDir = fgScanForOption("--fg-aircraft=", argc, argv);
298 if (aircraftDir.empty()) {
299 aircraftDir = fgScanForOption("--fg-aircraft=");
302 const char* envp = ::getenv("FG_AIRCRAFT");
303 if (aircraftDir.empty() && envp) {
304 globals->append_aircraft_paths(envp);
307 if (!aircraftDir.empty()) {
308 globals->append_aircraft_paths(aircraftDir);
313 // First parse command line options looking for --aircraft=, this
314 // will override anything specified in a config file
315 aircraft = fgScanForOption( "--aircraft=", argc, argv );
316 if ( aircraft.empty() ) {
317 // check synonym option
318 aircraft = fgScanForOption( "--vehicle=", argc, argv );
321 // Check in one of the user configuration files.
322 if ( aircraft.empty() ) {
323 aircraft = fgScanForOption( "--aircraft=" );
325 if ( aircraft.empty() ) {
326 aircraft = fgScanForOption( "--vehicle=" );
329 // if an aircraft was specified, set the property name
330 if ( !aircraft.empty() ) {
331 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
332 fgSetString("/sim/aircraft", aircraft.c_str() );
334 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
341 // Return the current base package version
342 string fgBasePackageVersion() {
343 SGPath base_path( globals->get_fg_root() );
344 base_path.append("version");
346 sg_gzifstream in( base_path.str() );
347 if ( !in.is_open() ) {
348 SGPath old_path( globals->get_fg_root() );
349 old_path.append( "Thanks" );
350 sg_gzifstream old( old_path.str() );
351 if ( !old.is_open() ) {
354 return "[old version]";
365 // Initialize the localization
366 SGPropertyNode *fgInitLocale(const char *language) {
367 SGPropertyNode *c_node = NULL, *d_node = NULL;
368 SGPropertyNode *intl = fgGetNode("/sim/intl");
370 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
372 // localization not defined
377 // Select the proper language from the list
379 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
380 for (unsigned int i = 0; i < locale.size(); i++) {
382 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
383 for (unsigned int j = 0; j < lang.size(); j++) {
385 if (!strcmp(lang[j]->getStringValue(), language)) {
394 d_node = intl->getChild("locale");
398 // Check for localized font
399 SGPropertyNode *font_n = c_node->getNode("font", true);
400 if ( !strcmp(font_n->getStringValue(), "") )
401 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
405 // Load the default strings
407 SGPath d_path( globals->get_fg_root() );
409 const char *d_path_str = d_node->getStringValue("strings");
411 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << d_node->getPath() << "/strings.");
415 d_path.append(d_path_str);
416 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << d_path.str());
418 SGPropertyNode *strings = c_node->getNode("strings");
420 readProperties(d_path.str(), strings);
421 } catch (const sg_exception &) {
422 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
427 // Load the language specific strings
429 if (c_node != d_node) {
430 SGPath c_path( globals->get_fg_root() );
432 const char *c_path_str = c_node->getStringValue("strings");
434 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << c_node->getPath() << "/strings");
438 c_path.append(c_path_str);
439 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << c_path.str());
442 readProperties(c_path.str(), strings);
443 } catch (const sg_exception &) {
444 SG_LOG(SG_GENERAL, SG_ALERT,
445 "Unable to read the localized strings from " << c_path.str());
455 // Initialize the localization routines
456 bool fgDetectLanguage() {
457 const char *language = ::getenv("LANG");
459 if (language == NULL) {
460 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
464 SGPropertyNode *locale = fgInitLocale(language);
466 SG_LOG(SG_GENERAL, SG_ALERT,
467 "No internationalization settings specified in preferences.xml" );
472 globals->set_locale( locale );
477 // Attempt to locate and parse the various non-XML config files in order
478 // from least precidence to greatest precidence
480 do_options (int argc, char ** argv)
482 // Check for $fg_root/system.fgfsrc
483 SGPath config( globals->get_fg_root() );
484 config.append( "system.fgfsrc" );
485 fgParseOptions(config.str());
487 #if defined( unix ) || defined( __CYGWIN__ ) || defined(_MSC_VER)
488 if( hostname != NULL && strlen(hostname) > 0 ) {
489 config.concat( "." );
490 config.concat( hostname );
491 fgParseOptions(config.str());
495 // Check for ~/.fgfsrc
496 if ( homedir != NULL ) {
497 config.set( homedir );
498 config.append( ".fgfsrc" );
499 fgParseOptions(config.str());
502 #if defined( unix ) || defined( __CYGWIN__ ) || defined(_MSC_VER)
503 if( hostname != NULL && strlen(hostname) > 0 ) {
504 // Check for ~/.fgfsrc.hostname
505 config.concat( "." );
506 config.concat( hostname );
507 fgParseOptions(config.str());
511 // Parse remaining command line options
512 // These will override anything specified in a config file
513 fgParseArgs(argc, argv);
517 bool fgFindAircraftInDir(const SGPath& dirPath, T* obj, bool (T::*pred)(const SGPath& p))
519 if (!dirPath.exists()) {
520 SG_LOG(SG_GENERAL, SG_WARN, "fgFindAircraftInDir: no such path:" << dirPath.str());
525 simgear::Dir dir(dirPath);
526 simgear::PathList setFiles(dir.children(simgear::Dir::TYPE_FILE, "-set.xml"));
527 simgear::PathList::iterator p;
528 for (p = setFiles.begin(); p != setFiles.end(); ++p) {
529 // check file name ends with -set.xml
531 // if we found a -set.xml at this level, don't recurse any deeper
534 bool done = (obj->*pred)(*p);
538 } // of -set.xml iteration
544 simgear::PathList subdirs(dir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT));
545 for (p = subdirs.begin(); p != subdirs.end(); ++p) {
546 if (p->file() == "CVS") {
550 if (fgFindAircraftInDir(*p, obj, pred)) {
553 } // of subdirs iteration
559 void fgFindAircraft(T* obj, bool (T::*pred)(const SGPath& p))
561 const string_list& paths(globals->get_aircraft_paths());
562 string_list::const_iterator it = paths.begin();
563 for (; it != paths.end(); ++it) {
564 bool done = fgFindAircraftInDir(SGPath(*it), obj, pred);
568 } // of aircraft paths iteration
570 // if we reach this point, search the default location (always last)
571 SGPath rootAircraft(globals->get_fg_root());
572 rootAircraft.append("Aircraft");
573 fgFindAircraftInDir(rootAircraft, obj, pred);
576 class FindAndCacheAircraft
579 FindAndCacheAircraft(SGPropertyNode* autoSave)
581 _cache = autoSave->getNode("sim/startup/path-cache", true);
586 std::string aircraft = fgGetString( "/sim/aircraft", "");
587 if (aircraft.empty()) {
588 SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
592 _searchAircraft = aircraft + "-set.xml";
594 // prepare cache for re-scan
595 SGPropertyNode *n = _cache->getNode("fg-root", true);
596 n->setStringValue(globals->get_fg_root().c_str());
597 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
598 n = _cache->getNode("fg-aircraft", true);
599 n->setStringValue(getAircraftPaths().c_str());
600 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
601 _cache->removeChildren("aircraft");
603 fgFindAircraft(this, &FindAndCacheAircraft::checkAircraft);
606 if (_foundPath.str().empty()) {
607 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
611 SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
612 fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
613 if (!_foundPath.exists()) {
614 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
619 readProperties(_foundPath.str(), globals->get_props());
620 } catch ( const sg_exception &e ) {
621 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
629 SGPath getAircraftPaths() {
630 string_list pathList = globals->get_aircraft_paths();
631 SGPath aircraftPaths;
632 string_list::const_iterator it = pathList.begin();
633 if (it != pathList.end()) {
634 aircraftPaths.set(*it);
637 for (; it != pathList.end(); ++it) {
638 aircraftPaths.add(*it);
640 return aircraftPaths;
645 if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
646 return false; // cache mismatch
649 if (getAircraftPaths().str() != _cache->getStringValue("fg-aircraft", "")) {
650 return false; // cache mismatch
653 vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
654 for (unsigned int i = 0; i < cache.size(); i++) {
655 const char *name = cache[i]->getStringValue("file", "");
656 if (!boost::equals(_searchAircraft, name, is_iequal())) {
660 SGPath xml(cache[i]->getStringValue("path", ""));
668 } // of aircraft in cache iteration
673 bool checkAircraft(const SGPath& p)
678 if (!_cache->getChild("aircraft", i++, false))
682 SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
684 std::string fileName(p.file());
685 n = entry->getNode("file", true);
686 n->setStringValue(fileName);
687 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
689 n = entry->getNode("path", true);
690 n->setStringValue(p.dir());
691 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
693 if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
701 std::string _searchAircraft;
703 SGPropertyNode* _cache;
706 // Read in configuration (file and command line)
707 bool fgInitConfig ( int argc, char **argv ) {
709 // First, set some sane default values
712 // Read global preferences from $FG_ROOT/preferences.xml
713 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
714 fgLoadProps("preferences.xml", globals->get_props());
715 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
717 // Detect the required language as early as possible
718 if ( !fgDetectLanguage() ) {
722 SGPropertyNode autosave;
724 char *envp = ::getenv( "APPDATA" );
726 SGPath config( envp );
727 config.append( "flightgear.org" );
729 if ( homedir != NULL ) {
730 SGPath config( homedir );
731 config.append( ".fgfs" );
733 const char *fg_home = getenv("FG_HOME");
737 SGPath home_export(config.str());
738 home_export.append("Export/dummy");
739 home_export.create_dir(0777);
741 // Set /sim/fg-home and don't allow malign code to override it until
742 // Nasal security is set up. Use FG_HOME if necessary.
743 SGPropertyNode *home = fgGetNode("/sim", true);
744 home->removeChild("fg-home", 0, false);
745 home = home->getChild("fg-home", 0, true);
746 home->setStringValue(config.c_str());
747 home->setAttribute(SGPropertyNode::WRITE, false);
749 config.append( "autosave.xml" );
750 if (config.exists()) {
751 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << config.str());
753 readProperties(config.str(), &autosave, SGPropertyNode::USERARCHIVE);
754 } catch (sg_exception& e) {
755 SG_LOG(SG_INPUT, SG_WARN, "failed to read user settings:" << e.getMessage()
756 << "(from " << e.getOrigin() << ")");
761 // Scan user config files and command line for a specified aircraft.
762 fgInitFGAircraft(argc, argv);
763 FindAndCacheAircraft f(&autosave);
764 if (!f.loadAircraft()) {
768 copyProperties(&autosave, globals->get_props());
770 // parse options after loading aircraft to ensure any user
771 // overrides of defaults are honored.
772 do_options(argc, argv);
777 // Set current tower position lon/lat given an airport id
778 static bool fgSetTowerPosFromAirportID( const string& id) {
779 const FGAirport *a = fgFindAirportID( id);
781 SGGeod tower = a->getTowerLocation();
782 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
783 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
784 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
792 struct FGTowerLocationListener : SGPropertyChangeListener {
793 void valueChanged(SGPropertyNode* node) {
794 string id(node->getStringValue());
795 if (fgGetBool("/sim/tower/auto-position",true))
797 // enforce using closest airport when auto-positioning is enabled
798 const char* closest_airport = fgGetString("/sim/airport/closest-airport-id", "");
799 if (closest_airport && (id != closest_airport))
801 id = closest_airport;
802 node->setStringValue(id);
805 fgSetTowerPosFromAirportID(id);
809 struct FGClosestTowerLocationListener : SGPropertyChangeListener
811 void valueChanged(SGPropertyNode* )
813 // closest airport has changed
814 if (fgGetBool("/sim/tower/auto-position",true))
816 // update tower position
817 const char* id = fgGetString("/sim/airport/closest-airport-id", "");
819 fgSetString("/sim/tower/airport-id", id);
824 void fgInitTowerLocationListener() {
825 fgGetNode("/sim/tower/airport-id", true)
826 ->addChangeListener( new FGTowerLocationListener(), true );
827 FGClosestTowerLocationListener* ntcl = new FGClosestTowerLocationListener();
828 fgGetNode("/sim/airport/closest-airport-id", true)
829 ->addChangeListener(ntcl , true );
830 fgGetNode("/sim/tower/auto-position", true)
831 ->addChangeListener(ntcl, true );
834 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
836 SGGeod startPos(aStartPos);
837 if (aTargetHeading == HUGE_VAL) {
838 aTargetHeading = aHeading;
841 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
842 double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
843 offsetDistance *= SG_NM_TO_METER;
844 double offsetAzimuth = aHeading;
845 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
846 offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
847 aHeading = aTargetHeading;
852 SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
857 fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
858 fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
859 fgSetDouble("/sim/presets/heading-deg", aHeading );
861 // other code depends on the actual values being set ...
862 fgSetDouble("/position/longitude-deg", startPos.getLongitudeDeg() );
863 fgSetDouble("/position/latitude-deg", startPos.getLatitudeDeg() );
864 fgSetDouble("/orientation/heading-deg", aHeading );
867 // Set current_options lon/lat given an airport id and heading (degrees)
868 bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
872 // set initial position from runway and heading
873 SG_LOG( SG_GENERAL, SG_INFO,
874 "Attempting to set starting position from airport code "
875 << id << " heading " << tgt_hdg );
877 const FGAirport* apt = fgFindAirportID(id);
878 if (!apt) return false;
879 FGRunway* r = apt->findBestRunwayForHeading(tgt_hdg);
880 fgSetString("/sim/atc/runway", r->ident().c_str());
882 SGGeod startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
883 fgApplyStartOffset(startPos, r->headingDeg(), tgt_hdg);
887 // Set current_options lon/lat given an airport id and parkig position name
888 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
892 // can't see an easy way around this const_cast at the moment
893 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
895 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
898 FGAirportDynamics* dcs = apt->getDynamics();
900 SG_LOG( SG_GENERAL, SG_ALERT,
901 "Failed to find parking position " << parkpos <<
902 " at airport " << id );
906 int park_index = dcs->getNrOfParkings() - 1;
907 while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
908 if (park_index < 0) {
909 SG_LOG( SG_GENERAL, SG_ALERT,
910 "Failed to find parking position " << parkpos <<
911 " at airport " << id );
914 FGParking* parking = dcs->getParking(park_index);
915 parking->setAvailable(false);
917 SGGeod::fromDeg(parking->getLongitude(), parking->getLatitude()),
918 parking->getHeading());
923 // Set current_options lon/lat given an airport id and runway number
924 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
928 // set initial position from airport and runway number
929 SG_LOG( SG_GENERAL, SG_INFO,
930 "Attempting to set starting position for "
931 << id << ":" << rwy );
933 const FGAirport* apt = fgFindAirportID(id);
935 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
939 if (!apt->hasRunwayWithIdent(rwy)) {
940 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
941 "Failed to find runway " << rwy <<
942 " at airport " << id << ". Using default runway." );
946 FGRunway* r(apt->getRunwayByIdent(rwy));
947 fgSetString("/sim/atc/runway", r->ident().c_str());
948 SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
949 fgApplyStartOffset(startPos, r->headingDeg());
954 static void fgSetDistOrAltFromGlideSlope() {
955 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
956 string apt_id = fgGetString("/sim/presets/airport-id");
957 double gs = fgGetDouble("/sim/presets/glideslope-deg")
958 * SG_DEGREES_TO_RADIANS ;
959 double od = fgGetDouble("/sim/presets/offset-distance-nm");
960 double alt = fgGetDouble("/sim/presets/altitude-ft");
962 double apt_elev = 0.0;
963 if ( ! apt_id.empty() ) {
964 apt_elev = fgGetAirportElev( apt_id );
965 if ( apt_elev < -9990.0 ) {
972 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
973 // set altitude from glideslope and offset-distance
974 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
975 alt = fabs(od*tan(gs)) + apt_elev;
976 fgSetDouble("/sim/presets/altitude-ft", alt);
977 fgSetBool("/sim/presets/onground", false);
978 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
980 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
981 // set offset-distance from glideslope and altitude
982 od = (alt - apt_elev) / tan(gs);
983 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
984 fgSetDouble("/sim/presets/offset-distance-nm", od);
985 fgSetBool("/sim/presets/onground", false);
986 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
988 } else if( fabs(gs) > 0.01 ) {
989 SG_LOG( SG_GENERAL, SG_ALERT,
990 "Glideslope given but not altitude or offset-distance." );
991 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
992 fgSetDouble("/sim/presets/glideslope-deg", 0);
993 fgSetBool("/sim/presets/onground", true);
998 // Set current_options lon/lat given an airport id and heading (degrees)
999 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
1001 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
1004 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1005 << id << ":" << freq );
1009 fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
1013 // Set current_options lon/lat given an aircraft carrier id
1014 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
1016 // set initial position from runway and heading
1020 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
1021 double lon = geodPos.getLongitudeDeg();
1022 double lat = geodPos.getLatitudeDeg();
1023 double alt = geodPos.getElevationFt();
1025 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1026 << carrier << " at lat = " << lat << ", lon = " << lon
1027 << ", alt = " << alt << ", heading = " << heading);
1029 fgSetDouble("/sim/presets/longitude-deg", lon);
1030 fgSetDouble("/sim/presets/latitude-deg", lat);
1031 fgSetDouble("/sim/presets/altitude-ft", alt);
1032 fgSetDouble("/sim/presets/heading-deg", heading);
1033 fgSetDouble("/position/longitude-deg", lon);
1034 fgSetDouble("/position/latitude-deg", lat);
1035 fgSetDouble("/position/altitude-ft", alt);
1036 fgSetDouble("/orientation/heading-deg", heading);
1038 fgSetString("/sim/presets/speed-set", "UVW");
1039 fgSetDouble("/velocities/uBody-fps", uvw(0));
1040 fgSetDouble("/velocities/vBody-fps", uvw(1));
1041 fgSetDouble("/velocities/wBody-fps", uvw(2));
1042 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
1043 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
1044 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
1046 fgSetBool("/sim/presets/onground", true);
1050 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
1056 // Set current_options lon/lat given an airport id and heading (degrees)
1057 static bool fgSetPosFromFix( const string& id )
1059 FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
1060 FGPositioned* fix = FGPositioned::findNextWithPartialId(NULL, id, &fixFilter);
1062 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
1066 fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
1071 * Initialize vor/ndb/ils/fix list management and query systems (as
1072 * well as simple airport db list)
1077 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
1079 SGPath aptdb( globals->get_fg_root() );
1080 aptdb.append( "Airports/apt.dat" );
1082 SGPath p_metar( globals->get_fg_root() );
1083 p_metar.append( "Airports/metar.dat" );
1085 fgAirportDBLoad( aptdb.str(), p_metar.str() );
1086 FGAirport::installPropertyListener();
1087 FGPositioned::installCommands();
1089 FGNavList *navlist = new FGNavList;
1090 FGNavList *loclist = new FGNavList;
1091 FGNavList *gslist = new FGNavList;
1092 FGNavList *dmelist = new FGNavList;
1093 FGNavList *tacanlist = new FGNavList;
1094 FGNavList *carrierlist = new FGNavList;
1095 FGTACANList *channellist = new FGTACANList;
1097 globals->set_navlist( navlist );
1098 globals->set_loclist( loclist );
1099 globals->set_gslist( gslist );
1100 globals->set_dmelist( dmelist );
1101 globals->set_tacanlist( tacanlist );
1102 globals->set_carrierlist( carrierlist );
1103 globals->set_channellist( channellist );
1105 if ( !fgNavDBInit(navlist, loclist, gslist, dmelist, tacanlist, carrierlist, channellist) ) {
1106 SG_LOG( SG_GENERAL, SG_ALERT,
1107 "Problems loading one or more navigational database" );
1110 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1111 SGPath p_fix( globals->get_fg_root() );
1112 p_fix.append( "Navaids/fix.dat" );
1114 fixlist.init( p_fix ); // adds fixes to the DB in positioned.cxx
1116 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
1117 flightgear::Airway::load();
1123 // Set the initial position based on presets (or defaults)
1124 bool fgInitPosition() {
1125 // cout << "fgInitPosition()" << endl;
1126 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1127 * SG_DEGREES_TO_RADIANS ;
1128 double od = fgGetDouble("/sim/presets/offset-distance-nm");
1129 double alt = fgGetDouble("/sim/presets/altitude-ft");
1131 bool set_pos = false;
1133 // If glideslope is specified, then calculate offset-distance or
1134 // altitude relative to glide slope if either of those was not
1136 if ( fabs( gs ) > 0.01 ) {
1137 fgSetDistOrAltFromGlideSlope();
1141 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1142 // If not, check for an airport-id and use that.
1143 // If not, default to the middle of the KSFO field.
1144 // The default values for lon/lat are deliberately out of range
1145 // so that the airport-id can take effect; valid lon/lat will
1146 // override airport-id, however.
1147 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1148 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1149 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1150 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1155 string apt = fgGetString("/sim/presets/airport-id");
1156 string rwy_no = fgGetString("/sim/presets/runway");
1157 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1158 string vor = fgGetString("/sim/presets/vor-id");
1159 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1160 string ndb = fgGetString("/sim/presets/ndb-id");
1161 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1162 string carrier = fgGetString("/sim/presets/carrier");
1163 string parkpos = fgGetString("/sim/presets/parkpos");
1164 string fix = fgGetString("/sim/presets/fix");
1165 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1166 double hdg = hdg_preset->getDoubleValue();
1168 // save some start parameters, so that we can later say what the
1169 // user really requested. TODO generalize that and move it to options.cxx
1170 static bool start_options_saved = false;
1171 if (!start_options_saved) {
1172 start_options_saved = true;
1173 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1175 opt->setDoubleValue("latitude-deg", lat_deg);
1176 opt->setDoubleValue("longitude-deg", lon_deg);
1177 opt->setDoubleValue("heading-deg", hdg);
1178 opt->setStringValue("airport", apt.c_str());
1179 opt->setStringValue("runway", rwy_no.c_str());
1183 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1185 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1186 // An airport + parking position is requested
1187 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1188 // set tower position
1189 fgSetString("/sim/airport/closest-airport-id", apt.c_str());
1190 fgSetString("/sim/tower/airport-id", apt.c_str());
1195 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1196 // An airport + runway is requested
1197 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1198 // set tower position (a little off the heading for single
1200 fgSetString("/sim/airport/closest-airport-id", apt.c_str());
1201 fgSetString("/sim/tower/airport-id", apt.c_str());
1206 if ( !set_pos && !apt.empty() ) {
1207 // An airport is requested (find runway closest to hdg)
1208 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1209 // set tower position (a little off the heading for single
1211 fgSetString("/sim/airport/closest-airport-id", apt.c_str());
1212 fgSetString("/sim/tower/airport-id", apt.c_str());
1217 if (hdg_preset->getDoubleValue() > 9990.0)
1218 hdg_preset->setDoubleValue(hdg);
1220 if ( !set_pos && !vor.empty() ) {
1221 // a VOR is requested
1222 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1227 if ( !set_pos && !ndb.empty() ) {
1228 // an NDB is requested
1229 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1234 if ( !set_pos && !carrier.empty() ) {
1235 // an aircraft carrier is requested
1236 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1241 if ( !set_pos && !fix.empty() ) {
1242 // a Fix is requested
1243 if ( fgSetPosFromFix( fix ) ) {
1249 // No lon/lat specified, no airport specified, default to
1250 // middle of KSFO field.
1251 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1252 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1255 fgSetDouble( "/position/longitude-deg",
1256 fgGetDouble("/sim/presets/longitude-deg") );
1257 fgSetDouble( "/position/latitude-deg",
1258 fgGetDouble("/sim/presets/latitude-deg") );
1259 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1261 // determine if this should be an on-ground or in-air start
1262 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1263 fgSetBool("/sim/presets/onground", false);
1265 fgSetBool("/sim/presets/onground", true);
1272 // General house keeping initializations
1273 bool fgInitGeneral() {
1276 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1277 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1279 root = globals->get_fg_root();
1280 if ( ! root.length() ) {
1281 // No root path set? Then bail ...
1282 SG_LOG( SG_GENERAL, SG_ALERT,
1283 "Cannot continue without a path to the base package "
1284 << "being defined." );
1287 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1289 globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1291 char buf[512], *cwd = getcwd(buf, 511);
1293 SGPropertyNode *curr = fgGetNode("/sim", true);
1294 curr->removeChild("fg-current", 0, false);
1295 curr = curr->getChild("fg-current", 0, true);
1296 curr->setStringValue(cwd ? cwd : "");
1297 curr->setAttribute(SGPropertyNode::WRITE, false);
1299 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
1300 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
1304 // This is the top level init routine which calls all the other
1305 // initialization routines. If you are adding a subsystem to flight
1306 // gear, its initialization call should located in this routine.
1307 // Returns non-zero if a problem encountered.
1308 bool fgInitSubsystems() {
1309 // static const SGPropertyNode *longitude
1310 // = fgGetNode("/sim/presets/longitude-deg");
1311 // static const SGPropertyNode *latitude
1312 // = fgGetNode("/sim/presets/latitude-deg");
1313 // static const SGPropertyNode *altitude
1314 // = fgGetNode("/sim/presets/altitude-ft");
1316 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1317 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1319 ////////////////////////////////////////////////////////////////////
1320 // Initialize the event manager subsystem.
1321 ////////////////////////////////////////////////////////////////////
1323 globals->get_event_mgr()->init();
1324 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1326 ////////////////////////////////////////////////////////////////////
1327 // Initialize the property interpolator subsystem. Put into the INIT
1328 // group because the "nasal" subsystem may need it at GENERAL take-down.
1329 ////////////////////////////////////////////////////////////////////
1330 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1333 ////////////////////////////////////////////////////////////////////
1334 // Add the FlightGear property utilities.
1335 ////////////////////////////////////////////////////////////////////
1336 globals->add_subsystem("properties", new FGProperties);
1338 ////////////////////////////////////////////////////////////////////
1339 // Initialize the material property subsystem.
1340 ////////////////////////////////////////////////////////////////////
1342 SGPath mpath( globals->get_fg_root() );
1343 mpath.append( "materials.xml" );
1344 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
1345 globals->get_props()) ) {
1346 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1351 ////////////////////////////////////////////////////////////////////
1352 // Initialize the scenery management subsystem.
1353 ////////////////////////////////////////////////////////////////////
1355 globals->get_scenery()->get_scene_graph()
1356 ->addChild(simgear::Particles::getCommonRoot());
1357 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
1359 ////////////////////////////////////////////////////////////////////
1360 // Initialize the flight model subsystem.
1361 ////////////////////////////////////////////////////////////////////
1363 globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
1365 ////////////////////////////////////////////////////////////////////
1366 // Initialize the weather subsystem.
1367 ////////////////////////////////////////////////////////////////////
1369 // Initialize the weather modeling subsystem
1370 globals->add_subsystem("environment", new FGEnvironmentMgr);
1372 ////////////////////////////////////////////////////////////////////
1373 // Initialize the aircraft systems and instrumentation (before the
1375 ////////////////////////////////////////////////////////////////////
1377 globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
1378 globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
1380 ////////////////////////////////////////////////////////////////////
1381 // Initialize the XML Autopilot subsystem.
1382 ////////////////////////////////////////////////////////////////////
1384 globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance(), SGSubsystemMgr::FDM );
1385 globals->add_subsystem( "route-manager", new FGRouteMgr );
1387 ////////////////////////////////////////////////////////////////////
1388 // Initialize the Input-Output subsystem
1389 ////////////////////////////////////////////////////////////////////
1390 globals->add_subsystem( "io", new FGIO );
1392 ////////////////////////////////////////////////////////////////////
1393 // Create and register the logger.
1394 ////////////////////////////////////////////////////////////////////
1396 globals->add_subsystem("logger", new FGLogger);
1398 ////////////////////////////////////////////////////////////////////
1399 // Create and register the XML GUI.
1400 ////////////////////////////////////////////////////////////////////
1402 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1404 //////////////////////////////////////////////////////////////////////
1405 // Initialize the 2D cloud subsystem.
1406 ////////////////////////////////////////////////////////////////////
1407 fgGetBool("/sim/rendering/bump-mapping", false);
1411 ////////////////////////////////////////////////////////////////////
1412 // Initialise the ATC Manager
1413 ////////////////////////////////////////////////////////////////////
1415 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1416 globals->set_ATC_mgr(new FGATCMgr);
1417 globals->get_ATC_mgr()->init();
1419 ////////////////////////////////////////////////////////////////////
1420 // Initialize multiplayer subsystem
1421 ////////////////////////////////////////////////////////////////////
1423 globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
1425 ////////////////////////////////////////////////////////////////////
1426 // Initialise the AI Model Manager
1427 ////////////////////////////////////////////////////////////////////
1428 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1429 globals->add_subsystem("ai_model", new FGAIManager, SGSubsystemMgr::POST_FDM);
1430 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
1433 // It's probably a good idea to initialize the top level traffic manager
1434 // After the AI and ATC systems have been initialized properly.
1435 // AI Traffic manager
1436 globals->add_subsystem("Traffic Manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
1438 ////////////////////////////////////////////////////////////////////
1439 // Add a new 2D panel.
1440 ////////////////////////////////////////////////////////////////////
1442 string panel_path(fgGetString("/sim/panel/path"));
1443 if (!panel_path.empty()) {
1444 FGPanel* p = fgReadPanel(panel_path);
1446 globals->set_current_panel(p);
1449 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1451 SG_LOG( SG_INPUT, SG_ALERT,
1452 "Error reading new panel from " << panel_path );
1456 ////////////////////////////////////////////////////////////////////
1457 // Initialize the controls subsystem.
1458 ////////////////////////////////////////////////////////////////////
1460 globals->get_controls()->init();
1461 globals->get_controls()->bind();
1464 ////////////////////////////////////////////////////////////////////
1465 // Initialize the input subsystem.
1466 ////////////////////////////////////////////////////////////////////
1468 globals->add_subsystem("input", new FGInput);
1471 ////////////////////////////////////////////////////////////////////
1472 // Initialize the replay subsystem
1473 ////////////////////////////////////////////////////////////////////
1474 globals->add_subsystem("replay", new FGReplay);
1476 #ifdef ENABLE_AUDIO_SUPPORT
1477 ////////////////////////////////////////////////////////////////////
1478 // Initialize the sound-effects subsystem.
1479 ////////////////////////////////////////////////////////////////////
1480 globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
1483 ////////////////////////////////////////////////////////////////////
1484 // Initialize the lighting subsystem.
1485 ////////////////////////////////////////////////////////////////////
1487 globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
1489 // ordering here is important : Nasal (via events), then models, then views
1490 globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
1492 FGAircraftModel* acm = new FGAircraftModel;
1493 globals->set_aircraft_model(acm);
1494 globals->add_subsystem("aircraft-model", acm, SGSubsystemMgr::DISPLAY);
1496 FGModelMgr* mm = new FGModelMgr;
1497 globals->set_model_mgr(mm);
1498 globals->add_subsystem("model-manager", mm, SGSubsystemMgr::DISPLAY);
1500 FGViewMgr *viewmgr = new FGViewMgr;
1501 globals->set_viewmgr( viewmgr );
1502 globals->add_subsystem("view-manager", viewmgr, SGSubsystemMgr::DISPLAY);
1504 globals->add_subsystem("tile-manager", globals->get_tile_mgr(),
1505 SGSubsystemMgr::DISPLAY);
1507 ////////////////////////////////////////////////////////////////////
1508 // Bind and initialize subsystems.
1509 ////////////////////////////////////////////////////////////////////
1511 globals->get_subsystem_mgr()->bind();
1512 globals->get_subsystem_mgr()->init();
1514 ////////////////////////////////////////////////////////////////////////
1515 // Initialize the Nasal interpreter.
1516 // Do this last, so that the loaded scripts see initialized state
1517 ////////////////////////////////////////////////////////////////////////
1518 FGNasalSys* nasal = new FGNasalSys();
1519 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1522 // initialize methods that depend on other subsystems.
1523 globals->get_subsystem_mgr()->postinit();
1525 ////////////////////////////////////////////////////////////////////////
1526 // End of subsystem initialization.
1527 ////////////////////////////////////////////////////////////////////
1529 fgSetBool("/sim/initialized", true);
1531 SG_LOG( SG_GENERAL, SG_INFO, endl);
1533 // Save the initial state for future
1535 globals->saveInitialState();
1540 // Reset: this is what the 'reset' command (and hence, GUI) is attached to
1541 void fgReInitSubsystems()
1543 static const SGPropertyNode *master_freeze
1544 = fgGetNode("/sim/freeze/master");
1546 SG_LOG( SG_GENERAL, SG_INFO, "fgReInitSubsystems()");
1548 // setup state to begin re-init
1549 bool freeze = master_freeze->getBoolValue();
1551 fgSetBool("/sim/freeze/master", true);
1554 fgSetBool("/sim/signals/reinit", true);
1555 fgSetBool("/sim/crashed", false);
1557 // do actual re-init steps
1558 globals->get_subsystem("flight")->unbind();
1560 // reset control state, before restoring initial state; -set or config files
1561 // may specify values for flaps, trim tabs, magnetos, etc
1562 globals->get_controls()->reset_all();
1564 globals->restoreInitialState();
1566 // update our position based on current presets
1569 // Force reupdating the positions of the ai 3d models. They are used for
1570 // initializing ground level for the FDM.
1571 globals->get_subsystem("ai_model")->reinit();
1573 // Initialize the FDM
1574 globals->get_subsystem("flight")->reinit();
1576 // reset replay buffers
1577 globals->get_subsystem("replay")->reinit();
1579 // reload offsets from config defaults
1580 globals->get_viewmgr()->reinit();
1582 globals->get_subsystem("time")->reinit();
1584 // need to bind FDMshell again, since we manually unbound it above...
1585 globals->get_subsystem("flight")->bind();
1587 // setup state to end re-init
1588 fgSetBool("/sim/signals/reinit", false);
1590 fgSetBool("/sim/freeze/master", false);
1592 fgSetBool("/sim/sceneryloaded",false);
1596 ///////////////////////////////////////////////////////////////////////////////
1597 // helper object to implement the --show-aircraft command.
1598 // resides here so we can share the fgFindAircraftInDir template above,
1599 // and hence ensure this command lists exectly the same aircraft as the normal
1606 _minStatus = getNumMaturity(fgGetString("/sim/aircraft-min-status", "all"));
1610 void show(const SGPath& path)
1612 fgFindAircraftInDir(path, this, &ShowAircraft::processAircraft);
1614 std::sort(_aircraft.begin(), _aircraft.end(), ciLessLibC());
1615 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on Windows
1616 cout << "Available aircraft:" << endl;
1617 for ( unsigned int i = 0; i < _aircraft.size(); i++ ) {
1618 cout << _aircraft[i] << endl;
1623 bool processAircraft(const SGPath& path)
1625 SGPropertyNode root;
1627 readProperties(path.str(), &root);
1628 } catch (sg_exception& ) {
1633 string descStr(" ");
1634 descStr += path.file();
1635 // trim common suffix from file names
1636 int nPos = descStr.rfind("-set.xml");
1637 if (nPos == (int)(descStr.size() - 8)) {
1638 descStr.resize(nPos);
1641 SGPropertyNode *node = root.getNode("sim");
1643 SGPropertyNode* desc = node->getNode("description");
1644 // if a status tag is found, read it in
1645 if (node->hasValue("status")) {
1646 maturity = getNumMaturity(node->getStringValue("status"));
1650 if (descStr.size() <= 27+3) {
1651 descStr.append(29+3-descStr.size(), ' ');
1654 descStr.append( 32, ' ');
1656 descStr += desc->getStringValue();
1658 } // of have 'sim' node
1660 if (maturity < _minStatus) {
1664 _aircraft.push_back(descStr);
1669 int getNumMaturity(const char * str)
1671 // changes should also be reflected in $FG_ROOT/data/options.xml &
1672 // $FG_ROOT/data/Translations/string-default.xml
1673 const char* levels[] = {"alpha","beta","early-production","production"};
1675 if (!strcmp(str, "all")) {
1679 for (size_t i=0; i<(sizeof(levels)/sizeof(levels[0]));i++)
1680 if (strcmp(str,levels[i])==0)
1686 // recommended in Meyers, Effective STL when internationalization and embedded
1687 // NULLs aren't an issue. Much faster than the STL or Boost lex versions.
1688 struct ciLessLibC : public std::binary_function<string, string, bool>
1690 bool operator()(const std::string &lhs, const std::string &rhs) const
1692 return strcasecmp(lhs.c_str(), rhs.c_str()) < 0 ? 1 : 0;
1697 string_list _aircraft;
1700 void fgShowAircraft(const SGPath &path)
1706 cout << "Hit a key to continue..." << endl;