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 simgear::Dir exportDir(simgear::Dir(dataPath).file("Export"));
411 if (!exportDir.exists()) {
412 exportDir.create(0777);
415 // Set /sim/fg-home and don't allow malign code to override it until
416 // Nasal security is set up. Use FG_HOME if necessary.
417 SGPropertyNode *home = fgGetNode("/sim", true);
418 home->removeChild("fg-home", 0, false);
419 home = home->getChild("fg-home", 0, true);
420 home->setStringValue(dataPath.c_str());
421 home->setAttribute(SGPropertyNode::WRITE, false);
423 flightgear::Options::sharedInstance()->init(argc, argv, dataPath);
425 // Read global preferences from $FG_ROOT/preferences.xml
426 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
427 fgLoadProps("preferences.xml", globals->get_props());
428 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
430 // do not load user settings when reset to default is requested
431 if (flightgear::Options::sharedInstance()->isOptionSet("restore-defaults"))
433 SG_LOG(SG_ALL, SG_ALERT, "Ignoring user settings. Restoring defaults.");
437 globals->loadUserSettings(dataPath);
440 // Scan user config files and command line for a specified aircraft.
441 flightgear::Options::sharedInstance()->initAircraft();
443 FindAndCacheAircraft f(globals->get_props());
444 if (!f.loadAircraft()) {
448 // parse options after loading aircraft to ensure any user
449 // overrides of defaults are honored.
450 flightgear::Options::sharedInstance()->processOptions();
455 // Set current tower position lon/lat given an airport id
456 static bool fgSetTowerPosFromAirportID( const string& id) {
457 const FGAirport *a = fgFindAirportID( id);
459 SGGeod tower = a->getTowerLocation();
460 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
461 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
462 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
470 struct FGTowerLocationListener : SGPropertyChangeListener {
471 void valueChanged(SGPropertyNode* node) {
472 string id(node->getStringValue());
473 if (fgGetBool("/sim/tower/auto-position",true))
475 // enforce using closest airport when auto-positioning is enabled
476 const char* closest_airport = fgGetString("/sim/airport/closest-airport-id", "");
477 if (closest_airport && (id != closest_airport))
479 id = closest_airport;
480 node->setStringValue(id);
483 fgSetTowerPosFromAirportID(id);
487 struct FGClosestTowerLocationListener : SGPropertyChangeListener
489 void valueChanged(SGPropertyNode* )
491 // closest airport has changed
492 if (fgGetBool("/sim/tower/auto-position",true))
494 // update tower position
495 const char* id = fgGetString("/sim/airport/closest-airport-id", "");
497 fgSetString("/sim/tower/airport-id", id);
502 void fgInitTowerLocationListener() {
503 fgGetNode("/sim/tower/airport-id", true)
504 ->addChangeListener( new FGTowerLocationListener(), true );
505 FGClosestTowerLocationListener* ntcl = new FGClosestTowerLocationListener();
506 fgGetNode("/sim/airport/closest-airport-id", true)
507 ->addChangeListener(ntcl , true );
508 fgGetNode("/sim/tower/auto-position", true)
509 ->addChangeListener(ntcl, true );
512 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
514 SGGeod startPos(aStartPos);
515 if (aTargetHeading == HUGE_VAL) {
516 aTargetHeading = aHeading;
519 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
520 double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
521 offsetDistance *= SG_NM_TO_METER;
522 double offsetAzimuth = aHeading;
523 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
524 offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
525 aHeading = aTargetHeading;
530 SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
535 fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
536 fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
537 fgSetDouble("/sim/presets/heading-deg", aHeading );
539 // other code depends on the actual values being set ...
540 fgSetDouble("/position/longitude-deg", startPos.getLongitudeDeg() );
541 fgSetDouble("/position/latitude-deg", startPos.getLatitudeDeg() );
542 fgSetDouble("/orientation/heading-deg", aHeading );
545 // Set current_options lon/lat given an airport id and heading (degrees)
546 bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
550 // set initial position from runway and heading
551 SG_LOG( SG_GENERAL, SG_INFO,
552 "Attempting to set starting position from airport code "
553 << id << " heading " << tgt_hdg );
555 const FGAirport* apt = fgFindAirportID(id);
556 if (!apt) return false;
557 FGRunway* r = apt->findBestRunwayForHeading(tgt_hdg);
558 fgSetString("/sim/atc/runway", r->ident().c_str());
560 SGGeod startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
561 fgApplyStartOffset(startPos, r->headingDeg(), tgt_hdg);
565 // Set current_options lon/lat given an airport id and parkig position name
566 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
570 // can't see an easy way around this const_cast at the moment
571 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
573 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
576 FGAirportDynamics* dcs = apt->getDynamics();
578 SG_LOG( SG_GENERAL, SG_ALERT,
579 "Airport " << id << "does not appear to have parking information available");
583 int park_index = dcs->getNrOfParkings() - 1;
585 double radius = fgGetDouble("/sim/dimensions/radius-m");
586 if ((parkpos == string("AVAILABLE")) && (radius > 0)) {
587 double lat, lon, heading;
592 acData = fgGetString("/sim/fg-home");
593 acData.append("aircraft-data");
594 string acfile = fgGetString("/sim/aircraft") + string(".xml");
595 acData.append(acfile);
597 readProperties(acData.str(), &root);
598 SGPropertyNode * node = root.getNode("sim");
599 fltType = node->getStringValue("aircraft-class", "NONE" );
600 acOperator = node->getStringValue("aircraft-operator", "NONE" );
601 } catch (const sg_exception &) {
602 SG_LOG(SG_GENERAL, SG_INFO,
603 "Could not load aircraft aircrat type and operator information from: " << acData.str() << ". Using defaults");
605 // cout << path.str() << endl;
607 if (fltType.empty() || fltType == "NONE") {
608 SG_LOG(SG_GENERAL, SG_INFO,
609 "Aircraft type information not found in: " << acData.str() << ". Using default value");
610 fltType = fgGetString("/sim/aircraft-class" );
612 if (acOperator.empty() || fltType == "NONE") {
613 SG_LOG(SG_GENERAL, SG_INFO,
614 "Aircraft operator information not found in: " << acData.str() << ". Using default value");
615 acOperator = fgGetString("/sim/aircraft-operator" );
618 cerr << "Running aircraft " << fltType << " of livery " << acOperator << endl;
619 string acType; // Currently not used by findAvailable parking, so safe to leave empty.
620 succes = dcs->getAvailableParking(&lat, &lon, &heading, &park_index, radius, fltType, acType, acOperator);
622 fgGetString("/sim/presets/parkpos");
623 fgSetString("/sim/presets/parkpos", dcs->getParking(park_index)->getName());
625 SG_LOG( SG_GENERAL, SG_ALERT,
626 "Failed to find a suitable parking at airport " << id );
630 //cerr << "We shouldn't get here when AVAILABLE" << endl;
631 while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
632 if (park_index < 0) {
633 SG_LOG( SG_GENERAL, SG_ALERT,
634 "Failed to find parking position " << parkpos <<
635 " at airport " << id );
639 FGParking* parking = dcs->getParking(park_index);
640 parking->setAvailable(false);
642 SGGeod::fromDeg(parking->getLongitude(), parking->getLatitude()),
643 parking->getHeading());
648 // Set current_options lon/lat given an airport id and runway number
649 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
653 // set initial position from airport and runway number
654 SG_LOG( SG_GENERAL, SG_INFO,
655 "Attempting to set starting position for "
656 << id << ":" << rwy );
658 const FGAirport* apt = fgFindAirportID(id);
660 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
664 if (!apt->hasRunwayWithIdent(rwy)) {
665 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
666 "Failed to find runway " << rwy <<
667 " at airport " << id << ". Using default runway." );
671 FGRunway* r(apt->getRunwayByIdent(rwy));
672 fgSetString("/sim/atc/runway", r->ident().c_str());
673 SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
674 fgApplyStartOffset(startPos, r->headingDeg());
679 static void fgSetDistOrAltFromGlideSlope() {
680 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
681 string apt_id = fgGetString("/sim/presets/airport-id");
682 double gs = fgGetDouble("/sim/presets/glideslope-deg")
683 * SG_DEGREES_TO_RADIANS ;
684 double od = fgGetDouble("/sim/presets/offset-distance-nm");
685 double alt = fgGetDouble("/sim/presets/altitude-ft");
687 double apt_elev = 0.0;
688 if ( ! apt_id.empty() ) {
689 apt_elev = fgGetAirportElev( apt_id );
690 if ( apt_elev < -9990.0 ) {
697 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
698 // set altitude from glideslope and offset-distance
699 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
700 alt = fabs(od*tan(gs)) + apt_elev;
701 fgSetDouble("/sim/presets/altitude-ft", alt);
702 fgSetBool("/sim/presets/onground", false);
703 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
705 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
706 // set offset-distance from glideslope and altitude
707 od = (alt - apt_elev) / tan(gs);
708 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
709 fgSetDouble("/sim/presets/offset-distance-nm", od);
710 fgSetBool("/sim/presets/onground", false);
711 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
713 } else if( fabs(gs) > 0.01 ) {
714 SG_LOG( SG_GENERAL, SG_ALERT,
715 "Glideslope given but not altitude or offset-distance." );
716 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
717 fgSetDouble("/sim/presets/glideslope-deg", 0);
718 fgSetBool("/sim/presets/onground", true);
723 // Set current_options lon/lat given an airport id and heading (degrees)
724 static bool fgSetPosFromNAV( const string& id, const double& freq, FGPositioned::Type type ) {
726 const nav_list_type navlist
727 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq, type );
729 if (navlist.size() == 0 ) {
730 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
731 << id << ":" << freq );
735 if( navlist.size() > 1 ) {
737 buf << "Ambigous NAV-ID: '" << id << "'. Specify id and frequency. Available stations:" << endl;
738 for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
739 // NDB stored in kHz, VOR stored in MHz * 100 :-P
740 double factor = (*it)->type() == FGPositioned::NDB ? 1.0 : 1/100.0;
741 string unit = (*it)->type() == FGPositioned::NDB ? "kHz" : "MHz";
742 buf << (*it)->ident() << " "
743 << setprecision(5) << (double)((*it)->get_freq() * factor) << " "
744 << (*it)->get_lat() << "/" << (*it)->get_lon()
748 SG_LOG( SG_GENERAL, SG_ALERT, buf.str() );
752 FGNavRecord *nav = navlist[0];
753 fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
757 // Set current_options lon/lat given an aircraft carrier id
758 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
760 // set initial position from runway and heading
764 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
765 double lon = geodPos.getLongitudeDeg();
766 double lat = geodPos.getLatitudeDeg();
767 double alt = geodPos.getElevationFt();
769 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
770 << carrier << " at lat = " << lat << ", lon = " << lon
771 << ", alt = " << alt << ", heading = " << heading);
773 fgSetDouble("/sim/presets/longitude-deg", lon);
774 fgSetDouble("/sim/presets/latitude-deg", lat);
775 fgSetDouble("/sim/presets/altitude-ft", alt);
776 fgSetDouble("/sim/presets/heading-deg", heading);
777 fgSetDouble("/position/longitude-deg", lon);
778 fgSetDouble("/position/latitude-deg", lat);
779 fgSetDouble("/position/altitude-ft", alt);
780 fgSetDouble("/orientation/heading-deg", heading);
782 fgSetString("/sim/presets/speed-set", "UVW");
783 fgSetDouble("/velocities/uBody-fps", uvw(0));
784 fgSetDouble("/velocities/vBody-fps", uvw(1));
785 fgSetDouble("/velocities/wBody-fps", uvw(2));
786 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
787 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
788 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
790 fgSetBool("/sim/presets/onground", true);
794 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
800 // Set current_options lon/lat given an airport id and heading (degrees)
801 static bool fgSetPosFromFix( const string& id )
803 FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
804 FGPositioned* fix = FGPositioned::findNextWithPartialId(NULL, id, &fixFilter);
806 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
810 fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
815 * Initialize vor/ndb/ils/fix list management and query systems (as
816 * well as simple airport db list)
821 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
823 SGPath aptdb( globals->get_fg_root() );
824 aptdb.append( "Airports/apt.dat" );
826 SGPath p_metar( globals->get_fg_root() );
827 p_metar.append( "Airports/metar.dat" );
829 fgAirportDBLoad( aptdb.str(), p_metar.str() );
831 FGNavList *navlist = new FGNavList;
832 FGNavList *loclist = new FGNavList;
833 FGNavList *gslist = new FGNavList;
834 FGNavList *dmelist = new FGNavList;
835 FGNavList *tacanlist = new FGNavList;
836 FGNavList *carrierlist = new FGNavList;
837 FGTACANList *channellist = new FGTACANList;
839 globals->set_navlist( navlist );
840 globals->set_loclist( loclist );
841 globals->set_gslist( gslist );
842 globals->set_dmelist( dmelist );
843 globals->set_tacanlist( tacanlist );
844 globals->set_carrierlist( carrierlist );
845 globals->set_channellist( channellist );
847 if ( !fgNavDBInit(navlist, loclist, gslist, dmelist, tacanlist, carrierlist, channellist) ) {
848 SG_LOG( SG_GENERAL, SG_ALERT,
849 "Problems loading one or more navigational database" );
852 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
853 SGPath p_fix( globals->get_fg_root() );
854 p_fix.append( "Navaids/fix.dat" );
856 fixlist.init( p_fix ); // adds fixes to the DB in positioned.cxx
858 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
859 flightgear::Airway::load();
865 // Set the initial position based on presets (or defaults)
866 bool fgInitPosition() {
867 // cout << "fgInitPosition()" << endl;
868 double gs = fgGetDouble("/sim/presets/glideslope-deg")
869 * SG_DEGREES_TO_RADIANS ;
870 double od = fgGetDouble("/sim/presets/offset-distance-nm");
871 double alt = fgGetDouble("/sim/presets/altitude-ft");
873 bool set_pos = false;
875 // If glideslope is specified, then calculate offset-distance or
876 // altitude relative to glide slope if either of those was not
878 if ( fabs( gs ) > 0.01 ) {
879 fgSetDistOrAltFromGlideSlope();
883 // If we have an explicit, in-range lon/lat, don't change it, just use it.
884 // If not, check for an airport-id and use that.
885 // If not, default to the middle of the KSFO field.
886 // The default values for lon/lat are deliberately out of range
887 // so that the airport-id can take effect; valid lon/lat will
888 // override airport-id, however.
889 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
890 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
891 if ( lon_deg >= -180.0 && lon_deg <= 180.0
892 && lat_deg >= -90.0 && lat_deg <= 90.0 )
897 string apt = fgGetString("/sim/presets/airport-id");
898 string rwy_no = fgGetString("/sim/presets/runway");
899 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
900 string vor = fgGetString("/sim/presets/vor-id");
901 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
902 string ndb = fgGetString("/sim/presets/ndb-id");
903 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
904 string carrier = fgGetString("/sim/presets/carrier");
905 string parkpos = fgGetString("/sim/presets/parkpos");
906 string fix = fgGetString("/sim/presets/fix");
907 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
908 double hdg = hdg_preset->getDoubleValue();
910 // save some start parameters, so that we can later say what the
911 // user really requested. TODO generalize that and move it to options.cxx
912 static bool start_options_saved = false;
913 if (!start_options_saved) {
914 start_options_saved = true;
915 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
917 opt->setDoubleValue("latitude-deg", lat_deg);
918 opt->setDoubleValue("longitude-deg", lon_deg);
919 opt->setDoubleValue("heading-deg", hdg);
920 opt->setStringValue("airport", apt.c_str());
921 opt->setStringValue("runway", rwy_no.c_str());
925 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
927 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
928 // An airport + parking position is requested
929 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
930 // set tower position
931 fgSetString("/sim/airport/closest-airport-id", apt.c_str());
932 fgSetString("/sim/tower/airport-id", apt.c_str());
937 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
938 // An airport + runway is requested
939 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
940 // set tower position (a little off the heading for single
942 fgSetString("/sim/airport/closest-airport-id", apt.c_str());
943 fgSetString("/sim/tower/airport-id", apt.c_str());
948 if ( !set_pos && !apt.empty() ) {
949 // An airport is requested (find runway closest to hdg)
950 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
951 // set tower position (a little off the heading for single
953 fgSetString("/sim/airport/closest-airport-id", apt.c_str());
954 fgSetString("/sim/tower/airport-id", apt.c_str());
959 if (hdg_preset->getDoubleValue() > 9990.0)
960 hdg_preset->setDoubleValue(hdg);
962 if ( !set_pos && !vor.empty() ) {
963 // a VOR is requested
964 if ( fgSetPosFromNAV( vor, vor_freq, FGPositioned::VOR ) ) {
969 if ( !set_pos && !ndb.empty() ) {
970 // an NDB is requested
971 if ( fgSetPosFromNAV( ndb, ndb_freq, FGPositioned::NDB ) ) {
976 if ( !set_pos && !carrier.empty() ) {
977 // an aircraft carrier is requested
978 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
983 if ( !set_pos && !fix.empty() ) {
984 // a Fix is requested
985 if ( fgSetPosFromFix( fix ) ) {
991 // No lon/lat specified, no airport specified, default to
992 // middle of KSFO field.
993 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
994 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
997 fgSetDouble( "/position/longitude-deg",
998 fgGetDouble("/sim/presets/longitude-deg") );
999 fgSetDouble( "/position/latitude-deg",
1000 fgGetDouble("/sim/presets/latitude-deg") );
1001 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1003 // determine if this should be an on-ground or in-air start
1004 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1005 fgSetBool("/sim/presets/onground", false);
1007 fgSetBool("/sim/presets/onground", true);
1014 // General house keeping initializations
1015 bool fgInitGeneral() {
1018 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1019 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1021 root = globals->get_fg_root();
1022 if ( ! root.length() ) {
1023 // No root path set? Then bail ...
1024 SG_LOG( SG_GENERAL, SG_ALERT,
1025 "Cannot continue without a path to the base package "
1026 << "being defined." );
1029 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1031 globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1033 simgear::Dir cwd(simgear::Dir::current());
1034 SGPropertyNode *curr = fgGetNode("/sim", true);
1035 curr->removeChild("fg-current", 0, false);
1036 curr = curr->getChild("fg-current", 0, true);
1037 curr->setStringValue(cwd.path().str());
1038 curr->setAttribute(SGPropertyNode::WRITE, false);
1040 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
1041 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
1045 // This is the top level init routine which calls all the other
1046 // initialization routines. If you are adding a subsystem to flight
1047 // gear, its initialization call should located in this routine.
1048 // Returns non-zero if a problem encountered.
1049 bool fgInitSubsystems() {
1051 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1052 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1054 ////////////////////////////////////////////////////////////////////
1055 // Initialize the sound subsystem.
1056 ////////////////////////////////////////////////////////////////////
1057 // Sound manager uses an own subsystem group "SOUND" which is the last
1058 // to be updated in every loop.
1059 // Sound manager is updated last so it can use the CPU while the GPU
1060 // is processing the scenery (doubled the frame-rate for me) -EMH-
1061 globals->add_subsystem("sound", new SGSoundMgr, SGSubsystemMgr::SOUND);
1063 ////////////////////////////////////////////////////////////////////
1064 // Initialize the event manager subsystem.
1065 ////////////////////////////////////////////////////////////////////
1067 globals->get_event_mgr()->init();
1068 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1070 ////////////////////////////////////////////////////////////////////
1071 // Initialize the property interpolator subsystem. Put into the INIT
1072 // group because the "nasal" subsystem may need it at GENERAL take-down.
1073 ////////////////////////////////////////////////////////////////////
1074 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1077 ////////////////////////////////////////////////////////////////////
1078 // Add the FlightGear property utilities.
1079 ////////////////////////////////////////////////////////////////////
1080 globals->add_subsystem("properties", new FGProperties);
1083 ////////////////////////////////////////////////////////////////////
1084 // Add the performance monitoring system.
1085 ////////////////////////////////////////////////////////////////////
1086 globals->add_subsystem("performance-mon",
1087 new SGPerformanceMonitor(globals->get_subsystem_mgr(),
1088 fgGetNode("/sim/performance-monitor", true)));
1090 ////////////////////////////////////////////////////////////////////
1091 // Initialize the material property subsystem.
1092 ////////////////////////////////////////////////////////////////////
1094 SGPath mpath( globals->get_fg_root() );
1095 mpath.append( fgGetString("/sim/rendering/materials-file") );
1096 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
1097 globals->get_props()) ) {
1098 SG_LOG( SG_GENERAL, SG_ALERT,
1099 "Error loading materials file " << mpath.str() );
1104 ////////////////////////////////////////////////////////////////////
1105 // Initialize the scenery management subsystem.
1106 ////////////////////////////////////////////////////////////////////
1108 globals->get_scenery()->get_scene_graph()
1109 ->addChild(simgear::Particles::getCommonRoot());
1110 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
1112 ////////////////////////////////////////////////////////////////////
1113 // Initialize the flight model subsystem.
1114 ////////////////////////////////////////////////////////////////////
1116 globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
1118 ////////////////////////////////////////////////////////////////////
1119 // Initialize the weather subsystem.
1120 ////////////////////////////////////////////////////////////////////
1122 // Initialize the weather modeling subsystem
1123 globals->add_subsystem("environment", new FGEnvironmentMgr);
1124 globals->add_subsystem("ephemeris", new Ephemeris);
1126 ////////////////////////////////////////////////////////////////////
1127 // Initialize the aircraft systems and instrumentation (before the
1129 ////////////////////////////////////////////////////////////////////
1131 globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
1132 globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
1134 ////////////////////////////////////////////////////////////////////
1135 // Initialize the XML Autopilot subsystem.
1136 ////////////////////////////////////////////////////////////////////
1138 globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance("autopilot"), SGSubsystemMgr::FDM );
1139 globals->add_subsystem( "xml-proprules", FGXMLAutopilotGroup::createInstance("property-rule"), SGSubsystemMgr::GENERAL );
1140 globals->add_subsystem( "route-manager", new FGRouteMgr );
1142 ////////////////////////////////////////////////////////////////////
1143 // Initialize the Input-Output subsystem
1144 ////////////////////////////////////////////////////////////////////
1145 globals->add_subsystem( "io", new FGIO );
1147 ////////////////////////////////////////////////////////////////////
1148 // Create and register the logger.
1149 ////////////////////////////////////////////////////////////////////
1151 globals->add_subsystem("logger", new FGLogger);
1153 ////////////////////////////////////////////////////////////////////
1154 // Create and register the XML GUI.
1155 ////////////////////////////////////////////////////////////////////
1157 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1159 //////////////////////////////////////////////////////////////////////
1160 // Initialize the 2D cloud subsystem.
1161 ////////////////////////////////////////////////////////////////////
1162 fgGetBool("/sim/rendering/bump-mapping", false);
1164 ////////////////////////////////////////////////////////////////////
1165 // Initialize the canvas 2d drawing subsystem.
1166 ////////////////////////////////////////////////////////////////////
1167 globals->add_subsystem("Canvas", new CanvasMgr, SGSubsystemMgr::DISPLAY);
1168 globals->add_subsystem("CanvasGUI", new GUIMgr, SGSubsystemMgr::DISPLAY);
1170 ////////////////////////////////////////////////////////////////////
1171 // Initialise the ATIS Manager
1172 // Note that this is old stuff, but is necessary for the
1173 // current ATIS implementation. Therefore, leave it in here
1174 // until the ATIS system is ported over to make use of the ATIS
1175 // sub system infrastructure.
1176 ////////////////////////////////////////////////////////////////////
1178 globals->add_subsystem("ATIS", new FGATISMgr, SGSubsystemMgr::INIT, 0.4);
1180 ////////////////////////////////////////////////////////////////////
1181 // Initialize the ATC subsystem
1182 ////////////////////////////////////////////////////////////////////
1183 globals->add_subsystem("ATC", new FGATCManager, SGSubsystemMgr::POST_FDM);
1185 ////////////////////////////////////////////////////////////////////
1186 // Initialize multiplayer subsystem
1187 ////////////////////////////////////////////////////////////////////
1189 globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
1191 ////////////////////////////////////////////////////////////////////
1192 // Initialise the AI Model Manager
1193 ////////////////////////////////////////////////////////////////////
1194 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1195 globals->add_subsystem("ai-model", new FGAIManager, SGSubsystemMgr::POST_FDM);
1196 globals->add_subsystem("submodel-mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
1199 // It's probably a good idea to initialize the top level traffic manager
1200 // After the AI and ATC systems have been initialized properly.
1201 // AI Traffic manager
1202 globals->add_subsystem("traffic-manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
1204 ////////////////////////////////////////////////////////////////////
1205 // Add a new 2D panel.
1206 ////////////////////////////////////////////////////////////////////
1208 fgSetArchivable("/sim/panel/visibility");
1209 fgSetArchivable("/sim/panel/x-offset");
1210 fgSetArchivable("/sim/panel/y-offset");
1211 fgSetArchivable("/sim/panel/jitter");
1213 ////////////////////////////////////////////////////////////////////
1214 // Initialize the controls subsystem.
1215 ////////////////////////////////////////////////////////////////////
1217 globals->get_controls()->init();
1218 globals->get_controls()->bind();
1221 ////////////////////////////////////////////////////////////////////
1222 // Initialize the input subsystem.
1223 ////////////////////////////////////////////////////////////////////
1225 globals->add_subsystem("input", new FGInput);
1228 ////////////////////////////////////////////////////////////////////
1229 // Initialize the replay subsystem
1230 ////////////////////////////////////////////////////////////////////
1231 globals->add_subsystem("replay", new FGReplay);
1233 #ifdef ENABLE_AUDIO_SUPPORT
1234 ////////////////////////////////////////////////////////////////////
1235 // Initialize the sound-effects subsystem.
1236 ////////////////////////////////////////////////////////////////////
1237 globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
1240 ////////////////////////////////////////////////////////////////////
1241 // Initialize the lighting subsystem.
1242 ////////////////////////////////////////////////////////////////////
1244 globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
1246 // ordering here is important : Nasal (via events), then models, then views
1247 globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
1249 FGAircraftModel* acm = new FGAircraftModel;
1250 globals->set_aircraft_model(acm);
1251 globals->add_subsystem("aircraft-model", acm, SGSubsystemMgr::DISPLAY);
1253 FGModelMgr* mm = new FGModelMgr;
1254 globals->set_model_mgr(mm);
1255 globals->add_subsystem("model-manager", mm, SGSubsystemMgr::DISPLAY);
1257 FGViewMgr *viewmgr = new FGViewMgr;
1258 globals->set_viewmgr( viewmgr );
1259 globals->add_subsystem("view-manager", viewmgr, SGSubsystemMgr::DISPLAY);
1261 globals->add_subsystem("tile-manager", globals->get_tile_mgr(),
1262 SGSubsystemMgr::DISPLAY);
1264 ////////////////////////////////////////////////////////////////////
1265 // Bind and initialize subsystems.
1266 ////////////////////////////////////////////////////////////////////
1268 globals->get_subsystem_mgr()->bind();
1269 globals->get_subsystem_mgr()->init();
1271 ////////////////////////////////////////////////////////////////////////
1272 // Initialize the Nasal interpreter.
1273 // Do this last, so that the loaded scripts see initialized state
1274 ////////////////////////////////////////////////////////////////////////
1275 FGNasalSys* nasal = new FGNasalSys();
1276 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1279 // initialize methods that depend on other subsystems.
1280 globals->get_subsystem_mgr()->postinit();
1282 ////////////////////////////////////////////////////////////////////
1283 // TODO FIXME! UGLY KLUDGE!
1284 ////////////////////////////////////////////////////////////////////
1286 /* Scenarios require Nasal, so FGAIManager loads the scenarios,
1287 * including its models such as a/c carriers, in its 'postinit',
1288 * which is the very last thing we do.
1289 * fgInitPosition is called very early in main.cxx/fgIdleFunction,
1290 * one of the first things we do, long before scenarios/carriers are
1291 * loaded. => When requested "initial preset position" relates to a
1292 * carrier, recalculate the 'initial' position here (how have things
1293 * ever worked before this hack - this init sequence has always been
1295 std::string carrier = fgGetString("/sim/presets/carrier","");
1298 // clear preset location and re-trigger position setup
1299 fgSetDouble("/sim/presets/longitude-deg", 9999);
1300 fgSetDouble("/sim/presets/latitude-deg", 9999);
1305 ////////////////////////////////////////////////////////////////////////
1306 // End of subsystem initialization.
1307 ////////////////////////////////////////////////////////////////////
1309 fgSetBool("/sim/crashed", false);
1310 fgSetBool("/sim/initialized", true);
1312 SG_LOG( SG_GENERAL, SG_INFO, endl);
1314 // Save the initial state for future
1316 globals->saveInitialState();
1321 // Reset: this is what the 'reset' command (and hence, GUI) is attached to
1322 void fgReInitSubsystems()
1324 static const SGPropertyNode *master_freeze
1325 = fgGetNode("/sim/freeze/master");
1327 SG_LOG( SG_GENERAL, SG_INFO, "fgReInitSubsystems()");
1329 // setup state to begin re-init
1330 bool freeze = master_freeze->getBoolValue();
1332 fgSetBool("/sim/freeze/master", true);
1335 fgSetBool("/sim/signals/reinit", true);
1336 fgSetBool("/sim/crashed", false);
1338 // do actual re-init steps
1339 globals->get_subsystem("flight")->unbind();
1341 // reset control state, before restoring initial state; -set or config files
1342 // may specify values for flaps, trim tabs, magnetos, etc
1343 globals->get_controls()->reset_all();
1345 globals->restoreInitialState();
1347 // update our position based on current presets
1350 // Force reupdating the positions of the ai 3d models. They are used for
1351 // initializing ground level for the FDM.
1352 globals->get_subsystem("ai-model")->reinit();
1354 // Initialize the FDM
1355 globals->get_subsystem("flight")->reinit();
1357 // reset replay buffers
1358 globals->get_subsystem("replay")->reinit();
1360 // reload offsets from config defaults
1361 globals->get_viewmgr()->reinit();
1363 globals->get_subsystem("time")->reinit();
1365 // need to bind FDMshell again, since we manually unbound it above...
1366 globals->get_subsystem("flight")->bind();
1368 // setup state to end re-init
1369 fgSetBool("/sim/signals/reinit", false);
1371 fgSetBool("/sim/freeze/master", false);
1373 fgSetBool("/sim/sceneryloaded",false);
1377 ///////////////////////////////////////////////////////////////////////////////
1378 // helper object to implement the --show-aircraft command.
1379 // resides here so we can share the fgFindAircraftInDir template above,
1380 // and hence ensure this command lists exectly the same aircraft as the normal
1387 _minStatus = getNumMaturity(fgGetString("/sim/aircraft-min-status", "all"));
1391 void show(const SGPath& path)
1393 fgFindAircraftInDir(path, this, &ShowAircraft::processAircraft);
1395 std::sort(_aircraft.begin(), _aircraft.end(), ciLessLibC());
1396 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on Windows
1397 cout << "Available aircraft:" << endl;
1398 for ( unsigned int i = 0; i < _aircraft.size(); i++ ) {
1399 cout << _aircraft[i] << endl;
1404 bool processAircraft(const SGPath& path)
1406 SGPropertyNode root;
1408 readProperties(path.str(), &root);
1409 } catch (sg_exception& ) {
1414 string descStr(" ");
1415 descStr += path.file();
1416 // trim common suffix from file names
1417 int nPos = descStr.rfind("-set.xml");
1418 if (nPos == (int)(descStr.size() - 8)) {
1419 descStr.resize(nPos);
1422 SGPropertyNode *node = root.getNode("sim");
1424 SGPropertyNode* desc = node->getNode("description");
1425 // if a status tag is found, read it in
1426 if (node->hasValue("status")) {
1427 maturity = getNumMaturity(node->getStringValue("status"));
1431 if (descStr.size() <= 27+3) {
1432 descStr.append(29+3-descStr.size(), ' ');
1435 descStr.append( 32, ' ');
1437 descStr += desc->getStringValue();
1439 } // of have 'sim' node
1441 if (maturity < _minStatus) {
1445 _aircraft.push_back(descStr);
1450 int getNumMaturity(const char * str)
1452 // changes should also be reflected in $FG_ROOT/data/options.xml &
1453 // $FG_ROOT/data/Translations/string-default.xml
1454 const char* levels[] = {"alpha","beta","early-production","production"};
1456 if (!strcmp(str, "all")) {
1460 for (size_t i=0; i<(sizeof(levels)/sizeof(levels[0]));i++)
1461 if (strcmp(str,levels[i])==0)
1467 // recommended in Meyers, Effective STL when internationalization and embedded
1468 // NULLs aren't an issue. Much faster than the STL or Boost lex versions.
1469 struct ciLessLibC : public std::binary_function<string, string, bool>
1471 bool operator()(const std::string &lhs, const std::string &rhs) const
1473 return strcasecmp(lhs.c_str(), rhs.c_str()) < 0 ? 1 : 0;
1478 string_list _aircraft;
1481 void fgShowAircraft(const SGPath &path)
1487 cout << "Hit a key to continue..." << endl;