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