]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
Merge branch 'next' of gitorious.org:fg/flightgear into next
[flightgear.git] / src / Main / fg_init.cxx
1 // fg_init.cxx -- Flight Gear top level initialization routines
2 //
3 // Written by Curtis Olson, started August 1997.
4 //
5 // Copyright (C) 1997  Curtis L. Olson  - http://www.flightgear.org/~curt
6 //
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.
11 //
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.
16 //
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.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>             // strcmp()
31
32 #ifdef _WIN32
33 #  include <io.h>               // isatty()
34 #  define isatty _isatty
35 #endif
36
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.
39 #ifdef linux
40 #  define _G_NO_EXTERN_TEMPLATES
41 #endif
42
43 #include <simgear/compiler.h>
44
45 #include <string>
46 #include <boost/algorithm/string/compare.hpp>
47 #include <boost/algorithm/string/predicate.hpp>
48
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>
59
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>
64
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>
71
72 #include <AIModel/AIManager.hxx>
73
74 #include <ATCDCL/ATISmgr.hxx>
75 #include <ATC/atc_mgr.hxx>
76
77 #include <Autopilot/route_mgr.hxx>
78 #include <Autopilot/autopilotgroup.hxx>
79
80 #include <Cockpit/panel.hxx>
81 #include <Cockpit/panel_io.hxx>
82
83 #include <Canvas/canvas_mgr.hxx>
84 #include <GUI/new_gui.hxx>
85 #include <Input/input.hxx>
86 #include <Instrumentation/instrument_mgr.hxx>
87 #include <Model/acmodel.hxx>
88 #include <Model/modelmgr.hxx>
89 #include <AIModel/submodel.hxx>
90 #include <AIModel/AIManager.hxx>
91 #include <Navaids/navdb.hxx>
92 #include <Navaids/navlist.hxx>
93 #include <Navaids/fix.hxx>
94 #include <Navaids/fixlist.hxx>
95 #include <Navaids/airways.hxx>
96 #include <Scenery/scenery.hxx>
97 #include <Scenery/tilemgr.hxx>
98 #include <Scripting/NasalSys.hxx>
99 #include <Sound/voice.hxx>
100 #include <Systems/system_mgr.hxx>
101 #include <Time/light.hxx>
102 #include <Traffic/TrafficMgr.hxx>
103 #include <MultiPlayer/multiplaymgr.hxx>
104 #include <FDM/fdm_shell.hxx>
105 #include <Environment/ephemeris.hxx>
106 #include <Environment/environment_mgr.hxx>
107 #include <Viewer/renderer.hxx>
108 #include <Viewer/viewmgr.hxx>
109
110 #include "fg_init.hxx"
111 #include "fg_io.hxx"
112 #include "fg_commands.hxx"
113 #include "fg_props.hxx"
114 #include "options.hxx"
115 #include "globals.hxx"
116 #include "logger.hxx"
117 #include "main.hxx"
118
119
120 using std::string;
121 using namespace boost::algorithm;
122
123
124 // Return the current base package version
125 string fgBasePackageVersion() {
126     SGPath base_path( globals->get_fg_root() );
127     base_path.append("version");
128
129     sg_gzifstream in( base_path.str() );
130     if ( !in.is_open() ) {
131         SGPath old_path( globals->get_fg_root() );
132         old_path.append( "Thanks" );
133         sg_gzifstream old( old_path.str() );
134         if ( !old.is_open() ) {
135             return "[none]";
136         } else {
137             return "[old version]";
138         }
139     }
140
141     string version;
142     in >> version;
143
144     return version;
145 }
146
147
148 template <class T>
149 bool fgFindAircraftInDir(const SGPath& dirPath, T* obj, bool (T::*pred)(const SGPath& p))
150 {
151   if (!dirPath.exists()) {
152     SG_LOG(SG_GENERAL, SG_WARN, "fgFindAircraftInDir: no such path:" << dirPath.str());
153     return false;
154   }
155     
156   bool recurse = true;
157   simgear::Dir dir(dirPath);
158   simgear::PathList setFiles(dir.children(simgear::Dir::TYPE_FILE, "-set.xml"));
159   simgear::PathList::iterator p;
160   for (p = setFiles.begin(); p != setFiles.end(); ++p) {
161     // check file name ends with -set.xml
162     
163     // if we found a -set.xml at this level, don't recurse any deeper
164     recurse = false;
165     
166     bool done = (obj->*pred)(*p);
167     if (done) {
168       return true;
169     }
170   } // of -set.xml iteration
171   
172   if (!recurse) {
173     return false;
174   }
175   
176   simgear::PathList subdirs(dir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT));
177   for (p = subdirs.begin(); p != subdirs.end(); ++p) {
178     if (p->file() == "CVS") {
179       continue;
180     }
181     
182     if (fgFindAircraftInDir(*p, obj, pred)) {
183       return true;
184     }
185   } // of subdirs iteration
186   
187   return false;
188 }
189
190 template <class T>
191 void fgFindAircraft(T* obj, bool (T::*pred)(const SGPath& p))
192 {
193   const string_list& paths(globals->get_aircraft_paths());
194   string_list::const_iterator it = paths.begin();
195   for (; it != paths.end(); ++it) {
196     bool done = fgFindAircraftInDir(SGPath(*it), obj, pred);
197     if (done) {
198       return;
199     }
200   } // of aircraft paths iteration
201   
202   // if we reach this point, search the default location (always last)
203   SGPath rootAircraft(globals->get_fg_root());
204   rootAircraft.append("Aircraft");
205   fgFindAircraftInDir(rootAircraft, obj, pred);
206 }
207
208 class FindAndCacheAircraft
209 {
210 public:
211   FindAndCacheAircraft(SGPropertyNode* autoSave)
212   {
213     _cache = autoSave->getNode("sim/startup/path-cache", true);
214   }
215   
216   bool loadAircraft()
217   {
218     std::string aircraft = fgGetString( "/sim/aircraft", "");
219     if (aircraft.empty()) {
220       SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
221       return false;
222     }
223     
224     _searchAircraft = aircraft + "-set.xml";
225     std::string aircraftDir = fgGetString("/sim/aircraft-dir", "");
226     if (!aircraftDir.empty()) {
227       // aircraft-dir was set, skip any searching at all, if it's valid
228       simgear::Dir acPath(aircraftDir);
229       SGPath setFile = acPath.file(_searchAircraft);
230       if (setFile.exists()) {
231         SG_LOG(SG_GENERAL, SG_INFO, "found aircraft in dir: " << aircraftDir );
232         
233         try {
234           readProperties(setFile.str(), globals->get_props());
235         } catch ( const sg_exception &e ) {
236           SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
237           return false;
238         }
239         
240         return true;
241       } else {
242         SG_LOG(SG_GENERAL, SG_ALERT, "aircraft '" << _searchAircraft << 
243                "' not found in specified dir:" << aircraftDir);
244         return false;
245       }
246     }
247     
248     if (!checkCache()) {
249       // prepare cache for re-scan
250       SGPropertyNode *n = _cache->getNode("fg-root", true);
251       n->setStringValue(globals->get_fg_root().c_str());
252       n->setAttribute(SGPropertyNode::USERARCHIVE, true);
253       n = _cache->getNode("fg-aircraft", true);
254       n->setStringValue(getAircraftPaths().c_str());
255       n->setAttribute(SGPropertyNode::USERARCHIVE, true);
256       _cache->removeChildren("aircraft");
257   
258       fgFindAircraft(this, &FindAndCacheAircraft::checkAircraft);
259     }
260     
261     if (_foundPath.str().empty()) {
262       SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
263       return false;
264     }
265     
266     SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
267     fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
268     if (!_foundPath.exists()) {
269       SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
270       return false;
271     }
272     
273     try {
274       readProperties(_foundPath.str(), globals->get_props());
275     } catch ( const sg_exception &e ) {
276       SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
277       return false;
278     }
279     
280     return true;
281   }
282   
283 private:
284   SGPath getAircraftPaths() {
285     string_list pathList = globals->get_aircraft_paths();
286     SGPath aircraftPaths;
287     string_list::const_iterator it = pathList.begin();
288     if (it != pathList.end()) {
289         aircraftPaths.set(*it);
290         it++;
291     }
292     for (; it != pathList.end(); ++it) {
293         aircraftPaths.add(*it);
294     }
295     return aircraftPaths;
296   }
297   
298   bool checkCache()
299   {
300     if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
301       return false; // cache mismatch
302     }
303
304     if (getAircraftPaths().str() != _cache->getStringValue("fg-aircraft", "")) {
305       return false; // cache mismatch
306     }
307     
308     vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
309     for (unsigned int i = 0; i < cache.size(); i++) {
310       const char *name = cache[i]->getStringValue("file", "");
311       if (!boost::equals(_searchAircraft, name, is_iequal())) {
312         continue;
313       }
314       
315       SGPath xml(cache[i]->getStringValue("path", ""));
316       xml.append(name);
317       if (xml.exists()) {
318         _foundPath = xml;
319         return true;
320       } 
321       
322       return false;
323     } // of aircraft in cache iteration
324     
325     return false;
326   }
327   
328   bool checkAircraft(const SGPath& p)
329   {
330     // create cache node
331     int i = 0;
332     while (1) {
333         if (!_cache->getChild("aircraft", i++, false))
334             break;
335     }
336     
337     SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
338
339     std::string fileName(p.file());
340     n = entry->getNode("file", true);
341     n->setStringValue(fileName);
342     n->setAttribute(SGPropertyNode::USERARCHIVE, true);
343
344     n = entry->getNode("path", true);
345     n->setStringValue(p.dir());
346     n->setAttribute(SGPropertyNode::USERARCHIVE, true);
347
348     if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
349         _foundPath = p;
350         return true;
351     }
352
353     return false;
354   }
355   
356   std::string _searchAircraft;
357   SGPath _foundPath;
358   SGPropertyNode* _cache;
359 };
360
361 #ifdef _WIN32
362 static SGPath platformDefaultDataPath()
363 {
364   char *envp = ::getenv( "APPDATA" );
365   SGPath config( envp );
366   config.append( "flightgear.org" );
367   return config;
368 }
369 #elif __APPLE__
370
371 #include <CoreServices/CoreServices.h>
372
373 static SGPath platformDefaultDataPath()
374 {
375   FSRef ref;
376   OSErr err = FSFindFolder(kUserDomain, kApplicationSupportFolderType, false, &ref);
377   if (err) {
378     return SGPath();
379   }
380   
381   unsigned char path[1024];
382   if (FSRefMakePath(&ref, path, 1024) != noErr) {
383     return SGPath();
384   }
385   
386   SGPath appData;
387   appData.set((const char*) path);
388   appData.append("FlightGear");
389   return appData;
390 }
391 #else
392 static SGPath platformDefaultDataPath()
393 {
394   SGPath config( homedir );
395   config.append( ".fgfs" );
396   return config;
397 }
398 #endif
399
400 // Read in configuration (file and command line)
401 bool fgInitConfig ( int argc, char **argv )
402 {
403     SGPath dataPath = platformDefaultDataPath();
404     
405     const char *fg_home = getenv("FG_HOME");
406     if (fg_home)
407       dataPath = fg_home;
408     
409     simgear::Dir exportDir(simgear::Dir(dataPath).file("Export"));
410     if (!exportDir.exists()) {
411       exportDir.create(0777);
412     }
413     
414     // Set /sim/fg-home and don't allow malign code to override it until
415     // Nasal security is set up.  Use FG_HOME if necessary.
416     SGPropertyNode *home = fgGetNode("/sim", true);
417     home->removeChild("fg-home", 0, false);
418     home = home->getChild("fg-home", 0, true);
419     home->setStringValue(dataPath.c_str());
420     home->setAttribute(SGPropertyNode::WRITE, false);
421   
422     flightgear::Options::sharedInstance()->init(argc, argv, dataPath);
423   
424     // Read global preferences from $FG_ROOT/preferences.xml
425     SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
426     fgLoadProps("preferences.xml", globals->get_props());
427     SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
428
429     globals->loadUserSettings(dataPath);
430
431     // Scan user config files and command line for a specified aircraft.
432     flightgear::Options::sharedInstance()->initAircraft();
433
434     FindAndCacheAircraft f(globals->get_props());
435     if (!f.loadAircraft()) {
436       return false;
437     }
438
439     // parse options after loading aircraft to ensure any user
440     // overrides of defaults are honored.
441     flightgear::Options::sharedInstance()->processOptions();
442       
443     return true;
444 }
445
446 // Set current tower position lon/lat given an airport id
447 static bool fgSetTowerPosFromAirportID( const string& id) {
448     const FGAirport *a = fgFindAirportID( id);
449     if (a) {
450         SGGeod tower = a->getTowerLocation();
451         fgSetDouble("/sim/tower/longitude-deg",  tower.getLongitudeDeg());
452         fgSetDouble("/sim/tower/latitude-deg",  tower.getLatitudeDeg());
453         fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
454         return true;
455     } else {
456         return false;
457     }
458
459 }
460
461 struct FGTowerLocationListener : SGPropertyChangeListener {
462     void valueChanged(SGPropertyNode* node) {
463         string id(node->getStringValue());
464         if (fgGetBool("/sim/tower/auto-position",true))
465         {
466             // enforce using closest airport when auto-positioning is enabled 
467             const char* closest_airport = fgGetString("/sim/airport/closest-airport-id", "");
468             if (closest_airport && (id != closest_airport))
469             {
470                 id = closest_airport;
471                 node->setStringValue(id);
472             }
473         }
474         fgSetTowerPosFromAirportID(id);
475     }
476 };
477
478 struct FGClosestTowerLocationListener : SGPropertyChangeListener
479 {
480     void valueChanged(SGPropertyNode* )
481     {
482         // closest airport has changed
483         if (fgGetBool("/sim/tower/auto-position",true))
484         {
485             // update tower position
486             const char* id = fgGetString("/sim/airport/closest-airport-id", "");
487             if (id && *id!=0)
488                 fgSetString("/sim/tower/airport-id", id);
489         }
490     }
491 };
492
493 void fgInitTowerLocationListener() {
494     fgGetNode("/sim/tower/airport-id",  true)
495         ->addChangeListener( new FGTowerLocationListener(), true );
496     FGClosestTowerLocationListener* ntcl = new FGClosestTowerLocationListener();
497     fgGetNode("/sim/airport/closest-airport-id", true)
498         ->addChangeListener(ntcl , true );
499     fgGetNode("/sim/tower/auto-position", true)
500            ->addChangeListener(ntcl, true );
501 }
502
503 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
504 {
505   SGGeod startPos(aStartPos);
506   if (aTargetHeading == HUGE_VAL) {
507     aTargetHeading = aHeading;
508   }
509   
510   if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
511     double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
512     offsetDistance *= SG_NM_TO_METER;
513     double offsetAzimuth = aHeading;
514     if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
515       offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
516       aHeading = aTargetHeading;
517     }
518
519     SGGeod offset;
520     double az2; // dummy
521     SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
522     startPos = offset;
523   }
524
525   // presets
526   fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
527   fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
528   fgSetDouble("/sim/presets/heading-deg", aHeading );
529
530   // other code depends on the actual values being set ...
531   fgSetDouble("/position/longitude-deg",  startPos.getLongitudeDeg() );
532   fgSetDouble("/position/latitude-deg",  startPos.getLatitudeDeg() );
533   fgSetDouble("/orientation/heading-deg", aHeading );
534 }
535
536 // Set current_options lon/lat given an airport id and heading (degrees)
537 bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
538     if ( id.empty() )
539         return false;
540
541     // set initial position from runway and heading
542     SG_LOG( SG_GENERAL, SG_INFO,
543             "Attempting to set starting position from airport code "
544             << id << " heading " << tgt_hdg );
545
546     const FGAirport* apt = fgFindAirportID(id);
547     if (!apt) return false;
548     FGRunway* r = apt->findBestRunwayForHeading(tgt_hdg);
549     fgSetString("/sim/atc/runway", r->ident().c_str());
550
551     SGGeod startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
552           fgApplyStartOffset(startPos, r->headingDeg(), tgt_hdg);
553     return true;
554 }
555
556 // Set current_options lon/lat given an airport id and parkig position name
557 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
558     if ( id.empty() )
559         return false;
560
561     // can't see an easy way around this const_cast at the moment
562     FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
563     if (!apt) {
564         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
565         return false;
566     }
567     FGAirportDynamics* dcs = apt->getDynamics();
568     if (!dcs) {
569         SG_LOG( SG_GENERAL, SG_ALERT,
570                 "Airport " << id << "does not appear to have parking information available");
571         return false;
572     }
573     
574     int park_index = dcs->getNrOfParkings() - 1;
575     bool succes;
576     double radius = fgGetDouble("/sim/dimensions/radius-m");
577     if ((parkpos == string("AVAILABLE")) && (radius > 0)) {
578         double lat, lon, heading;
579         string fltType;
580         string acOperator;
581         SGPath acData;
582         try {
583             acData = fgGetString("/sim/fg-home");
584             acData.append("aircraft-data");
585             string acfile = fgGetString("/sim/aircraft") + string(".xml");
586             acData.append(acfile);
587             SGPropertyNode root;
588             readProperties(acData.str(), &root);
589             SGPropertyNode * node = root.getNode("sim");
590             fltType    = node->getStringValue("aircraft-class", "NONE"     );
591             acOperator = node->getStringValue("aircraft-operator", "NONE"     );
592         } catch (const sg_exception &) {
593             SG_LOG(SG_GENERAL, SG_INFO,
594                 "Could not load aircraft aircrat type and operator information from: " << acData.str() << ". Using defaults");
595
596        // cout << path.str() << endl;
597         }
598         if (fltType.empty() || fltType == "NONE") {
599             SG_LOG(SG_GENERAL, SG_INFO,
600                 "Aircraft type information not found in: " << acData.str() << ". Using default value");
601                 fltType = fgGetString("/sim/aircraft-class"   );
602         }
603         if (acOperator.empty() || fltType == "NONE") {
604             SG_LOG(SG_GENERAL, SG_INFO,
605                 "Aircraft operator information not found in: " << acData.str() << ". Using default value");
606                 acOperator = fgGetString("/sim/aircraft-operator"   );
607         }
608
609         cerr << "Running aircraft " << fltType << " of livery " << acOperator << endl;
610         string acType; // Currently not used by findAvailable parking, so safe to leave empty. 
611         succes = dcs->getAvailableParking(&lat, &lon, &heading, &park_index, radius, fltType, acType, acOperator);
612         if (succes) {
613             fgGetString("/sim/presets/parkpos");
614             fgSetString("/sim/presets/parkpos", dcs->getParking(park_index)->getName());
615         } else {
616             SG_LOG( SG_GENERAL, SG_ALERT,
617                     "Failed to find a suitable parking at airport " << id );
618             return false;
619         }
620     } else {
621         //cerr << "We shouldn't get here when AVAILABLE" << endl;
622         while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
623         if (park_index < 0) {
624             SG_LOG( SG_GENERAL, SG_ALERT,
625                     "Failed to find parking position " << parkpos <<
626                     " at airport " << id );
627             return false;
628         }
629     }
630     FGParking* parking = dcs->getParking(park_index);
631     parking->setAvailable(false);
632     fgApplyStartOffset(
633       SGGeod::fromDeg(parking->getLongitude(), parking->getLatitude()),
634       parking->getHeading());
635     return true;
636 }
637
638
639 // Set current_options lon/lat given an airport id and runway number
640 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
641     if ( id.empty() )
642         return false;
643
644     // set initial position from airport and runway number
645     SG_LOG( SG_GENERAL, SG_INFO,
646             "Attempting to set starting position for "
647             << id << ":" << rwy );
648
649     const FGAirport* apt = fgFindAirportID(id);
650     if (!apt) {
651       SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
652       return false;
653     }
654     
655     if (!apt->hasRunwayWithIdent(rwy)) {
656       SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
657                 "Failed to find runway " << rwy <<
658                 " at airport " << id << ". Using default runway." );
659       return false;
660     }
661     
662     FGRunway* r(apt->getRunwayByIdent(rwy));
663     fgSetString("/sim/atc/runway", r->ident().c_str());
664     SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
665           fgApplyStartOffset(startPos, r->headingDeg());
666     return true;
667 }
668
669
670 static void fgSetDistOrAltFromGlideSlope() {
671     // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
672     string apt_id = fgGetString("/sim/presets/airport-id");
673     double gs = fgGetDouble("/sim/presets/glideslope-deg")
674         * SG_DEGREES_TO_RADIANS ;
675     double od = fgGetDouble("/sim/presets/offset-distance-nm");
676     double alt = fgGetDouble("/sim/presets/altitude-ft");
677
678     double apt_elev = 0.0;
679     if ( ! apt_id.empty() ) {
680         apt_elev = fgGetAirportElev( apt_id );
681         if ( apt_elev < -9990.0 ) {
682             apt_elev = 0.0;
683         }
684     } else {
685         apt_elev = 0.0;
686     }
687
688     if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
689         // set altitude from glideslope and offset-distance
690         od *= SG_NM_TO_METER * SG_METER_TO_FEET;
691         alt = fabs(od*tan(gs)) + apt_elev;
692         fgSetDouble("/sim/presets/altitude-ft", alt);
693         fgSetBool("/sim/presets/onground", false);
694         SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
695                 << alt  << " ft" );
696     } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
697         // set offset-distance from glideslope and altitude
698         od  = (alt - apt_elev) / tan(gs);
699         od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
700         fgSetDouble("/sim/presets/offset-distance-nm", od);
701         fgSetBool("/sim/presets/onground", false);
702         SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: " 
703                 << od  << " nm" );
704     } else if( fabs(gs) > 0.01 ) {
705         SG_LOG( SG_GENERAL, SG_ALERT,
706                 "Glideslope given but not altitude or offset-distance." );
707         SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
708         fgSetDouble("/sim/presets/glideslope-deg", 0);
709         fgSetBool("/sim/presets/onground", true);
710     }
711 }
712
713
714 // Set current_options lon/lat given an airport id and heading (degrees)
715 static bool fgSetPosFromNAV( const string& id, const double& freq, FGPositioned::Type type ) {
716
717     const nav_list_type navlist
718         = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq, type );
719
720     if (navlist.size() == 0 ) {
721         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
722             << id << ":" << freq );
723         return false;
724     }
725
726     if( navlist.size() > 1 ) {
727         ostringstream buf;
728         buf << "Ambigous NAV-ID: '" << id << "'. Specify id and frequency. Available stations:" << endl;
729         for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
730             // NDB stored in kHz, VOR stored in MHz * 100 :-P
731             double factor = (*it)->type() == FGPositioned::NDB ? 1.0 : 1/100.0;
732             string unit = (*it)->type() == FGPositioned::NDB ? "kHz" : "MHz";
733             buf << (*it)->ident() << " "
734                 << setprecision(5) << (double)((*it)->get_freq() * factor) << " "
735                 << (*it)->get_lat() << "/" << (*it)->get_lon()
736                 << endl;
737         }
738
739         SG_LOG( SG_GENERAL, SG_ALERT, buf.str() );
740         return false;
741     }
742
743     FGNavRecord *nav = navlist[0];
744     fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
745     return true;
746 }
747
748 // Set current_options lon/lat given an aircraft carrier id
749 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
750
751     // set initial position from runway and heading
752     SGGeod geodPos;
753     double heading;
754     SGVec3d uvw;
755     if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
756         double lon = geodPos.getLongitudeDeg();
757         double lat = geodPos.getLatitudeDeg();
758         double alt = geodPos.getElevationFt();
759
760         SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
761                 << carrier << " at lat = " << lat << ", lon = " << lon
762                 << ", alt = " << alt << ", heading = " << heading);
763
764         fgSetDouble("/sim/presets/longitude-deg",  lon);
765         fgSetDouble("/sim/presets/latitude-deg",  lat);
766         fgSetDouble("/sim/presets/altitude-ft", alt);
767         fgSetDouble("/sim/presets/heading-deg", heading);
768         fgSetDouble("/position/longitude-deg",  lon);
769         fgSetDouble("/position/latitude-deg",  lat);
770         fgSetDouble("/position/altitude-ft", alt);
771         fgSetDouble("/orientation/heading-deg", heading);
772
773         fgSetString("/sim/presets/speed-set", "UVW");
774         fgSetDouble("/velocities/uBody-fps", uvw(0));
775         fgSetDouble("/velocities/vBody-fps", uvw(1));
776         fgSetDouble("/velocities/wBody-fps", uvw(2));
777         fgSetDouble("/sim/presets/uBody-fps", uvw(0));
778         fgSetDouble("/sim/presets/vBody-fps", uvw(1));
779         fgSetDouble("/sim/presets/wBody-fps", uvw(2));
780
781         fgSetBool("/sim/presets/onground", true);
782
783         return true;
784     } else {
785         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
786                 << carrier );
787         return false;
788     }
789 }
790  
791 // Set current_options lon/lat given an airport id and heading (degrees)
792 static bool fgSetPosFromFix( const string& id )
793 {
794   FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
795   FGPositioned* fix = FGPositioned::findNextWithPartialId(NULL, id, &fixFilter);
796   if (!fix) {
797     SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
798     return false;
799   }
800   
801   fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
802   return true;
803 }
804
805 /**
806  * Initialize vor/ndb/ils/fix list management and query systems (as
807  * well as simple airport db list)
808  */
809 bool
810 fgInitNav ()
811 {
812     SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
813
814     SGPath aptdb( globals->get_fg_root() );
815     aptdb.append( "Airports/apt.dat" );
816
817     SGPath p_metar( globals->get_fg_root() );
818     p_metar.append( "Airports/metar.dat" );
819
820     fgAirportDBLoad( aptdb.str(), p_metar.str() );
821     
822     FGNavList *navlist = new FGNavList;
823     FGNavList *loclist = new FGNavList;
824     FGNavList *gslist = new FGNavList;
825     FGNavList *dmelist = new FGNavList;
826     FGNavList *tacanlist = new FGNavList;
827     FGNavList *carrierlist = new FGNavList;
828     FGTACANList *channellist = new FGTACANList;
829
830     globals->set_navlist( navlist );
831     globals->set_loclist( loclist );
832     globals->set_gslist( gslist );
833     globals->set_dmelist( dmelist );
834     globals->set_tacanlist( tacanlist );
835     globals->set_carrierlist( carrierlist );
836     globals->set_channellist( channellist );
837
838     if ( !fgNavDBInit(navlist, loclist, gslist, dmelist, tacanlist, carrierlist, channellist) ) {
839         SG_LOG( SG_GENERAL, SG_ALERT,
840                 "Problems loading one or more navigational database" );
841     }
842     
843     SG_LOG(SG_GENERAL, SG_INFO, "  Fixes");
844     SGPath p_fix( globals->get_fg_root() );
845     p_fix.append( "Navaids/fix.dat" );
846     FGFixList fixlist;
847     fixlist.init( p_fix );  // adds fixes to the DB in positioned.cxx
848
849     SG_LOG(SG_GENERAL, SG_INFO, "  Airways");
850     flightgear::Airway::load();
851     
852     return true;
853 }
854
855
856 // Set the initial position based on presets (or defaults)
857 bool fgInitPosition() {
858     // cout << "fgInitPosition()" << endl;
859     double gs = fgGetDouble("/sim/presets/glideslope-deg")
860         * SG_DEGREES_TO_RADIANS ;
861     double od = fgGetDouble("/sim/presets/offset-distance-nm");
862     double alt = fgGetDouble("/sim/presets/altitude-ft");
863
864     bool set_pos = false;
865
866     // If glideslope is specified, then calculate offset-distance or
867     // altitude relative to glide slope if either of those was not
868     // specified.
869     if ( fabs( gs ) > 0.01 ) {
870         fgSetDistOrAltFromGlideSlope();
871     }
872
873
874     // If we have an explicit, in-range lon/lat, don't change it, just use it.
875     // If not, check for an airport-id and use that.
876     // If not, default to the middle of the KSFO field.
877     // The default values for lon/lat are deliberately out of range
878     // so that the airport-id can take effect; valid lon/lat will
879     // override airport-id, however.
880     double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
881     double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
882     if ( lon_deg >= -180.0 && lon_deg <= 180.0
883          && lat_deg >= -90.0 && lat_deg <= 90.0 )
884     {
885         set_pos = true;
886     }
887
888     string apt = fgGetString("/sim/presets/airport-id");
889     string rwy_no = fgGetString("/sim/presets/runway");
890     bool rwy_req = fgGetBool("/sim/presets/runway-requested");
891     string vor = fgGetString("/sim/presets/vor-id");
892     double vor_freq = fgGetDouble("/sim/presets/vor-freq");
893     string ndb = fgGetString("/sim/presets/ndb-id");
894     double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
895     string carrier = fgGetString("/sim/presets/carrier");
896     string parkpos = fgGetString("/sim/presets/parkpos");
897     string fix = fgGetString("/sim/presets/fix");
898     SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
899     double hdg = hdg_preset->getDoubleValue();
900
901     // save some start parameters, so that we can later say what the
902     // user really requested. TODO generalize that and move it to options.cxx
903     static bool start_options_saved = false;
904     if (!start_options_saved) {
905         start_options_saved = true;
906         SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
907
908         opt->setDoubleValue("latitude-deg", lat_deg);
909         opt->setDoubleValue("longitude-deg", lon_deg);
910         opt->setDoubleValue("heading-deg", hdg);
911         opt->setStringValue("airport", apt.c_str());
912         opt->setStringValue("runway", rwy_no.c_str());
913     }
914
915     if (hdg > 9990.0)
916         hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
917
918     if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
919         // An airport + parking position is requested
920         if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
921             // set tower position
922             fgSetString("/sim/airport/closest-airport-id",  apt.c_str());
923             fgSetString("/sim/tower/airport-id",  apt.c_str());
924             set_pos = true;
925         }
926     }
927
928     if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
929         // An airport + runway is requested
930         if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
931             // set tower position (a little off the heading for single
932             // runway airports)
933             fgSetString("/sim/airport/closest-airport-id",  apt.c_str());
934             fgSetString("/sim/tower/airport-id",  apt.c_str());
935             set_pos = true;
936         }
937     }
938
939     if ( !set_pos && !apt.empty() ) {
940         // An airport is requested (find runway closest to hdg)
941         if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
942             // set tower position (a little off the heading for single
943             // runway airports)
944             fgSetString("/sim/airport/closest-airport-id",  apt.c_str());
945             fgSetString("/sim/tower/airport-id",  apt.c_str());
946             set_pos = true;
947         }
948     }
949
950     if (hdg_preset->getDoubleValue() > 9990.0)
951         hdg_preset->setDoubleValue(hdg);
952
953     if ( !set_pos && !vor.empty() ) {
954         // a VOR is requested
955         if ( fgSetPosFromNAV( vor, vor_freq, FGPositioned::VOR ) ) {
956             set_pos = true;
957         }
958     }
959
960     if ( !set_pos && !ndb.empty() ) {
961         // an NDB is requested
962         if ( fgSetPosFromNAV( ndb, ndb_freq, FGPositioned::NDB ) ) {
963             set_pos = true;
964         }
965     }
966
967     if ( !set_pos && !carrier.empty() ) {
968         // an aircraft carrier is requested
969         if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
970             set_pos = true;
971         }
972     }
973
974     if ( !set_pos && !fix.empty() ) {
975         // a Fix is requested
976         if ( fgSetPosFromFix( fix ) ) {
977             set_pos = true;
978         }
979     }
980
981     if ( !set_pos ) {
982         // No lon/lat specified, no airport specified, default to
983         // middle of KSFO field.
984         fgSetDouble("/sim/presets/longitude-deg", -122.374843);
985         fgSetDouble("/sim/presets/latitude-deg", 37.619002);
986     }
987
988     fgSetDouble( "/position/longitude-deg",
989                  fgGetDouble("/sim/presets/longitude-deg") );
990     fgSetDouble( "/position/latitude-deg",
991                  fgGetDouble("/sim/presets/latitude-deg") );
992     fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
993
994     // determine if this should be an on-ground or in-air start
995     if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
996         fgSetBool("/sim/presets/onground", false);
997     } else {
998         fgSetBool("/sim/presets/onground", true);
999     }
1000
1001     return true;
1002 }
1003
1004
1005 // General house keeping initializations
1006 bool fgInitGeneral() {
1007     string root;
1008
1009     SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1010     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1011
1012     root = globals->get_fg_root();
1013     if ( ! root.length() ) {
1014         // No root path set? Then bail ...
1015         SG_LOG( SG_GENERAL, SG_ALERT,
1016                 "Cannot continue without a path to the base package "
1017                 << "being defined." );
1018         exit(-1);
1019     }
1020     SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1021
1022     globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1023
1024     simgear::Dir cwd(simgear::Dir::current());
1025     SGPropertyNode *curr = fgGetNode("/sim", true);
1026     curr->removeChild("fg-current", 0, false);
1027     curr = curr->getChild("fg-current", 0, true);
1028     curr->setStringValue(cwd.path().str());
1029     curr->setAttribute(SGPropertyNode::WRITE, false);
1030
1031     fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
1032     fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
1033     return true;
1034 }
1035
1036 // This is the top level init routine which calls all the other
1037 // initialization routines.  If you are adding a subsystem to flight
1038 // gear, its initialization call should located in this routine.
1039 // Returns non-zero if a problem encountered.
1040 bool fgInitSubsystems() {
1041
1042     SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1043     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1044
1045     ////////////////////////////////////////////////////////////////////
1046     // Initialize the sound subsystem.
1047     ////////////////////////////////////////////////////////////////////
1048     // Sound manager uses an own subsystem group "SOUND" which is the last
1049     // to be updated in every loop.
1050     // Sound manager is updated last so it can use the CPU while the GPU
1051     // is processing the scenery (doubled the frame-rate for me) -EMH-
1052     globals->add_subsystem("sound", new SGSoundMgr, SGSubsystemMgr::SOUND);
1053
1054     ////////////////////////////////////////////////////////////////////
1055     // Initialize the event manager subsystem.
1056     ////////////////////////////////////////////////////////////////////
1057
1058     globals->get_event_mgr()->init();
1059     globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1060
1061     ////////////////////////////////////////////////////////////////////
1062     // Initialize the property interpolator subsystem. Put into the INIT
1063     // group because the "nasal" subsystem may need it at GENERAL take-down.
1064     ////////////////////////////////////////////////////////////////////
1065     globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1066
1067
1068     ////////////////////////////////////////////////////////////////////
1069     // Add the FlightGear property utilities.
1070     ////////////////////////////////////////////////////////////////////
1071     globals->add_subsystem("properties", new FGProperties);
1072
1073
1074     ////////////////////////////////////////////////////////////////////
1075     // Add the performance monitoring system.
1076     ////////////////////////////////////////////////////////////////////
1077     globals->add_subsystem("performance-mon",
1078             new SGPerformanceMonitor(globals->get_subsystem_mgr(),
1079                                      fgGetNode("/sim/performance-monitor", true)));
1080
1081     ////////////////////////////////////////////////////////////////////
1082     // Initialize the material property subsystem.
1083     ////////////////////////////////////////////////////////////////////
1084
1085     SGPath mpath( globals->get_fg_root() );
1086     mpath.append( fgGetString("/sim/rendering/materials-file") );
1087     if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
1088             globals->get_props()) ) {
1089         SG_LOG( SG_GENERAL, SG_ALERT,
1090                 "Error loading materials file " << mpath.str() );
1091         exit(-1);
1092     }
1093
1094
1095     ////////////////////////////////////////////////////////////////////
1096     // Initialize the scenery management subsystem.
1097     ////////////////////////////////////////////////////////////////////
1098
1099     globals->get_scenery()->get_scene_graph()
1100         ->addChild(simgear::Particles::getCommonRoot());
1101     simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
1102
1103     ////////////////////////////////////////////////////////////////////
1104     // Initialize the flight model subsystem.
1105     ////////////////////////////////////////////////////////////////////
1106
1107     globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
1108
1109     ////////////////////////////////////////////////////////////////////
1110     // Initialize the weather subsystem.
1111     ////////////////////////////////////////////////////////////////////
1112
1113     // Initialize the weather modeling subsystem
1114     globals->add_subsystem("environment", new FGEnvironmentMgr);
1115     globals->add_subsystem("ephemeris", new Ephemeris);
1116     
1117     ////////////////////////////////////////////////////////////////////
1118     // Initialize the aircraft systems and instrumentation (before the
1119     // autopilot.)
1120     ////////////////////////////////////////////////////////////////////
1121
1122     globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
1123     globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
1124
1125     ////////////////////////////////////////////////////////////////////
1126     // Initialize the XML Autopilot subsystem.
1127     ////////////////////////////////////////////////////////////////////
1128
1129     globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance("autopilot"), SGSubsystemMgr::FDM );
1130     globals->add_subsystem( "xml-proprules", FGXMLAutopilotGroup::createInstance("property-rule"), SGSubsystemMgr::GENERAL );
1131     globals->add_subsystem( "route-manager", new FGRouteMgr );
1132
1133     ////////////////////////////////////////////////////////////////////
1134     // Initialize the Input-Output subsystem
1135     ////////////////////////////////////////////////////////////////////
1136     globals->add_subsystem( "io", new FGIO );
1137
1138     ////////////////////////////////////////////////////////////////////
1139     // Create and register the logger.
1140     ////////////////////////////////////////////////////////////////////
1141     
1142     globals->add_subsystem("logger", new FGLogger);
1143
1144     ////////////////////////////////////////////////////////////////////
1145     // Create and register the XML GUI.
1146     ////////////////////////////////////////////////////////////////////
1147
1148     globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1149
1150     //////////////////////////////////////////////////////////////////////
1151     // Initialize the 2D cloud subsystem.
1152     ////////////////////////////////////////////////////////////////////
1153     fgGetBool("/sim/rendering/bump-mapping", false);
1154
1155     ////////////////////////////////////////////////////////////////////
1156     // Initialize the canvas 2d drawing subsystem.
1157     ////////////////////////////////////////////////////////////////////
1158     globals->add_subsystem("Canvas2D", new CanvasMgr, SGSubsystemMgr::DISPLAY);
1159
1160     ////////////////////////////////////////////////////////////////////
1161     // Initialise the ATIS Manager
1162     // Note that this is old stuff, but is necessary for the
1163     // current ATIS implementation. Therefore, leave it in here
1164     // until the ATIS system is ported over to make use of the ATIS 
1165     // sub system infrastructure.
1166     ////////////////////////////////////////////////////////////////////
1167
1168     globals->add_subsystem("ATIS", new FGATISMgr, SGSubsystemMgr::INIT, 0.4);
1169
1170     ////////////////////////////////////////////////////////////////////
1171    // Initialize the ATC subsystem
1172     ////////////////////////////////////////////////////////////////////
1173     globals->add_subsystem("ATC", new FGATCManager, SGSubsystemMgr::POST_FDM);
1174
1175     ////////////////////////////////////////////////////////////////////
1176     // Initialize multiplayer subsystem
1177     ////////////////////////////////////////////////////////////////////
1178
1179     globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
1180
1181     ////////////////////////////////////////////////////////////////////
1182     // Initialise the AI Model Manager
1183     ////////////////////////////////////////////////////////////////////
1184     SG_LOG(SG_GENERAL, SG_INFO, "  AI Model Manager");
1185     globals->add_subsystem("ai-model", new FGAIManager, SGSubsystemMgr::POST_FDM);
1186     globals->add_subsystem("submodel-mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
1187
1188
1189     // It's probably a good idea to initialize the top level traffic manager
1190     // After the AI and ATC systems have been initialized properly.
1191     // AI Traffic manager
1192     globals->add_subsystem("traffic-manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
1193
1194     ////////////////////////////////////////////////////////////////////
1195     // Add a new 2D panel.
1196     ////////////////////////////////////////////////////////////////////
1197
1198     fgSetArchivable("/sim/panel/visibility");
1199     fgSetArchivable("/sim/panel/x-offset");
1200     fgSetArchivable("/sim/panel/y-offset");
1201     fgSetArchivable("/sim/panel/jitter");
1202   
1203     ////////////////////////////////////////////////////////////////////
1204     // Initialize the controls subsystem.
1205     ////////////////////////////////////////////////////////////////////
1206
1207     globals->get_controls()->init();
1208     globals->get_controls()->bind();
1209
1210
1211     ////////////////////////////////////////////////////////////////////
1212     // Initialize the input subsystem.
1213     ////////////////////////////////////////////////////////////////////
1214
1215     globals->add_subsystem("input", new FGInput);
1216
1217
1218     ////////////////////////////////////////////////////////////////////
1219     // Initialize the replay subsystem
1220     ////////////////////////////////////////////////////////////////////
1221     globals->add_subsystem("replay", new FGReplay);
1222
1223 #ifdef ENABLE_AUDIO_SUPPORT
1224     ////////////////////////////////////////////////////////////////////
1225     // Initialize the sound-effects subsystem.
1226     ////////////////////////////////////////////////////////////////////
1227     globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
1228 #endif
1229
1230     ////////////////////////////////////////////////////////////////////
1231     // Initialize the lighting subsystem.
1232     ////////////////////////////////////////////////////////////////////
1233
1234     globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
1235     
1236     // ordering here is important : Nasal (via events), then models, then views
1237     globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
1238     
1239     FGAircraftModel* acm = new FGAircraftModel;
1240     globals->set_aircraft_model(acm);
1241     globals->add_subsystem("aircraft-model", acm, SGSubsystemMgr::DISPLAY);
1242
1243     FGModelMgr* mm = new FGModelMgr;
1244     globals->set_model_mgr(mm);
1245     globals->add_subsystem("model-manager", mm, SGSubsystemMgr::DISPLAY);
1246
1247     FGViewMgr *viewmgr = new FGViewMgr;
1248     globals->set_viewmgr( viewmgr );
1249     globals->add_subsystem("view-manager", viewmgr, SGSubsystemMgr::DISPLAY);
1250
1251     globals->add_subsystem("tile-manager", globals->get_tile_mgr(), 
1252       SGSubsystemMgr::DISPLAY);
1253       
1254     ////////////////////////////////////////////////////////////////////
1255     // Bind and initialize subsystems.
1256     ////////////////////////////////////////////////////////////////////
1257
1258     globals->get_subsystem_mgr()->bind();
1259     globals->get_subsystem_mgr()->init();
1260
1261     ////////////////////////////////////////////////////////////////////////
1262     // Initialize the Nasal interpreter.
1263     // Do this last, so that the loaded scripts see initialized state
1264     ////////////////////////////////////////////////////////////////////////
1265     FGNasalSys* nasal = new FGNasalSys();
1266     globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1267     nasal->init();
1268
1269     // initialize methods that depend on other subsystems.
1270     globals->get_subsystem_mgr()->postinit();
1271
1272     ////////////////////////////////////////////////////////////////////////
1273     // End of subsystem initialization.
1274     ////////////////////////////////////////////////////////////////////
1275
1276     fgSetBool("/sim/crashed", false);
1277     fgSetBool("/sim/initialized", true);
1278
1279     SG_LOG( SG_GENERAL, SG_INFO, endl);
1280
1281                                 // Save the initial state for future
1282                                 // reference.
1283     globals->saveInitialState();
1284     
1285     return true;
1286 }
1287
1288 // Reset: this is what the 'reset' command (and hence, GUI) is attached to
1289 void fgReInitSubsystems()
1290 {
1291     static const SGPropertyNode *master_freeze
1292         = fgGetNode("/sim/freeze/master");
1293
1294     SG_LOG( SG_GENERAL, SG_INFO, "fgReInitSubsystems()");
1295
1296 // setup state to begin re-init
1297     bool freeze = master_freeze->getBoolValue();
1298     if ( !freeze ) {
1299         fgSetBool("/sim/freeze/master", true);
1300     }
1301     
1302     fgSetBool("/sim/signals/reinit", true);
1303     fgSetBool("/sim/crashed", false);
1304
1305 // do actual re-init steps
1306     globals->get_subsystem("flight")->unbind();
1307     
1308   // reset control state, before restoring initial state; -set or config files
1309   // may specify values for flaps, trim tabs, magnetos, etc
1310     globals->get_controls()->reset_all();
1311         
1312     globals->restoreInitialState();
1313
1314     // update our position based on current presets
1315     fgInitPosition();
1316     
1317     // Force reupdating the positions of the ai 3d models. They are used for
1318     // initializing ground level for the FDM.
1319     globals->get_subsystem("ai-model")->reinit();
1320
1321     // Initialize the FDM
1322     globals->get_subsystem("flight")->reinit();
1323
1324     // reset replay buffers
1325     globals->get_subsystem("replay")->reinit();
1326     
1327     // reload offsets from config defaults
1328     globals->get_viewmgr()->reinit();
1329
1330     globals->get_subsystem("time")->reinit();
1331
1332     // need to bind FDMshell again, since we manually unbound it above...
1333     globals->get_subsystem("flight")->bind();
1334
1335 // setup state to end re-init
1336     fgSetBool("/sim/signals/reinit", false);
1337     if ( !freeze ) {
1338         fgSetBool("/sim/freeze/master", false);
1339     }
1340     fgSetBool("/sim/sceneryloaded",false);
1341 }
1342
1343
1344 ///////////////////////////////////////////////////////////////////////////////
1345 // helper object to implement the --show-aircraft command.
1346 // resides here so we can share the fgFindAircraftInDir template above,
1347 // and hence ensure this command lists exectly the same aircraft as the normal
1348 // loading path.
1349 class ShowAircraft 
1350 {
1351 public:
1352   ShowAircraft()
1353   {
1354     _minStatus = getNumMaturity(fgGetString("/sim/aircraft-min-status", "all"));
1355   }
1356   
1357   
1358   void show(const SGPath& path)
1359   {
1360     fgFindAircraftInDir(path, this, &ShowAircraft::processAircraft);
1361   
1362     std::sort(_aircraft.begin(), _aircraft.end(), ciLessLibC());
1363     SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on Windows
1364     cout << "Available aircraft:" << endl;
1365     for ( unsigned int i = 0; i < _aircraft.size(); i++ ) {
1366         cout << _aircraft[i] << endl;
1367     }
1368   }
1369   
1370 private:
1371   bool processAircraft(const SGPath& path)
1372   {
1373     SGPropertyNode root;
1374     try {
1375        readProperties(path.str(), &root);
1376     } catch (sg_exception& ) {
1377        return false;
1378     }
1379   
1380     int maturity = 0;
1381     string descStr("   ");
1382     descStr += path.file();
1383   // trim common suffix from file names
1384     int nPos = descStr.rfind("-set.xml");
1385     if (nPos == (int)(descStr.size() - 8)) {
1386       descStr.resize(nPos);
1387     }
1388     
1389     SGPropertyNode *node = root.getNode("sim");
1390     if (node) {
1391       SGPropertyNode* desc = node->getNode("description");
1392       // if a status tag is found, read it in
1393       if (node->hasValue("status")) {
1394         maturity = getNumMaturity(node->getStringValue("status"));
1395       }
1396       
1397       if (desc) {
1398         if (descStr.size() <= 27+3) {
1399           descStr.append(29+3-descStr.size(), ' ');
1400         } else {
1401           descStr += '\n';
1402           descStr.append( 32, ' ');
1403         }
1404         descStr += desc->getStringValue();
1405       }
1406     } // of have 'sim' node
1407     
1408     if (maturity < _minStatus) {
1409       return false;
1410     }
1411
1412     _aircraft.push_back(descStr);
1413     return false;
1414   }
1415
1416
1417   int getNumMaturity(const char * str) 
1418   {
1419     // changes should also be reflected in $FG_ROOT/data/options.xml & 
1420     // $FG_ROOT/data/Translations/string-default.xml
1421     const char* levels[] = {"alpha","beta","early-production","production"}; 
1422
1423     if (!strcmp(str, "all")) {
1424       return 0;
1425     }
1426
1427     for (size_t i=0; i<(sizeof(levels)/sizeof(levels[0]));i++) 
1428       if (strcmp(str,levels[i])==0)
1429         return i;
1430
1431     return 0;
1432   }
1433
1434   // recommended in Meyers, Effective STL when internationalization and embedded
1435   // NULLs aren't an issue.  Much faster than the STL or Boost lex versions.
1436   struct ciLessLibC : public std::binary_function<string, string, bool>
1437   {
1438     bool operator()(const std::string &lhs, const std::string &rhs) const
1439     {
1440       return strcasecmp(lhs.c_str(), rhs.c_str()) < 0 ? 1 : 0;
1441     }
1442   };
1443
1444   int _minStatus;
1445   string_list _aircraft;
1446 };
1447
1448 void fgShowAircraft(const SGPath &path)
1449 {
1450     ShowAircraft s;
1451     s.show(path);
1452         
1453 #ifdef _MSC_VER
1454     cout << "Hit a key to continue..." << endl;
1455     cin.get();
1456 #endif
1457 }
1458
1459