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