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