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