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