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