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