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()
33 # include <io.h> // isatty()
34 # define isatty _isatty
37 // work around a stdc++ lib bug in some versions of linux, but doesn't
38 // seem to hurt to have this here for all versions of Linux.
40 # define _G_NO_EXTERN_TEMPLATES
43 #include <simgear/compiler.h>
46 #include <boost/algorithm/string/compare.hpp>
47 #include <boost/algorithm/string/predicate.hpp>
49 #include <simgear/constants.h>
50 #include <simgear/debug/logstream.hxx>
51 #include <simgear/structure/exception.hxx>
52 #include <simgear/structure/event_mgr.hxx>
53 #include <simgear/structure/SGPerfMon.hxx>
54 #include <simgear/misc/sg_path.hxx>
55 #include <simgear/misc/sg_dir.hxx>
56 #include <simgear/misc/sgstream.hxx>
57 #include <simgear/misc/strutils.hxx>
58 #include <simgear/props/props_io.hxx>
60 #include <simgear/misc/interpolator.hxx>
61 #include <simgear/scene/material/matlib.hxx>
62 #include <simgear/scene/model/particles.hxx>
63 #include <simgear/sound/soundmgr_openal.hxx>
65 #include <Aircraft/controls.hxx>
66 #include <Aircraft/replay.hxx>
67 #include <Airports/apt_loader.hxx>
68 #include <Airports/runways.hxx>
69 #include <Airports/simple.hxx>
70 #include <Airports/dynamics.hxx>
72 #include <AIModel/AIManager.hxx>
74 #include <ATCDCL/ATISmgr.hxx>
75 #include <ATC/atc_mgr.hxx>
77 #include <Autopilot/route_mgr.hxx>
78 #include <Autopilot/autopilotgroup.hxx>
80 #include <Cockpit/panel.hxx>
81 #include <Cockpit/panel_io.hxx>
83 #include <Canvas/canvas_mgr.hxx>
84 #include <Canvas/gui_mgr.hxx>
85 #include <GUI/new_gui.hxx>
86 #include <Input/input.hxx>
87 #include <Instrumentation/instrument_mgr.hxx>
88 #include <Model/acmodel.hxx>
89 #include <Model/modelmgr.hxx>
90 #include <AIModel/submodel.hxx>
91 #include <AIModel/AIManager.hxx>
92 #include <Navaids/navdb.hxx>
93 #include <Navaids/navlist.hxx>
94 #include <Navaids/fix.hxx>
95 #include <Navaids/fixlist.hxx>
96 #include <Navaids/airways.hxx>
97 #include <Scenery/scenery.hxx>
98 #include <Scenery/tilemgr.hxx>
99 #include <Scripting/NasalSys.hxx>
100 #include <Sound/voice.hxx>
101 #include <Systems/system_mgr.hxx>
102 #include <Time/light.hxx>
103 #include <Traffic/TrafficMgr.hxx>
104 #include <MultiPlayer/multiplaymgr.hxx>
105 #include <FDM/fdm_shell.hxx>
106 #include <Environment/ephemeris.hxx>
107 #include <Environment/environment_mgr.hxx>
108 #include <Viewer/renderer.hxx>
109 #include <Viewer/viewmgr.hxx>
111 #include "fg_init.hxx"
113 #include "fg_commands.hxx"
114 #include "fg_props.hxx"
115 #include "options.hxx"
116 #include "globals.hxx"
117 #include "logger.hxx"
122 using namespace boost::algorithm;
125 // Return the current base package version
126 string fgBasePackageVersion() {
127 SGPath base_path( globals->get_fg_root() );
128 base_path.append("version");
130 sg_gzifstream in( base_path.str() );
131 if ( !in.is_open() ) {
132 SGPath old_path( globals->get_fg_root() );
133 old_path.append( "Thanks" );
134 sg_gzifstream old( old_path.str() );
135 if ( !old.is_open() ) {
138 return "[old version]";
150 bool fgFindAircraftInDir(const SGPath& dirPath, T* obj, bool (T::*pred)(const SGPath& p))
152 if (!dirPath.exists()) {
153 SG_LOG(SG_GENERAL, SG_WARN, "fgFindAircraftInDir: no such path:" << dirPath.str());
158 simgear::Dir dir(dirPath);
159 simgear::PathList setFiles(dir.children(simgear::Dir::TYPE_FILE, "-set.xml"));
160 simgear::PathList::iterator p;
161 for (p = setFiles.begin(); p != setFiles.end(); ++p) {
162 // check file name ends with -set.xml
164 // if we found a -set.xml at this level, don't recurse any deeper
167 bool done = (obj->*pred)(*p);
171 } // of -set.xml iteration
177 simgear::PathList subdirs(dir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT));
178 for (p = subdirs.begin(); p != subdirs.end(); ++p) {
179 if (p->file() == "CVS") {
183 if (fgFindAircraftInDir(*p, obj, pred)) {
186 } // of subdirs iteration
192 void fgFindAircraft(T* obj, bool (T::*pred)(const SGPath& p))
194 const string_list& paths(globals->get_aircraft_paths());
195 string_list::const_iterator it = paths.begin();
196 for (; it != paths.end(); ++it) {
197 bool done = fgFindAircraftInDir(SGPath(*it), obj, pred);
201 } // of aircraft paths iteration
203 // if we reach this point, search the default location (always last)
204 SGPath rootAircraft(globals->get_fg_root());
205 rootAircraft.append("Aircraft");
206 fgFindAircraftInDir(rootAircraft, obj, pred);
209 class FindAndCacheAircraft
212 FindAndCacheAircraft(SGPropertyNode* autoSave)
214 _cache = autoSave->getNode("sim/startup/path-cache", true);
219 std::string aircraft = fgGetString( "/sim/aircraft", "");
220 if (aircraft.empty()) {
221 SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
225 _searchAircraft = aircraft + "-set.xml";
226 std::string aircraftDir = fgGetString("/sim/aircraft-dir", "");
227 if (!aircraftDir.empty()) {
228 // aircraft-dir was set, skip any searching at all, if it's valid
229 simgear::Dir acPath(aircraftDir);
230 SGPath setFile = acPath.file(_searchAircraft);
231 if (setFile.exists()) {
232 SG_LOG(SG_GENERAL, SG_INFO, "found aircraft in dir: " << aircraftDir );
235 readProperties(setFile.str(), globals->get_props());
236 } catch ( const sg_exception &e ) {
237 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
243 SG_LOG(SG_GENERAL, SG_ALERT, "aircraft '" << _searchAircraft <<
244 "' not found in specified dir:" << aircraftDir);
250 // prepare cache for re-scan
251 SGPropertyNode *n = _cache->getNode("fg-root", true);
252 n->setStringValue(globals->get_fg_root().c_str());
253 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
254 n = _cache->getNode("fg-aircraft", true);
255 n->setStringValue(getAircraftPaths().c_str());
256 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
257 _cache->removeChildren("aircraft");
259 fgFindAircraft(this, &FindAndCacheAircraft::checkAircraft);
262 if (_foundPath.str().empty()) {
263 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
267 SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
268 fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
269 if (!_foundPath.exists()) {
270 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
275 readProperties(_foundPath.str(), globals->get_props());
276 } catch ( const sg_exception &e ) {
277 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
285 SGPath getAircraftPaths() {
286 string_list pathList = globals->get_aircraft_paths();
287 SGPath aircraftPaths;
288 string_list::const_iterator it = pathList.begin();
289 if (it != pathList.end()) {
290 aircraftPaths.set(*it);
293 for (; it != pathList.end(); ++it) {
294 aircraftPaths.add(*it);
296 return aircraftPaths;
301 if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
302 return false; // cache mismatch
305 if (getAircraftPaths().str() != _cache->getStringValue("fg-aircraft", "")) {
306 return false; // cache mismatch
309 vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
310 for (unsigned int i = 0; i < cache.size(); i++) {
311 const char *name = cache[i]->getStringValue("file", "");
312 if (!boost::equals(_searchAircraft, name, is_iequal())) {
316 SGPath xml(cache[i]->getStringValue("path", ""));
324 } // of aircraft in cache iteration
329 bool checkAircraft(const SGPath& p)
334 if (!_cache->getChild("aircraft", i++, false))
338 SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
340 std::string fileName(p.file());
341 n = entry->getNode("file", true);
342 n->setStringValue(fileName);
343 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
345 n = entry->getNode("path", true);
346 n->setStringValue(p.dir());
347 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
349 if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
357 std::string _searchAircraft;
359 SGPropertyNode* _cache;
363 static SGPath platformDefaultDataPath()
365 char *envp = ::getenv( "APPDATA" );
366 SGPath config( envp );
367 config.append( "flightgear.org" );
372 #include <CoreServices/CoreServices.h>
374 static SGPath platformDefaultDataPath()
377 OSErr err = FSFindFolder(kUserDomain, kApplicationSupportFolderType, false, &ref);
382 unsigned char path[1024];
383 if (FSRefMakePath(&ref, path, 1024) != noErr) {
388 appData.set((const char*) path);
389 appData.append("FlightGear");
393 static SGPath platformDefaultDataPath()
395 SGPath config( homedir );
396 config.append( ".fgfs" );
401 // Read in configuration (file and command line)
402 bool fgInitConfig ( int argc, char **argv )
404 SGPath dataPath = platformDefaultDataPath();
406 const char *fg_home = getenv("FG_HOME");
410 globals->set_fg_home(dataPath.c_str());
412 simgear::Dir exportDir(simgear::Dir(dataPath).file("Export"));
413 if (!exportDir.exists()) {
414 exportDir.create(0777);
417 // Set /sim/fg-home and don't allow malign code to override it until
418 // Nasal security is set up. Use FG_HOME if necessary.
419 SGPropertyNode *home = fgGetNode("/sim", true);
420 home->removeChild("fg-home", 0, false);
421 home = home->getChild("fg-home", 0, true);
422 home->setStringValue(dataPath.c_str());
423 home->setAttribute(SGPropertyNode::WRITE, false);
425 flightgear::Options::sharedInstance()->init(argc, argv, dataPath);
427 // Read global preferences from $FG_ROOT/preferences.xml
428 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
429 fgLoadProps("preferences.xml", globals->get_props());
430 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
432 // do not load user settings when reset to default is requested
433 if (flightgear::Options::sharedInstance()->isOptionSet("restore-defaults"))
435 SG_LOG(SG_ALL, SG_ALERT, "Ignoring user settings. Restoring defaults.");
439 globals->loadUserSettings(dataPath);
442 // Scan user config files and command line for a specified aircraft.
443 flightgear::Options::sharedInstance()->initAircraft();
445 FindAndCacheAircraft f(globals->get_props());
446 if (!f.loadAircraft()) {
450 // parse options after loading aircraft to ensure any user
451 // overrides of defaults are honored.
452 flightgear::Options::sharedInstance()->processOptions();
457 // Set current tower position lon/lat given an airport id
458 static bool fgSetTowerPosFromAirportID( const string& id) {
459 const FGAirport *a = fgFindAirportID( id);
461 SGGeod tower = a->getTowerLocation();
462 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
463 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
464 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
472 struct FGTowerLocationListener : SGPropertyChangeListener {
473 void valueChanged(SGPropertyNode* node) {
474 string id(node->getStringValue());
475 if (fgGetBool("/sim/tower/auto-position",true))
477 // enforce using closest airport when auto-positioning is enabled
478 const char* closest_airport = fgGetString("/sim/airport/closest-airport-id", "");
479 if (closest_airport && (id != closest_airport))
481 id = closest_airport;
482 node->setStringValue(id);
485 fgSetTowerPosFromAirportID(id);
489 struct FGClosestTowerLocationListener : SGPropertyChangeListener
491 void valueChanged(SGPropertyNode* )
493 // closest airport has changed
494 if (fgGetBool("/sim/tower/auto-position",true))
496 // update tower position
497 const char* id = fgGetString("/sim/airport/closest-airport-id", "");
499 fgSetString("/sim/tower/airport-id", id);
504 void fgInitTowerLocationListener() {
505 fgGetNode("/sim/tower/airport-id", true)
506 ->addChangeListener( new FGTowerLocationListener(), true );
507 FGClosestTowerLocationListener* ntcl = new FGClosestTowerLocationListener();
508 fgGetNode("/sim/airport/closest-airport-id", true)
509 ->addChangeListener(ntcl , true );
510 fgGetNode("/sim/tower/auto-position", true)
511 ->addChangeListener(ntcl, true );
514 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
516 SGGeod startPos(aStartPos);
517 if (aTargetHeading == HUGE_VAL) {
518 aTargetHeading = aHeading;
521 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
522 double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
523 offsetDistance *= SG_NM_TO_METER;
524 double offsetAzimuth = aHeading;
525 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
526 offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
527 aHeading = aTargetHeading;
532 SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
537 fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
538 fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
539 fgSetDouble("/sim/presets/heading-deg", aHeading );
541 // other code depends on the actual values being set ...
542 fgSetDouble("/position/longitude-deg", startPos.getLongitudeDeg() );
543 fgSetDouble("/position/latitude-deg", startPos.getLatitudeDeg() );
544 fgSetDouble("/orientation/heading-deg", aHeading );
547 // Set current_options lon/lat given an airport id and heading (degrees)
548 bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
552 // set initial position from runway and heading
553 SG_LOG( SG_GENERAL, SG_INFO,
554 "Attempting to set starting position from airport code "
555 << id << " heading " << tgt_hdg );
557 const FGAirport* apt = fgFindAirportID(id);
558 if (!apt) return false;
559 FGRunway* r = apt->findBestRunwayForHeading(tgt_hdg);
560 fgSetString("/sim/atc/runway", r->ident().c_str());
562 SGGeod startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
563 fgApplyStartOffset(startPos, r->headingDeg(), tgt_hdg);
567 // Set current_options lon/lat given an airport id and parkig position name
568 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
572 // can't see an easy way around this const_cast at the moment
573 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
575 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
578 FGAirportDynamics* dcs = apt->getDynamics();
580 SG_LOG( SG_GENERAL, SG_ALERT,
581 "Airport " << id << "does not appear to have parking information available");
585 int park_index = dcs->getNrOfParkings() - 1;
587 double radius = fgGetDouble("/sim/dimensions/radius-m");
588 if ((parkpos == string("AVAILABLE")) && (radius > 0)) {
589 double lat, lon, heading;
594 acData = globals->get_fg_home();
595 acData.append("aircraft-data");
596 string acfile = fgGetString("/sim/aircraft") + string(".xml");
597 acData.append(acfile);
599 readProperties(acData.str(), &root);
600 SGPropertyNode * node = root.getNode("sim");
601 fltType = node->getStringValue("aircraft-class", "NONE" );
602 acOperator = node->getStringValue("aircraft-operator", "NONE" );
603 } catch (const sg_exception &) {
604 SG_LOG(SG_GENERAL, SG_INFO,
605 "Could not load aircraft aircrat type and operator information from: " << acData.str() << ". Using defaults");
607 // cout << path.str() << endl;
609 if (fltType.empty() || fltType == "NONE") {
610 SG_LOG(SG_GENERAL, SG_INFO,
611 "Aircraft type information not found in: " << acData.str() << ". Using default value");
612 fltType = fgGetString("/sim/aircraft-class" );
614 if (acOperator.empty() || fltType == "NONE") {
615 SG_LOG(SG_GENERAL, SG_INFO,
616 "Aircraft operator information not found in: " << acData.str() << ". Using default value");
617 acOperator = fgGetString("/sim/aircraft-operator" );
620 cerr << "Running aircraft " << fltType << " of livery " << acOperator << endl;
621 string acType; // Currently not used by findAvailable parking, so safe to leave empty.
622 succes = dcs->getAvailableParking(&lat, &lon, &heading, &park_index, radius, fltType, acType, acOperator);
624 fgGetString("/sim/presets/parkpos");
625 fgSetString("/sim/presets/parkpos", dcs->getParking(park_index)->getName());
627 SG_LOG( SG_GENERAL, SG_ALERT,
628 "Failed to find a suitable parking at airport " << id );
632 //cerr << "We shouldn't get here when AVAILABLE" << endl;
633 while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
634 if (park_index < 0) {
635 SG_LOG( SG_GENERAL, SG_ALERT,
636 "Failed to find parking position " << parkpos <<
637 " at airport " << id );
641 FGParking* parking = dcs->getParking(park_index);
642 parking->setAvailable(false);
644 SGGeod::fromDeg(parking->getLongitude(), parking->getLatitude()),
645 parking->getHeading());
650 // Set current_options lon/lat given an airport id and runway number
651 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
655 // set initial position from airport and runway number
656 SG_LOG( SG_GENERAL, SG_INFO,
657 "Attempting to set starting position for "
658 << id << ":" << rwy );
660 const FGAirport* apt = fgFindAirportID(id);
662 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
666 if (!apt->hasRunwayWithIdent(rwy)) {
667 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
668 "Failed to find runway " << rwy <<
669 " at airport " << id << ". Using default runway." );
673 FGRunway* r(apt->getRunwayByIdent(rwy));
674 fgSetString("/sim/atc/runway", r->ident().c_str());
675 SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
676 fgApplyStartOffset(startPos, r->headingDeg());
681 static void fgSetDistOrAltFromGlideSlope() {
682 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
683 string apt_id = fgGetString("/sim/presets/airport-id");
684 double gs = fgGetDouble("/sim/presets/glideslope-deg")
685 * SG_DEGREES_TO_RADIANS ;
686 double od = fgGetDouble("/sim/presets/offset-distance-nm");
687 double alt = fgGetDouble("/sim/presets/altitude-ft");
689 double apt_elev = 0.0;
690 if ( ! apt_id.empty() ) {
691 apt_elev = fgGetAirportElev( apt_id );
692 if ( apt_elev < -9990.0 ) {
699 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
700 // set altitude from glideslope and offset-distance
701 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
702 alt = fabs(od*tan(gs)) + apt_elev;
703 fgSetDouble("/sim/presets/altitude-ft", alt);
704 fgSetBool("/sim/presets/onground", false);
705 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
707 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
708 // set offset-distance from glideslope and altitude
709 od = (alt - apt_elev) / tan(gs);
710 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
711 fgSetDouble("/sim/presets/offset-distance-nm", od);
712 fgSetBool("/sim/presets/onground", false);
713 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
715 } else if( fabs(gs) > 0.01 ) {
716 SG_LOG( SG_GENERAL, SG_ALERT,
717 "Glideslope given but not altitude or offset-distance." );
718 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
719 fgSetDouble("/sim/presets/glideslope-deg", 0);
720 fgSetBool("/sim/presets/onground", true);
725 // Set current_options lon/lat given an airport id and heading (degrees)
726 static bool fgSetPosFromNAV( const string& id, const double& freq, FGPositioned::Type type ) {
728 const nav_list_type navlist
729 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq, type );
731 if (navlist.size() == 0 ) {
732 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
733 << id << ":" << freq );
737 if( navlist.size() > 1 ) {
739 buf << "Ambigous NAV-ID: '" << id << "'. Specify id and frequency. Available stations:" << endl;
740 for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
741 // NDB stored in kHz, VOR stored in MHz * 100 :-P
742 double factor = (*it)->type() == FGPositioned::NDB ? 1.0 : 1/100.0;
743 string unit = (*it)->type() == FGPositioned::NDB ? "kHz" : "MHz";
744 buf << (*it)->ident() << " "
745 << setprecision(5) << (double)((*it)->get_freq() * factor) << " "
746 << (*it)->get_lat() << "/" << (*it)->get_lon()
750 SG_LOG( SG_GENERAL, SG_ALERT, buf.str() );
754 FGNavRecord *nav = navlist[0];
755 fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
759 // Set current_options lon/lat given an aircraft carrier id
760 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
762 // set initial position from runway and heading
766 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
767 double lon = geodPos.getLongitudeDeg();
768 double lat = geodPos.getLatitudeDeg();
769 double alt = geodPos.getElevationFt();
771 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
772 << carrier << " at lat = " << lat << ", lon = " << lon
773 << ", alt = " << alt << ", heading = " << heading);
775 fgSetDouble("/sim/presets/longitude-deg", lon);
776 fgSetDouble("/sim/presets/latitude-deg", lat);
777 fgSetDouble("/sim/presets/altitude-ft", alt);
778 fgSetDouble("/sim/presets/heading-deg", heading);
779 fgSetDouble("/position/longitude-deg", lon);
780 fgSetDouble("/position/latitude-deg", lat);
781 fgSetDouble("/position/altitude-ft", alt);
782 fgSetDouble("/orientation/heading-deg", heading);
784 fgSetString("/sim/presets/speed-set", "UVW");
785 fgSetDouble("/velocities/uBody-fps", uvw(0));
786 fgSetDouble("/velocities/vBody-fps", uvw(1));
787 fgSetDouble("/velocities/wBody-fps", uvw(2));
788 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
789 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
790 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
792 fgSetBool("/sim/presets/onground", true);
796 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
802 // Set current_options lon/lat given an airport id and heading (degrees)
803 static bool fgSetPosFromFix( const string& id )
805 FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
806 FGPositioned* fix = FGPositioned::findNextWithPartialId(NULL, id, &fixFilter);
808 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
812 fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
817 * Initialize vor/ndb/ils/fix list management and query systems (as
818 * well as simple airport db list)
823 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
825 SGPath aptdb( globals->get_fg_root() );
826 aptdb.append( "Airports/apt.dat" );
828 SGPath p_metar( globals->get_fg_root() );
829 p_metar.append( "Airports/metar.dat" );
831 fgAirportDBLoad( aptdb.str(), p_metar.str() );
833 FGNavList *navlist = new FGNavList;
834 FGNavList *loclist = new FGNavList;
835 FGNavList *gslist = new FGNavList;
836 FGNavList *dmelist = new FGNavList;
837 FGNavList *tacanlist = new FGNavList;
838 FGNavList *carrierlist = new FGNavList;
839 FGTACANList *channellist = new FGTACANList;
841 globals->set_navlist( navlist );
842 globals->set_loclist( loclist );
843 globals->set_gslist( gslist );
844 globals->set_dmelist( dmelist );
845 globals->set_tacanlist( tacanlist );
846 globals->set_carrierlist( carrierlist );
847 globals->set_channellist( channellist );
849 if ( !fgNavDBInit(navlist, loclist, gslist, dmelist, tacanlist, carrierlist, channellist) ) {
850 SG_LOG( SG_GENERAL, SG_ALERT,
851 "Problems loading one or more navigational database" );
854 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
855 SGPath p_fix( globals->get_fg_root() );
856 p_fix.append( "Navaids/fix.dat" );
858 fixlist.init( p_fix ); // adds fixes to the DB in positioned.cxx
860 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
861 flightgear::Airway::load();
867 // Set the initial position based on presets (or defaults)
868 bool fgInitPosition() {
869 // cout << "fgInitPosition()" << endl;
870 double gs = fgGetDouble("/sim/presets/glideslope-deg")
871 * SG_DEGREES_TO_RADIANS ;
872 double od = fgGetDouble("/sim/presets/offset-distance-nm");
873 double alt = fgGetDouble("/sim/presets/altitude-ft");
875 bool set_pos = false;
877 // If glideslope is specified, then calculate offset-distance or
878 // altitude relative to glide slope if either of those was not
880 if ( fabs( gs ) > 0.01 ) {
881 fgSetDistOrAltFromGlideSlope();
885 // If we have an explicit, in-range lon/lat, don't change it, just use it.
886 // If not, check for an airport-id and use that.
887 // If not, default to the middle of the KSFO field.
888 // The default values for lon/lat are deliberately out of range
889 // so that the airport-id can take effect; valid lon/lat will
890 // override airport-id, however.
891 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
892 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
893 if ( lon_deg >= -180.0 && lon_deg <= 180.0
894 && lat_deg >= -90.0 && lat_deg <= 90.0 )
899 string apt = fgGetString("/sim/presets/airport-id");
900 string rwy_no = fgGetString("/sim/presets/runway");
901 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
902 string vor = fgGetString("/sim/presets/vor-id");
903 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
904 string ndb = fgGetString("/sim/presets/ndb-id");
905 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
906 string carrier = fgGetString("/sim/presets/carrier");
907 string parkpos = fgGetString("/sim/presets/parkpos");
908 string fix = fgGetString("/sim/presets/fix");
909 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
910 double hdg = hdg_preset->getDoubleValue();
912 // save some start parameters, so that we can later say what the
913 // user really requested. TODO generalize that and move it to options.cxx
914 static bool start_options_saved = false;
915 if (!start_options_saved) {
916 start_options_saved = true;
917 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
919 opt->setDoubleValue("latitude-deg", lat_deg);
920 opt->setDoubleValue("longitude-deg", lon_deg);
921 opt->setDoubleValue("heading-deg", hdg);
922 opt->setStringValue("airport", apt.c_str());
923 opt->setStringValue("runway", rwy_no.c_str());
927 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
929 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
930 // An airport + parking position is requested
931 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
932 // set tower position
933 fgSetString("/sim/airport/closest-airport-id", apt.c_str());
934 fgSetString("/sim/tower/airport-id", apt.c_str());
939 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
940 // An airport + runway is requested
941 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
942 // set tower position (a little off the heading for single
944 fgSetString("/sim/airport/closest-airport-id", apt.c_str());
945 fgSetString("/sim/tower/airport-id", apt.c_str());
950 if ( !set_pos && !apt.empty() ) {
951 // An airport is requested (find runway closest to hdg)
952 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
953 // set tower position (a little off the heading for single
955 fgSetString("/sim/airport/closest-airport-id", apt.c_str());
956 fgSetString("/sim/tower/airport-id", apt.c_str());
961 if (hdg_preset->getDoubleValue() > 9990.0)
962 hdg_preset->setDoubleValue(hdg);
964 if ( !set_pos && !vor.empty() ) {
965 // a VOR is requested
966 if ( fgSetPosFromNAV( vor, vor_freq, FGPositioned::VOR ) ) {
971 if ( !set_pos && !ndb.empty() ) {
972 // an NDB is requested
973 if ( fgSetPosFromNAV( ndb, ndb_freq, FGPositioned::NDB ) ) {
978 if ( !set_pos && !carrier.empty() ) {
979 // an aircraft carrier is requested
980 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
985 if ( !set_pos && !fix.empty() ) {
986 // a Fix is requested
987 if ( fgSetPosFromFix( fix ) ) {
993 // No lon/lat specified, no airport specified, default to
994 // middle of KSFO field.
995 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
996 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
999 fgSetDouble( "/position/longitude-deg",
1000 fgGetDouble("/sim/presets/longitude-deg") );
1001 fgSetDouble( "/position/latitude-deg",
1002 fgGetDouble("/sim/presets/latitude-deg") );
1003 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1005 // determine if this should be an on-ground or in-air start
1006 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1007 fgSetBool("/sim/presets/onground", false);
1009 fgSetBool("/sim/presets/onground", true);
1016 // General house keeping initializations
1017 bool fgInitGeneral() {
1020 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1021 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1023 root = globals->get_fg_root();
1024 if ( ! root.length() ) {
1025 // No root path set? Then bail ...
1026 SG_LOG( SG_GENERAL, SG_ALERT,
1027 "Cannot continue without a path to the base package "
1028 << "being defined." );
1031 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1033 // Note: browser command is hard-coded for Mac/Windows, so this only affects other platforms
1034 globals->set_browser(fgGetString("/sim/startup/browser-app", WEB_BROWSER));
1035 fgSetString("/sim/startup/browser-app", globals->get_browser());
1037 simgear::Dir cwd(simgear::Dir::current());
1038 SGPropertyNode *curr = fgGetNode("/sim", true);
1039 curr->removeChild("fg-current", 0, false);
1040 curr = curr->getChild("fg-current", 0, true);
1041 curr->setStringValue(cwd.path().str());
1042 curr->setAttribute(SGPropertyNode::WRITE, false);
1044 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
1045 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
1049 // This is the top level init routine which calls all the other
1050 // initialization routines. If you are adding a subsystem to flight
1051 // gear, its initialization call should located in this routine.
1052 // Returns non-zero if a problem encountered.
1053 bool fgInitSubsystems() {
1055 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1056 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1058 ////////////////////////////////////////////////////////////////////
1059 // Initialize the sound subsystem.
1060 ////////////////////////////////////////////////////////////////////
1061 // Sound manager uses an own subsystem group "SOUND" which is the last
1062 // to be updated in every loop.
1063 // Sound manager is updated last so it can use the CPU while the GPU
1064 // is processing the scenery (doubled the frame-rate for me) -EMH-
1065 globals->add_subsystem("sound", new SGSoundMgr, SGSubsystemMgr::SOUND);
1067 ////////////////////////////////////////////////////////////////////
1068 // Initialize the event manager subsystem.
1069 ////////////////////////////////////////////////////////////////////
1071 globals->get_event_mgr()->init();
1072 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1074 ////////////////////////////////////////////////////////////////////
1075 // Initialize the property interpolator subsystem. Put into the INIT
1076 // group because the "nasal" subsystem may need it at GENERAL take-down.
1077 ////////////////////////////////////////////////////////////////////
1078 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1081 ////////////////////////////////////////////////////////////////////
1082 // Add the FlightGear property utilities.
1083 ////////////////////////////////////////////////////////////////////
1084 globals->add_subsystem("properties", new FGProperties);
1087 ////////////////////////////////////////////////////////////////////
1088 // Add the performance monitoring system.
1089 ////////////////////////////////////////////////////////////////////
1090 globals->add_subsystem("performance-mon",
1091 new SGPerformanceMonitor(globals->get_subsystem_mgr(),
1092 fgGetNode("/sim/performance-monitor", true)));
1094 ////////////////////////////////////////////////////////////////////
1095 // Initialize the material property subsystem.
1096 ////////////////////////////////////////////////////////////////////
1098 SGPath mpath( globals->get_fg_root() );
1099 mpath.append( fgGetString("/sim/rendering/materials-file") );
1100 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
1101 globals->get_props()) ) {
1102 SG_LOG( SG_GENERAL, SG_ALERT,
1103 "Error loading materials file " << mpath.str() );
1108 ////////////////////////////////////////////////////////////////////
1109 // Initialize the scenery management subsystem.
1110 ////////////////////////////////////////////////////////////////////
1112 globals->get_scenery()->get_scene_graph()
1113 ->addChild(simgear::Particles::getCommonRoot());
1114 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
1116 ////////////////////////////////////////////////////////////////////
1117 // Initialize the flight model subsystem.
1118 ////////////////////////////////////////////////////////////////////
1120 globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
1122 ////////////////////////////////////////////////////////////////////
1123 // Initialize the weather subsystem.
1124 ////////////////////////////////////////////////////////////////////
1126 // Initialize the weather modeling subsystem
1127 globals->add_subsystem("environment", new FGEnvironmentMgr);
1128 globals->add_subsystem("ephemeris", new Ephemeris);
1130 ////////////////////////////////////////////////////////////////////
1131 // Initialize the aircraft systems and instrumentation (before the
1133 ////////////////////////////////////////////////////////////////////
1135 globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
1136 globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
1138 ////////////////////////////////////////////////////////////////////
1139 // Initialize the XML Autopilot subsystem.
1140 ////////////////////////////////////////////////////////////////////
1142 globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance("autopilot"), SGSubsystemMgr::FDM );
1143 globals->add_subsystem( "xml-proprules", FGXMLAutopilotGroup::createInstance("property-rule"), SGSubsystemMgr::GENERAL );
1144 globals->add_subsystem( "route-manager", new FGRouteMgr );
1146 ////////////////////////////////////////////////////////////////////
1147 // Initialize the Input-Output subsystem
1148 ////////////////////////////////////////////////////////////////////
1149 globals->add_subsystem( "io", new FGIO );
1151 ////////////////////////////////////////////////////////////////////
1152 // Create and register the logger.
1153 ////////////////////////////////////////////////////////////////////
1155 globals->add_subsystem("logger", new FGLogger);
1157 ////////////////////////////////////////////////////////////////////
1158 // Create and register the XML GUI.
1159 ////////////////////////////////////////////////////////////////////
1161 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1163 //////////////////////////////////////////////////////////////////////
1164 // Initialize the 2D cloud subsystem.
1165 ////////////////////////////////////////////////////////////////////
1166 fgGetBool("/sim/rendering/bump-mapping", false);
1168 ////////////////////////////////////////////////////////////////////
1169 // Initialize the canvas 2d drawing subsystem.
1170 ////////////////////////////////////////////////////////////////////
1171 globals->add_subsystem("Canvas", new CanvasMgr, SGSubsystemMgr::DISPLAY);
1172 globals->add_subsystem("CanvasGUI", new GUIMgr, SGSubsystemMgr::DISPLAY);
1174 ////////////////////////////////////////////////////////////////////
1175 // Initialise the ATIS Manager
1176 // Note that this is old stuff, but is necessary for the
1177 // current ATIS implementation. Therefore, leave it in here
1178 // until the ATIS system is ported over to make use of the ATIS
1179 // sub system infrastructure.
1180 ////////////////////////////////////////////////////////////////////
1182 globals->add_subsystem("ATIS", new FGATISMgr, SGSubsystemMgr::INIT, 0.4);
1184 ////////////////////////////////////////////////////////////////////
1185 // Initialize the ATC subsystem
1186 ////////////////////////////////////////////////////////////////////
1187 globals->add_subsystem("ATC", new FGATCManager, SGSubsystemMgr::POST_FDM);
1189 ////////////////////////////////////////////////////////////////////
1190 // Initialize multiplayer subsystem
1191 ////////////////////////////////////////////////////////////////////
1193 globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
1195 ////////////////////////////////////////////////////////////////////
1196 // Initialise the AI Model Manager
1197 ////////////////////////////////////////////////////////////////////
1198 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1199 globals->add_subsystem("ai-model", new FGAIManager, SGSubsystemMgr::POST_FDM);
1200 globals->add_subsystem("submodel-mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
1203 // It's probably a good idea to initialize the top level traffic manager
1204 // After the AI and ATC systems have been initialized properly.
1205 // AI Traffic manager
1206 globals->add_subsystem("traffic-manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
1208 ////////////////////////////////////////////////////////////////////
1209 // Add a new 2D panel.
1210 ////////////////////////////////////////////////////////////////////
1212 fgSetArchivable("/sim/panel/visibility");
1213 fgSetArchivable("/sim/panel/x-offset");
1214 fgSetArchivable("/sim/panel/y-offset");
1215 fgSetArchivable("/sim/panel/jitter");
1217 ////////////////////////////////////////////////////////////////////
1218 // Initialize the controls subsystem.
1219 ////////////////////////////////////////////////////////////////////
1221 globals->get_controls()->init();
1222 globals->get_controls()->bind();
1225 ////////////////////////////////////////////////////////////////////
1226 // Initialize the input subsystem.
1227 ////////////////////////////////////////////////////////////////////
1229 globals->add_subsystem("input", new FGInput);
1232 ////////////////////////////////////////////////////////////////////
1233 // Initialize the replay subsystem
1234 ////////////////////////////////////////////////////////////////////
1235 globals->add_subsystem("replay", new FGReplay);
1237 #ifdef ENABLE_AUDIO_SUPPORT
1238 ////////////////////////////////////////////////////////////////////
1239 // Initialize the sound-effects subsystem.
1240 ////////////////////////////////////////////////////////////////////
1241 globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
1244 ////////////////////////////////////////////////////////////////////
1245 // Initialize the lighting subsystem.
1246 ////////////////////////////////////////////////////////////////////
1248 globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
1250 // ordering here is important : Nasal (via events), then models, then views
1251 globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
1253 FGAircraftModel* acm = new FGAircraftModel;
1254 globals->set_aircraft_model(acm);
1255 globals->add_subsystem("aircraft-model", acm, SGSubsystemMgr::DISPLAY);
1257 FGModelMgr* mm = new FGModelMgr;
1258 globals->set_model_mgr(mm);
1259 globals->add_subsystem("model-manager", mm, SGSubsystemMgr::DISPLAY);
1261 FGViewMgr *viewmgr = new FGViewMgr;
1262 globals->set_viewmgr( viewmgr );
1263 globals->add_subsystem("view-manager", viewmgr, SGSubsystemMgr::DISPLAY);
1265 globals->add_subsystem("tile-manager", globals->get_tile_mgr(),
1266 SGSubsystemMgr::DISPLAY);
1268 ////////////////////////////////////////////////////////////////////
1269 // Bind and initialize subsystems.
1270 ////////////////////////////////////////////////////////////////////
1272 globals->get_subsystem_mgr()->bind();
1273 globals->get_subsystem_mgr()->init();
1275 ////////////////////////////////////////////////////////////////////////
1276 // Initialize the Nasal interpreter.
1277 // Do this last, so that the loaded scripts see initialized state
1278 ////////////////////////////////////////////////////////////////////////
1279 FGNasalSys* nasal = new FGNasalSys();
1280 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1283 // initialize methods that depend on other subsystems.
1284 globals->get_subsystem_mgr()->postinit();
1286 ////////////////////////////////////////////////////////////////////
1287 // TODO FIXME! UGLY KLUDGE!
1288 ////////////////////////////////////////////////////////////////////
1290 /* Scenarios require Nasal, so FGAIManager loads the scenarios,
1291 * including its models such as a/c carriers, in its 'postinit',
1292 * which is the very last thing we do.
1293 * fgInitPosition is called very early in main.cxx/fgIdleFunction,
1294 * one of the first things we do, long before scenarios/carriers are
1295 * loaded. => When requested "initial preset position" relates to a
1296 * carrier, recalculate the 'initial' position here (how have things
1297 * ever worked before this hack - this init sequence has always been
1299 std::string carrier = fgGetString("/sim/presets/carrier","");
1302 // clear preset location and re-trigger position setup
1303 fgSetDouble("/sim/presets/longitude-deg", 9999);
1304 fgSetDouble("/sim/presets/latitude-deg", 9999);
1309 ////////////////////////////////////////////////////////////////////////
1310 // End of subsystem initialization.
1311 ////////////////////////////////////////////////////////////////////
1313 fgSetBool("/sim/crashed", false);
1314 fgSetBool("/sim/initialized", true);
1316 SG_LOG( SG_GENERAL, SG_INFO, endl);
1318 // Save the initial state for future
1320 globals->saveInitialState();
1325 // Reset: this is what the 'reset' command (and hence, GUI) is attached to
1326 void fgReInitSubsystems()
1328 static const SGPropertyNode *master_freeze
1329 = fgGetNode("/sim/freeze/master");
1331 SG_LOG( SG_GENERAL, SG_INFO, "fgReInitSubsystems()");
1333 // setup state to begin re-init
1334 bool freeze = master_freeze->getBoolValue();
1336 fgSetBool("/sim/freeze/master", true);
1339 fgSetBool("/sim/signals/reinit", true);
1340 fgSetBool("/sim/crashed", false);
1342 // do actual re-init steps
1343 globals->get_subsystem("flight")->unbind();
1345 // reset control state, before restoring initial state; -set or config files
1346 // may specify values for flaps, trim tabs, magnetos, etc
1347 globals->get_controls()->reset_all();
1349 globals->restoreInitialState();
1351 // update our position based on current presets
1354 // Force reupdating the positions of the ai 3d models. They are used for
1355 // initializing ground level for the FDM.
1356 globals->get_subsystem("ai-model")->reinit();
1358 // Initialize the FDM
1359 globals->get_subsystem("flight")->reinit();
1361 // reset replay buffers
1362 globals->get_subsystem("replay")->reinit();
1364 // reload offsets from config defaults
1365 globals->get_viewmgr()->reinit();
1367 globals->get_subsystem("time")->reinit();
1369 // need to bind FDMshell again, since we manually unbound it above...
1370 globals->get_subsystem("flight")->bind();
1372 // setup state to end re-init
1373 fgSetBool("/sim/signals/reinit", false);
1375 fgSetBool("/sim/freeze/master", false);
1377 fgSetBool("/sim/sceneryloaded",false);
1381 ///////////////////////////////////////////////////////////////////////////////
1382 // helper object to implement the --show-aircraft command.
1383 // resides here so we can share the fgFindAircraftInDir template above,
1384 // and hence ensure this command lists exectly the same aircraft as the normal
1391 _minStatus = getNumMaturity(fgGetString("/sim/aircraft-min-status", "all"));
1395 void show(const SGPath& path)
1397 fgFindAircraftInDir(path, this, &ShowAircraft::processAircraft);
1399 std::sort(_aircraft.begin(), _aircraft.end(), ciLessLibC());
1400 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on Windows
1401 cout << "Available aircraft:" << endl;
1402 for ( unsigned int i = 0; i < _aircraft.size(); i++ ) {
1403 cout << _aircraft[i] << endl;
1408 bool processAircraft(const SGPath& path)
1410 SGPropertyNode root;
1412 readProperties(path.str(), &root);
1413 } catch (sg_exception& ) {
1418 string descStr(" ");
1419 descStr += path.file();
1420 // trim common suffix from file names
1421 int nPos = descStr.rfind("-set.xml");
1422 if (nPos == (int)(descStr.size() - 8)) {
1423 descStr.resize(nPos);
1426 SGPropertyNode *node = root.getNode("sim");
1428 SGPropertyNode* desc = node->getNode("description");
1429 // if a status tag is found, read it in
1430 if (node->hasValue("status")) {
1431 maturity = getNumMaturity(node->getStringValue("status"));
1435 if (descStr.size() <= 27+3) {
1436 descStr.append(29+3-descStr.size(), ' ');
1439 descStr.append( 32, ' ');
1441 descStr += desc->getStringValue();
1443 } // of have 'sim' node
1445 if (maturity < _minStatus) {
1449 _aircraft.push_back(descStr);
1454 int getNumMaturity(const char * str)
1456 // changes should also be reflected in $FG_ROOT/data/options.xml &
1457 // $FG_ROOT/data/Translations/string-default.xml
1458 const char* levels[] = {"alpha","beta","early-production","production"};
1460 if (!strcmp(str, "all")) {
1464 for (size_t i=0; i<(sizeof(levels)/sizeof(levels[0]));i++)
1465 if (strcmp(str,levels[i])==0)
1471 // recommended in Meyers, Effective STL when internationalization and embedded
1472 // NULLs aren't an issue. Much faster than the STL or Boost lex versions.
1473 struct ciLessLibC : public std::binary_function<string, string, bool>
1475 bool operator()(const std::string &lhs, const std::string &rhs) const
1477 return strcasecmp(lhs.c_str(), rhs.c_str()) < 0 ? 1 : 0;
1482 string_list _aircraft;
1485 void fgShowAircraft(const SGPath &path)
1491 cout << "Hit a key to continue..." << endl;