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