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