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