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