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