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>
78 # include <ATCDCL/ATCmgr.hxx>
79 # include "ATCDCL/commlist.hxx"
81 # include "ATC/atis.hxx"
82 # include "ATC/atcutils.hxx"
85 #include <Autopilot/route_mgr.hxx>
86 #include <Autopilot/autopilotgroup.hxx>
88 #include <Cockpit/panel.hxx>
89 #include <Cockpit/panel_io.hxx>
91 #include <GUI/new_gui.hxx>
92 #include <Input/input.hxx>
93 #include <Instrumentation/instrument_mgr.hxx>
94 #include <Model/acmodel.hxx>
95 #include <Model/modelmgr.hxx>
96 #include <AIModel/submodel.hxx>
97 #include <AIModel/AIManager.hxx>
98 #include <Navaids/navdb.hxx>
99 #include <Navaids/navlist.hxx>
100 #include <Navaids/fix.hxx>
101 #include <Navaids/fixlist.hxx>
102 #include <Navaids/airways.hxx>
103 #include <Scenery/scenery.hxx>
104 #include <Scenery/tilemgr.hxx>
105 #include <Scripting/NasalSys.hxx>
106 #include <Sound/voice.hxx>
107 #include <Systems/system_mgr.hxx>
108 #include <Time/light.hxx>
109 #include <Traffic/TrafficMgr.hxx>
110 #include <MultiPlayer/multiplaymgr.hxx>
111 #include <FDM/fdm_shell.hxx>
113 #include <Environment/environment_mgr.hxx>
115 #include "fg_init.hxx"
117 #include "fg_commands.hxx"
118 #include "fg_props.hxx"
119 #include "options.hxx"
120 #include "globals.hxx"
121 #include "logger.hxx"
122 #include "renderer.hxx"
123 #include "viewmgr.hxx"
128 # include <CoreFoundation/CoreFoundation.h>
132 using namespace boost::algorithm;
134 extern const char *default_root;
137 // Scan the command line options for the specified option and return
139 static string fgScanForOption( const string& option, int argc, char **argv ) {
142 if (hostname == NULL)
145 if( gethostname(_hostname, 256) >= 0 ) {
146 hostname = strdup(_hostname);
147 free_hostname = true;
151 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
153 int len = option.length();
156 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
158 string arg = argv[i];
159 if ( arg.find( option ) == 0 ) {
160 return arg.substr( len );
170 // Scan the user config files for the specified option and return
172 static string fgScanForOption( const string& option, const string& path ) {
173 sg_gzifstream in( path );
174 if ( !in.is_open() ) {
178 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
180 int len = option.length();
183 while ( ! in.eof() ) {
185 getline( in, line, '\n' );
187 // catch extraneous (DOS) line ending character
188 if ( line[line.length() - 1] < 32 ) {
189 line = line.substr( 0, line.length()-1 );
192 if ( line.find( option ) == 0 ) {
193 return line.substr( len );
202 // Scan the user config files for the specified option and return
204 static string fgScanForOption( const string& option ) {
207 #if defined( unix ) || defined( __CYGWIN__ ) || defined(_MSC_VER)
208 // Next check home directory for .fgfsrc.hostname file
210 if ( homedir != NULL && hostname != NULL && strlen(hostname) > 0) {
211 SGPath config( homedir );
212 config.append( ".fgfsrc" );
213 config.concat( "." );
214 config.concat( hostname );
215 arg = fgScanForOption( option, config.str() );
220 // Next check home directory for .fgfsrc file
222 if ( homedir != NULL ) {
223 SGPath config( homedir );
224 config.append( ".fgfsrc" );
225 arg = fgScanForOption( option, config.str() );
230 // Check for $fg_root/system.fgfsrc
231 SGPath config( globals->get_fg_root() );
232 config.append( "system.fgfsrc" );
233 arg = fgScanForOption( option, config.str() );
240 // Read in configuration (files and command line options) but only set
241 // fg_root and aircraft_paths, which are needed *before* do_options() is called
244 bool fgInitFGRoot ( int argc, char **argv ) {
247 // First parse command line options looking for --fg-root=, this
248 // will override anything specified in a config file
249 root = fgScanForOption( "--fg-root=", argc, argv);
251 // Check in one of the user configuration files.
253 root = fgScanForOption( "--fg-root=" );
255 // Next check if fg-root is set as an env variable
256 if ( root.empty() ) {
257 char *envp = ::getenv( "FG_ROOT" );
258 if ( envp != NULL ) {
263 // Otherwise, default to a random compiled-in location if we can't
264 // find fg-root any other way.
265 if ( root.empty() ) {
266 #if defined( __CYGWIN__ )
268 #elif defined( _WIN32 )
270 #elif defined(__APPLE__)
272 The following code looks for the base package inside the application
273 bundle, in the standard Contents/Resources location.
275 CFURLRef resourcesUrl = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
277 // look for a 'data' subdir
278 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, resourcesUrl, CFSTR("data"), true);
280 // now convert down to a path, and the a c-string
281 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
282 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
284 CFRelease(resourcesUrl);
292 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
293 globals->set_fg_root(root);
299 // Read in configuration (files and command line options) but only set
301 bool fgInitFGAircraft ( int argc, char **argv ) {
303 string aircraftDir = fgScanForOption("--fg-aircraft=", argc, argv);
304 if (aircraftDir.empty()) {
305 aircraftDir = fgScanForOption("--fg-aircraft=");
308 const char* envp = ::getenv("FG_AIRCRAFT");
309 if (aircraftDir.empty() && envp) {
310 globals->append_aircraft_paths(envp);
313 if (!aircraftDir.empty()) {
314 globals->append_aircraft_paths(aircraftDir);
319 // First parse command line options looking for --aircraft=, this
320 // will override anything specified in a config file
321 aircraft = fgScanForOption( "--aircraft=", argc, argv );
322 if ( aircraft.empty() ) {
323 // check synonym option
324 aircraft = fgScanForOption( "--vehicle=", argc, argv );
327 // Check in one of the user configuration files.
328 if ( aircraft.empty() ) {
329 aircraft = fgScanForOption( "--aircraft=" );
331 if ( aircraft.empty() ) {
332 aircraft = fgScanForOption( "--vehicle=" );
335 // if an aircraft was specified, set the property name
336 if ( !aircraft.empty() ) {
337 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
338 fgSetString("/sim/aircraft", aircraft.c_str() );
340 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
347 // Return the current base package version
348 string fgBasePackageVersion() {
349 SGPath base_path( globals->get_fg_root() );
350 base_path.append("version");
352 sg_gzifstream in( base_path.str() );
353 if ( !in.is_open() ) {
354 SGPath old_path( globals->get_fg_root() );
355 old_path.append( "Thanks" );
356 sg_gzifstream old( old_path.str() );
357 if ( !old.is_open() ) {
360 return "[old version]";
371 // Initialize the localization
372 SGPropertyNode *fgInitLocale(const char *language) {
373 SGPropertyNode *c_node = NULL, *d_node = NULL;
374 SGPropertyNode *intl = fgGetNode("/sim/intl");
376 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
378 // localization not defined
383 // Select the proper language from the list
385 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
386 for (unsigned int i = 0; i < locale.size(); i++) {
388 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
389 for (unsigned int j = 0; j < lang.size(); j++) {
391 if (!strcmp(lang[j]->getStringValue(), language)) {
400 d_node = intl->getChild("locale");
404 // Check for localized font
405 SGPropertyNode *font_n = c_node->getNode("font", true);
406 if ( !strcmp(font_n->getStringValue(), "") )
407 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
411 // Load the default strings
413 SGPath d_path( globals->get_fg_root() );
415 const char *d_path_str = d_node->getStringValue("strings");
417 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << d_node->getPath() << "/strings.");
421 d_path.append(d_path_str);
422 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << d_path.str());
424 SGPropertyNode *strings = c_node->getNode("strings");
426 readProperties(d_path.str(), strings);
427 } catch (const sg_exception &) {
428 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
433 // Load the language specific strings
435 if (c_node != d_node) {
436 SGPath c_path( globals->get_fg_root() );
438 const char *c_path_str = c_node->getStringValue("strings");
440 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << c_node->getPath() << "/strings");
444 c_path.append(c_path_str);
445 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << c_path.str());
448 readProperties(c_path.str(), strings);
449 } catch (const sg_exception &) {
450 SG_LOG(SG_GENERAL, SG_ALERT,
451 "Unable to read the localized strings from " << c_path.str());
461 // Initialize the localization routines
462 bool fgDetectLanguage() {
463 const char *language = ::getenv("LANG");
465 if (language == NULL) {
466 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
470 SGPropertyNode *locale = fgInitLocale(language);
472 SG_LOG(SG_GENERAL, SG_ALERT,
473 "No internationalization settings specified in preferences.xml" );
478 globals->set_locale( locale );
483 // Attempt to locate and parse the various non-XML config files in order
484 // from least precidence to greatest precidence
486 do_options (int argc, char ** argv)
488 // Check for $fg_root/system.fgfsrc
489 SGPath config( globals->get_fg_root() );
490 config.append( "system.fgfsrc" );
491 fgParseOptions(config.str());
493 #if defined( unix ) || defined( __CYGWIN__ ) || defined(_MSC_VER)
494 if( hostname != NULL && strlen(hostname) > 0 ) {
495 config.concat( "." );
496 config.concat( hostname );
497 fgParseOptions(config.str());
501 // Check for ~/.fgfsrc
502 if ( homedir != NULL ) {
503 config.set( homedir );
504 config.append( ".fgfsrc" );
505 fgParseOptions(config.str());
508 #if defined( unix ) || defined( __CYGWIN__ ) || defined(_MSC_VER)
509 if( hostname != NULL && strlen(hostname) > 0 ) {
510 // Check for ~/.fgfsrc.hostname
511 config.concat( "." );
512 config.concat( hostname );
513 fgParseOptions(config.str());
517 // Parse remaining command line options
518 // These will override anything specified in a config file
519 fgParseArgs(argc, argv);
523 bool fgFindAircraftInDir(const SGPath& dirPath, T* obj, bool (T::*pred)(const SGPath& p))
525 if (!dirPath.exists()) {
526 SG_LOG(SG_GENERAL, SG_WARN, "fgFindAircraftInDir: no such path:" << dirPath.str());
531 simgear::Dir dir(dirPath);
532 simgear::PathList setFiles(dir.children(simgear::Dir::TYPE_FILE, "-set.xml"));
533 simgear::PathList::iterator p;
534 for (p = setFiles.begin(); p != setFiles.end(); ++p) {
535 // check file name ends with -set.xml
537 // if we found a -set.xml at this level, don't recurse any deeper
540 bool done = (obj->*pred)(*p);
544 } // of -set.xml iteration
550 simgear::PathList subdirs(dir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT));
551 for (p = subdirs.begin(); p != subdirs.end(); ++p) {
552 if (p->file() == "CVS") {
556 if (fgFindAircraftInDir(*p, obj, pred)) {
559 } // of subdirs iteration
565 void fgFindAircraft(T* obj, bool (T::*pred)(const SGPath& p))
567 const string_list& paths(globals->get_aircraft_paths());
568 string_list::const_iterator it = paths.begin();
569 for (; it != paths.end(); ++it) {
570 bool done = fgFindAircraftInDir(SGPath(*it), obj, pred);
574 } // of aircraft paths iteration
576 // if we reach this point, search the default location (always last)
577 SGPath rootAircraft(globals->get_fg_root());
578 rootAircraft.append("Aircraft");
579 fgFindAircraftInDir(rootAircraft, obj, pred);
582 class FindAndCacheAircraft
585 FindAndCacheAircraft(SGPropertyNode* autoSave)
587 _cache = autoSave->getNode("sim/startup/path-cache", true);
592 std::string aircraft = fgGetString( "/sim/aircraft", "");
593 if (aircraft.empty()) {
594 SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
598 _searchAircraft = aircraft + "-set.xml";
600 // prepare cache for re-scan
601 SGPropertyNode *n = _cache->getNode("fg-root", true);
602 n->setStringValue(globals->get_fg_root().c_str());
603 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
604 n = _cache->getNode("fg-aircraft", true);
605 n->setStringValue(getAircraftPaths().c_str());
606 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
607 _cache->removeChildren("aircraft");
609 fgFindAircraft(this, &FindAndCacheAircraft::checkAircraft);
612 if (_foundPath.str().empty()) {
613 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
617 SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
618 fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
619 if (!_foundPath.exists()) {
620 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
625 readProperties(_foundPath.str(), globals->get_props());
626 } catch ( const sg_exception &e ) {
627 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
635 SGPath getAircraftPaths() {
636 string_list pathList = globals->get_aircraft_paths();
637 SGPath aircraftPaths;
638 string_list::const_iterator it = pathList.begin();
639 if (it != pathList.end()) {
640 aircraftPaths.set(*it);
643 for (; it != pathList.end(); ++it) {
644 aircraftPaths.add(*it);
646 return aircraftPaths;
651 if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
652 return false; // cache mismatch
655 if (getAircraftPaths().str() != _cache->getStringValue("fg-aircraft", "")) {
656 return false; // cache mismatch
659 vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
660 for (unsigned int i = 0; i < cache.size(); i++) {
661 const char *name = cache[i]->getStringValue("file", "");
662 if (!boost::equals(_searchAircraft, name, is_iequal())) {
666 SGPath xml(cache[i]->getStringValue("path", ""));
674 } // of aircraft in cache iteration
679 bool checkAircraft(const SGPath& p)
684 if (!_cache->getChild("aircraft", i++, false))
688 SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
690 std::string fileName(p.file());
691 n = entry->getNode("file", true);
692 n->setStringValue(fileName);
693 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
695 n = entry->getNode("path", true);
696 n->setStringValue(p.dir());
697 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
699 if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
707 std::string _searchAircraft;
709 SGPropertyNode* _cache;
712 // Read in configuration (file and command line)
713 bool fgInitConfig ( int argc, char **argv ) {
715 // First, set some sane default values
718 // Read global preferences from $FG_ROOT/preferences.xml
719 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
720 fgLoadProps("preferences.xml", globals->get_props());
721 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
723 // Detect the required language as early as possible
724 if ( !fgDetectLanguage() ) {
728 SGPropertyNode autosave;
730 char *envp = ::getenv( "APPDATA" );
732 SGPath config( envp );
733 config.append( "flightgear.org" );
735 if ( homedir != NULL ) {
736 SGPath config( homedir );
737 config.append( ".fgfs" );
739 const char *fg_home = getenv("FG_HOME");
743 SGPath home_export(config.str());
744 home_export.append("Export/dummy");
745 home_export.create_dir(0777);
747 // Set /sim/fg-home and don't allow malign code to override it until
748 // Nasal security is set up. Use FG_HOME if necessary.
749 SGPropertyNode *home = fgGetNode("/sim", true);
750 home->removeChild("fg-home", 0, false);
751 home = home->getChild("fg-home", 0, true);
752 home->setStringValue(config.c_str());
753 home->setAttribute(SGPropertyNode::WRITE, false);
755 config.append( "autosave.xml" );
756 if (config.exists()) {
757 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << config.str());
759 readProperties(config.str(), &autosave, SGPropertyNode::USERARCHIVE);
760 } catch (sg_exception& e) {
761 SG_LOG(SG_INPUT, SG_WARN, "failed to read user settings:" << e.getMessage()
762 << "(from " << e.getOrigin() << ")");
767 // Scan user config files and command line for a specified aircraft.
768 fgInitFGAircraft(argc, argv);
769 FindAndCacheAircraft f(&autosave);
770 if (!f.loadAircraft()) {
774 copyProperties(&autosave, globals->get_props());
776 // parse options after loading aircraft to ensure any user
777 // overrides of defaults are honored.
778 do_options(argc, argv);
783 // Set current tower position lon/lat given an airport id
784 static bool fgSetTowerPosFromAirportID( const string& id) {
785 const FGAirport *a = fgFindAirportID( id);
787 SGGeod tower = a->getTowerLocation();
788 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
789 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
790 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
798 struct FGTowerLocationListener : SGPropertyChangeListener {
799 void valueChanged(SGPropertyNode* node) {
800 const string id(node->getStringValue());
801 fgSetTowerPosFromAirportID(id);
805 void fgInitTowerLocationListener() {
806 fgGetNode("/sim/tower/airport-id", true)
807 ->addChangeListener( new FGTowerLocationListener(), true );
810 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
812 SGGeod startPos(aStartPos);
813 if (aTargetHeading == HUGE_VAL) {
814 aTargetHeading = aHeading;
817 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
818 double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
819 offsetDistance *= SG_NM_TO_METER;
820 double offsetAzimuth = aHeading;
821 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
822 offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
823 aHeading = aTargetHeading;
828 SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
833 fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
834 fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
835 fgSetDouble("/sim/presets/heading-deg", aHeading );
837 // other code depends on the actual values being set ...
838 fgSetDouble("/position/longitude-deg", startPos.getLongitudeDeg() );
839 fgSetDouble("/position/latitude-deg", startPos.getLatitudeDeg() );
840 fgSetDouble("/orientation/heading-deg", aHeading );
843 // Set current_options lon/lat given an airport id and heading (degrees)
844 bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
848 // set initial position from runway and heading
849 SG_LOG( SG_GENERAL, SG_INFO,
850 "Attempting to set starting position from airport code "
851 << id << " heading " << tgt_hdg );
853 const FGAirport* apt = fgFindAirportID(id);
854 if (!apt) return false;
855 FGRunway* r = apt->findBestRunwayForHeading(tgt_hdg);
856 fgSetString("/sim/atc/runway", r->ident().c_str());
858 SGGeod startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
859 fgApplyStartOffset(startPos, r->headingDeg(), tgt_hdg);
863 // Set current_options lon/lat given an airport id and parkig position name
864 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
868 // can't see an easy way around this const_cast at the moment
869 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
871 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
874 FGAirportDynamics* dcs = apt->getDynamics();
876 SG_LOG( SG_GENERAL, SG_ALERT,
877 "Failed to find parking position " << parkpos <<
878 " at airport " << id );
882 int park_index = dcs->getNrOfParkings() - 1;
883 while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
884 if (park_index < 0) {
885 SG_LOG( SG_GENERAL, SG_ALERT,
886 "Failed to find parking position " << parkpos <<
887 " at airport " << id );
890 FGParking* parking = dcs->getParking(park_index);
891 parking->setAvailable(false);
893 SGGeod::fromDeg(parking->getLongitude(), parking->getLatitude()),
894 parking->getHeading());
899 // Set current_options lon/lat given an airport id and runway number
900 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
904 // set initial position from airport and runway number
905 SG_LOG( SG_GENERAL, SG_INFO,
906 "Attempting to set starting position for "
907 << id << ":" << rwy );
909 const FGAirport* apt = fgFindAirportID(id);
911 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
915 if (!apt->hasRunwayWithIdent(rwy)) {
916 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
917 "Failed to find runway " << rwy <<
918 " at airport " << id << ". Using default runway." );
922 FGRunway* r(apt->getRunwayByIdent(rwy));
923 fgSetString("/sim/atc/runway", r->ident().c_str());
924 SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
925 fgApplyStartOffset(startPos, r->headingDeg());
930 static void fgSetDistOrAltFromGlideSlope() {
931 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
932 string apt_id = fgGetString("/sim/presets/airport-id");
933 double gs = fgGetDouble("/sim/presets/glideslope-deg")
934 * SG_DEGREES_TO_RADIANS ;
935 double od = fgGetDouble("/sim/presets/offset-distance-nm");
936 double alt = fgGetDouble("/sim/presets/altitude-ft");
938 double apt_elev = 0.0;
939 if ( ! apt_id.empty() ) {
940 apt_elev = fgGetAirportElev( apt_id );
941 if ( apt_elev < -9990.0 ) {
948 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
949 // set altitude from glideslope and offset-distance
950 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
951 alt = fabs(od*tan(gs)) + apt_elev;
952 fgSetDouble("/sim/presets/altitude-ft", alt);
953 fgSetBool("/sim/presets/onground", false);
954 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
956 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
957 // set offset-distance from glideslope and altitude
958 od = (alt - apt_elev) / tan(gs);
959 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
960 fgSetDouble("/sim/presets/offset-distance-nm", od);
961 fgSetBool("/sim/presets/onground", false);
962 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
964 } else if( fabs(gs) > 0.01 ) {
965 SG_LOG( SG_GENERAL, SG_ALERT,
966 "Glideslope given but not altitude or offset-distance." );
967 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
968 fgSetDouble("/sim/presets/glideslope-deg", 0);
969 fgSetBool("/sim/presets/onground", true);
974 // Set current_options lon/lat given an airport id and heading (degrees)
975 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
977 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
980 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
981 << id << ":" << freq );
985 fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
989 // Set current_options lon/lat given an aircraft carrier id
990 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
992 // set initial position from runway and heading
996 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
997 double lon = geodPos.getLongitudeDeg();
998 double lat = geodPos.getLatitudeDeg();
999 double alt = geodPos.getElevationFt();
1001 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1002 << carrier << " at lat = " << lat << ", lon = " << lon
1003 << ", alt = " << alt << ", heading = " << heading);
1005 fgSetDouble("/sim/presets/longitude-deg", lon);
1006 fgSetDouble("/sim/presets/latitude-deg", lat);
1007 fgSetDouble("/sim/presets/altitude-ft", alt);
1008 fgSetDouble("/sim/presets/heading-deg", heading);
1009 fgSetDouble("/position/longitude-deg", lon);
1010 fgSetDouble("/position/latitude-deg", lat);
1011 fgSetDouble("/position/altitude-ft", alt);
1012 fgSetDouble("/orientation/heading-deg", heading);
1014 fgSetString("/sim/presets/speed-set", "UVW");
1015 fgSetDouble("/velocities/uBody-fps", uvw(0));
1016 fgSetDouble("/velocities/vBody-fps", uvw(1));
1017 fgSetDouble("/velocities/wBody-fps", uvw(2));
1018 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
1019 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
1020 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
1022 fgSetBool("/sim/presets/onground", true);
1026 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
1032 // Set current_options lon/lat given an airport id and heading (degrees)
1033 static bool fgSetPosFromFix( const string& id )
1035 FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
1036 FGPositioned* fix = FGPositioned::findNextWithPartialId(NULL, id, &fixFilter);
1038 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
1042 fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
1047 * Initialize vor/ndb/ils/fix list management and query systems (as
1048 * well as simple airport db list)
1053 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
1055 SGPath aptdb( globals->get_fg_root() );
1056 aptdb.append( "Airports/apt.dat" );
1058 SGPath p_metar( globals->get_fg_root() );
1059 p_metar.append( "Airports/metar.dat" );
1061 // Initialise the frequency search map BEFORE reading
1062 // the airport database:
1066 current_commlist = new FGCommList;
1067 current_commlist->init( globals->get_fg_root() );
1068 fgAirportDBLoad( aptdb.str(), current_commlist, p_metar.str() );
1070 FGNavList *navlist = new FGNavList;
1071 FGNavList *loclist = new FGNavList;
1072 FGNavList *gslist = new FGNavList;
1073 FGNavList *dmelist = new FGNavList;
1074 FGNavList *tacanlist = new FGNavList;
1075 FGNavList *carrierlist = new FGNavList;
1076 FGTACANList *channellist = new FGTACANList;
1078 globals->set_navlist( navlist );
1079 globals->set_loclist( loclist );
1080 globals->set_gslist( gslist );
1081 globals->set_dmelist( dmelist );
1082 globals->set_tacanlist( tacanlist );
1083 globals->set_carrierlist( carrierlist );
1084 globals->set_channellist( channellist );
1086 if ( !fgNavDBInit(navlist, loclist, gslist, dmelist, tacanlist, carrierlist, channellist) ) {
1087 SG_LOG( SG_GENERAL, SG_ALERT,
1088 "Problems loading one or more navigational database" );
1091 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1092 SGPath p_fix( globals->get_fg_root() );
1093 p_fix.append( "Navaids/fix.dat" );
1095 fixlist.init( p_fix ); // adds fixes to the DB in positioned.cxx
1097 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
1098 flightgear::Airway::load();
1104 // Set the initial position based on presets (or defaults)
1105 bool fgInitPosition() {
1106 // cout << "fgInitPosition()" << endl;
1107 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1108 * SG_DEGREES_TO_RADIANS ;
1109 double od = fgGetDouble("/sim/presets/offset-distance-nm");
1110 double alt = fgGetDouble("/sim/presets/altitude-ft");
1112 bool set_pos = false;
1114 // If glideslope is specified, then calculate offset-distance or
1115 // altitude relative to glide slope if either of those was not
1117 if ( fabs( gs ) > 0.01 ) {
1118 fgSetDistOrAltFromGlideSlope();
1122 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1123 // If not, check for an airport-id and use that.
1124 // If not, default to the middle of the KSFO field.
1125 // The default values for lon/lat are deliberately out of range
1126 // so that the airport-id can take effect; valid lon/lat will
1127 // override airport-id, however.
1128 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1129 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1130 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1131 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1136 string apt = fgGetString("/sim/presets/airport-id");
1137 string rwy_no = fgGetString("/sim/presets/runway");
1138 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1139 string vor = fgGetString("/sim/presets/vor-id");
1140 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1141 string ndb = fgGetString("/sim/presets/ndb-id");
1142 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1143 string carrier = fgGetString("/sim/presets/carrier");
1144 string parkpos = fgGetString("/sim/presets/parkpos");
1145 string fix = fgGetString("/sim/presets/fix");
1146 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1147 double hdg = hdg_preset->getDoubleValue();
1149 // save some start parameters, so that we can later say what the
1150 // user really requested. TODO generalize that and move it to options.cxx
1151 static bool start_options_saved = false;
1152 if (!start_options_saved) {
1153 start_options_saved = true;
1154 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1156 opt->setDoubleValue("latitude-deg", lat_deg);
1157 opt->setDoubleValue("longitude-deg", lon_deg);
1158 opt->setDoubleValue("heading-deg", hdg);
1159 opt->setStringValue("airport", apt.c_str());
1160 opt->setStringValue("runway", rwy_no.c_str());
1164 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1166 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1167 // An airport + parking position is requested
1168 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1169 // set tower position
1170 fgSetString("/sim/tower/airport-id", apt.c_str());
1175 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1176 // An airport + runway is requested
1177 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1178 // set tower position (a little off the heading for single
1180 fgSetString("/sim/tower/airport-id", apt.c_str());
1185 if ( !set_pos && !apt.empty() ) {
1186 // An airport is requested (find runway closest to hdg)
1187 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1188 // set tower position (a little off the heading for single
1190 fgSetString("/sim/tower/airport-id", apt.c_str());
1195 if (hdg_preset->getDoubleValue() > 9990.0)
1196 hdg_preset->setDoubleValue(hdg);
1198 if ( !set_pos && !vor.empty() ) {
1199 // a VOR is requested
1200 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1205 if ( !set_pos && !ndb.empty() ) {
1206 // an NDB is requested
1207 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1212 if ( !set_pos && !carrier.empty() ) {
1213 // an aircraft carrier is requested
1214 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1219 if ( !set_pos && !fix.empty() ) {
1220 // a Fix is requested
1221 if ( fgSetPosFromFix( fix ) ) {
1227 // No lon/lat specified, no airport specified, default to
1228 // middle of KSFO field.
1229 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1230 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1233 fgSetDouble( "/position/longitude-deg",
1234 fgGetDouble("/sim/presets/longitude-deg") );
1235 fgSetDouble( "/position/latitude-deg",
1236 fgGetDouble("/sim/presets/latitude-deg") );
1237 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1239 // determine if this should be an on-ground or in-air start
1240 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1241 fgSetBool("/sim/presets/onground", false);
1243 fgSetBool("/sim/presets/onground", true);
1250 // General house keeping initializations
1251 bool fgInitGeneral() {
1254 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1255 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1257 root = globals->get_fg_root();
1258 if ( ! root.length() ) {
1259 // No root path set? Then bail ...
1260 SG_LOG( SG_GENERAL, SG_ALERT,
1261 "Cannot continue without a path to the base package "
1262 << "being defined." );
1265 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1267 globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1269 char buf[512], *cwd = getcwd(buf, 511);
1271 SGPropertyNode *curr = fgGetNode("/sim", true);
1272 curr->removeChild("fg-current", 0, false);
1273 curr = curr->getChild("fg-current", 0, true);
1274 curr->setStringValue(cwd ? cwd : "");
1275 curr->setAttribute(SGPropertyNode::WRITE, false);
1277 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
1278 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
1282 // This is the top level init routine which calls all the other
1283 // initialization routines. If you are adding a subsystem to flight
1284 // gear, its initialization call should located in this routine.
1285 // Returns non-zero if a problem encountered.
1286 bool fgInitSubsystems() {
1287 // static const SGPropertyNode *longitude
1288 // = fgGetNode("/sim/presets/longitude-deg");
1289 // static const SGPropertyNode *latitude
1290 // = fgGetNode("/sim/presets/latitude-deg");
1291 // static const SGPropertyNode *altitude
1292 // = fgGetNode("/sim/presets/altitude-ft");
1294 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1295 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1297 ////////////////////////////////////////////////////////////////////
1298 // Initialize the event manager subsystem.
1299 ////////////////////////////////////////////////////////////////////
1301 globals->get_event_mgr()->init();
1302 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1304 ////////////////////////////////////////////////////////////////////
1305 // Initialize the property interpolator subsystem. Put into the INIT
1306 // group because the "nasal" subsystem may need it at GENERAL take-down.
1307 ////////////////////////////////////////////////////////////////////
1308 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1311 ////////////////////////////////////////////////////////////////////
1312 // Add the FlightGear property utilities.
1313 ////////////////////////////////////////////////////////////////////
1314 globals->add_subsystem("properties", new FGProperties);
1316 ////////////////////////////////////////////////////////////////////
1317 // Initialize the material property subsystem.
1318 ////////////////////////////////////////////////////////////////////
1320 SGPath mpath( globals->get_fg_root() );
1321 mpath.append( "materials.xml" );
1322 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
1323 globals->get_props()) ) {
1324 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1329 ////////////////////////////////////////////////////////////////////
1330 // Initialize the scenery management subsystem.
1331 ////////////////////////////////////////////////////////////////////
1333 globals->get_scenery()->get_scene_graph()
1334 ->addChild(simgear::Particles::getCommonRoot());
1335 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
1337 ////////////////////////////////////////////////////////////////////
1338 // Initialize the flight model subsystem.
1339 ////////////////////////////////////////////////////////////////////
1341 globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
1343 ////////////////////////////////////////////////////////////////////
1344 // Initialize the weather subsystem.
1345 ////////////////////////////////////////////////////////////////////
1347 // Initialize the weather modeling subsystem
1348 globals->add_subsystem("environment", new FGEnvironmentMgr);
1350 ////////////////////////////////////////////////////////////////////
1351 // Initialize the aircraft systems and instrumentation (before the
1353 ////////////////////////////////////////////////////////////////////
1355 globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
1356 globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
1358 ////////////////////////////////////////////////////////////////////
1359 // Initialize the XML Autopilot subsystem.
1360 ////////////////////////////////////////////////////////////////////
1362 globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance(), SGSubsystemMgr::FDM );
1363 globals->add_subsystem( "route-manager", new FGRouteMgr );
1365 ////////////////////////////////////////////////////////////////////
1366 // Initialize the Input-Output subsystem
1367 ////////////////////////////////////////////////////////////////////
1368 globals->add_subsystem( "io", new FGIO );
1370 ////////////////////////////////////////////////////////////////////
1371 // Create and register the logger.
1372 ////////////////////////////////////////////////////////////////////
1374 globals->add_subsystem("logger", new FGLogger);
1376 ////////////////////////////////////////////////////////////////////
1377 // Create and register the XML GUI.
1378 ////////////////////////////////////////////////////////////////////
1380 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1382 //////////////////////////////////////////////////////////////////////
1383 // Initialize the 2D cloud subsystem.
1384 ////////////////////////////////////////////////////////////////////
1385 fgGetBool("/sim/rendering/bump-mapping", false);
1389 ////////////////////////////////////////////////////////////////////
1390 // Initialise the ATC Manager
1391 ////////////////////////////////////////////////////////////////////
1394 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1395 globals->set_ATC_mgr(new FGATCMgr);
1396 globals->get_ATC_mgr()->init();
1398 ////////////////////////////////////////////////////////////////////
1399 // Initialise the ATIS Manager
1400 ////////////////////////////////////////////////////////////////////
1401 globals->add_subsystem("atis", new FGAtisManager, SGSubsystemMgr::POST_FDM);
1405 ////////////////////////////////////////////////////////////////////
1406 // Initialize multiplayer subsystem
1407 ////////////////////////////////////////////////////////////////////
1409 globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
1411 ////////////////////////////////////////////////////////////////////
1412 // Initialise the AI Model Manager
1413 ////////////////////////////////////////////////////////////////////
1414 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1415 globals->add_subsystem("ai_model", new FGAIManager, SGSubsystemMgr::POST_FDM);
1416 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
1419 // It's probably a good idea to initialize the top level traffic manager
1420 // After the AI and ATC systems have been initialized properly.
1421 // AI Traffic manager
1422 globals->add_subsystem("Traffic Manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
1424 ////////////////////////////////////////////////////////////////////
1425 // Add a new 2D panel.
1426 ////////////////////////////////////////////////////////////////////
1428 string panel_path(fgGetString("/sim/panel/path"));
1429 if (!panel_path.empty()) {
1430 FGPanel* p = fgReadPanel(panel_path);
1432 globals->set_current_panel(p);
1435 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1437 SG_LOG( SG_INPUT, SG_ALERT,
1438 "Error reading new panel from " << panel_path );
1442 ////////////////////////////////////////////////////////////////////
1443 // Initialize the controls subsystem.
1444 ////////////////////////////////////////////////////////////////////
1446 globals->get_controls()->init();
1447 globals->get_controls()->bind();
1450 ////////////////////////////////////////////////////////////////////
1451 // Initialize the input subsystem.
1452 ////////////////////////////////////////////////////////////////////
1454 globals->add_subsystem("input", new FGInput);
1457 ////////////////////////////////////////////////////////////////////
1458 // Initialize the replay subsystem
1459 ////////////////////////////////////////////////////////////////////
1460 globals->add_subsystem("replay", new FGReplay);
1462 #ifdef ENABLE_AUDIO_SUPPORT
1463 ////////////////////////////////////////////////////////////////////
1464 // Initialize the sound-effects subsystem.
1465 ////////////////////////////////////////////////////////////////////
1466 globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
1469 ////////////////////////////////////////////////////////////////////
1470 // Initialize the lighting subsystem.
1471 ////////////////////////////////////////////////////////////////////
1473 globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
1475 // ordering here is important : Nasal (via events), then models, then views
1476 globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
1478 FGAircraftModel* acm = new FGAircraftModel;
1479 globals->set_aircraft_model(acm);
1480 globals->add_subsystem("aircraft-model", acm, SGSubsystemMgr::DISPLAY);
1482 FGModelMgr* mm = new FGModelMgr;
1483 globals->set_model_mgr(mm);
1484 globals->add_subsystem("model-manager", mm, SGSubsystemMgr::DISPLAY);
1486 FGViewMgr *viewmgr = new FGViewMgr;
1487 globals->set_viewmgr( viewmgr );
1488 globals->add_subsystem("view-manager", viewmgr, SGSubsystemMgr::DISPLAY);
1490 globals->add_subsystem("tile-manager", globals->get_tile_mgr(),
1491 SGSubsystemMgr::DISPLAY);
1493 ////////////////////////////////////////////////////////////////////
1494 // Bind and initialize subsystems.
1495 ////////////////////////////////////////////////////////////////////
1497 globals->get_subsystem_mgr()->bind();
1498 globals->get_subsystem_mgr()->init();
1500 ////////////////////////////////////////////////////////////////////////
1501 // Initialize the Nasal interpreter.
1502 // Do this last, so that the loaded scripts see initialized state
1503 ////////////////////////////////////////////////////////////////////////
1504 FGNasalSys* nasal = new FGNasalSys();
1505 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1508 // initialize methods that depend on other subsystems.
1509 globals->get_subsystem_mgr()->postinit();
1511 ////////////////////////////////////////////////////////////////////////
1512 // End of subsystem initialization.
1513 ////////////////////////////////////////////////////////////////////
1515 fgSetBool("/sim/initialized", true);
1517 SG_LOG( SG_GENERAL, SG_INFO, endl);
1519 // Save the initial state for future
1521 globals->saveInitialState();
1527 void fgReInitSubsystems()
1529 static const SGPropertyNode *master_freeze
1530 = fgGetNode("/sim/freeze/master");
1532 SG_LOG( SG_GENERAL, SG_INFO, "fgReInitSubsystems()");
1534 // setup state to begin re-init
1535 bool freeze = master_freeze->getBoolValue();
1537 fgSetBool("/sim/freeze/master", true);
1540 fgSetBool("/sim/signals/reinit", true);
1541 fgSetBool("/sim/crashed", false);
1543 // do actual re-init steps
1544 globals->get_subsystem("flight")->unbind();
1546 // reset control state, before restoring initial state; -set or config files
1547 // may specify values for flaps, trim tabs, magnetos, etc
1548 globals->get_controls()->reset_all();
1550 globals->restoreInitialState();
1552 // update our position based on current presets
1555 // Force reupdating the positions of the ai 3d models. They are used for
1556 // initializing ground level for the FDM.
1557 globals->get_subsystem("ai_model")->reinit();
1559 // Initialize the FDM
1560 globals->get_subsystem("flight")->reinit();
1562 // reload offsets from config defaults
1563 globals->get_viewmgr()->reinit();
1565 globals->get_subsystem("time")->reinit();
1566 globals->get_subsystem("tile-manager")->reinit();
1568 // setup state to end re-init
1569 fgSetBool("/sim/signals/reinit", false);
1571 fgSetBool("/sim/freeze/master", false);
1573 fgSetBool("/sim/sceneryloaded",false);
1577 void doSimulatorReset(void) // from gui_local.cxx -- TODO merge with fgReInitSubsystems()
1581 fgReInitSubsystems();
1584 ///////////////////////////////////////////////////////////////////////////////
1585 // helper object to implement the --show-aircraft command.
1586 // resides here so we can share the fgFindAircraftInDir template above,
1587 // and hence ensure this command lists exectly the same aircraft as the normal
1594 _minStatus = getNumMaturity(fgGetString("/sim/aircraft-min-status", "all"));
1598 void show(const SGPath& path)
1600 fgFindAircraftInDir(path, this, &ShowAircraft::processAircraft);
1602 std::sort(_aircraft.begin(), _aircraft.end(), ciLessLibC());
1603 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on Windows
1604 cout << "Available aircraft:" << endl;
1605 for ( unsigned int i = 0; i < _aircraft.size(); i++ ) {
1606 cout << _aircraft[i] << endl;
1611 bool processAircraft(const SGPath& path)
1613 SGPropertyNode root;
1615 readProperties(path.str(), &root);
1616 } catch (sg_exception& ) {
1621 string descStr(" ");
1622 descStr += path.file();
1623 // trim common suffix from file names
1624 int nPos = descStr.rfind("-set.xml");
1625 if (nPos == (int)(descStr.size() - 8)) {
1626 descStr.resize(nPos);
1629 SGPropertyNode *node = root.getNode("sim");
1631 SGPropertyNode* desc = node->getNode("description");
1632 // if a status tag is found, read it in
1633 if (node->hasValue("status")) {
1634 maturity = getNumMaturity(node->getStringValue("status"));
1638 if (descStr.size() <= 27+3) {
1639 descStr.append(29+3-descStr.size(), ' ');
1642 descStr.append( 32, ' ');
1644 descStr += desc->getStringValue();
1646 } // of have 'sim' node
1648 if (maturity < _minStatus) {
1652 _aircraft.push_back(descStr);
1657 int getNumMaturity(const char * str)
1659 // changes should also be reflected in $FG_ROOT/data/options.xml &
1660 // $FG_ROOT/data/Translations/string-default.xml
1661 const char* levels[] = {"alpha","beta","early-production","production"};
1663 if (!strcmp(str, "all")) {
1667 for (size_t i=0; i<(sizeof(levels)/sizeof(levels[0]));i++)
1668 if (strcmp(str,levels[i])==0)
1674 // recommended in Meyers, Effective STL when internationalization and embedded
1675 // NULLs aren't an issue. Much faster than the STL or Boost lex versions.
1676 struct ciLessLibC : public std::binary_function<string, string, bool>
1678 bool operator()(const std::string &lhs, const std::string &rhs) const
1680 return strcasecmp(lhs.c_str(), rhs.c_str()) < 0 ? 1 : 0;
1685 string_list _aircraft;
1688 void fgShowAircraft(const SGPath &path)
1694 cout << "Hit a key to continue..." << endl;