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