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