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