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