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