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