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