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