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