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/structure/SGPerfMon.hxx>
60 #include <simgear/misc/sg_path.hxx>
61 #include <simgear/misc/sg_dir.hxx>
62 #include <simgear/misc/sgstream.hxx>
63 #include <simgear/misc/strutils.hxx>
64 #include <simgear/props/props_io.hxx>
66 #include <simgear/misc/interpolator.hxx>
67 #include <simgear/scene/material/matlib.hxx>
68 #include <simgear/scene/model/particles.hxx>
69 #include <simgear/sound/soundmgr_openal.hxx>
71 #include <Aircraft/controls.hxx>
72 #include <Aircraft/replay.hxx>
73 #include <Airports/apt_loader.hxx>
74 #include <Airports/runways.hxx>
75 #include <Airports/simple.hxx>
76 #include <Airports/dynamics.hxx>
78 #include <AIModel/AIManager.hxx>
80 #include <ATCDCL/ATCmgr.hxx>
81 #include <ATC/atc_mgr.hxx>
83 #include <Autopilot/route_mgr.hxx>
84 #include <Autopilot/autopilotgroup.hxx>
86 #include <Cockpit/panel.hxx>
87 #include <Cockpit/panel_io.hxx>
89 #include <GUI/new_gui.hxx>
90 #include <Input/input.hxx>
91 #include <Instrumentation/instrument_mgr.hxx>
92 #include <Model/acmodel.hxx>
93 #include <Model/modelmgr.hxx>
94 #include <AIModel/submodel.hxx>
95 #include <AIModel/AIManager.hxx>
96 #include <Navaids/navdb.hxx>
97 #include <Navaids/navlist.hxx>
98 #include <Navaids/fix.hxx>
99 #include <Navaids/fixlist.hxx>
100 #include <Navaids/airways.hxx>
101 #include <Scenery/scenery.hxx>
102 #include <Scenery/tilemgr.hxx>
103 #include <Scripting/NasalSys.hxx>
104 #include <Sound/voice.hxx>
105 #include <Systems/system_mgr.hxx>
106 #include <Time/light.hxx>
107 #include <Traffic/TrafficMgr.hxx>
108 #include <MultiPlayer/multiplaymgr.hxx>
109 #include <FDM/fdm_shell.hxx>
110 #include <Environment/ephemeris.hxx>
111 #include <Environment/environment_mgr.hxx>
113 #include "fg_init.hxx"
115 #include "fg_commands.hxx"
116 #include "fg_props.hxx"
117 #include "options.hxx"
118 #include "globals.hxx"
119 #include "logger.hxx"
120 #include "renderer.hxx"
121 #include "viewmgr.hxx"
126 using namespace boost::algorithm;
129 // Return the current base package version
130 string fgBasePackageVersion() {
131 SGPath base_path( globals->get_fg_root() );
132 base_path.append("version");
134 sg_gzifstream in( base_path.str() );
135 if ( !in.is_open() ) {
136 SGPath old_path( globals->get_fg_root() );
137 old_path.append( "Thanks" );
138 sg_gzifstream old( old_path.str() );
139 if ( !old.is_open() ) {
142 return "[old version]";
153 // Initialize the localization
154 SGPropertyNode *fgInitLocale(const char *language) {
155 SGPropertyNode *c_node = NULL, *d_node = NULL;
156 SGPropertyNode *intl = fgGetNode("/sim/intl");
158 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
160 // localization not defined
165 // Select the proper language from the list
167 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
168 for (unsigned int i = 0; i < locale.size(); i++) {
170 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
171 for (unsigned int j = 0; j < lang.size(); j++) {
173 if (!strcmp(lang[j]->getStringValue(), language)) {
182 d_node = intl->getChild("locale");
186 // Check for localized font
187 SGPropertyNode *font_n = c_node->getNode("font", true);
188 if ( !strcmp(font_n->getStringValue(), "") )
189 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
193 // Load the default strings
195 SGPath d_path( globals->get_fg_root() );
197 const char *d_path_str = d_node->getStringValue("strings");
199 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << d_node->getPath() << "/strings.");
203 d_path.append(d_path_str);
204 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << d_path.str());
206 SGPropertyNode *strings = c_node->getNode("strings");
208 readProperties(d_path.str(), strings);
209 } catch (const sg_exception &) {
210 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
215 // Load the language specific strings
217 if (c_node != d_node) {
218 SGPath c_path( globals->get_fg_root() );
220 const char *c_path_str = c_node->getStringValue("strings");
222 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << c_node->getPath() << "/strings");
226 c_path.append(c_path_str);
227 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << c_path.str());
230 readProperties(c_path.str(), strings);
231 } catch (const sg_exception &) {
232 SG_LOG(SG_GENERAL, SG_ALERT,
233 "Unable to read the localized strings from " << c_path.str());
243 // Initialize the localization routines
244 bool fgDetectLanguage() {
245 const char *language = ::getenv("LANG");
247 if (language == NULL) {
248 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
252 SGPropertyNode *locale = fgInitLocale(language);
254 SG_LOG(SG_GENERAL, SG_ALERT,
255 "No internationalization settings specified in preferences.xml" );
260 globals->set_locale( locale );
266 bool fgFindAircraftInDir(const SGPath& dirPath, T* obj, bool (T::*pred)(const SGPath& p))
268 if (!dirPath.exists()) {
269 SG_LOG(SG_GENERAL, SG_WARN, "fgFindAircraftInDir: no such path:" << dirPath.str());
274 simgear::Dir dir(dirPath);
275 simgear::PathList setFiles(dir.children(simgear::Dir::TYPE_FILE, "-set.xml"));
276 simgear::PathList::iterator p;
277 for (p = setFiles.begin(); p != setFiles.end(); ++p) {
278 // check file name ends with -set.xml
280 // if we found a -set.xml at this level, don't recurse any deeper
283 bool done = (obj->*pred)(*p);
287 } // of -set.xml iteration
293 simgear::PathList subdirs(dir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT));
294 for (p = subdirs.begin(); p != subdirs.end(); ++p) {
295 if (p->file() == "CVS") {
299 if (fgFindAircraftInDir(*p, obj, pred)) {
302 } // of subdirs iteration
308 void fgFindAircraft(T* obj, bool (T::*pred)(const SGPath& p))
310 const string_list& paths(globals->get_aircraft_paths());
311 string_list::const_iterator it = paths.begin();
312 for (; it != paths.end(); ++it) {
313 bool done = fgFindAircraftInDir(SGPath(*it), obj, pred);
317 } // of aircraft paths iteration
319 // if we reach this point, search the default location (always last)
320 SGPath rootAircraft(globals->get_fg_root());
321 rootAircraft.append("Aircraft");
322 fgFindAircraftInDir(rootAircraft, obj, pred);
325 class FindAndCacheAircraft
328 FindAndCacheAircraft(SGPropertyNode* autoSave)
330 _cache = autoSave->getNode("sim/startup/path-cache", true);
335 std::string aircraft = fgGetString( "/sim/aircraft", "");
336 if (aircraft.empty()) {
337 SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
341 _searchAircraft = aircraft + "-set.xml";
342 std::string aircraftDir = fgGetString("/sim/aircraft-dir", "");
343 if (!aircraftDir.empty()) {
344 // aircraft-dir was set, skip any searching at all, if it's valid
345 simgear::Dir acPath(aircraftDir);
346 SGPath setFile = acPath.file(_searchAircraft);
347 if (setFile.exists()) {
348 SG_LOG(SG_GENERAL, SG_INFO, "found aircraft in dir: " << aircraftDir );
351 readProperties(setFile.str(), globals->get_props());
352 } catch ( const sg_exception &e ) {
353 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
359 SG_LOG(SG_GENERAL, SG_ALERT, "aircraft '" << _searchAircraft <<
360 "' not found in specified dir:" << aircraftDir);
366 // prepare cache for re-scan
367 SGPropertyNode *n = _cache->getNode("fg-root", true);
368 n->setStringValue(globals->get_fg_root().c_str());
369 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
370 n = _cache->getNode("fg-aircraft", true);
371 n->setStringValue(getAircraftPaths().c_str());
372 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
373 _cache->removeChildren("aircraft");
375 fgFindAircraft(this, &FindAndCacheAircraft::checkAircraft);
378 if (_foundPath.str().empty()) {
379 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
383 SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
384 fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
385 if (!_foundPath.exists()) {
386 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
391 readProperties(_foundPath.str(), globals->get_props());
392 } catch ( const sg_exception &e ) {
393 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
401 SGPath getAircraftPaths() {
402 string_list pathList = globals->get_aircraft_paths();
403 SGPath aircraftPaths;
404 string_list::const_iterator it = pathList.begin();
405 if (it != pathList.end()) {
406 aircraftPaths.set(*it);
409 for (; it != pathList.end(); ++it) {
410 aircraftPaths.add(*it);
412 return aircraftPaths;
417 if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
418 return false; // cache mismatch
421 if (getAircraftPaths().str() != _cache->getStringValue("fg-aircraft", "")) {
422 return false; // cache mismatch
425 vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
426 for (unsigned int i = 0; i < cache.size(); i++) {
427 const char *name = cache[i]->getStringValue("file", "");
428 if (!boost::equals(_searchAircraft, name, is_iequal())) {
432 SGPath xml(cache[i]->getStringValue("path", ""));
440 } // of aircraft in cache iteration
445 bool checkAircraft(const SGPath& p)
450 if (!_cache->getChild("aircraft", i++, false))
454 SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
456 std::string fileName(p.file());
457 n = entry->getNode("file", true);
458 n->setStringValue(fileName);
459 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
461 n = entry->getNode("path", true);
462 n->setStringValue(p.dir());
463 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
465 if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
473 std::string _searchAircraft;
475 SGPropertyNode* _cache;
479 static SGPath platformDefaultDataPath()
481 char *envp = ::getenv( "APPDATA" );
482 SGPath config( envp );
483 config.append( "flightgear.org" );
488 #include <CoreServices/CoreServices.h>
490 static SGPath platformDefaultDataPath()
493 OSErr err = FSFindFolder(kUserDomain, kApplicationSupportFolderType, false, &ref);
498 unsigned char path[1024];
499 if (FSRefMakePath(&ref, path, 1024) != noErr) {
504 appData.set((const char*) path);
505 appData.append("flightgear.org");
509 static SGPath platformDefaultDataPath()
511 SGPath config( homedir );
512 config.append( ".fgfs" );
517 // Read in configuration (file and command line)
518 bool fgInitConfig ( int argc, char **argv )
520 SGPath dataPath = platformDefaultDataPath();
522 const char *fg_home = getenv("FG_HOME");
526 simgear::Dir exportDir(simgear::Dir(dataPath).file("Export"));
527 if (!exportDir.exists()) {
528 exportDir.create(0777);
531 // Set /sim/fg-home and don't allow malign code to override it until
532 // Nasal security is set up. Use FG_HOME if necessary.
533 SGPropertyNode *home = fgGetNode("/sim", true);
534 home->removeChild("fg-home", 0, false);
535 home = home->getChild("fg-home", 0, true);
536 home->setStringValue(dataPath.c_str());
537 home->setAttribute(SGPropertyNode::WRITE, false);
539 flightgear::Options::sharedInstance()->init(argc, argv, dataPath);
541 // Read global preferences from $FG_ROOT/preferences.xml
542 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
543 fgLoadProps("preferences.xml", globals->get_props());
544 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
546 // Detect the required language as early as possible
547 if ( !fgDetectLanguage() ) {
551 SGPropertyNode autosave;
554 SGPath autosaveFile = simgear::Dir(dataPath).file("autosave.xml");
555 if (autosaveFile.exists()) {
556 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << autosaveFile.str());
558 readProperties(autosaveFile.str(), &autosave, SGPropertyNode::USERARCHIVE);
559 } catch (sg_exception& e) {
560 SG_LOG(SG_INPUT, SG_WARN, "failed to read user settings:" << e.getMessage()
561 << "(from " << e.getOrigin() << ")");
565 // Scan user config files and command line for a specified aircraft.
566 flightgear::Options::sharedInstance()->initAircraft();
568 FindAndCacheAircraft f(&autosave);
569 if (!f.loadAircraft()) {
573 copyProperties(&autosave, globals->get_props());
575 // parse options after loading aircraft to ensure any user
576 // overrides of defaults are honored.
577 flightgear::Options::sharedInstance()->processOptions();
582 // Set current tower position lon/lat given an airport id
583 static bool fgSetTowerPosFromAirportID( const string& id) {
584 const FGAirport *a = fgFindAirportID( id);
586 SGGeod tower = a->getTowerLocation();
587 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
588 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
589 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
597 struct FGTowerLocationListener : SGPropertyChangeListener {
598 void valueChanged(SGPropertyNode* node) {
599 string id(node->getStringValue());
600 if (fgGetBool("/sim/tower/auto-position",true))
602 // enforce using closest airport when auto-positioning is enabled
603 const char* closest_airport = fgGetString("/sim/airport/closest-airport-id", "");
604 if (closest_airport && (id != closest_airport))
606 id = closest_airport;
607 node->setStringValue(id);
610 fgSetTowerPosFromAirportID(id);
614 struct FGClosestTowerLocationListener : SGPropertyChangeListener
616 void valueChanged(SGPropertyNode* )
618 // closest airport has changed
619 if (fgGetBool("/sim/tower/auto-position",true))
621 // update tower position
622 const char* id = fgGetString("/sim/airport/closest-airport-id", "");
624 fgSetString("/sim/tower/airport-id", id);
629 void fgInitTowerLocationListener() {
630 fgGetNode("/sim/tower/airport-id", true)
631 ->addChangeListener( new FGTowerLocationListener(), true );
632 FGClosestTowerLocationListener* ntcl = new FGClosestTowerLocationListener();
633 fgGetNode("/sim/airport/closest-airport-id", true)
634 ->addChangeListener(ntcl , true );
635 fgGetNode("/sim/tower/auto-position", true)
636 ->addChangeListener(ntcl, true );
639 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
641 SGGeod startPos(aStartPos);
642 if (aTargetHeading == HUGE_VAL) {
643 aTargetHeading = aHeading;
646 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
647 double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
648 offsetDistance *= SG_NM_TO_METER;
649 double offsetAzimuth = aHeading;
650 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
651 offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
652 aHeading = aTargetHeading;
657 SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
662 fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
663 fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
664 fgSetDouble("/sim/presets/heading-deg", aHeading );
666 // other code depends on the actual values being set ...
667 fgSetDouble("/position/longitude-deg", startPos.getLongitudeDeg() );
668 fgSetDouble("/position/latitude-deg", startPos.getLatitudeDeg() );
669 fgSetDouble("/orientation/heading-deg", aHeading );
672 // Set current_options lon/lat given an airport id and heading (degrees)
673 bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
677 // set initial position from runway and heading
678 SG_LOG( SG_GENERAL, SG_INFO,
679 "Attempting to set starting position from airport code "
680 << id << " heading " << tgt_hdg );
682 const FGAirport* apt = fgFindAirportID(id);
683 if (!apt) return false;
684 FGRunway* r = apt->findBestRunwayForHeading(tgt_hdg);
685 fgSetString("/sim/atc/runway", r->ident().c_str());
687 SGGeod startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
688 fgApplyStartOffset(startPos, r->headingDeg(), tgt_hdg);
692 // Set current_options lon/lat given an airport id and parkig position name
693 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
697 // can't see an easy way around this const_cast at the moment
698 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
700 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
703 FGAirportDynamics* dcs = apt->getDynamics();
705 SG_LOG( SG_GENERAL, SG_ALERT,
706 "Airport " << id << "does not appear to have parking information available");
710 int park_index = dcs->getNrOfParkings() - 1;
712 double radius = fgGetDouble("/sim/dimensions/radius-m");
713 if ((parkpos == string("AVAILABLE")) && (radius > 0)) {
714 double lat, lon, heading;
719 acData = fgGetString("/sim/fg-home");
720 acData.append("aircraft-data");
721 string acfile = fgGetString("/sim/aircraft") + string(".xml");
722 acData.append(acfile);
724 readProperties(acData.str(), &root);
725 SGPropertyNode * node = root.getNode("sim");
726 fltType = node->getStringValue("aircraft-class", "NONE" );
727 acOperator = node->getStringValue("aircraft-operator", "NONE" );
728 } catch (const sg_exception &) {
729 SG_LOG(SG_GENERAL, SG_INFO,
730 "Could not load aircraft aircrat type and operator information from: " << acData.str() << ". Using defaults");
732 // cout << path.str() << endl;
734 if (fltType.empty() || fltType == "NONE") {
735 SG_LOG(SG_GENERAL, SG_INFO,
736 "Aircraft type information not found in: " << acData.str() << ". Using default value");
737 fltType = fgGetString("/sim/aircraft-class" );
739 if (acOperator.empty() || fltType == "NONE") {
740 SG_LOG(SG_GENERAL, SG_INFO,
741 "Aircraft operator information not found in: " << acData.str() << ". Using default value");
742 acOperator = fgGetString("/sim/aircraft-operator" );
745 cerr << "Running aircraft " << fltType << " of livery " << acOperator << endl;
746 string acType; // Currently not used by findAvailable parking, so safe to leave empty.
747 succes = dcs->getAvailableParking(&lat, &lon, &heading, &park_index, radius, fltType, acType, acOperator);
749 fgGetString("/sim/presets/parkpos");
750 fgSetString("/sim/presets/parkpos", dcs->getParking(park_index)->getName());
752 SG_LOG( SG_GENERAL, SG_ALERT,
753 "Failed to find a suitable parking at airport " << id );
757 //cerr << "We shouldn't get here when AVAILABLE" << endl;
758 while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
759 if (park_index < 0) {
760 SG_LOG( SG_GENERAL, SG_ALERT,
761 "Failed to find parking position " << parkpos <<
762 " at airport " << id );
766 FGParking* parking = dcs->getParking(park_index);
767 parking->setAvailable(false);
769 SGGeod::fromDeg(parking->getLongitude(), parking->getLatitude()),
770 parking->getHeading());
775 // Set current_options lon/lat given an airport id and runway number
776 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
780 // set initial position from airport and runway number
781 SG_LOG( SG_GENERAL, SG_INFO,
782 "Attempting to set starting position for "
783 << id << ":" << rwy );
785 const FGAirport* apt = fgFindAirportID(id);
787 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
791 if (!apt->hasRunwayWithIdent(rwy)) {
792 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
793 "Failed to find runway " << rwy <<
794 " at airport " << id << ". Using default runway." );
798 FGRunway* r(apt->getRunwayByIdent(rwy));
799 fgSetString("/sim/atc/runway", r->ident().c_str());
800 SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
801 fgApplyStartOffset(startPos, r->headingDeg());
806 static void fgSetDistOrAltFromGlideSlope() {
807 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
808 string apt_id = fgGetString("/sim/presets/airport-id");
809 double gs = fgGetDouble("/sim/presets/glideslope-deg")
810 * SG_DEGREES_TO_RADIANS ;
811 double od = fgGetDouble("/sim/presets/offset-distance-nm");
812 double alt = fgGetDouble("/sim/presets/altitude-ft");
814 double apt_elev = 0.0;
815 if ( ! apt_id.empty() ) {
816 apt_elev = fgGetAirportElev( apt_id );
817 if ( apt_elev < -9990.0 ) {
824 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
825 // set altitude from glideslope and offset-distance
826 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
827 alt = fabs(od*tan(gs)) + apt_elev;
828 fgSetDouble("/sim/presets/altitude-ft", alt);
829 fgSetBool("/sim/presets/onground", false);
830 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
832 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
833 // set offset-distance from glideslope and altitude
834 od = (alt - apt_elev) / tan(gs);
835 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
836 fgSetDouble("/sim/presets/offset-distance-nm", od);
837 fgSetBool("/sim/presets/onground", false);
838 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
840 } else if( fabs(gs) > 0.01 ) {
841 SG_LOG( SG_GENERAL, SG_ALERT,
842 "Glideslope given but not altitude or offset-distance." );
843 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
844 fgSetDouble("/sim/presets/glideslope-deg", 0);
845 fgSetBool("/sim/presets/onground", true);
850 // Set current_options lon/lat given an airport id and heading (degrees)
851 static bool fgSetPosFromNAV( const string& id, const double& freq, FGPositioned::Type type ) {
853 const nav_list_type navlist
854 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq, type );
856 if (navlist.size() == 0 ) {
857 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
858 << id << ":" << freq );
862 if( navlist.size() > 1 ) {
864 buf << "Ambigous NAV-ID: '" << id << "'. Specify id and frequency. Available stations:" << endl;
865 for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
866 // NDB stored in kHz, VOR stored in MHz * 100 :-P
867 double factor = (*it)->type() == FGPositioned::NDB ? 1.0 : 1/100.0;
868 string unit = (*it)->type() == FGPositioned::NDB ? "kHz" : "MHz";
869 buf << (*it)->ident() << " "
870 << setprecision(5) << (double)((*it)->get_freq() * factor) << " "
871 << (*it)->get_lat() << "/" << (*it)->get_lon()
875 SG_LOG( SG_GENERAL, SG_ALERT, buf.str() );
879 FGNavRecord *nav = navlist[0];
880 fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
884 // Set current_options lon/lat given an aircraft carrier id
885 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
887 // set initial position from runway and heading
891 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
892 double lon = geodPos.getLongitudeDeg();
893 double lat = geodPos.getLatitudeDeg();
894 double alt = geodPos.getElevationFt();
896 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
897 << carrier << " at lat = " << lat << ", lon = " << lon
898 << ", alt = " << alt << ", heading = " << heading);
900 fgSetDouble("/sim/presets/longitude-deg", lon);
901 fgSetDouble("/sim/presets/latitude-deg", lat);
902 fgSetDouble("/sim/presets/altitude-ft", alt);
903 fgSetDouble("/sim/presets/heading-deg", heading);
904 fgSetDouble("/position/longitude-deg", lon);
905 fgSetDouble("/position/latitude-deg", lat);
906 fgSetDouble("/position/altitude-ft", alt);
907 fgSetDouble("/orientation/heading-deg", heading);
909 fgSetString("/sim/presets/speed-set", "UVW");
910 fgSetDouble("/velocities/uBody-fps", uvw(0));
911 fgSetDouble("/velocities/vBody-fps", uvw(1));
912 fgSetDouble("/velocities/wBody-fps", uvw(2));
913 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
914 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
915 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
917 fgSetBool("/sim/presets/onground", true);
921 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
927 // Set current_options lon/lat given an airport id and heading (degrees)
928 static bool fgSetPosFromFix( const string& id )
930 FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
931 FGPositioned* fix = FGPositioned::findNextWithPartialId(NULL, id, &fixFilter);
933 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
937 fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
942 * Initialize vor/ndb/ils/fix list management and query systems (as
943 * well as simple airport db list)
948 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
950 SGPath aptdb( globals->get_fg_root() );
951 aptdb.append( "Airports/apt.dat" );
953 SGPath p_metar( globals->get_fg_root() );
954 p_metar.append( "Airports/metar.dat" );
956 fgAirportDBLoad( aptdb.str(), p_metar.str() );
957 FGAirport::installPropertyListener();
958 FGPositioned::installCommands();
960 FGNavList *navlist = new FGNavList;
961 FGNavList *loclist = new FGNavList;
962 FGNavList *gslist = new FGNavList;
963 FGNavList *dmelist = new FGNavList;
964 FGNavList *tacanlist = new FGNavList;
965 FGNavList *carrierlist = new FGNavList;
966 FGTACANList *channellist = new FGTACANList;
968 globals->set_navlist( navlist );
969 globals->set_loclist( loclist );
970 globals->set_gslist( gslist );
971 globals->set_dmelist( dmelist );
972 globals->set_tacanlist( tacanlist );
973 globals->set_carrierlist( carrierlist );
974 globals->set_channellist( channellist );
976 if ( !fgNavDBInit(navlist, loclist, gslist, dmelist, tacanlist, carrierlist, channellist) ) {
977 SG_LOG( SG_GENERAL, SG_ALERT,
978 "Problems loading one or more navigational database" );
981 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
982 SGPath p_fix( globals->get_fg_root() );
983 p_fix.append( "Navaids/fix.dat" );
985 fixlist.init( p_fix ); // adds fixes to the DB in positioned.cxx
987 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
988 flightgear::Airway::load();
994 // Set the initial position based on presets (or defaults)
995 bool fgInitPosition() {
996 // cout << "fgInitPosition()" << endl;
997 double gs = fgGetDouble("/sim/presets/glideslope-deg")
998 * SG_DEGREES_TO_RADIANS ;
999 double od = fgGetDouble("/sim/presets/offset-distance-nm");
1000 double alt = fgGetDouble("/sim/presets/altitude-ft");
1002 bool set_pos = false;
1004 // If glideslope is specified, then calculate offset-distance or
1005 // altitude relative to glide slope if either of those was not
1007 if ( fabs( gs ) > 0.01 ) {
1008 fgSetDistOrAltFromGlideSlope();
1012 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1013 // If not, check for an airport-id and use that.
1014 // If not, default to the middle of the KSFO field.
1015 // The default values for lon/lat are deliberately out of range
1016 // so that the airport-id can take effect; valid lon/lat will
1017 // override airport-id, however.
1018 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1019 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1020 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1021 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1026 string apt = fgGetString("/sim/presets/airport-id");
1027 string rwy_no = fgGetString("/sim/presets/runway");
1028 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1029 string vor = fgGetString("/sim/presets/vor-id");
1030 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1031 string ndb = fgGetString("/sim/presets/ndb-id");
1032 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1033 string carrier = fgGetString("/sim/presets/carrier");
1034 string parkpos = fgGetString("/sim/presets/parkpos");
1035 string fix = fgGetString("/sim/presets/fix");
1036 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1037 double hdg = hdg_preset->getDoubleValue();
1039 // save some start parameters, so that we can later say what the
1040 // user really requested. TODO generalize that and move it to options.cxx
1041 static bool start_options_saved = false;
1042 if (!start_options_saved) {
1043 start_options_saved = true;
1044 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1046 opt->setDoubleValue("latitude-deg", lat_deg);
1047 opt->setDoubleValue("longitude-deg", lon_deg);
1048 opt->setDoubleValue("heading-deg", hdg);
1049 opt->setStringValue("airport", apt.c_str());
1050 opt->setStringValue("runway", rwy_no.c_str());
1054 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1056 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1057 // An airport + parking position is requested
1058 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1059 // set tower position
1060 fgSetString("/sim/airport/closest-airport-id", apt.c_str());
1061 fgSetString("/sim/tower/airport-id", apt.c_str());
1066 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1067 // An airport + runway is requested
1068 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1069 // set tower position (a little off the heading for single
1071 fgSetString("/sim/airport/closest-airport-id", apt.c_str());
1072 fgSetString("/sim/tower/airport-id", apt.c_str());
1077 if ( !set_pos && !apt.empty() ) {
1078 // An airport is requested (find runway closest to hdg)
1079 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1080 // set tower position (a little off the heading for single
1082 fgSetString("/sim/airport/closest-airport-id", apt.c_str());
1083 fgSetString("/sim/tower/airport-id", apt.c_str());
1088 if (hdg_preset->getDoubleValue() > 9990.0)
1089 hdg_preset->setDoubleValue(hdg);
1091 if ( !set_pos && !vor.empty() ) {
1092 // a VOR is requested
1093 if ( fgSetPosFromNAV( vor, vor_freq, FGPositioned::VOR ) ) {
1098 if ( !set_pos && !ndb.empty() ) {
1099 // an NDB is requested
1100 if ( fgSetPosFromNAV( ndb, ndb_freq, FGPositioned::NDB ) ) {
1105 if ( !set_pos && !carrier.empty() ) {
1106 // an aircraft carrier is requested
1107 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1112 if ( !set_pos && !fix.empty() ) {
1113 // a Fix is requested
1114 if ( fgSetPosFromFix( fix ) ) {
1120 // No lon/lat specified, no airport specified, default to
1121 // middle of KSFO field.
1122 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1123 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1126 fgSetDouble( "/position/longitude-deg",
1127 fgGetDouble("/sim/presets/longitude-deg") );
1128 fgSetDouble( "/position/latitude-deg",
1129 fgGetDouble("/sim/presets/latitude-deg") );
1130 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1132 // determine if this should be an on-ground or in-air start
1133 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1134 fgSetBool("/sim/presets/onground", false);
1136 fgSetBool("/sim/presets/onground", true);
1143 // General house keeping initializations
1144 bool fgInitGeneral() {
1147 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1148 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1150 root = globals->get_fg_root();
1151 if ( ! root.length() ) {
1152 // No root path set? Then bail ...
1153 SG_LOG( SG_GENERAL, SG_ALERT,
1154 "Cannot continue without a path to the base package "
1155 << "being defined." );
1158 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1160 globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1162 char buf[512], *cwd = getcwd(buf, 511);
1164 SGPropertyNode *curr = fgGetNode("/sim", true);
1165 curr->removeChild("fg-current", 0, false);
1166 curr = curr->getChild("fg-current", 0, true);
1167 curr->setStringValue(cwd ? cwd : "");
1168 curr->setAttribute(SGPropertyNode::WRITE, false);
1170 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
1171 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
1175 // This is the top level init routine which calls all the other
1176 // initialization routines. If you are adding a subsystem to flight
1177 // gear, its initialization call should located in this routine.
1178 // Returns non-zero if a problem encountered.
1179 bool fgInitSubsystems() {
1181 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1182 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1184 ////////////////////////////////////////////////////////////////////
1185 // Initialize the sound subsystem.
1186 ////////////////////////////////////////////////////////////////////
1187 // Sound manager uses an own subsystem group "SOUND" which is the last
1188 // to be updated in every loop.
1189 // Sound manager is updated last so it can use the CPU while the GPU
1190 // is processing the scenery (doubled the frame-rate for me) -EMH-
1191 globals->add_subsystem("sound", new SGSoundMgr, SGSubsystemMgr::SOUND);
1193 ////////////////////////////////////////////////////////////////////
1194 // Initialize the event manager subsystem.
1195 ////////////////////////////////////////////////////////////////////
1197 globals->get_event_mgr()->init();
1198 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1200 ////////////////////////////////////////////////////////////////////
1201 // Initialize the property interpolator subsystem. Put into the INIT
1202 // group because the "nasal" subsystem may need it at GENERAL take-down.
1203 ////////////////////////////////////////////////////////////////////
1204 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1207 ////////////////////////////////////////////////////////////////////
1208 // Add the FlightGear property utilities.
1209 ////////////////////////////////////////////////////////////////////
1210 globals->add_subsystem("properties", new FGProperties);
1213 ////////////////////////////////////////////////////////////////////
1214 // Add the performance monitoring system.
1215 ////////////////////////////////////////////////////////////////////
1216 globals->add_subsystem("performance-mon",
1217 new SGPerformanceMonitor(globals->get_subsystem_mgr(),
1218 fgGetNode("/sim/performance-monitor", true)));
1220 ////////////////////////////////////////////////////////////////////
1221 // Initialize the material property subsystem.
1222 ////////////////////////////////////////////////////////////////////
1224 SGPath mpath( globals->get_fg_root() );
1225 mpath.append( fgGetString("/sim/rendering/materials-file") );
1226 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
1227 globals->get_props()) ) {
1228 SG_LOG( SG_GENERAL, SG_ALERT,
1229 "Error loading materials file " << mpath.str() );
1234 ////////////////////////////////////////////////////////////////////
1235 // Initialize the scenery management subsystem.
1236 ////////////////////////////////////////////////////////////////////
1238 globals->get_scenery()->get_scene_graph()
1239 ->addChild(simgear::Particles::getCommonRoot());
1240 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
1242 ////////////////////////////////////////////////////////////////////
1243 // Initialize the flight model subsystem.
1244 ////////////////////////////////////////////////////////////////////
1246 globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
1248 ////////////////////////////////////////////////////////////////////
1249 // Initialize the weather subsystem.
1250 ////////////////////////////////////////////////////////////////////
1252 // Initialize the weather modeling subsystem
1253 globals->add_subsystem("environment", new FGEnvironmentMgr);
1254 globals->add_subsystem("ephemeris", new Ephemeris);
1256 ////////////////////////////////////////////////////////////////////
1257 // Initialize the aircraft systems and instrumentation (before the
1259 ////////////////////////////////////////////////////////////////////
1261 globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
1262 globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
1264 ////////////////////////////////////////////////////////////////////
1265 // Initialize the XML Autopilot subsystem.
1266 ////////////////////////////////////////////////////////////////////
1268 globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance(), SGSubsystemMgr::FDM );
1269 globals->add_subsystem( "route-manager", new FGRouteMgr );
1271 ////////////////////////////////////////////////////////////////////
1272 // Initialize the Input-Output subsystem
1273 ////////////////////////////////////////////////////////////////////
1274 globals->add_subsystem( "io", new FGIO );
1276 ////////////////////////////////////////////////////////////////////
1277 // Create and register the logger.
1278 ////////////////////////////////////////////////////////////////////
1280 globals->add_subsystem("logger", new FGLogger);
1282 ////////////////////////////////////////////////////////////////////
1283 // Create and register the XML GUI.
1284 ////////////////////////////////////////////////////////////////////
1286 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1288 //////////////////////////////////////////////////////////////////////
1289 // Initialize the 2D cloud subsystem.
1290 ////////////////////////////////////////////////////////////////////
1291 fgGetBool("/sim/rendering/bump-mapping", false);
1295 ////////////////////////////////////////////////////////////////////
1296 // Initialise the ATC Manager
1297 // Note that this is old stuff, but might be necessesary for the
1298 // current ATIS implementation. Therefore, leave it in here
1299 // until the ATIS system is ported over to make use of the ATIS
1300 // sub system infrastructure.
1301 ////////////////////////////////////////////////////////////////////
1303 globals->add_subsystem("ATC-old", new FGATCMgr, SGSubsystemMgr::INIT);
1305 ////////////////////////////////////////////////////////////////////
1306 // Initialize the ATC subsystem
1307 ////////////////////////////////////////////////////////////////////
1308 globals->add_subsystem("ATC", new FGATCManager, SGSubsystemMgr::POST_FDM);
1309 ////////////////////////////////////////////////////////////////////
1310 // Initialise the ATIS Subsystem
1311 ////////////////////////////////////////////////////////////////////
1312 //globals->add_subsystem("atis", new FGAtisManager, SGSubsystemMgr::POST_FDM);
1315 ////////////////////////////////////////////////////////////////////
1316 // Initialize multiplayer subsystem
1317 ////////////////////////////////////////////////////////////////////
1319 globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
1321 ////////////////////////////////////////////////////////////////////
1322 // Initialise the AI Model Manager
1323 ////////////////////////////////////////////////////////////////////
1324 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1325 globals->add_subsystem("ai-model", new FGAIManager, SGSubsystemMgr::POST_FDM);
1326 globals->add_subsystem("submodel-mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
1329 // It's probably a good idea to initialize the top level traffic manager
1330 // After the AI and ATC systems have been initialized properly.
1331 // AI Traffic manager
1332 globals->add_subsystem("traffic-manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
1334 ////////////////////////////////////////////////////////////////////
1335 // Add a new 2D panel.
1336 ////////////////////////////////////////////////////////////////////
1338 string panel_path(fgGetString("/sim/panel/path"));
1339 if (!panel_path.empty()) {
1340 FGPanel* p = fgReadPanel(panel_path);
1342 globals->set_current_panel(p);
1345 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1347 SG_LOG( SG_INPUT, SG_ALERT,
1348 "Error reading new panel from " << panel_path );
1352 ////////////////////////////////////////////////////////////////////
1353 // Initialize the controls subsystem.
1354 ////////////////////////////////////////////////////////////////////
1356 globals->get_controls()->init();
1357 globals->get_controls()->bind();
1360 ////////////////////////////////////////////////////////////////////
1361 // Initialize the input subsystem.
1362 ////////////////////////////////////////////////////////////////////
1364 globals->add_subsystem("input", new FGInput);
1367 ////////////////////////////////////////////////////////////////////
1368 // Initialize the replay subsystem
1369 ////////////////////////////////////////////////////////////////////
1370 globals->add_subsystem("replay", new FGReplay);
1372 #ifdef ENABLE_AUDIO_SUPPORT
1373 ////////////////////////////////////////////////////////////////////
1374 // Initialize the sound-effects subsystem.
1375 ////////////////////////////////////////////////////////////////////
1376 globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
1379 ////////////////////////////////////////////////////////////////////
1380 // Initialize the lighting subsystem.
1381 ////////////////////////////////////////////////////////////////////
1383 globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
1385 // ordering here is important : Nasal (via events), then models, then views
1386 globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
1388 FGAircraftModel* acm = new FGAircraftModel;
1389 globals->set_aircraft_model(acm);
1390 globals->add_subsystem("aircraft-model", acm, SGSubsystemMgr::DISPLAY);
1392 FGModelMgr* mm = new FGModelMgr;
1393 globals->set_model_mgr(mm);
1394 globals->add_subsystem("model-manager", mm, SGSubsystemMgr::DISPLAY);
1396 FGViewMgr *viewmgr = new FGViewMgr;
1397 globals->set_viewmgr( viewmgr );
1398 globals->add_subsystem("view-manager", viewmgr, SGSubsystemMgr::DISPLAY);
1400 globals->add_subsystem("tile-manager", globals->get_tile_mgr(),
1401 SGSubsystemMgr::DISPLAY);
1403 ////////////////////////////////////////////////////////////////////
1404 // Bind and initialize subsystems.
1405 ////////////////////////////////////////////////////////////////////
1407 globals->get_subsystem_mgr()->bind();
1408 globals->get_subsystem_mgr()->init();
1410 ////////////////////////////////////////////////////////////////////////
1411 // Initialize the Nasal interpreter.
1412 // Do this last, so that the loaded scripts see initialized state
1413 ////////////////////////////////////////////////////////////////////////
1414 FGNasalSys* nasal = new FGNasalSys();
1415 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1418 // initialize methods that depend on other subsystems.
1419 globals->get_subsystem_mgr()->postinit();
1421 ////////////////////////////////////////////////////////////////////////
1422 // End of subsystem initialization.
1423 ////////////////////////////////////////////////////////////////////
1425 fgSetBool("/sim/initialized", true);
1427 SG_LOG( SG_GENERAL, SG_INFO, endl);
1429 // Save the initial state for future
1431 globals->saveInitialState();
1436 // Reset: this is what the 'reset' command (and hence, GUI) is attached to
1437 void fgReInitSubsystems()
1439 static const SGPropertyNode *master_freeze
1440 = fgGetNode("/sim/freeze/master");
1442 SG_LOG( SG_GENERAL, SG_INFO, "fgReInitSubsystems()");
1444 // setup state to begin re-init
1445 bool freeze = master_freeze->getBoolValue();
1447 fgSetBool("/sim/freeze/master", true);
1450 fgSetBool("/sim/signals/reinit", true);
1451 fgSetBool("/sim/crashed", false);
1453 // do actual re-init steps
1454 globals->get_subsystem("flight")->unbind();
1456 // reset control state, before restoring initial state; -set or config files
1457 // may specify values for flaps, trim tabs, magnetos, etc
1458 globals->get_controls()->reset_all();
1460 globals->restoreInitialState();
1462 // update our position based on current presets
1465 // Force reupdating the positions of the ai 3d models. They are used for
1466 // initializing ground level for the FDM.
1467 globals->get_subsystem("ai-model")->reinit();
1469 // Initialize the FDM
1470 globals->get_subsystem("flight")->reinit();
1472 // reset replay buffers
1473 globals->get_subsystem("replay")->reinit();
1475 // reload offsets from config defaults
1476 globals->get_viewmgr()->reinit();
1478 globals->get_subsystem("time")->reinit();
1480 // need to bind FDMshell again, since we manually unbound it above...
1481 globals->get_subsystem("flight")->bind();
1483 // setup state to end re-init
1484 fgSetBool("/sim/signals/reinit", false);
1486 fgSetBool("/sim/freeze/master", false);
1488 fgSetBool("/sim/sceneryloaded",false);
1492 ///////////////////////////////////////////////////////////////////////////////
1493 // helper object to implement the --show-aircraft command.
1494 // resides here so we can share the fgFindAircraftInDir template above,
1495 // and hence ensure this command lists exectly the same aircraft as the normal
1502 _minStatus = getNumMaturity(fgGetString("/sim/aircraft-min-status", "all"));
1506 void show(const SGPath& path)
1508 fgFindAircraftInDir(path, this, &ShowAircraft::processAircraft);
1510 std::sort(_aircraft.begin(), _aircraft.end(), ciLessLibC());
1511 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on Windows
1512 cout << "Available aircraft:" << endl;
1513 for ( unsigned int i = 0; i < _aircraft.size(); i++ ) {
1514 cout << _aircraft[i] << endl;
1519 bool processAircraft(const SGPath& path)
1521 SGPropertyNode root;
1523 readProperties(path.str(), &root);
1524 } catch (sg_exception& ) {
1529 string descStr(" ");
1530 descStr += path.file();
1531 // trim common suffix from file names
1532 int nPos = descStr.rfind("-set.xml");
1533 if (nPos == (int)(descStr.size() - 8)) {
1534 descStr.resize(nPos);
1537 SGPropertyNode *node = root.getNode("sim");
1539 SGPropertyNode* desc = node->getNode("description");
1540 // if a status tag is found, read it in
1541 if (node->hasValue("status")) {
1542 maturity = getNumMaturity(node->getStringValue("status"));
1546 if (descStr.size() <= 27+3) {
1547 descStr.append(29+3-descStr.size(), ' ');
1550 descStr.append( 32, ' ');
1552 descStr += desc->getStringValue();
1554 } // of have 'sim' node
1556 if (maturity < _minStatus) {
1560 _aircraft.push_back(descStr);
1565 int getNumMaturity(const char * str)
1567 // changes should also be reflected in $FG_ROOT/data/options.xml &
1568 // $FG_ROOT/data/Translations/string-default.xml
1569 const char* levels[] = {"alpha","beta","early-production","production"};
1571 if (!strcmp(str, "all")) {
1575 for (size_t i=0; i<(sizeof(levels)/sizeof(levels[0]));i++)
1576 if (strcmp(str,levels[i])==0)
1582 // recommended in Meyers, Effective STL when internationalization and embedded
1583 // NULLs aren't an issue. Much faster than the STL or Boost lex versions.
1584 struct ciLessLibC : public std::binary_function<string, string, bool>
1586 bool operator()(const std::string &lhs, const std::string &rhs) const
1588 return strcasecmp(lhs.c_str(), rhs.c_str()) < 0 ? 1 : 0;
1593 string_list _aircraft;
1596 void fgShowAircraft(const SGPath &path)
1602 cout << "Hit a key to continue..." << endl;