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