]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
6a83efb412f6cf2edaac395fce3603b03fff971b
[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 #if defined(FX) && defined(XMESA)
1394     // initialize full screen flag
1395     globals->set_fullscreen(false);
1396     if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1397         // Test for the MESA_GLX_FX env variable
1398         if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
1399             // test if we are fullscreen mesa/glide
1400             if ( (mesa_win_state[0] == 'f') ||
1401                  (mesa_win_state[0] == 'F') ) {
1402                 globals->set_fullscreen(true);
1403             }
1404         }
1405     }
1406 #endif
1407
1408     char buf[512], *cwd = getcwd(buf, 511);
1409     buf[511] = '\0';
1410     SGPropertyNode *curr = fgGetNode("/sim", true);
1411     curr->removeChild("fg-current", 0, false);
1412     curr = curr->getChild("fg-current", 0, true);
1413     curr->setStringValue(cwd ? cwd : "");
1414     curr->setAttribute(SGPropertyNode::WRITE, false);
1415     return true;
1416 }
1417
1418
1419 // Initialize the flight model subsystem.  This just creates the
1420 // object.  The actual fdm initialization is delayed until we get a
1421 // proper scenery elevation hit.  This is checked for in main.cxx
1422
1423 void fgInitFDM() {
1424
1425     if ( cur_fdm_state ) {
1426         delete cur_fdm_state;
1427         cur_fdm_state = 0;
1428     }
1429
1430     double dt = 1.0 / fgGetInt("/sim/model-hz");
1431     string model = fgGetString("/sim/flight-model");
1432
1433     if ( model == "larcsim" ) {
1434         cur_fdm_state = new FGLaRCsim( dt );
1435     } else if ( model == "jsb" ) {
1436         cur_fdm_state = new FGJSBsim( dt );
1437 #if ENABLE_SP_FDM
1438     } else if ( model == "ada" ) {
1439         cur_fdm_state = new FGADA( dt );
1440     } else if ( model == "acms" ) {
1441         cur_fdm_state = new FGACMS( dt );
1442 #endif
1443     } else if ( model == "balloon" ) {
1444         cur_fdm_state = new FGBalloonSim( dt );
1445     } else if ( model == "magic" ) {
1446         cur_fdm_state = new FGMagicCarpet( dt );
1447     } else if ( model == "ufo" ) {
1448         cur_fdm_state = new FGUFO( dt );
1449     } else if ( model == "external" ) {
1450         // external is a synonym for "--fdm=null" and is
1451         // maintained here for backwards compatibility
1452         cur_fdm_state = new FGNullFDM( dt );
1453     } else if ( model.find("network") == 0 ) {
1454         string host = "localhost";
1455         int port1 = 5501;
1456         int port2 = 5502;
1457         int port3 = 5503;
1458         string net_options = model.substr(8);
1459         string::size_type begin, end;
1460         begin = 0;
1461         // host
1462         end = net_options.find( ",", begin );
1463         if ( end != string::npos ) {
1464             host = net_options.substr(begin, end - begin);
1465             begin = end + 1;
1466         }
1467         // port1
1468         end = net_options.find( ",", begin );
1469         if ( end != string::npos ) {
1470             port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1471             begin = end + 1;
1472         }
1473         // port2
1474         end = net_options.find( ",", begin );
1475         if ( end != string::npos ) {
1476             port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1477             begin = end + 1;
1478         }
1479         // port3
1480         end = net_options.find( ",", begin );
1481         if ( end != string::npos ) {
1482             port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1483             begin = end + 1;
1484         }
1485         cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1486     } else if ( model.find("pipe") == 0 ) {
1487         // /* old */ string pipe_path = model.substr(5);
1488         // /* old */ cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1489         string pipe_path = "";
1490         string pipe_protocol = "";
1491         string pipe_options = model.substr(5);
1492         string::size_type begin, end;
1493         begin = 0;
1494         // pipe file path
1495         end = pipe_options.find( ",", begin );
1496         if ( end != string::npos ) {
1497             pipe_path = pipe_options.substr(begin, end - begin);
1498             begin = end + 1;
1499         }
1500         // protocol (last option)
1501         pipe_protocol = pipe_options.substr(begin);
1502         cur_fdm_state = new FGExternalPipe( dt, pipe_path, pipe_protocol );
1503     } else if ( model == "null" ) {
1504         cur_fdm_state = new FGNullFDM( dt );
1505     } else if ( model == "yasim" ) {
1506         cur_fdm_state = new YASim( dt );
1507     } else {
1508         throw sg_throwable(string("Unrecognized flight model '") + model
1509                + "', cannot init flight dynamics model.");
1510     }
1511 }
1512
1513 // Initialize view parameters
1514 void fgInitView() {
1515   // force update of model so that viewer can get some data...
1516   globals->get_aircraft_model()->update(0);
1517   // run update for current view so that data is current...
1518   globals->get_viewmgr()->update(0);
1519 }
1520
1521
1522 SGTime *fgInitTime() {
1523     // Initialize time
1524     static const SGPropertyNode *longitude
1525         = fgGetNode("/position/longitude-deg");
1526     static const SGPropertyNode *latitude
1527         = fgGetNode("/position/latitude-deg");
1528     static const SGPropertyNode *cur_time_override
1529         = fgGetNode("/sim/time/cur-time-override", true);
1530
1531     SGPath zone( globals->get_fg_root() );
1532     zone.append( "Timezone" );
1533     SGTime *t = new SGTime( longitude->getDoubleValue()
1534                               * SGD_DEGREES_TO_RADIANS,
1535                             latitude->getDoubleValue()
1536                               * SGD_DEGREES_TO_RADIANS,
1537                             zone.str(),
1538                             cur_time_override->getLongValue() );
1539
1540     globals->set_warp_delta( 0 );
1541
1542     t->update( 0.0, 0.0,
1543                cur_time_override->getLongValue(),
1544                globals->get_warp() );
1545
1546     return t;
1547 }
1548
1549
1550 // set up a time offset (aka warp) if one is specified
1551 void fgInitTimeOffset() {
1552     static const SGPropertyNode *longitude
1553         = fgGetNode("/position/longitude-deg");
1554     static const SGPropertyNode *latitude
1555         = fgGetNode("/position/latitude-deg");
1556     static const SGPropertyNode *cur_time_override
1557         = fgGetNode("/sim/time/cur-time-override", true);
1558
1559     // Handle potential user specified time offsets
1560     int orig_warp = globals->get_warp();
1561     SGTime *t = globals->get_time_params();
1562     time_t cur_time = t->get_cur_time();
1563     time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1564     time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1565     time_t aircraftLocalTime = 
1566         sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1567     
1568     // Okay, we now have several possible scenarios
1569     int offset = fgGetInt("/sim/startup/time-offset");
1570     string offset_type = fgGetString("/sim/startup/time-offset-type");
1571
1572     int warp = 0;
1573     if ( offset_type == "real" ) {
1574         warp = 0;
1575     } else if ( offset_type == "dawn" ) {
1576         warp = fgTimeSecondsUntilSunAngle( cur_time,
1577                                            longitude->getDoubleValue()
1578                                              * SGD_DEGREES_TO_RADIANS,
1579                                            latitude->getDoubleValue()
1580                                              * SGD_DEGREES_TO_RADIANS,
1581                                            90.0, true ); 
1582     } else if ( offset_type == "morning" ) {
1583         warp = fgTimeSecondsUntilSunAngle( cur_time,
1584                                            longitude->getDoubleValue()
1585                                              * SGD_DEGREES_TO_RADIANS,
1586                                            latitude->getDoubleValue()
1587                                              * SGD_DEGREES_TO_RADIANS,
1588                                            75.0, true ); 
1589     } else if ( offset_type == "noon" ) {
1590         warp = fgTimeSecondsUntilSunAngle( cur_time,
1591                                            longitude->getDoubleValue()
1592                                              * SGD_DEGREES_TO_RADIANS,
1593                                            latitude->getDoubleValue()
1594                                              * SGD_DEGREES_TO_RADIANS,
1595                                            0.0, true ); 
1596     } else if ( offset_type == "afternoon" ) {
1597         warp = fgTimeSecondsUntilSunAngle( cur_time,
1598                                            longitude->getDoubleValue()
1599                                              * SGD_DEGREES_TO_RADIANS,
1600                                            latitude->getDoubleValue()
1601                                              * SGD_DEGREES_TO_RADIANS,
1602                                            60.0, false ); 
1603      } else if ( offset_type == "dusk" ) {
1604         warp = fgTimeSecondsUntilSunAngle( cur_time,
1605                                            longitude->getDoubleValue()
1606                                              * SGD_DEGREES_TO_RADIANS,
1607                                            latitude->getDoubleValue()
1608                                              * SGD_DEGREES_TO_RADIANS,
1609                                            90.0, false ); 
1610      } else if ( offset_type == "evening" ) {
1611         warp = fgTimeSecondsUntilSunAngle( cur_time,
1612                                            longitude->getDoubleValue()
1613                                              * SGD_DEGREES_TO_RADIANS,
1614                                            latitude->getDoubleValue()
1615                                              * SGD_DEGREES_TO_RADIANS,
1616                                            100.0, false ); 
1617     } else if ( offset_type == "midnight" ) {
1618         warp = fgTimeSecondsUntilSunAngle( cur_time,
1619                                            longitude->getDoubleValue()
1620                                              * SGD_DEGREES_TO_RADIANS,
1621                                            latitude->getDoubleValue()
1622                                              * SGD_DEGREES_TO_RADIANS,
1623                                            180.0, false ); 
1624     } else if ( offset_type == "system-offset" ) {
1625         warp = offset;
1626         orig_warp = 0;
1627     } else if ( offset_type == "gmt-offset" ) {
1628         warp = offset - (currGMT - systemLocalTime);
1629         orig_warp = 0;
1630     } else if ( offset_type == "latitude-offset" ) {
1631         warp = offset - (aircraftLocalTime - systemLocalTime);
1632         orig_warp = 0;
1633     } else if ( offset_type == "system" ) {
1634       warp = offset - (systemLocalTime - currGMT) - cur_time;
1635     } else if ( offset_type == "gmt" ) {
1636         warp = offset - cur_time;
1637     } else if ( offset_type == "latitude" ) {
1638         warp = offset - (aircraftLocalTime - currGMT)- cur_time; 
1639     } else {
1640         SG_LOG( SG_GENERAL, SG_ALERT,
1641                 "FG_TIME::Unsupported offset type " << offset_type );
1642         exit( -1 );
1643     }
1644     globals->set_warp( orig_warp + warp );
1645     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1646                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1647                cur_time_override->getLongValue(),
1648                globals->get_warp() );
1649
1650     SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = " 
1651             << globals->get_warp() );
1652 }
1653
1654
1655 // This is the top level init routine which calls all the other
1656 // initialization routines.  If you are adding a subsystem to flight
1657 // gear, its initialization call should located in this routine.
1658 // Returns non-zero if a problem encountered.
1659 bool fgInitSubsystems() {
1660     // static const SGPropertyNode *longitude
1661     //     = fgGetNode("/sim/presets/longitude-deg");
1662     // static const SGPropertyNode *latitude
1663     //     = fgGetNode("/sim/presets/latitude-deg");
1664     // static const SGPropertyNode *altitude
1665     //     = fgGetNode("/sim/presets/altitude-ft");
1666     SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1667     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1668
1669     ////////////////////////////////////////////////////////////////////
1670     // Initialize the event manager subsystem.
1671     ////////////////////////////////////////////////////////////////////
1672
1673     globals->get_event_mgr()->init();
1674     globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1675
1676     ////////////////////////////////////////////////////////////////////
1677     // Initialize the property interpolator subsystem. Put into the INIT
1678     // group because the "nasal" subsystem may need it at GENERAL take-down.
1679     ////////////////////////////////////////////////////////////////////
1680     globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1681
1682
1683     ////////////////////////////////////////////////////////////////////
1684     // Add the FlightGear property utilities.
1685     ////////////////////////////////////////////////////////////////////
1686     globals->add_subsystem("properties", new FGProperties);
1687
1688     ////////////////////////////////////////////////////////////////////
1689     // Initialize the material property subsystem.
1690     ////////////////////////////////////////////////////////////////////
1691
1692     SGPath mpath( globals->get_fg_root() );
1693     mpath.append( "materials.xml" );
1694     string season = fgGetString("/sim/startup/season", "summer");
1695     if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(), season.c_str(),
1696             globals->get_props()) ) {
1697         SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1698         exit(-1);
1699     }
1700
1701
1702     ////////////////////////////////////////////////////////////////////
1703     // Initialize the scenery management subsystem.
1704     ////////////////////////////////////////////////////////////////////
1705
1706     if ( globals->get_tile_mgr()->init() ) {
1707         // Load the local scenery data
1708         double visibility_meters = fgGetDouble("/environment/visibility-m");
1709                 
1710         globals->get_tile_mgr()->update( visibility_meters );
1711     } else {
1712         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1713         exit(-1);
1714     }
1715
1716     globals->get_scenery()->get_scene_graph()
1717         ->addChild(simgear::Particles::getCommonRoot());
1718
1719     ////////////////////////////////////////////////////////////////////
1720     // Initialize the flight model subsystem.
1721     ////////////////////////////////////////////////////////////////////
1722
1723     fgInitFDM();
1724         
1725     // allocates structures so must happen before any of the flight
1726     // model or control parameters are set
1727     fgAircraftInit();   // In the future this might not be the case.
1728
1729
1730     ////////////////////////////////////////////////////////////////////
1731     // Initialize the weather subsystem.
1732     ////////////////////////////////////////////////////////////////////
1733
1734     // Initialize the weather modeling subsystem
1735     globals->add_subsystem("environment", new FGEnvironmentMgr);
1736
1737
1738     ////////////////////////////////////////////////////////////////////
1739     // Initialize the aircraft systems and instrumentation (before the
1740     // autopilot.)
1741     ////////////////////////////////////////////////////////////////////
1742
1743     globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1744     globals->add_subsystem("systems", new FGSystemMgr);
1745
1746     ////////////////////////////////////////////////////////////////////
1747     // Initialize the XML Autopilot subsystem.
1748     ////////////////////////////////////////////////////////////////////
1749
1750     globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1751     globals->add_subsystem( "route-manager", new FGRouteMgr );
1752
1753   
1754     ////////////////////////////////////////////////////////////////////
1755     // Initialize the view manager subsystem.
1756     ////////////////////////////////////////////////////////////////////
1757
1758     fgInitView();
1759
1760     ////////////////////////////////////////////////////////////////////
1761     // Create and register the logger.
1762     ////////////////////////////////////////////////////////////////////
1763     
1764     globals->add_subsystem("logger", new FGLogger);
1765
1766     ////////////////////////////////////////////////////////////////////
1767     // Create and register the XML GUI.
1768     ////////////////////////////////////////////////////////////////////
1769
1770     globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1771
1772
1773     ////////////////////////////////////////////////////////////////////
1774     // Initialize the local time subsystem.
1775     ////////////////////////////////////////////////////////////////////
1776
1777     // update the current timezone each 30 minutes
1778     globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1779                                        &fgUpdateLocalTime, 30*60 );
1780     fgInitTimeOffset();         // the environment subsystem needs this
1781
1782
1783     ////////////////////////////////////////////////////////////////////
1784     // Initialize the lighting subsystem.
1785     ////////////////////////////////////////////////////////////////////
1786
1787     globals->add_subsystem("lighting", new FGLight);
1788
1789     //////////////////////////////////////////////////////////////////////
1790     // Initialize the 2D cloud subsystem.
1791     ////////////////////////////////////////////////////////////////////
1792     fgGetBool("/sim/rendering/bump-mapping", false);
1793
1794 #ifdef ENABLE_AUDIO_SUPPORT
1795     ////////////////////////////////////////////////////////////////////
1796     // Initialize the sound subsystem.
1797     ////////////////////////////////////////////////////////////////////
1798
1799     init_volume = fgGetFloat("/sim/sound/volume");
1800     fgSetFloat("/sim/sound/volume", 0.0f);
1801     globals->set_soundmgr(new SGSoundMgr);
1802     globals->get_soundmgr()->init();
1803     globals->get_soundmgr()->bind();
1804
1805
1806     ////////////////////////////////////////////////////////////////////
1807     // Initialize the sound-effects subsystem.
1808     ////////////////////////////////////////////////////////////////////
1809
1810     globals->add_subsystem("fx", new FGFX);
1811     globals->add_subsystem("voice", new FGVoiceMgr);
1812 #endif
1813
1814     ////////////////////////////////////////////////////////////////////
1815     // Initialise the ATC Manager 
1816     ////////////////////////////////////////////////////////////////////
1817
1818     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Manager");
1819     globals->set_ATC_mgr(new FGATCMgr);
1820     globals->get_ATC_mgr()->init(); 
1821     
1822     ////////////////////////////////////////////////////////////////////
1823     // Initialise the AI Manager 
1824     ////////////////////////////////////////////////////////////////////
1825
1826     SG_LOG(SG_GENERAL, SG_INFO, "  AI Manager");
1827     globals->set_AI_mgr(new FGAIMgr);
1828     globals->get_AI_mgr()->init();
1829
1830     ////////////////////////////////////////////////////////////////////
1831     // Initialise the AI Model Manager
1832     ////////////////////////////////////////////////////////////////////
1833     SG_LOG(SG_GENERAL, SG_INFO, "  AI Model Manager");
1834     globals->add_subsystem("ai_model", new FGAIManager);
1835     globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1836
1837
1838     // It's probably a good idea to initialize the top level traffic manager
1839     // After the AI and ATC systems have been initialized properly.
1840     // AI Traffic manager
1841     globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1842
1843
1844     ////////////////////////////////////////////////////////////////////
1845     // Initialize the cockpit subsystem
1846     ////////////////////////////////////////////////////////////////////
1847     if( fgCockpitInit( &current_aircraft )) {
1848         // Cockpit initialized ok.
1849     } else {
1850         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1851         exit(-1);
1852     }
1853
1854
1855     ////////////////////////////////////////////////////////////////////
1856     // Initialize I/O subsystem.
1857     ////////////////////////////////////////////////////////////////////
1858
1859     globals->get_io()->init();
1860     globals->get_io()->bind();
1861
1862
1863     ////////////////////////////////////////////////////////////////////
1864     // Add a new 2D panel.
1865     ////////////////////////////////////////////////////////////////////
1866
1867     string panel_path = fgGetString("/sim/panel/path",
1868                                     "Panels/Default/default.xml");
1869
1870     globals->set_current_panel( fgReadPanel(panel_path) );
1871     if (globals->get_current_panel() == 0) {
1872         SG_LOG( SG_INPUT, SG_ALERT,
1873                 "Error reading new panel from " << panel_path );
1874     } else {
1875         SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1876         globals->get_current_panel()->init();
1877         globals->get_current_panel()->bind();
1878     }
1879
1880
1881     ////////////////////////////////////////////////////////////////////
1882     // Initialize the controls subsystem.
1883     ////////////////////////////////////////////////////////////////////
1884
1885     globals->get_controls()->init();
1886     globals->get_controls()->bind();
1887
1888
1889     ////////////////////////////////////////////////////////////////////
1890     // Initialize the input subsystem.
1891     ////////////////////////////////////////////////////////////////////
1892
1893     globals->add_subsystem("input", new FGInput);
1894
1895
1896     ////////////////////////////////////////////////////////////////////
1897     // Initialize the replay subsystem
1898     ////////////////////////////////////////////////////////////////////
1899     globals->add_subsystem("replay", new FGReplay);
1900
1901     ////////////////////////////////////////////////////////////////////
1902     // Bind and initialize subsystems.
1903     ////////////////////////////////////////////////////////////////////
1904
1905     globals->get_subsystem_mgr()->bind();
1906     globals->get_subsystem_mgr()->init();
1907
1908     ////////////////////////////////////////////////////////////////////
1909     // Initialize multiplayer subsystem
1910     ////////////////////////////////////////////////////////////////////
1911
1912     globals->set_multiplayer_mgr(new FGMultiplayMgr);
1913     globals->get_multiplayer_mgr()->init();
1914
1915     ////////////////////////////////////////////////////////////////////////
1916     // Initialize the Nasal interpreter.
1917     // Do this last, so that the loaded scripts see initialized state
1918     ////////////////////////////////////////////////////////////////////////
1919     FGNasalSys* nasal = new FGNasalSys();
1920     globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1921     nasal->init();
1922
1923     // initialize methods that depend on other subsystems.
1924     globals->get_subsystem_mgr()->postinit();
1925
1926     ////////////////////////////////////////////////////////////////////////
1927     // End of subsystem initialization.
1928     ////////////////////////////////////////////////////////////////////
1929
1930     SG_LOG( SG_GENERAL, SG_INFO, endl);
1931
1932                                 // Save the initial state for future
1933                                 // reference.
1934     globals->saveInitialState();
1935     
1936     return true;
1937 }
1938
1939
1940 void fgReInitSubsystems()
1941 {
1942     // static const SGPropertyNode *longitude
1943     //     = fgGetNode("/sim/presets/longitude-deg");
1944     // static const SGPropertyNode *latitude
1945     //     = fgGetNode("/sim/presets/latitude-deg");
1946     static const SGPropertyNode *altitude
1947         = fgGetNode("/sim/presets/altitude-ft");
1948     static const SGPropertyNode *master_freeze
1949         = fgGetNode("/sim/freeze/master");
1950
1951     SG_LOG( SG_GENERAL, SG_INFO,
1952             "fgReInitSubsystems(): /position/altitude = "
1953             << altitude->getDoubleValue() );
1954
1955     bool freeze = master_freeze->getBoolValue();
1956     if ( !freeze ) {
1957         fgSetBool("/sim/freeze/master", true);
1958     }
1959     fgSetBool("/sim/crashed", false);
1960
1961     // Force reupdating the positions of the ai 3d models. They are used for
1962     // initializing ground level for the FDM.
1963     globals->get_subsystem("ai_model")->reinit();
1964
1965     // Initialize the FDM
1966     fgInitFDM();
1967     
1968     // allocates structures so must happen before any of the flight
1969     // model or control parameters are set
1970     fgAircraftInit();   // In the future this might not be the case.
1971
1972     // reload offsets from config defaults
1973     globals->get_viewmgr()->reinit();
1974
1975     fgInitView();
1976
1977     globals->get_controls()->reset_all();
1978
1979     fgUpdateLocalTime();
1980
1981     // re-init to proper time of day setting
1982     fgInitTimeOffset();
1983
1984     if ( !freeze ) {
1985         fgSetBool("/sim/freeze/master", false);
1986     }
1987     fgSetBool("/sim/sceneryloaded",false);
1988 }
1989
1990
1991 void reInit(void)  // from gui_local.cxx -- TODO merge with fgReInitSubsystems()
1992 {
1993     static SGPropertyNode_ptr master_freeze = fgGetNode("/sim/freeze/master", true);
1994
1995     bool freeze = master_freeze->getBoolValue();
1996     if (!freeze)
1997         master_freeze->setBoolValue(true);
1998
1999     fgSetBool("/sim/signals/reinit", true);
2000     cur_fdm_state->unbind();
2001
2002     // in case user has changed window size as
2003     // restoreInitialState() overwrites these
2004     int xsize = fgGetInt("/sim/startup/xsize");
2005     int ysize = fgGetInt("/sim/startup/ysize");
2006
2007     globals->restoreInitialState();
2008
2009     // update our position based on current presets
2010     fgInitPosition();
2011
2012     // We don't know how to resize the window, so keep the last values
2013     //  for xsize and ysize, and don't use the one set initially
2014     fgSetInt("/sim/startup/xsize", xsize);
2015     fgSetInt("/sim/startup/ysize", ysize);
2016
2017     SGTime *t = globals->get_time_params();
2018     delete t;
2019     t = fgInitTime();
2020     globals->set_time_params(t);
2021
2022     fgReInitSubsystems();
2023
2024     globals->get_tile_mgr()->update(fgGetDouble("/environment/visibility-m"));
2025     globals->get_renderer()->resize(xsize, ysize);
2026     fgSetBool("/sim/signals/reinit", false);
2027
2028     if (!freeze)
2029         master_freeze->setBoolValue(false);
2030 }
2031