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