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