]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
Durk Talsma:
[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  - curt@infoplane.com
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 #ifdef FG_USE_CLOUDS_3D
64 #  include <simgear/scene/sky/clouds3d/SkySceneLoader.hpp>
65 #  include <simgear/scene/sky/clouds3d/SkyUtil.hpp>
66 #  include <simgear/screen/texture.hxx>
67 #endif
68 #include <simgear/timing/sg_time.hxx>
69 #include <simgear/timing/lowleveltime.h>
70
71 #include <Aircraft/aircraft.hxx>
72 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
73 #include <Airports/runways.hxx>
74 #include <Airports/simple.hxx>
75 #include <ATC/ATCdisplay.hxx>
76 #include <ATC/ATCmgr.hxx>
77 #include <ATC/AIMgr.hxx>
78 #include <Autopilot/auto_gui.hxx>
79 #include <Autopilot/route_mgr.hxx>
80 #include <Autopilot/xmlauto.hxx>
81 #include <Cockpit/cockpit.hxx>
82 #include <Cockpit/radiostack.hxx>
83 #include <Cockpit/panel.hxx>
84 #include <Cockpit/panel_io.hxx>
85 #include <FDM/ADA.hxx>
86 #include <FDM/Balloon.h>
87 #include <FDM/ExternalNet/ExternalNet.hxx>
88 #include <FDM/ExternalPipe/ExternalPipe.hxx>
89 #include <FDM/JSBSim/JSBSim.hxx>
90 #include <FDM/LaRCsim/LaRCsim.hxx>
91 #include <FDM/MagicCarpet.hxx>
92 #include <FDM/UFO.hxx>
93 #include <FDM/NullFDM.hxx>
94 #include <FDM/YASim/YASim.hxx>
95 #include <GUI/new_gui.hxx>
96 #include <Include/general.hxx>
97 #include <Input/input.hxx>
98 #include <Instrumentation/instrument_mgr.hxx>
99 #include <Model/acmodel.hxx>
100 #include <AIModel/AIManager.hxx>
101 #include <Navaids/fixlist.hxx>
102 #include <Navaids/ilslist.hxx>
103 #include <Navaids/mkrbeacons.hxx>
104 #include <Navaids/navlist.hxx>
105 #include <Replay/replay.hxx>
106 #include <Scenery/scenery.hxx>
107 #include <Scenery/tilemgr.hxx>
108 #include <Scripting/NasalSys.hxx>
109 #include <Sound/fg_fx.hxx>
110 #include <Systems/system_mgr.hxx>
111 #include <Time/light.hxx>
112 #include <Time/moonpos.hxx>
113 #include <Time/sunpos.hxx>
114 #include <Time/sunsolver.hxx>
115 #include <Time/tmp.hxx>
116
117 #ifdef FG_MPLAYER_AS
118 #include <MultiPlayer/multiplaytxmgr.hxx>
119 #include <MultiPlayer/multiplayrxmgr.hxx>
120 #endif
121
122 #include <Environment/environment_mgr.hxx>
123
124 #include "fg_init.hxx"
125 #include "fg_io.hxx"
126 #include "fg_commands.hxx"
127 #include "fg_props.hxx"
128 #include "options.hxx"
129 #include "globals.hxx"
130 #include "logger.hxx"
131 #include "viewmgr.hxx"
132
133 #if defined(FX) && defined(XMESA)
134 #include <GL/xmesa.h>
135 #endif
136
137 SG_USING_STD(string);
138
139
140 class Sound;
141
142 extern const char *default_root;
143 extern string_list waypoints;
144
145 #ifdef FG_USE_CLOUDS_3D
146   SkySceneLoader *sgCloud3d;
147 #endif
148
149
150 // Scan the command line options for the specified option and return
151 // the value.
152 static string fgScanForOption( const string& option, int argc, char **argv ) {
153     int i = 1;
154
155     SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
156
157     int len = option.length();
158
159     while ( i < argc ) {
160         SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
161
162         string arg = argv[i];
163         if ( arg.find( option ) == 0 ) {
164             return arg.substr( len );
165         }
166
167         i++;
168     }
169
170     return "";
171 }
172
173
174 // Scan the user config files for the specified option and return
175 // the value.
176 static string fgScanForOption( const string& option, const string& path ) {
177     sg_gzifstream in( path );
178     if ( !in.is_open() ) {
179         return "";
180     }
181
182     SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
183
184     int len = option.length();
185
186     in >> skipcomment;
187 #ifndef __MWERKS__
188     while ( ! in.eof() ) {
189 #else
190     char c = '\0';
191     while ( in.get(c) && c != '\0' ) {
192         in.putback(c);
193 #endif
194         string line;
195
196 #if defined( macintosh )
197         getline( in, line, '\r' );
198 #else
199         getline( in, line, '\n' );
200 #endif
201
202         // catch extraneous (DOS) line ending character
203         if ( line[line.length() - 1] < 32 ) {
204             line = line.substr( 0, line.length()-1 );
205         }
206
207         if ( line.find( option ) == 0 ) {
208             return line.substr( len );
209         }
210
211         in >> skipcomment;
212     }
213
214     return "";
215 }
216
217
218 // Read in configuration (files and command line options) but only set
219 // fg_root
220 bool fgInitFGRoot ( int argc, char **argv ) {
221     string root;
222     char* envp;
223
224     // First parse command line options looking for --fg-root=, this
225     // will override anything specified in a config file
226     root = fgScanForOption( "--fg-root=", argc, argv);
227
228 #if defined( unix ) || defined( __CYGWIN__ )
229     // Next check home directory for .fgfsrc.hostname file
230     if ( root.empty() ) {
231         envp = ::getenv( "HOME" );
232         if ( envp != NULL ) {
233             SGPath config( envp );
234             config.append( ".fgfsrc" );
235             char name[256];
236             gethostname( name, 256 );
237             config.concat( "." );
238             config.concat( name );
239             root = fgScanForOption( "--fg-root=", config.str() );
240         }
241     }
242 #endif
243
244     // Next check home directory for .fgfsrc file
245     if ( root.empty() ) {
246         envp = ::getenv( "HOME" );
247         if ( envp != NULL ) {
248             SGPath config( envp );
249             config.append( ".fgfsrc" );
250             root = fgScanForOption( "--fg-root=", config.str() );
251         }
252     }
253     
254     // Next check if fg-root is set as an env variable
255     if ( root.empty() ) {
256         envp = ::getenv( "FG_ROOT" );
257         if ( envp != NULL ) {
258             root = envp;
259         }
260     }
261
262     // Otherwise, default to a random compiled-in location if we can't
263     // find fg-root any other way.
264     if ( root.empty() ) {
265 #if defined( __CYGWIN__ )
266         root = "/FlightGear";
267 #elif defined( WIN32 )
268         root = "\\FlightGear";
269 #elif defined(OSX_BUNDLE) 
270         /* the following code looks for the base package directly inside
271             the application bundle. This can be changed fairly easily by
272             fiddling with the code below. And yes, I know it's ugly and verbose.
273         */
274         CFBundleRef appBundle = CFBundleGetMainBundle();
275         CFURLRef appUrl = CFBundleCopyBundleURL(appBundle);
276         CFRelease(appBundle);
277
278         // look for a 'data' subdir directly inside the bundle : is there
279         // a better place? maybe in Resources? I don't know ...
280         CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, appUrl, CFSTR("data"), true);
281
282         // now convert down to a path, and the a c-string
283         CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
284         root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
285
286         // tidy up.
287         CFRelease(appBundle);
288         CFRelease(dataDir);
289         CFRelease(path);
290 #else
291         root = PKGLIBDIR;
292 #endif
293     }
294
295     SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
296     globals->set_fg_root(root);
297
298     return true;
299 }
300
301
302 // Read in configuration (files and command line options) but only set
303 // aircraft
304 bool fgInitFGAircraft ( int argc, char **argv ) {
305     string aircraft;
306     char* envp;
307
308     // First parse command line options looking for --aircraft=, this
309     // will override anything specified in a config file
310     aircraft = fgScanForOption( "--aircraft=", argc, argv );
311
312 #if defined( unix ) || defined( __CYGWIN__ )
313     // Next check home directory for .fgfsrc.hostname file
314     if ( aircraft.empty() ) {
315         envp = ::getenv( "HOME" );
316         if ( envp != NULL ) {
317             SGPath config( envp );
318             config.append( ".fgfsrc" );
319             char name[256];
320             gethostname( name, 256 );
321             config.concat( "." );
322             config.concat( name );
323             aircraft = fgScanForOption( "--aircraft=", config.str() );
324         }
325     }
326 #endif
327
328     // Next check home directory for .fgfsrc file
329     if ( aircraft.empty() ) {
330         envp = ::getenv( "HOME" );
331         if ( envp != NULL ) {
332             SGPath config( envp );
333             config.append( ".fgfsrc" );
334             aircraft = fgScanForOption( "--aircraft=", config.str() );
335         }
336     }
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." << 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     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.id.empty() ) {
629             SG_LOG( SG_GENERAL, SG_ALERT,
630                     "Failed to find " << id << " in basic.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->longitude << ", "
642             << a->latitude << ")" );
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.elevation;
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.longitude + fudge_lon);
711         fgSetDouble("/sim/tower/latitude-deg",  a.latitude + fudge_lat);
712         fgSetDouble("/sim/tower/altitude-ft", a.elevation + towerheight);
713         return true;
714     } else {
715         return false;
716     }
717
718 }
719
720
721 // Set current_options lon/lat given an airport id and heading (degrees)
722 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
723     FGRunway r;
724
725     if ( id.length() ) {
726         // set initial position from runway and heading
727
728         SG_LOG( SG_GENERAL, SG_INFO,
729                 "Attempting to set starting position from airport code "
730                 << id << " heading " << tgt_hdg );
731                 
732         if ( ! globals->get_runways()->search( id, (int)tgt_hdg, &r ) ) {
733             SG_LOG( SG_GENERAL, SG_ALERT,
734                     "Failed to find a good runway for " << id << '\n' );
735             return false;
736         }       
737     } else {
738         return false;
739     }
740
741     double lat2, lon2, az2;
742     double heading = r.heading;
743     double azimuth = heading + 180.0;
744     while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
745
746     SG_LOG( SG_GENERAL, SG_INFO,
747             "runway =  " << r.lon << ", " << r.lat
748             << " length = " << r.length * SG_FEET_TO_METER 
749             << " heading = " << azimuth );
750             
751     geo_direct_wgs_84 ( 0, r.lat, r.lon, azimuth, 
752                         r.length * SG_FEET_TO_METER * 0.5 - 5.0,
753                         &lat2, &lon2, &az2 );
754
755     if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON ) {
756         double olat, olon;
757         double odist = fgGetDouble("/sim/presets/offset-distance");
758         odist *= SG_NM_TO_METER;
759         double oaz = azimuth;
760         if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON ) {
761             oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
762             heading = tgt_hdg;
763         }
764         while ( oaz >= 360.0 ) { oaz -= 360.0; }
765         geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
766         lat2=olat;
767         lon2=olon;
768     }
769
770     // presets
771     fgSetDouble("/sim/presets/longitude-deg",  lon2 );
772     fgSetDouble("/sim/presets/latitude-deg",  lat2 );
773     fgSetDouble("/sim/presets/heading-deg", heading );
774
775     // other code depends on the actual values being set ...
776     fgSetDouble("/position/longitude-deg",  lon2 );
777     fgSetDouble("/position/latitude-deg",  lat2 );
778     fgSetDouble("/orientation/heading-deg", heading );
779
780     SG_LOG( SG_GENERAL, SG_INFO,
781             "Position for " << id << " is ("
782             << lon2 << ", "
783             << lat2 << ") new heading is "
784             << heading );
785             
786     return true;
787 }
788
789
790 // Set current_options lon/lat given an airport id and runway number
791 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy ) {
792     FGRunway r;
793
794     if ( id.length() ) {
795         // set initial position from airport and runway number
796
797         SG_LOG( SG_GENERAL, SG_INFO,
798                 "Attempting to set starting position for "
799                 << id << ":" << rwy );
800
801         if ( ! globals->get_runways()->search( id, rwy, &r ) ) {
802             SG_LOG( SG_GENERAL, SG_ALERT,
803                     "Failed to find runway " << rwy << 
804                     " at airport " << id );
805             return false;
806         }
807     } else {
808         return false;
809     }
810
811     double lat2, lon2, az2;
812     double heading = r.heading;
813     double azimuth = heading + 180.0;
814     while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
815     
816     SG_LOG( SG_GENERAL, SG_INFO,
817     "runway =  " << r.lon << ", " << r.lat
818     << " length = " << r.length * SG_FEET_TO_METER 
819     << " heading = " << azimuth );
820     
821     geo_direct_wgs_84 ( 0, r.lat, r.lon, 
822     azimuth,
823     r.length * SG_FEET_TO_METER * 0.5 - 5.0,
824     &lat2, &lon2, &az2 );
825     
826     if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
827     {
828         double olat, olon;
829         double odist = fgGetDouble("/sim/presets/offset-distance");
830         odist *= SG_NM_TO_METER;
831         double oaz = azimuth;
832         if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON )
833         {
834             oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
835             heading = fgGetDouble("/sim/presets/heading-deg");
836         }
837         while ( oaz >= 360.0 ) { oaz -= 360.0; }
838         geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
839         lat2=olat;
840         lon2=olon;
841     }
842     
843     // presets
844     fgSetDouble("/sim/presets/longitude-deg",  lon2 );
845     fgSetDouble("/sim/presets/latitude-deg",  lat2 );
846     fgSetDouble("/sim/presets/heading-deg", heading );
847     
848     // other code depends on the actual values being set ...
849     fgSetDouble("/position/longitude-deg",  lon2 );
850     fgSetDouble("/position/latitude-deg",  lat2 );
851     fgSetDouble("/orientation/heading-deg", heading );
852     
853     SG_LOG( SG_GENERAL, SG_INFO,
854     "Position for " << id << " is ("
855     << lon2 << ", "
856     << lat2 << ") new heading is "
857     << heading );
858     
859     return true;
860 }
861
862
863 static void fgSetDistOrAltFromGlideSlope() {
864     // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
865     string apt_id = fgGetString("/sim/presets/airport-id");
866     double gs = fgGetDouble("/sim/presets/glideslope-deg")
867         * SG_DEGREES_TO_RADIANS ;
868     double od = fgGetDouble("/sim/presets/offset-distance");
869     double alt = fgGetDouble("/sim/presets/altitude-ft");
870
871     double apt_elev = 0.0;
872     if ( ! apt_id.empty() ) {
873         apt_elev = fgGetAirportElev( apt_id );
874         if ( apt_elev < -9990.0 ) {
875             apt_elev = 0.0;
876         }
877     } else {
878         apt_elev = 0.0;
879     }
880
881     if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
882         // set altitude from glideslope and offset-distance
883         od *= SG_NM_TO_METER * SG_METER_TO_FEET;
884         alt = fabs(od*tan(gs)) + apt_elev;
885         fgSetDouble("/sim/presets/altitude-ft", alt);
886         fgSetBool("/sim/presets/onground", false);
887         SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
888                 << alt  << " ft" );
889     } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
890         // set offset-distance from glideslope and altitude
891         od  = (alt - apt_elev) / tan(gs);
892         od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
893         fgSetDouble("/sim/presets/offset-distance", od);
894         fgSetBool("/sim/presets/onground", false);
895         SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: " 
896                 << od  << " nm" );
897     } else if( fabs(gs) > 0.01 ) {
898         SG_LOG( SG_GENERAL, SG_ALERT,
899                 "Glideslope given but not altitude or offset-distance." );
900         SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
901         fgSetDouble("/sim/presets/glideslope-deg", 0);
902         fgSetBool("/sim/presets/onground", true);
903     }                              
904 }
905
906
907 // Set current_options lon/lat given an airport id and heading (degrees)
908 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
909     FGNav *nav = current_navlist->findByIdentAndFreq( id.c_str(), freq );
910
911     // set initial position from runway and heading
912     if ( nav != NULL ) {
913         SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
914                 << id << ":" << freq );
915
916         double lon = nav->get_lon();
917         double lat = nav->get_lat();
918
919         if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
920         {
921             double odist = fgGetDouble("/sim/presets/offset-distance")
922                 * SG_NM_TO_METER;
923             double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
924                 + 180.0;
925             while ( oaz >= 360.0 ) { oaz -= 360.0; }
926             double olat, olon, az2;
927             geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
928
929             lat = olat;
930             lon = olon;
931         }
932
933         // presets
934         fgSetDouble("/sim/presets/longitude-deg",  lon );
935         fgSetDouble("/sim/presets/latitude-deg",  lat );
936
937         // other code depends on the actual values being set ...
938         fgSetDouble("/position/longitude-deg",  lon );
939         fgSetDouble("/position/latitude-deg",  lat );
940         fgSetDouble("/orientation/heading-deg", 
941                     fgGetDouble("/sim/presets/heading-deg") );
942
943         SG_LOG( SG_GENERAL, SG_INFO,
944                 "Position for " << id << ":" << freq << " is ("
945                 << lon << ", "<< lat << ")" );
946
947         return true;
948     } else {
949         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
950                 << id << ":" << freq );
951         return false;
952     }
953 }
954
955
956 // Set current_options lon/lat given an airport id and heading (degrees)
957 static bool fgSetPosFromFix( const string& id ) {
958     FGFix fix;
959
960     // set initial position from runway and heading
961     if ( current_fixlist->query( id.c_str(), &fix ) ) {
962         SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
963                 << id );
964
965         double lon = fix.get_lon();
966         double lat = fix.get_lat();
967
968         if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
969         {
970             double odist = fgGetDouble("/sim/presets/offset-distance")
971                 * SG_NM_TO_METER;
972             double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
973                 + 180.0;
974             while ( oaz >= 360.0 ) { oaz -= 360.0; }
975             double olat, olon, az2;
976             geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
977
978             lat = olat;
979             lon = olon;
980         }
981
982         // presets
983         fgSetDouble("/sim/presets/longitude-deg",  lon );
984         fgSetDouble("/sim/presets/latitude-deg",  lat );
985
986         // other code depends on the actual values being set ...
987         fgSetDouble("/position/longitude-deg",  lon );
988         fgSetDouble("/position/latitude-deg",  lat );
989         fgSetDouble("/orientation/heading-deg", 
990                     fgGetDouble("/sim/presets/heading-deg") );
991
992         SG_LOG( SG_GENERAL, SG_INFO,
993                 "Position for " << id << " is ("
994                 << lon << ", "<< lat << ")" );
995
996         return true;
997     } else {
998         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
999                 << id );
1000         return false;
1001     }
1002 }
1003  
1004 static bool parseWaypoints()
1005   {
1006     vector<string>::iterator i;
1007     for (i = waypoints.begin(); 
1008          i  != waypoints.end();
1009          i++)
1010       {
1011         NewWaypoint(*i);
1012         // string arg = *i;
1013 //      string id, alt_str;
1014 //      double alt = 0.0;
1015         
1016 //      string::size_type pos = arg.find( "@" );
1017 //      if ( pos != string::npos ) {
1018 //        id = arg.substr( 0, pos );
1019 //        alt_str = arg.substr( pos + 1 );
1020 //        cout << "id str = " << id << "  alt str = " << alt_str << endl;
1021 //        alt = atof( alt_str.c_str() );
1022 //        if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
1023 //          alt *= SG_FEET_TO_METER;
1024 //        }
1025 //      } else {
1026 //        id = arg;
1027 //      }
1028         
1029 //      FGAirport a;
1030 //      if ( fgFindAirportID( id, &a ) ) {
1031 //        FGRouteMgr *rm = (FGRouteMgr *)globals->get_subsystem("route-manager");
1032 //        SGWayPoint wp( a.longitude, a.latitude, alt, SGWayPoint::WGS84, id );
1033 //        rm->add_waypoint( wp );
1034           
1035 //        //return true;
1036 //      } else {
1037 //        return false;
1038 //      }
1039 //       }
1040 //     //    waypoints.begin() = waypoints.erase(waypoints.begin());
1041 //     return true;
1042       }
1043    }
1044
1045  
1046  
1047
1048
1049 /**
1050  * Initialize vor/ndb/ils/fix list management and query systems (as
1051  * well as simple airport db list)
1052  */
1053 bool
1054 fgInitNav ()
1055 {
1056     SG_LOG(SG_GENERAL, SG_INFO, "Loading Simple Airport List");
1057     SGPath p_simple( globals->get_fg_root() );
1058     p_simple.append( "Airports/basic.dat" );
1059     SGPath p_metar( globals->get_fg_root() );
1060     p_metar.append( "Airports/metar.dat" );
1061     FGAirportList *airports = new FGAirportList(p_simple.str(), p_metar.str());
1062     globals->set_airports( airports );
1063
1064     SG_LOG(SG_GENERAL, SG_INFO, "Loading Runway List");
1065     SGPath p_runway( globals->get_fg_root() );
1066     p_runway.append( "Airports/runways.dat" );
1067     FGRunwayList *runways = new FGRunwayList( p_runway.str() );
1068     globals->set_runways( runways );
1069
1070     SG_LOG(SG_GENERAL, SG_INFO, "Loading Navaids");
1071
1072     SG_LOG(SG_GENERAL, SG_INFO, "  VOR/NDB");
1073     current_navlist = new FGNavList;
1074     SGPath p_nav( globals->get_fg_root() );
1075     p_nav.append( "Navaids/default.nav" );
1076     current_navlist->init( p_nav );
1077
1078     SG_LOG(SG_GENERAL, SG_INFO, "  ILS and Marker Beacons");
1079     current_beacons = new FGMarkerBeacons;
1080     current_beacons->init();
1081     current_ilslist = new FGILSList;
1082     SGPath p_ils( globals->get_fg_root() );
1083     p_ils.append( "Navaids/default.ils" );
1084     current_ilslist->init( p_ils );
1085
1086     SG_LOG(SG_GENERAL, SG_INFO, "  Fixes");
1087     current_fixlist = new FGFixList;
1088     SGPath p_fix( globals->get_fg_root() );
1089     p_fix.append( "Navaids/default.fix" );
1090     current_fixlist->init( p_fix );
1091
1092     return true;
1093 }
1094
1095
1096 // Set the initial position based on presets (or defaults)
1097 bool fgInitPosition() {
1098     // cout << "fgInitPosition()" << endl;
1099     double gs = fgGetDouble("/sim/presets/glideslope-deg")
1100         * SG_DEGREES_TO_RADIANS ;
1101     double od = fgGetDouble("/sim/presets/offset-distance");
1102     double alt = fgGetDouble("/sim/presets/altitude-ft");
1103
1104     bool set_pos = false;
1105
1106     // If glideslope is specified, then calculate offset-distance or
1107     // altitude relative to glide slope if either of those was not
1108     // specified.
1109     if ( fabs( gs ) > 0.01 ) {
1110         fgSetDistOrAltFromGlideSlope();
1111     }
1112
1113
1114     // If we have an explicit, in-range lon/lat, don't change it, just use it.
1115     // If not, check for an airport-id and use that.
1116     // If not, default to the middle of the KSFO field.
1117     // The default values for lon/lat are deliberately out of range
1118     // so that the airport-id can take effect; valid lon/lat will
1119     // override airport-id, however.
1120     double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1121     double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1122     if ( lon_deg >= -180.0 && lon_deg <= 180.0
1123          && lat_deg >= -90.0 && lat_deg <= 90.0 )
1124     {
1125         set_pos = true;
1126     }
1127
1128     string apt = fgGetString("/sim/presets/airport-id");
1129     string rwy_no = fgGetString("/sim/presets/runway");
1130     double hdg = fgGetDouble("/sim/presets/heading-deg");
1131     string vor = fgGetString("/sim/presets/vor-id");
1132     double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1133     string ndb = fgGetString("/sim/presets/ndb-id");
1134     double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1135     string fix = fgGetString("/sim/presets/fix");
1136
1137     if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1138         // An airport + runway is requested
1139         if ( fgSetPosFromAirportIDandRwy( apt, rwy_no ) ) {
1140             // set tower position (a little off the heading for single
1141             // runway airports)
1142             fgSetTowerPosFromAirportID( apt, hdg );
1143             set_pos = true;
1144         }
1145     }
1146
1147     if ( !set_pos && !apt.empty() ) {
1148         // An airport is requested (find runway closest to hdg)
1149         if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1150             // set tower position (a little off the heading for single
1151             // runway airports)
1152             fgSetTowerPosFromAirportID( apt, hdg );
1153             set_pos = true;
1154         }
1155     }
1156
1157     if ( !set_pos && !vor.empty() ) {
1158         // a VOR is requested
1159         if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1160             set_pos = true;
1161         }
1162     }
1163
1164     if ( !set_pos && !ndb.empty() ) {
1165         // an NDB is requested
1166         if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1167             set_pos = true;
1168         }
1169     }
1170
1171     if ( !set_pos && !fix.empty() ) {
1172         // a Fix is requested
1173         if ( fgSetPosFromFix( fix ) ) {
1174             set_pos = true;
1175         }
1176     }
1177
1178     if ( !set_pos ) {
1179         // No lon/lat specified, no airport specified, default to
1180         // middle of KSFO field.
1181         fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1182         fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1183     }
1184
1185     fgSetDouble( "/position/longitude-deg",
1186                  fgGetDouble("/sim/presets/longitude-deg") );
1187     fgSetDouble( "/position/latitude-deg",
1188                  fgGetDouble("/sim/presets/latitude-deg") );
1189     fgSetDouble( "/orientation/heading-deg",
1190                  fgGetDouble("/sim/presets/heading-deg") );
1191
1192     // determine if this should be an on-ground or in-air start
1193     if ( fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1 ) {
1194         fgSetBool("/sim/presets/onground", false);
1195     } else {
1196         fgSetBool("/sim/presets/onground", true);
1197     }                              
1198
1199     return true;
1200 }
1201
1202
1203 // General house keeping initializations
1204 bool fgInitGeneral() {
1205     string root;
1206
1207 #if defined(FX) && defined(XMESA)
1208     char *mesa_win_state;
1209 #endif
1210
1211     SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1212     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1213
1214     root = globals->get_fg_root();
1215     if ( ! root.length() ) {
1216         // No root path set? Then bail ...
1217         SG_LOG( SG_GENERAL, SG_ALERT,
1218                 "Cannot continue without a path to the base package "
1219                 << "being defined." );
1220         exit(-1);
1221     }
1222     SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1223
1224 #if defined(FX) && defined(XMESA)
1225     // initialize full screen flag
1226     globals->set_fullscreen(false);
1227     if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1228         // Test for the MESA_GLX_FX env variable
1229         if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
1230             // test if we are fullscreen mesa/glide
1231             if ( (mesa_win_state[0] == 'f') ||
1232                  (mesa_win_state[0] == 'F') ) {
1233                 globals->set_fullscreen(true);
1234             }
1235         }
1236     }
1237 #endif
1238
1239     return true;
1240 }
1241
1242
1243 // Initialize the flight model subsystem.  This just creates the
1244 // object.  The actual fdm initialization is delayed until we get a
1245 // proper scenery elevation hit.  This is checked for in main.cxx
1246
1247 void fgInitFDM() {
1248
1249     if ( cur_fdm_state ) {
1250         delete cur_fdm_state;
1251         cur_fdm_state = 0;
1252     }
1253
1254     double dt = 1.0 / fgGetInt("/sim/model-hz");
1255     aircraft_dir = fgGetString("/sim/aircraft-dir");
1256     const string &model = fgGetString("/sim/flight-model");
1257
1258     try {
1259         if ( model == "larcsim" ) {
1260             cur_fdm_state = new FGLaRCsim( dt );
1261         } else if ( model == "jsb" ) {
1262             cur_fdm_state = new FGJSBsim( dt );
1263         } else if ( model == "ada" ) {
1264             cur_fdm_state = new FGADA( dt );
1265         } else if ( model == "balloon" ) {
1266             cur_fdm_state = new FGBalloonSim( dt );
1267         } else if ( model == "magic" ) {
1268             cur_fdm_state = new FGMagicCarpet( dt );
1269         } else if ( model == "ufo" ) {
1270             cur_fdm_state = new FGUFO( dt );
1271         } else if ( model == "external" ) {
1272             // external is a synonym for "--fdm=null" and is
1273             // maintained here for backwards compatibility
1274             cur_fdm_state = new FGNullFDM( dt );
1275         } else if ( model.find("network") == 0 ) {
1276             string host = "localhost";
1277             int port1 = 5501;
1278             int port2 = 5502;
1279             int port3 = 5503;
1280             string net_options = model.substr(8);
1281             string::size_type begin, end;
1282             begin = 0;
1283             // host
1284             end = net_options.find( ",", begin );
1285             if ( end != string::npos ) {
1286                 host = net_options.substr(begin, end - begin);
1287                 begin = end + 1;
1288             }
1289             // port1
1290             end = net_options.find( ",", begin );
1291             if ( end != string::npos ) {
1292                 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1293                 begin = end + 1;
1294             }
1295             // port2
1296             end = net_options.find( ",", begin );
1297             if ( end != string::npos ) {
1298                 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1299                 begin = end + 1;
1300             }
1301             // port3
1302             end = net_options.find( ",", begin );
1303             if ( end != string::npos ) {
1304                 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1305                 begin = end + 1;
1306             }
1307             cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1308         } else if ( model.find("pipe") == 0 ) {
1309             string pipe_path = model.substr(5);
1310             cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1311         } else if ( model == "null" ) {
1312             cur_fdm_state = new FGNullFDM( dt );
1313         } else if ( model == "yasim" ) {
1314             cur_fdm_state = new YASim( dt );
1315         } else {
1316             SG_LOG(SG_GENERAL, SG_ALERT,
1317                    "Unrecognized flight model '" << model
1318                    << "', cannot init flight dynamics model.");
1319             exit(-1);
1320         }
1321     } catch ( ... ) {
1322         SG_LOG(SG_GENERAL, SG_ALERT, "FlightGear aborting\n\n");
1323         exit(-1);
1324     }
1325 }
1326
1327 static void printMat(const sgVec4 *mat, char *name="")
1328 {
1329     int i;
1330     SG_LOG(SG_GENERAL, SG_BULK, name );
1331     for(i=0; i<4; i++) {
1332         SG_LOG(SG_GENERAL, SG_BULK, "  " << mat[i][0] << " " << mat[i][1]
1333                                     << " " << mat[i][2] << " " << mat[i][3] );
1334     }
1335 }
1336
1337 // Initialize view parameters
1338 void fgInitView() {
1339   // force update of model so that viewer can get some data...
1340   globals->get_aircraft_model()->update(0);
1341   // run update for current view so that data is current...
1342   globals->get_viewmgr()->update(0);
1343
1344   printMat(globals->get_current_view()->get_VIEW(),"VIEW");
1345   printMat(globals->get_current_view()->get_UP(),"UP");
1346   // printMat(globals->get_current_view()->get_LOCAL(),"LOCAL");
1347   
1348 }
1349
1350
1351 SGTime *fgInitTime() {
1352     // Initialize time
1353     static const SGPropertyNode *longitude
1354         = fgGetNode("/position/longitude-deg");
1355     static const SGPropertyNode *latitude
1356         = fgGetNode("/position/latitude-deg");
1357     static const SGPropertyNode *cur_time_override
1358         = fgGetNode("/sim/time/cur-time-override", true);
1359
1360     SGPath zone( globals->get_fg_root() );
1361     zone.append( "Timezone" );
1362     SGTime *t = new SGTime( longitude->getDoubleValue()
1363                               * SGD_DEGREES_TO_RADIANS,
1364                             latitude->getDoubleValue()
1365                               * SGD_DEGREES_TO_RADIANS,
1366                             zone.str(),
1367                             cur_time_override->getLongValue() );
1368
1369     globals->set_warp_delta( 0 );
1370
1371     t->update( 0.0, 0.0,
1372                cur_time_override->getLongValue(),
1373                globals->get_warp() );
1374
1375     return t;
1376 }
1377
1378
1379 // set up a time offset (aka warp) if one is specified
1380 void fgInitTimeOffset() {
1381     static const SGPropertyNode *longitude
1382         = fgGetNode("/position/longitude-deg");
1383     static const SGPropertyNode *latitude
1384         = fgGetNode("/position/latitude-deg");
1385     static const SGPropertyNode *cur_time_override
1386         = fgGetNode("/sim/time/cur-time-override", true);
1387
1388     // Handle potential user specified time offsets
1389     int orig_warp = globals->get_warp();
1390     SGTime *t = globals->get_time_params();
1391     time_t cur_time = t->get_cur_time();
1392     time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1393     time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1394     time_t aircraftLocalTime = 
1395         sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1396
1397     // Okay, we now have several possible scenarios
1398     int offset = fgGetInt("/sim/startup/time-offset");
1399     const string &offset_type = fgGetString("/sim/startup/time-offset-type");
1400
1401     int warp = 0;
1402     if ( offset_type == "real" ) {
1403         warp = 0;
1404     } else if ( offset_type == "dawn" ) {
1405         warp = fgTimeSecondsUntilSunAngle( cur_time,
1406                                            longitude->getDoubleValue()
1407                                              * SGD_DEGREES_TO_RADIANS,
1408                                            latitude->getDoubleValue()
1409                                              * SGD_DEGREES_TO_RADIANS,
1410                                            90.0, true ); 
1411     } else if ( offset_type == "morning" ) {
1412         warp = fgTimeSecondsUntilSunAngle( cur_time,
1413                                            longitude->getDoubleValue()
1414                                              * SGD_DEGREES_TO_RADIANS,
1415                                            latitude->getDoubleValue()
1416                                              * SGD_DEGREES_TO_RADIANS,
1417                                            75.0, true ); 
1418     } else if ( offset_type == "noon" ) {
1419         warp = fgTimeSecondsUntilSunAngle( cur_time,
1420                                            longitude->getDoubleValue()
1421                                              * SGD_DEGREES_TO_RADIANS,
1422                                            latitude->getDoubleValue()
1423                                              * SGD_DEGREES_TO_RADIANS,
1424                                            0.0, true ); 
1425     } else if ( offset_type == "afternoon" ) {
1426         warp = fgTimeSecondsUntilSunAngle( cur_time,
1427                                            longitude->getDoubleValue()
1428                                              * SGD_DEGREES_TO_RADIANS,
1429                                            latitude->getDoubleValue()
1430                                              * SGD_DEGREES_TO_RADIANS,
1431                                            60.0, false ); 
1432      } else if ( offset_type == "dusk" ) {
1433         warp = fgTimeSecondsUntilSunAngle( cur_time,
1434                                            longitude->getDoubleValue()
1435                                              * SGD_DEGREES_TO_RADIANS,
1436                                            latitude->getDoubleValue()
1437                                              * SGD_DEGREES_TO_RADIANS,
1438                                            90.0, false ); 
1439      } else if ( offset_type == "evening" ) {
1440         warp = fgTimeSecondsUntilSunAngle( cur_time,
1441                                            longitude->getDoubleValue()
1442                                              * SGD_DEGREES_TO_RADIANS,
1443                                            latitude->getDoubleValue()
1444                                              * SGD_DEGREES_TO_RADIANS,
1445                                            100.0, false ); 
1446     } else if ( offset_type == "midnight" ) {
1447         warp = fgTimeSecondsUntilSunAngle( cur_time,
1448                                            longitude->getDoubleValue()
1449                                              * SGD_DEGREES_TO_RADIANS,
1450                                            latitude->getDoubleValue()
1451                                              * SGD_DEGREES_TO_RADIANS,
1452                                            180.0, false ); 
1453     } else if ( offset_type == "system-offset" ) {
1454         warp = offset;
1455     } else if ( offset_type == "gmt-offset" ) {
1456         warp = offset - (currGMT - systemLocalTime);
1457     } else if ( offset_type == "latitude-offset" ) {
1458         warp = offset - (aircraftLocalTime - systemLocalTime);
1459     } else if ( offset_type == "system" ) {
1460         warp = offset - cur_time;
1461     } else if ( offset_type == "gmt" ) {
1462         warp = offset - currGMT;
1463     } else if ( offset_type == "latitude" ) {
1464         warp = offset - (aircraftLocalTime - systemLocalTime) - cur_time; 
1465     } else {
1466         SG_LOG( SG_GENERAL, SG_ALERT,
1467                 "FG_TIME::Unsupported offset type " << offset_type );
1468         exit( -1 );
1469     }
1470     globals->set_warp( orig_warp + warp );
1471     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1472                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1473                cur_time_override->getLongValue(),
1474                globals->get_warp() );
1475
1476     SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = " 
1477             << globals->get_warp() );
1478 }
1479
1480 // This is the top level init routine which calls all the other
1481 // initialization routines.  If you are adding a subsystem to flight
1482 // gear, its initialization call should located in this routine.
1483 // Returns non-zero if a problem encountered.
1484 bool fgInitSubsystems() {
1485     // static const SGPropertyNode *longitude
1486     //     = fgGetNode("/sim/presets/longitude-deg");
1487     // static const SGPropertyNode *latitude
1488     //     = fgGetNode("/sim/presets/latitude-deg");
1489     // static const SGPropertyNode *altitude
1490     //     = fgGetNode("/sim/presets/altitude-ft");
1491
1492     SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1493     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1494
1495     ////////////////////////////////////////////////////////////////////
1496     // Initialize the event manager subsystem.
1497     ////////////////////////////////////////////////////////////////////
1498
1499      globals->get_event_mgr()->init();
1500      globals->get_event_mgr()->setFreezeProperty(fgGetNode("/sim/freeze/clock"));
1501
1502     ////////////////////////////////////////////////////////////////////
1503     // Initialize the property interpolator subsystem
1504     ////////////////////////////////////////////////////////////////////
1505     globals->add_subsystem("interpolator", new SGInterpolator);
1506
1507
1508     ////////////////////////////////////////////////////////////////////
1509     // Add the FlightGear property utilities.
1510     ////////////////////////////////////////////////////////////////////
1511     globals->add_subsystem("properties", new FGProperties);
1512
1513     ////////////////////////////////////////////////////////////////////
1514     // Initialize the material property subsystem.
1515     ////////////////////////////////////////////////////////////////////
1516
1517     SGPath mpath( globals->get_fg_root() );
1518     mpath.append( "materials.xml" );
1519     if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str()) ) {
1520         SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1521         exit(-1);
1522     }
1523
1524
1525     ////////////////////////////////////////////////////////////////////
1526     // Initialize the scenery management subsystem.
1527     ////////////////////////////////////////////////////////////////////
1528
1529     if ( globals->get_tile_mgr()->init() ) {
1530         // Load the local scenery data
1531         double visibility_meters = fgGetDouble("/environment/visibility-m");
1532                 
1533         globals->get_tile_mgr()->update( visibility_meters );
1534     } else {
1535         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1536         exit(-1);
1537     }
1538
1539     // cause refresh of viewer scenery timestamps every 15 seconds...
1540     globals->get_event_mgr()->addTask( "FGTileMgr::refresh_view_timestamps()",
1541                                        globals->get_tile_mgr(),
1542                                        &FGTileMgr::refresh_view_timestamps,
1543                                        15 );
1544
1545     SG_LOG( SG_GENERAL, SG_DEBUG,
1546             "Current terrain elevation after tile mgr init " <<
1547             globals->get_scenery()->get_cur_elev() );
1548
1549
1550     ////////////////////////////////////////////////////////////////////
1551     // Initialize the flight model subsystem.
1552     ////////////////////////////////////////////////////////////////////
1553
1554     fgInitFDM();
1555         
1556     // allocates structures so must happen before any of the flight
1557     // model or control parameters are set
1558     fgAircraftInit();   // In the future this might not be the case.
1559
1560
1561     ////////////////////////////////////////////////////////////////////
1562     // Initialize the XML Autopilot subsystem.
1563     ////////////////////////////////////////////////////////////////////
1564
1565     globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1566     globals->add_subsystem( "route-manager", new FGRouteMgr );
1567
1568   
1569     ////////////////////////////////////////////////////////////////////
1570     // Initialize the view manager subsystem.
1571     ////////////////////////////////////////////////////////////////////
1572
1573     fgInitView();
1574
1575     ////////////////////////////////////////////////////////////////////
1576     // Create and register the logger.
1577     ////////////////////////////////////////////////////////////////////
1578     
1579     globals->add_subsystem("logger", new FGLogger);
1580
1581     ////////////////////////////////////////////////////////////////////
1582     // Create and register the XML GUI.
1583     ////////////////////////////////////////////////////////////////////
1584
1585     globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1586
1587
1588     ////////////////////////////////////////////////////////////////////
1589     // Initialize the local time subsystem.
1590     ////////////////////////////////////////////////////////////////////
1591
1592     // update the current timezone each 30 minutes
1593     globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1594                                        &fgUpdateLocalTime, 30*60 );
1595
1596
1597     ////////////////////////////////////////////////////////////////////
1598     // Initialize the weather subsystem.
1599     ////////////////////////////////////////////////////////////////////
1600
1601     // Initialize the weather modeling subsystem
1602     globals->add_subsystem("environment", new FGEnvironmentMgr);
1603
1604
1605     ////////////////////////////////////////////////////////////////////
1606     // Initialize the lighting subsystem.
1607     ////////////////////////////////////////////////////////////////////
1608
1609     globals->add_subsystem("lighting", new FGLight);
1610
1611
1612 #ifdef FG_USE_CLOUDS_3D
1613     ////////////////////////////////////////////////////////////////////
1614     // Initialize the 3D cloud subsystem.
1615     ////////////////////////////////////////////////////////////////////
1616     if ( fgGetBool("/sim/rendering/clouds3d") ) {
1617         static const SGPropertyNode *longitude
1618            = fgGetNode("/sim/presets/longitude-deg");
1619         static const SGPropertyNode *latitude
1620            = fgGetNode("/sim/presets/latitude-deg");
1621         // static const SGPropertyNode *altitude
1622         //    = fgGetNode("/sim/presets/altitude-ft");
1623
1624         SGPath cloud_path(globals->get_fg_root());
1625 #if 0
1626         cloud_path.append("Textures/Sky/scattered.rgba");
1627         SG_LOG(SG_GENERAL, SG_INFO, "Loading CLOUDS3d from: " << cloud_path.c_str());
1628
1629         SGTexture tx;
1630         tx.read_rgba_texture(cloud_path.c_str());
1631         if ( !sgCloud3d->Load( tx.texture(), tx.width(),
1632 #else
1633         cloud_path.append("large.sky");
1634         if ( !sgCloud3d->Load( cloud_path.str(),
1635 #endif
1636                                latitude->getDoubleValue(),
1637                                longitude->getDoubleValue()) )
1638         {
1639             fgSetBool("/sim/rendering/clouds3d", false);
1640             SG_LOG(SG_GENERAL, SG_INFO, "CLOUDS3d FAILED: ");
1641         }
1642         SG_LOG(SG_GENERAL, SG_INFO, "CLOUDS3d Loaded: ");
1643     }
1644 #endif
1645
1646     ////////////////////////////////////////////////////////////////////
1647     // Initialise ATC display system
1648     ////////////////////////////////////////////////////////////////////
1649
1650     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Display");
1651     globals->set_ATC_display(new FGATCDisplay);
1652     globals->get_ATC_display()->init(); 
1653
1654     ////////////////////////////////////////////////////////////////////
1655     // Initialise the ATC Manager 
1656     ////////////////////////////////////////////////////////////////////
1657
1658     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Manager");
1659     globals->set_ATC_mgr(new FGATCMgr);
1660     globals->get_ATC_mgr()->init(); 
1661     
1662     ////////////////////////////////////////////////////////////////////
1663     // Initialise the AI Manager 
1664     ////////////////////////////////////////////////////////////////////
1665
1666     SG_LOG(SG_GENERAL, SG_INFO, "  AI Manager");
1667     globals->set_AI_mgr(new FGAIMgr);
1668     globals->get_AI_mgr()->init();
1669
1670
1671     ////////////////////////////////////////////////////////////////////
1672     // Initialise the AI Model Manager
1673     ////////////////////////////////////////////////////////////////////
1674
1675     SG_LOG(SG_GENERAL, SG_INFO, "  AI Model Manager");
1676     globals->add_subsystem("ai_model", new FGAIManager);
1677
1678
1679 #ifdef ENABLE_AUDIO_SUPPORT
1680     ////////////////////////////////////////////////////////////////////
1681     // Initialize the sound subsystem.
1682     ////////////////////////////////////////////////////////////////////
1683
1684     globals->set_soundmgr(new SGSoundMgr);
1685     globals->get_soundmgr()->init();
1686     globals->get_soundmgr()->bind();
1687
1688
1689     ////////////////////////////////////////////////////////////////////
1690     // Initialize the sound-effects subsystem.
1691     ////////////////////////////////////////////////////////////////////
1692
1693     globals->add_subsystem("fx", new FGFX);
1694     
1695 #endif
1696
1697     globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1698     globals->add_subsystem("systems", new FGSystemMgr);
1699
1700     ////////////////////////////////////////////////////////////////////
1701     // Initialize the radio stack subsystem.
1702     ////////////////////////////////////////////////////////////////////
1703
1704     current_radiostack = new FGRadioStack;
1705     current_radiostack->init();
1706     current_radiostack->bind();
1707
1708
1709     ////////////////////////////////////////////////////////////////////
1710     // Initialize the cockpit subsystem
1711     ////////////////////////////////////////////////////////////////////
1712
1713     if( fgCockpitInit( &current_aircraft )) {
1714         // Cockpit initialized ok.
1715     } else {
1716         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1717         exit(-1);
1718     }
1719
1720
1721     ////////////////////////////////////////////////////////////////////
1722     // Initialize the autopilot subsystem.
1723     ////////////////////////////////////////////////////////////////////
1724
1725                                 // FIXME: these should go in the
1726                                 // GUI initialization code, not here.
1727     // fgAPAdjustInit();
1728     NewTgtAirportInit();
1729     NewHeadingInit();
1730     NewAltitudeInit();
1731
1732     ////////////////////////////////////////////////////////////////////
1733     // Initialize I/O subsystem.
1734     ////////////////////////////////////////////////////////////////////
1735
1736     globals->get_io()->init();
1737     globals->get_io()->bind();
1738
1739
1740     ////////////////////////////////////////////////////////////////////
1741     // Add a new 2D panel.
1742     ////////////////////////////////////////////////////////////////////
1743
1744     string panel_path = fgGetString("/sim/panel/path",
1745                                     "Panels/Default/default.xml");
1746
1747     globals->set_current_panel( fgReadPanel(panel_path) );
1748     if (globals->get_current_panel() == 0) {
1749         SG_LOG( SG_INPUT, SG_ALERT, 
1750                 "Error reading new panel from " << panel_path );
1751     } else {
1752         SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1753         globals->get_current_panel()->init();
1754         globals->get_current_panel()->bind();
1755     }
1756
1757     
1758     ////////////////////////////////////////////////////////////////////
1759     // Initialize the controls subsystem.
1760     ////////////////////////////////////////////////////////////////////
1761
1762     globals->get_controls()->init();
1763     globals->get_controls()->bind();
1764
1765
1766     ////////////////////////////////////////////////////////////////////
1767     // Initialize the input subsystem.
1768     ////////////////////////////////////////////////////////////////////
1769
1770     globals->add_subsystem("input", new FGInput);
1771
1772
1773     ////////////////////////////////////////////////////////////////////
1774     // Initialize the replay subsystem
1775     ////////////////////////////////////////////////////////////////////
1776     globals->add_subsystem("replay", new FGReplay);
1777
1778     ////////////////////////////////////////////////////////////////////
1779     // Bind and initialize subsystems.
1780     ////////////////////////////////////////////////////////////////////
1781
1782     globals->get_subsystem_mgr()->bind();
1783     globals->get_subsystem_mgr()->init();
1784
1785 #ifdef FG_MPLAYER_AS
1786     ////////////////////////////////////////////////////////////////////
1787     // Initialize multiplayer subsystem
1788     ////////////////////////////////////////////////////////////////////
1789
1790     globals->set_multiplayer_tx_mgr(new FGMultiplayTxMgr);
1791     globals->get_multiplayer_tx_mgr()->init();
1792
1793     globals->set_multiplayer_rx_mgr(new FGMultiplayRxMgr);
1794     globals->get_multiplayer_rx_mgr()->init();
1795 #endif
1796
1797     ////////////////////////////////////////////////////////////////////////
1798     // Initialize the Nasal interpreter.
1799     // Do this last, so that the loaded scripts see initialized state
1800     ////////////////////////////////////////////////////////////////////////
1801     FGNasalSys* nasal = new FGNasalSys();
1802     globals->add_subsystem("nasal", nasal);
1803     nasal->init();
1804
1805     ////////////////////////////////////////////////////////////////////
1806     // At this point we could try and parse the waypoint options
1807     ///////////////////////////////////////////////////////////////////
1808     parseWaypoints();
1809
1810
1811     ////////////////////////////////////////////////////////////////////////
1812     // End of subsystem initialization.
1813     ////////////////////////////////////////////////////////////////////
1814
1815     SG_LOG( SG_GENERAL, SG_INFO, endl);
1816
1817                                 // Save the initial state for future
1818                                 // reference.
1819     globals->saveInitialState();
1820
1821     return true;
1822 }
1823
1824
1825 void fgReInitSubsystems()
1826 {
1827     // static const SGPropertyNode *longitude
1828     //     = fgGetNode("/sim/presets/longitude-deg");
1829     // static const SGPropertyNode *latitude
1830     //     = fgGetNode("/sim/presets/latitude-deg");
1831     static const SGPropertyNode *altitude
1832         = fgGetNode("/sim/presets/altitude-ft");
1833     static const SGPropertyNode *master_freeze
1834         = fgGetNode("/sim/freeze/master");
1835
1836     SG_LOG( SG_GENERAL, SG_INFO,
1837             "fgReInitSubsystems(): /position/altitude = "
1838             << altitude->getDoubleValue() );
1839
1840     bool freeze = master_freeze->getBoolValue();
1841     if ( !freeze ) {
1842         fgSetBool("/sim/freeze/master", true);
1843     }
1844     fgSetBool("/sim/crashed", false);
1845
1846     // Initialize the FDM
1847     fgInitFDM();
1848     
1849     // allocates structures so must happen before any of the flight
1850     // model or control parameters are set
1851     fgAircraftInit();   // In the future this might not be the case.
1852
1853     // reload offsets from config defaults
1854     globals->get_viewmgr()->reinit();
1855
1856     fgInitView();
1857
1858     globals->get_controls()->reset_all();
1859
1860     fgUpdateLocalTime();
1861
1862     // re-init to proper time of day setting
1863     fgInitTimeOffset();
1864
1865     if ( !freeze ) {
1866         fgSetBool("/sim/freeze/master", false);
1867     }
1868 }
1869