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