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