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