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