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