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