1 // fg_init.cxx -- Flight Gear top level initialization routines
3 // Written by Curtis Olson, started August 1997.
5 // Copyright (C) 1997 Curtis L. Olson - http://www.flightgear.org/~curt
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.
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.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
28 // For BC 5.01 this must be included before OpenGL includes.
29 #ifdef SG_MATH_EXCEPTION_CLASH
35 #include <string.h> // strcmp()
37 #if defined( unix ) || defined( __CYGWIN__ )
38 # include <unistd.h> // for gethostname()
40 #if defined( _MSC_VER) || defined(__MINGW32__)
41 # include <direct.h> // for getcwd()
42 # define getcwd _getcwd
45 // work around a stdc++ lib bug in some versions of linux, but doesn't
46 // seem to hurt to have this here for all versions of Linux.
48 # define _G_NO_EXTERN_TEMPLATES
51 #include <simgear/compiler.h>
55 #include <simgear/constants.h>
56 #include <simgear/debug/logstream.hxx>
57 #include <simgear/structure/exception.hxx>
58 #include <simgear/structure/event_mgr.hxx>
59 #include <simgear/math/point3d.hxx>
60 #include <simgear/math/polar3d.hxx>
61 #include <simgear/math/sg_geodesy.hxx>
62 #include <simgear/misc/sg_path.hxx>
63 #include <simgear/misc/interpolator.hxx>
64 #include <simgear/scene/material/matlib.hxx>
65 #include <simgear/scene/model/particles.hxx>
66 #include <simgear/timing/sg_time.hxx>
67 #include <simgear/timing/lowleveltime.h>
69 #include <Aircraft/aircraft.hxx>
70 #include <Aircraft/replay.hxx>
71 #include <Airports/apt_loader.hxx>
72 #include <Airports/runways.hxx>
73 #include <Airports/simple.hxx>
74 #include <AIModel/AIManager.hxx>
75 #include <ATCDCL/ATCmgr.hxx>
76 #include <ATCDCL/AIMgr.hxx>
77 #include <Autopilot/route_mgr.hxx>
78 #include <Autopilot/xmlauto.hxx>
79 #include <Cockpit/cockpit.hxx>
80 #include <Cockpit/panel.hxx>
81 #include <Cockpit/panel_io.hxx>
83 #include <FDM/SP/ADA.hxx>
84 #include <FDM/SP/ACMS.hxx>
86 #include <FDM/Balloon.h>
87 #include <FDM/ExternalNet/ExternalNet.hxx>
88 #include <FDM/ExternalPipe/ExternalPipe.hxx>
89 #include <FDM/JSBSim/JSBSim.hxx>
90 #include <FDM/LaRCsim/LaRCsim.hxx>
91 #include <FDM/MagicCarpet.hxx>
92 #include <FDM/UFO.hxx>
93 #include <FDM/NullFDM.hxx>
94 #include <FDM/YASim/YASim.hxx>
95 #include <GUI/new_gui.hxx>
96 #include <Include/general.hxx>
97 #include <Input/input.hxx>
98 #include <Instrumentation/instrument_mgr.hxx>
99 #include <Model/acmodel.hxx>
100 #include <AIModel/submodel.hxx>
101 #include <AIModel/AIManager.hxx>
102 #include <Navaids/navdb.hxx>
103 #include <Navaids/navlist.hxx>
104 #include <Scenery/scenery.hxx>
105 #include <Scenery/tilemgr.hxx>
106 #include <Scripting/NasalSys.hxx>
107 #include <Sound/fg_fx.hxx>
108 #include <Sound/beacon.hxx>
109 #include <Sound/morse.hxx>
110 #include <Sound/voice.hxx>
111 #include <Systems/system_mgr.hxx>
112 #include <Time/light.hxx>
113 #include <Time/sunsolver.hxx>
114 #include <Time/tmp.hxx>
115 #include <Traffic/TrafficMgr.hxx>
116 #include <MultiPlayer/multiplaymgr.hxx>
118 #include <Environment/environment_mgr.hxx>
120 #include "fg_init.hxx"
122 #include "fg_commands.hxx"
123 #include "fg_props.hxx"
124 #include "options.hxx"
125 #include "globals.hxx"
126 #include "logger.hxx"
127 #include "viewmgr.hxx"
130 #if defined(FX) && defined(XMESA)
131 #include <GL/xmesa.h>
134 SG_USING_STD(string);
138 extern const char *default_root;
142 // Scan the command line options for the specified option and return
144 static string fgScanForOption( const string& option, int argc, char **argv ) {
147 if (hostname == NULL)
150 gethostname(_hostname, 256);
151 hostname = strdup(_hostname);
152 free_hostname = true;
155 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
157 int len = option.length();
160 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
162 string arg = argv[i];
163 if ( arg.find( option ) == 0 ) {
164 return arg.substr( len );
174 // Scan the user config files for the specified option and return
176 static string fgScanForOption( const string& option, const string& path ) {
177 sg_gzifstream in( path );
178 if ( !in.is_open() ) {
182 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
184 int len = option.length();
188 while ( ! in.eof() ) {
191 while ( in.get(c) && c != '\0' ) {
196 #if defined( macintosh )
197 getline( in, line, '\r' );
199 getline( in, line, '\n' );
202 // catch extraneous (DOS) line ending character
203 if ( line[line.length() - 1] < 32 ) {
204 line = line.substr( 0, line.length()-1 );
207 if ( line.find( option ) == 0 ) {
208 return line.substr( len );
217 // Scan the user config files for the specified option and return
219 static string fgScanForOption( const string& option ) {
222 #if defined( unix ) || defined( __CYGWIN__ )
223 // Next check home directory for .fgfsrc.hostname file
225 if ( homedir != NULL ) {
226 SGPath config( homedir );
227 config.append( ".fgfsrc" );
228 config.concat( "." );
229 config.concat( hostname );
230 arg = fgScanForOption( option, config.str() );
235 // Next check home directory for .fgfsrc file
237 if ( homedir != NULL ) {
238 SGPath config( homedir );
239 config.append( ".fgfsrc" );
240 arg = fgScanForOption( option, config.str() );
245 // Check for $fg_root/system.fgfsrc
246 SGPath config( globals->get_fg_root() );
247 config.append( "system.fgfsrc" );
248 arg = fgScanForOption( option, config.str() );
255 // Read in configuration (files and command line options) but only set
257 bool fgInitFGRoot ( int argc, char **argv ) {
260 // First parse command line options looking for --fg-root=, this
261 // will override anything specified in a config file
262 root = fgScanForOption( "--fg-root=", argc, argv);
264 // Check in one of the user configuration files.
266 root = fgScanForOption( "--fg-root=" );
268 // Next check if fg-root is set as an env variable
269 if ( root.empty() ) {
270 char *envp = ::getenv( "FG_ROOT" );
271 if ( envp != NULL ) {
276 // Otherwise, default to a random compiled-in location if we can't
277 // find fg-root any other way.
278 if ( root.empty() ) {
279 #if defined( __CYGWIN__ )
280 root = "/FlightGear";
281 #elif defined( WIN32 )
282 root = "\\FlightGear";
283 #elif defined(OSX_BUNDLE)
284 /* the following code looks for the base package directly inside
285 the application bundle. This can be changed fairly easily by
286 fiddling with the code below. And yes, I know it's ugly and verbose.
288 CFBundleRef appBundle = CFBundleGetMainBundle();
289 CFURLRef appUrl = CFBundleCopyBundleURL(appBundle);
290 CFRelease(appBundle);
292 // look for a 'data' subdir directly inside the bundle : is there
293 // a better place? maybe in Resources? I don't know ...
294 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, appUrl, CFSTR("data"), true);
296 // now convert down to a path, and the a c-string
297 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
298 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
301 CFRelease(appBundle);
309 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
310 globals->set_fg_root(root);
316 // Read in configuration (files and command line options) but only set
318 bool fgInitFGAircraft ( int argc, char **argv ) {
321 // First parse command line options looking for --aircraft=, this
322 // will override anything specified in a config file
323 aircraft = fgScanForOption( "--aircraft=", argc, argv );
324 if ( aircraft.empty() ) {
325 // check synonym option
326 aircraft = fgScanForOption( "--vehicle=", argc, argv );
329 // Check in one of the user configuration files.
330 if ( aircraft.empty() ) {
331 aircraft = fgScanForOption( "--aircraft=" );
333 if ( aircraft.empty() ) {
334 aircraft = fgScanForOption( "--vehicle=" );
337 // if an aircraft was specified, set the property name
338 if ( !aircraft.empty() ) {
339 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
340 fgSetString("/sim/aircraft", aircraft.c_str() );
342 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
349 // Return the current base package version
350 string fgBasePackageVersion() {
351 SGPath base_path( globals->get_fg_root() );
352 base_path.append("version");
354 sg_gzifstream in( base_path.str() );
355 if ( !in.is_open() ) {
356 SGPath old_path( globals->get_fg_root() );
357 old_path.append( "Thanks" );
358 sg_gzifstream old( old_path.str() );
359 if ( !old.is_open() ) {
362 return "[old version]";
373 // Initialize the localization
374 SGPropertyNode *fgInitLocale(const char *language) {
375 SGPropertyNode *c_node = NULL, *d_node = NULL;
376 SGPropertyNode *intl = fgGetNode("/sim/intl");
378 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
380 // localization not defined
385 // Select the proper language from the list
387 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
388 for (unsigned int i = 0; i < locale.size(); i++) {
390 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
391 for (unsigned int j = 0; j < lang.size(); j++) {
393 if (!strcmp(lang[j]->getStringValue(), language)) {
402 d_node = intl->getChild("locale");
406 // Check for localized font
407 SGPropertyNode *font_n = c_node->getNode("font", true);
408 if ( !strcmp(font_n->getStringValue(), "") )
409 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
413 // Load the default strings
415 SGPath d_path( globals->get_fg_root() );
417 const char *d_path_str = d_node->getStringValue("strings");
419 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << d_node->getPath() << "/strings.");
423 d_path.append(d_path_str);
424 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << d_path.str());
426 SGPropertyNode *strings = c_node->getNode("strings");
428 readProperties(d_path.str(), strings);
429 } catch (const sg_exception &e) {
430 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
435 // Load the language specific strings
437 if (c_node != d_node) {
438 SGPath c_path( globals->get_fg_root() );
440 const char *c_path_str = c_node->getStringValue("strings");
442 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << c_node->getPath() << "/strings");
446 c_path.append(c_path_str);
447 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << c_path.str());
450 readProperties(c_path.str(), strings);
451 } catch (const sg_exception &e) {
452 SG_LOG(SG_GENERAL, SG_ALERT,
453 "Unable to read the localized strings from " << c_path.str());
463 // Initialize the localization routines
464 bool fgDetectLanguage() {
465 const char *language = ::getenv("LANG");
467 if (language == NULL) {
468 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
472 SGPropertyNode *locale = fgInitLocale(language);
474 SG_LOG(SG_GENERAL, SG_ALERT,
475 "No internationalization settings specified in preferences.xml" );
480 globals->set_locale( locale );
485 // Attempt to locate and parse the various non-XML config files in order
486 // from least precidence to greatest precidence
488 do_options (int argc, char ** argv)
490 // Check for $fg_root/system.fgfsrc
491 SGPath config( globals->get_fg_root() );
492 config.append( "system.fgfsrc" );
493 fgParseOptions(config.str());
495 #if defined( unix ) || defined( __CYGWIN__ )
496 config.concat( "." );
497 config.concat( hostname );
498 fgParseOptions(config.str());
501 // Check for ~/.fgfsrc
502 if ( homedir != NULL ) {
503 config.set( homedir );
504 config.append( ".fgfsrc" );
505 fgParseOptions(config.str());
508 #if defined( unix ) || defined( __CYGWIN__ )
509 // Check for ~/.fgfsrc.hostname
510 config.concat( "." );
511 config.concat( hostname );
512 fgParseOptions(config.str());
515 // Parse remaining command line options
516 // These will override anything specified in a config file
517 fgParseArgs(argc, argv);
521 static string fgFindAircraftPath( const SGPath &path, const string &aircraft,
522 SGPropertyNode *cache, int depth = 0 )
524 const int MAXDEPTH = 1;
527 ulDir *dirp = ulOpenDir(path.str().c_str());
529 cerr << "Unable to open aircraft directory '" << path.str() << '\'' << endl;
534 while ((dire = ulReadDir(dirp)) != NULL) {
536 if (depth > MAXDEPTH)
539 if (!strcmp("CVS", dire->d_name) || !strcmp(".", dire->d_name)
540 || !strcmp("..", dire->d_name) || !strcmp("AI", dire->d_name))
544 next.append(dire->d_name);
546 result = fgFindAircraftPath( next, aircraft, cache, depth + 1 );
547 if ( ! result.empty() )
551 int len = strlen(dire->d_name);
552 if (len < 9 || strcmp(dire->d_name + len - 8, "-set.xml"))
558 if (!cache->getChild("aircraft", i++, false))
561 SGPropertyNode *n, *entry = cache->getChild("aircraft", --i, true);
563 n = entry->getNode("file", true);
564 n->setStringValue(dire->d_name);
565 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
567 n = entry->getNode("path", true);
568 n->setStringValue(path.str().c_str());
569 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
571 if ( !strcmp(dire->d_name, aircraft.c_str()) ) {
583 // Read in configuration (file and command line)
584 bool fgInitConfig ( int argc, char **argv ) {
586 // First, set some sane default values
589 // Read global preferences from $FG_ROOT/preferences.xml
590 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
591 fgLoadProps("preferences.xml", globals->get_props());
592 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
594 // Detect the required language as early as possible
595 if ( !fgDetectLanguage() ) {
599 SGPropertyNode autosave;
601 char *envp = ::getenv( "APPDATA" );
603 SGPath config( envp );
604 config.append( "flightgear.org" );
606 if ( homedir != NULL ) {
607 SGPath config( homedir );
608 config.append( ".fgfs" );
610 const char *fg_home = getenv("FG_HOME");
614 // Set /sim/fg-home and don't allow malign code to override it until
615 // Nasal security is set up. Use FG_HOME if necessary.
616 SGPropertyNode *home = fgGetNode("/sim", true);
617 home->removeChild("fg-home", 0, false);
618 home = home->getChild("fg-home", 0, true);
619 home->setStringValue(config.c_str());
620 home->setAttribute(SGPropertyNode::WRITE, false);
622 config.append( "autosave.xml" );
623 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << config.str());
625 readProperties(config.str(), &autosave, SGPropertyNode::USERARCHIVE);
627 SG_LOG(SG_INPUT, SG_DEBUG, "First time reading user settings");
629 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Reading user settings");
631 SGPropertyNode *cache_root = autosave.getNode("sim/startup/path-cache", true);
634 // Scan user config files and command line for a specified aircraft.
635 fgInitFGAircraft(argc, argv);
637 string aircraft = fgGetString( "/sim/aircraft", "" );
638 if ( aircraft.size() > 0 ) {
639 SGPath aircraft_search( globals->get_fg_root() );
640 aircraft_search.append( "Aircraft" );
642 string aircraft_set = aircraft + "-set.xml";
645 // check if the *-set.xml file is already in the cache
646 if (globals->get_fg_root() == cache_root->getStringValue("fg-root", "")) {
647 vector<SGPropertyNode_ptr> cache = cache_root->getChildren("aircraft");
648 for (unsigned int i = 0; i < cache.size(); i++) {
649 const char *name = cache[i]->getStringValue("file", "");
650 if (aircraft_set == name) {
651 const char *path = cache[i]->getStringValue("path", "");
661 if (result.empty()) {
662 // prepare cache for rescan
663 SGPropertyNode *n = cache_root->getNode("fg-root", true);
664 n->setStringValue(globals->get_fg_root().c_str());
665 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
666 cache_root->removeChildren("aircraft");
668 result = fgFindAircraftPath( aircraft_search, aircraft_set, cache_root );
671 if ( !result.empty() ) {
672 fgSetString( "/sim/aircraft-dir", result.c_str() );
673 SGPath full_name( result );
674 full_name.append( aircraft_set );
676 SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
677 << " from " << full_name.str());
679 readProperties( full_name.str(), globals->get_props() );
680 } catch ( const sg_exception &e ) {
681 string message = "Error reading default aircraft: ";
682 message += e.getFormattedMessage();
683 SG_LOG(SG_INPUT, SG_ALERT, message);
687 SG_LOG( SG_INPUT, SG_ALERT, "Cannot find specified aircraft: "
693 SG_LOG( SG_INPUT, SG_ALERT, "No default aircraft specified" );
696 copyProperties(&autosave, globals->get_props());
698 // parse options after loading aircraft to ensure any user
699 // overrides of defaults are honored.
700 do_options(argc, argv);
711 // This function is never used, but maybe useful in the future ???
714 // Preset lon/lat given an airport id
715 static bool fgSetPosFromAirportID( const string& id ) {
719 SG_LOG( SG_GENERAL, SG_INFO,
720 "Attempting to set starting position from airport code " << id );
722 if ( fgFindAirportID( id, &a ) ) {
724 fgSetDouble("/sim/presets/longitude-deg", a->longitude );
725 fgSetDouble("/sim/presets/latitude-deg", a->latitude );
727 // other code depends on the actual postition being set so set
729 fgSetDouble("/position/longitude-deg", a->longitude );
730 fgSetDouble("/position/latitude-deg", a->latitude );
732 SG_LOG( SG_GENERAL, SG_INFO,
733 "Position for " << id << " is (" << a->longitude
734 << ", " << a->latitude << ")" );
744 // Set current tower position lon/lat given an airport id
745 static bool fgSetTowerPosFromAirportID( const string& id) {
746 const FGAirport *a = fgFindAirportID( id);
748 SGGeod tower = a->getTowerLocation();
749 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
750 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
751 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
759 struct FGTowerLocationListener : SGPropertyChangeListener {
760 void valueChanged(SGPropertyNode* node) {
761 const string id(node->getStringValue());
762 fgSetTowerPosFromAirportID(id);
766 void fgInitTowerLocationListener() {
767 fgGetNode("/sim/tower/airport-id", true)
768 ->addChangeListener( new FGTowerLocationListener(), true );
771 // Set current_options lon/lat given an airport id and heading (degrees)
772 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
778 // set initial position from runway and heading
779 SG_LOG( SG_GENERAL, SG_INFO,
780 "Attempting to set starting position from airport code "
781 << id << " heading " << tgt_hdg );
783 if ( ! globals->get_runways()->search( id, (int)tgt_hdg, &r ) ) {
784 SG_LOG( SG_GENERAL, SG_ALERT,
785 "Failed to find a good runway for " << id << '\n' );
788 fgSetString("/sim/atc/runway", r._rwy_no.c_str());
790 double lat2, lon2, az2;
791 double heading = r._heading;
792 double azimuth = heading + 180.0;
793 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
795 SG_LOG( SG_GENERAL, SG_INFO,
796 "runway = " << r._lon << ", " << r._lat
797 << " length = " << r._length * SG_FEET_TO_METER
798 << " heading = " << azimuth );
800 geo_direct_wgs_84 ( 0, r._lat, r._lon, azimuth, r._length * SG_FEET_TO_METER * 0.5
801 - fgGetDouble("/sim/airport/runways/start-offset-m", 5.0),
802 &lat2, &lon2, &az2 );
804 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
806 double odist = fgGetDouble("/sim/presets/offset-distance-nm");
807 odist *= SG_NM_TO_METER;
808 double oaz = azimuth;
809 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
810 oaz = fgGetDouble("/sim/presets/offset-azimuth-deg") + 180;
813 while ( oaz >= 360.0 ) { oaz -= 360.0; }
814 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
820 fgSetDouble("/sim/presets/longitude-deg", lon2 );
821 fgSetDouble("/sim/presets/latitude-deg", lat2 );
822 fgSetDouble("/sim/presets/heading-deg", heading );
824 // other code depends on the actual values being set ...
825 fgSetDouble("/position/longitude-deg", lon2 );
826 fgSetDouble("/position/latitude-deg", lat2 );
827 fgSetDouble("/orientation/heading-deg", heading );
829 SG_LOG( SG_GENERAL, SG_INFO,
830 "Position for " << id << " is ("
832 << lat2 << ") new heading is "
838 // Set current_options lon/lat given an airport id and parkig position name
839 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
843 // can't see an easy way around this const_cast at the moment
844 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
846 SG_LOG( SG_GENERAL, SG_ALERT,
847 "Failed to find airport " << id );
850 FGAirportDynamics* dcs = apt->getDynamics();
852 SG_LOG( SG_GENERAL, SG_ALERT,
853 "Failed to find parking position " << parkpos <<
854 " at airport " << id );
858 int park_index = dcs->getNrOfParkings() - 1;
859 while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
860 if (park_index < 0) {
861 SG_LOG( SG_GENERAL, SG_ALERT,
862 "Failed to find parking position " << parkpos <<
863 " at airport " << id );
866 FGParking* parking = dcs->getParking(park_index);
868 double lat = parking->getLatitude();
869 double lon = parking->getLongitude();
870 double hdg = parking->getHeading();
873 fgSetDouble("/sim/presets/longitude-deg", lon );
874 fgSetDouble("/sim/presets/latitude-deg", lat );
875 fgSetDouble("/sim/presets/heading-deg", hdg );
877 // other code depends on the actual values being set ...
878 fgSetDouble("/position/longitude-deg", lon );
879 fgSetDouble("/position/latitude-deg", lat );
880 fgSetDouble("/orientation/heading-deg", hdg );
882 SG_LOG( SG_GENERAL, SG_INFO,
883 "Position for " << id << " is ("
885 << lat << ") new heading is "
892 // Set current_options lon/lat given an airport id and runway number
893 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
899 // set initial position from airport and runway number
900 SG_LOG( SG_GENERAL, SG_INFO,
901 "Attempting to set starting position for "
902 << id << ":" << rwy );
904 if ( ! globals->get_runways()->search( id, rwy, &r ) ) {
905 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
906 "Failed to find runway " << rwy <<
907 " at airport " << id << ". Using default runway." );
910 fgSetString("/sim/atc/runway", r._rwy_no.c_str());
912 double lat2, lon2, az2;
913 double heading = r._heading;
914 double azimuth = heading + 180.0;
915 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
917 SG_LOG( SG_GENERAL, SG_INFO,
918 "runway = " << r._lon << ", " << r._lat
919 << " length = " << r._length * SG_FEET_TO_METER
920 << " heading = " << azimuth );
922 geo_direct_wgs_84 ( 0, r._lat, r._lon, azimuth, r._length * SG_FEET_TO_METER * 0.5
923 - fgGetDouble("/sim/airport/runways/start-offset-m", 5.0),
924 &lat2, &lon2, &az2 );
926 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON )
929 double odist = fgGetDouble("/sim/presets/offset-distance-nm");
930 odist *= SG_NM_TO_METER;
931 double oaz = azimuth;
932 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON )
934 oaz = fgGetDouble("/sim/presets/offset-azimuth-deg") + 180;
935 heading = fgGetDouble("/sim/presets/heading-deg");
937 while ( oaz >= 360.0 ) { oaz -= 360.0; }
938 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
944 fgSetDouble("/sim/presets/longitude-deg", lon2 );
945 fgSetDouble("/sim/presets/latitude-deg", lat2 );
946 fgSetDouble("/sim/presets/heading-deg", heading );
948 // other code depends on the actual values being set ...
949 fgSetDouble("/position/longitude-deg", lon2 );
950 fgSetDouble("/position/latitude-deg", lat2 );
951 fgSetDouble("/orientation/heading-deg", heading );
953 SG_LOG( SG_GENERAL, SG_INFO,
954 "Position for " << id << " is ("
956 << lat2 << ") new heading is "
963 static void fgSetDistOrAltFromGlideSlope() {
964 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
965 string apt_id = fgGetString("/sim/presets/airport-id");
966 double gs = fgGetDouble("/sim/presets/glideslope-deg")
967 * SG_DEGREES_TO_RADIANS ;
968 double od = fgGetDouble("/sim/presets/offset-distance-nm");
969 double alt = fgGetDouble("/sim/presets/altitude-ft");
971 double apt_elev = 0.0;
972 if ( ! apt_id.empty() ) {
973 apt_elev = fgGetAirportElev( apt_id );
974 if ( apt_elev < -9990.0 ) {
981 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
982 // set altitude from glideslope and offset-distance
983 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
984 alt = fabs(od*tan(gs)) + apt_elev;
985 fgSetDouble("/sim/presets/altitude-ft", alt);
986 fgSetBool("/sim/presets/onground", false);
987 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
989 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
990 // set offset-distance from glideslope and altitude
991 od = (alt - apt_elev) / tan(gs);
992 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
993 fgSetDouble("/sim/presets/offset-distance-nm", od);
994 fgSetBool("/sim/presets/onground", false);
995 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
997 } else if( fabs(gs) > 0.01 ) {
998 SG_LOG( SG_GENERAL, SG_ALERT,
999 "Glideslope given but not altitude or offset-distance." );
1000 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
1001 fgSetDouble("/sim/presets/glideslope-deg", 0);
1002 fgSetBool("/sim/presets/onground", true);
1007 // Set current_options lon/lat given an airport id and heading (degrees)
1008 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
1010 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
1012 // set initial position from runway and heading
1013 if ( nav != NULL ) {
1014 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1015 << id << ":" << freq );
1017 double lon = nav->get_lon();
1018 double lat = nav->get_lat();
1020 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON )
1022 double odist = fgGetDouble("/sim/presets/offset-distance-nm")
1024 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth-deg"))
1026 while ( oaz >= 360.0 ) { oaz -= 360.0; }
1027 double olat, olon, az2;
1028 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
1035 fgSetDouble("/sim/presets/longitude-deg", lon );
1036 fgSetDouble("/sim/presets/latitude-deg", lat );
1038 // other code depends on the actual values being set ...
1039 fgSetDouble("/position/longitude-deg", lon );
1040 fgSetDouble("/position/latitude-deg", lat );
1041 fgSetDouble("/orientation/heading-deg",
1042 fgGetDouble("/sim/presets/heading-deg") );
1044 SG_LOG( SG_GENERAL, SG_INFO,
1045 "Position for " << id << ":" << freq << " is ("
1046 << lon << ", "<< lat << ")" );
1050 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1051 << id << ":" << freq );
1056 // Set current_options lon/lat given an aircraft carrier id
1057 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
1059 // set initial position from runway and heading
1063 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
1064 double lon = geodPos.getLongitudeDeg();
1065 double lat = geodPos.getLatitudeDeg();
1066 double alt = geodPos.getElevationFt();
1068 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1069 << carrier << " at lat = " << lat << ", lon = " << lon
1070 << ", alt = " << alt << ", heading = " << heading);
1072 fgSetDouble("/sim/presets/longitude-deg", lon);
1073 fgSetDouble("/sim/presets/latitude-deg", lat);
1074 fgSetDouble("/sim/presets/altitude-ft", alt);
1075 fgSetDouble("/sim/presets/heading-deg", heading);
1076 fgSetDouble("/position/longitude-deg", lon);
1077 fgSetDouble("/position/latitude-deg", lat);
1078 fgSetDouble("/position/altitude-ft", alt);
1079 fgSetDouble("/orientation/heading-deg", heading);
1081 fgSetString("/sim/presets/speed-set", "UVW");
1082 fgSetDouble("/velocities/uBody-fps", uvw(0));
1083 fgSetDouble("/velocities/vBody-fps", uvw(1));
1084 fgSetDouble("/velocities/wBody-fps", uvw(2));
1085 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
1086 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
1087 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
1089 fgSetBool("/sim/presets/onground", true);
1093 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
1099 // Set current_options lon/lat given an airport id and heading (degrees)
1100 static bool fgSetPosFromFix( const string& id ) {
1103 // set initial position from runway and heading
1104 if ( globals->get_fixlist()->query( id.c_str(), &fix ) ) {
1105 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1108 double lon = fix.get_lon();
1109 double lat = fix.get_lat();
1111 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON )
1113 double odist = fgGetDouble("/sim/presets/offset-distance-nm")
1115 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth-deg"))
1117 while ( oaz >= 360.0 ) { oaz -= 360.0; }
1118 double olat, olon, az2;
1119 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
1126 fgSetDouble("/sim/presets/longitude-deg", lon );
1127 fgSetDouble("/sim/presets/latitude-deg", lat );
1129 // other code depends on the actual values being set ...
1130 fgSetDouble("/position/longitude-deg", lon );
1131 fgSetDouble("/position/latitude-deg", lat );
1132 fgSetDouble("/orientation/heading-deg",
1133 fgGetDouble("/sim/presets/heading-deg") );
1135 SG_LOG( SG_GENERAL, SG_INFO,
1136 "Position for " << id << " is ("
1137 << lon << ", "<< lat << ")" );
1141 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1149 * Initialize vor/ndb/ils/fix list management and query systems (as
1150 * well as simple airport db list)
1155 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
1157 SGPath aptdb( globals->get_fg_root() );
1158 aptdb.append( "Airports/apt.dat" );
1160 SGPath p_metar( globals->get_fg_root() );
1161 p_metar.append( "Airports/metar.dat" );
1163 FGAirportList *airports = new FGAirportList();
1164 globals->set_airports( airports );
1165 FGRunwayList *runways = new FGRunwayList();
1166 globals->set_runways( runways );
1168 fgAirportDBLoad( airports, runways, aptdb.str(), p_metar.str() );
1170 FGNavList *navlist = new FGNavList;
1171 FGNavList *loclist = new FGNavList;
1172 FGNavList *gslist = new FGNavList;
1173 FGNavList *dmelist = new FGNavList;
1174 FGNavList *mkrlist = new FGNavList;
1175 FGNavList *tacanlist = new FGNavList;
1176 FGNavList *carrierlist = new FGNavList;
1177 FGTACANList *channellist = new FGTACANList;
1179 globals->set_navlist( navlist );
1180 globals->set_loclist( loclist );
1181 globals->set_gslist( gslist );
1182 globals->set_dmelist( dmelist );
1183 globals->set_mkrlist( mkrlist );
1184 globals->set_tacanlist( tacanlist );
1185 globals->set_carrierlist( carrierlist );
1186 globals->set_channellist( channellist );
1188 if ( !fgNavDBInit(airports, navlist, loclist, gslist, dmelist, mkrlist, tacanlist, carrierlist, channellist) ) {
1189 SG_LOG( SG_GENERAL, SG_ALERT,
1190 "Problems loading one or more navigational database" );
1193 if ( fgGetBool("/sim/navdb/localizers/auto-align", true) ) {
1194 // align all the localizers with their corresponding runways
1195 // since data sources are good for cockpit navigation
1196 // purposes, but not always to the error tolerances needed to
1197 // exactly place these items.
1199 = fgGetDouble( "/sim/navdb/localizers/auto-align-threshold-deg",
1201 fgNavDBAlignLOCwithRunway( runways, loclist, threshold );
1204 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1205 SGPath p_fix( globals->get_fg_root() );
1206 p_fix.append( "Navaids/fix.dat" );
1207 FGFixList *fixlist = new FGFixList;
1208 fixlist->init( p_fix );
1209 globals->set_fixlist( fixlist );
1211 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
1212 SGPath p_awy( globals->get_fg_root() );
1213 p_awy.append( "Navaids/awy.dat" );
1214 FGAirwayNetwork *awyNet = new FGAirwayNetwork;
1215 //cerr << "Loading Airways" << endl;
1216 awyNet->load (p_awy );
1218 //cerr << "initializing airways" << endl;
1219 globals->set_airwaynet( awyNet );
1225 // Set the initial position based on presets (or defaults)
1226 bool fgInitPosition() {
1227 // cout << "fgInitPosition()" << endl;
1228 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1229 * SG_DEGREES_TO_RADIANS ;
1230 double od = fgGetDouble("/sim/presets/offset-distance-nm");
1231 double alt = fgGetDouble("/sim/presets/altitude-ft");
1233 bool set_pos = false;
1235 // If glideslope is specified, then calculate offset-distance or
1236 // altitude relative to glide slope if either of those was not
1238 if ( fabs( gs ) > 0.01 ) {
1239 fgSetDistOrAltFromGlideSlope();
1243 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1244 // If not, check for an airport-id and use that.
1245 // If not, default to the middle of the KSFO field.
1246 // The default values for lon/lat are deliberately out of range
1247 // so that the airport-id can take effect; valid lon/lat will
1248 // override airport-id, however.
1249 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1250 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1251 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1252 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1257 string apt = fgGetString("/sim/presets/airport-id");
1258 string rwy_no = fgGetString("/sim/presets/runway");
1259 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1260 string vor = fgGetString("/sim/presets/vor-id");
1261 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1262 string ndb = fgGetString("/sim/presets/ndb-id");
1263 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1264 string carrier = fgGetString("/sim/presets/carrier");
1265 string parkpos = fgGetString("/sim/presets/parkpos");
1266 string fix = fgGetString("/sim/presets/fix");
1267 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1268 double hdg = hdg_preset->getDoubleValue();
1270 // save some start parameters, so that we can later say what the
1271 // user really requested. TODO generalize that and move it to options.cxx
1272 static bool start_options_saved = false;
1273 if (!start_options_saved) {
1274 start_options_saved = true;
1275 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1277 opt->setDoubleValue("latitude-deg", lat_deg);
1278 opt->setDoubleValue("longitude-deg", lon_deg);
1279 opt->setDoubleValue("heading-deg", hdg);
1280 opt->setStringValue("airport", apt.c_str());
1281 opt->setStringValue("runway", rwy_no.c_str());
1285 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1287 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1288 // An airport + parking position is requested
1289 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1290 // set tower position
1291 fgSetString("/sim/tower/airport-id", apt.c_str());
1296 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1297 // An airport + runway is requested
1298 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1299 // set tower position (a little off the heading for single
1301 fgSetString("/sim/tower/airport-id", apt.c_str());
1306 if ( !set_pos && !apt.empty() ) {
1307 // An airport is requested (find runway closest to hdg)
1308 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1309 // set tower position (a little off the heading for single
1311 fgSetString("/sim/tower/airport-id", apt.c_str());
1316 if (hdg_preset->getDoubleValue() > 9990.0)
1317 hdg_preset->setDoubleValue(hdg);
1319 if ( !set_pos && !vor.empty() ) {
1320 // a VOR is requested
1321 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1326 if ( !set_pos && !ndb.empty() ) {
1327 // an NDB is requested
1328 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1333 if ( !set_pos && !carrier.empty() ) {
1334 // an aircraft carrier is requested
1335 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1340 if ( !set_pos && !fix.empty() ) {
1341 // a Fix is requested
1342 if ( fgSetPosFromFix( fix ) ) {
1348 // No lon/lat specified, no airport specified, default to
1349 // middle of KSFO field.
1350 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1351 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1354 fgSetDouble( "/position/longitude-deg",
1355 fgGetDouble("/sim/presets/longitude-deg") );
1356 fgSetDouble( "/position/latitude-deg",
1357 fgGetDouble("/sim/presets/latitude-deg") );
1358 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1360 // determine if this should be an on-ground or in-air start
1361 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1362 fgSetBool("/sim/presets/onground", false);
1364 fgSetBool("/sim/presets/onground", true);
1371 // General house keeping initializations
1372 bool fgInitGeneral() {
1375 #if defined(FX) && defined(XMESA)
1376 char *mesa_win_state;
1379 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1380 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1382 root = globals->get_fg_root();
1383 if ( ! root.length() ) {
1384 // No root path set? Then bail ...
1385 SG_LOG( SG_GENERAL, SG_ALERT,
1386 "Cannot continue without a path to the base package "
1387 << "being defined." );
1390 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1392 #if defined(FX) && defined(XMESA)
1393 // initialize full screen flag
1394 globals->set_fullscreen(false);
1395 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1396 // Test for the MESA_GLX_FX env variable
1397 if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
1398 // test if we are fullscreen mesa/glide
1399 if ( (mesa_win_state[0] == 'f') ||
1400 (mesa_win_state[0] == 'F') ) {
1401 globals->set_fullscreen(true);
1407 char buf[512], *cwd = getcwd(buf, 512);
1408 fgSetString("/sim/fg-current", cwd ? cwd : "");
1413 // Initialize the flight model subsystem. This just creates the
1414 // object. The actual fdm initialization is delayed until we get a
1415 // proper scenery elevation hit. This is checked for in main.cxx
1419 if ( cur_fdm_state ) {
1420 delete cur_fdm_state;
1424 double dt = 1.0 / fgGetInt("/sim/model-hz");
1425 string model = fgGetString("/sim/flight-model");
1427 if ( model == "larcsim" ) {
1428 cur_fdm_state = new FGLaRCsim( dt );
1429 } else if ( model == "jsb" ) {
1430 cur_fdm_state = new FGJSBsim( dt );
1432 } else if ( model == "ada" ) {
1433 cur_fdm_state = new FGADA( dt );
1434 } else if ( model == "acms" ) {
1435 cur_fdm_state = new FGACMS( dt );
1437 } else if ( model == "balloon" ) {
1438 cur_fdm_state = new FGBalloonSim( dt );
1439 } else if ( model == "magic" ) {
1440 cur_fdm_state = new FGMagicCarpet( dt );
1441 } else if ( model == "ufo" ) {
1442 cur_fdm_state = new FGUFO( dt );
1443 } else if ( model == "external" ) {
1444 // external is a synonym for "--fdm=null" and is
1445 // maintained here for backwards compatibility
1446 cur_fdm_state = new FGNullFDM( dt );
1447 } else if ( model.find("network") == 0 ) {
1448 string host = "localhost";
1452 string net_options = model.substr(8);
1453 string::size_type begin, end;
1456 end = net_options.find( ",", begin );
1457 if ( end != string::npos ) {
1458 host = net_options.substr(begin, end - begin);
1462 end = net_options.find( ",", begin );
1463 if ( end != string::npos ) {
1464 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1468 end = net_options.find( ",", begin );
1469 if ( end != string::npos ) {
1470 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1474 end = net_options.find( ",", begin );
1475 if ( end != string::npos ) {
1476 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1479 cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1480 } else if ( model.find("pipe") == 0 ) {
1481 // /* old */ string pipe_path = model.substr(5);
1482 // /* old */ cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1483 string pipe_path = "";
1484 string pipe_protocol = "";
1485 string pipe_options = model.substr(5);
1486 string::size_type begin, end;
1489 end = pipe_options.find( ",", begin );
1490 if ( end != string::npos ) {
1491 pipe_path = pipe_options.substr(begin, end - begin);
1494 // protocol (last option)
1495 pipe_protocol = pipe_options.substr(begin);
1496 cur_fdm_state = new FGExternalPipe( dt, pipe_path, pipe_protocol );
1497 } else if ( model == "null" ) {
1498 cur_fdm_state = new FGNullFDM( dt );
1499 } else if ( model == "yasim" ) {
1500 cur_fdm_state = new YASim( dt );
1502 throw sg_throwable(string("Unrecognized flight model '") + model
1503 + "', cannot init flight dynamics model.");
1507 // Initialize view parameters
1509 // force update of model so that viewer can get some data...
1510 globals->get_aircraft_model()->update(0);
1511 // run update for current view so that data is current...
1512 globals->get_viewmgr()->update(0);
1516 SGTime *fgInitTime() {
1518 static const SGPropertyNode *longitude
1519 = fgGetNode("/position/longitude-deg");
1520 static const SGPropertyNode *latitude
1521 = fgGetNode("/position/latitude-deg");
1522 static const SGPropertyNode *cur_time_override
1523 = fgGetNode("/sim/time/cur-time-override", true);
1525 SGPath zone( globals->get_fg_root() );
1526 zone.append( "Timezone" );
1527 SGTime *t = new SGTime( longitude->getDoubleValue()
1528 * SGD_DEGREES_TO_RADIANS,
1529 latitude->getDoubleValue()
1530 * SGD_DEGREES_TO_RADIANS,
1532 cur_time_override->getLongValue() );
1534 globals->set_warp_delta( 0 );
1536 t->update( 0.0, 0.0,
1537 cur_time_override->getLongValue(),
1538 globals->get_warp() );
1544 // set up a time offset (aka warp) if one is specified
1545 void fgInitTimeOffset() {
1546 static const SGPropertyNode *longitude
1547 = fgGetNode("/position/longitude-deg");
1548 static const SGPropertyNode *latitude
1549 = fgGetNode("/position/latitude-deg");
1550 static const SGPropertyNode *cur_time_override
1551 = fgGetNode("/sim/time/cur-time-override", true);
1553 // Handle potential user specified time offsets
1554 int orig_warp = globals->get_warp();
1555 SGTime *t = globals->get_time_params();
1556 time_t cur_time = t->get_cur_time();
1557 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1558 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1559 time_t aircraftLocalTime =
1560 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1562 // Okay, we now have several possible scenarios
1563 int offset = fgGetInt("/sim/startup/time-offset");
1564 string offset_type = fgGetString("/sim/startup/time-offset-type");
1567 if ( offset_type == "real" ) {
1569 } else if ( offset_type == "dawn" ) {
1570 warp = fgTimeSecondsUntilSunAngle( cur_time,
1571 longitude->getDoubleValue()
1572 * SGD_DEGREES_TO_RADIANS,
1573 latitude->getDoubleValue()
1574 * SGD_DEGREES_TO_RADIANS,
1576 } else if ( offset_type == "morning" ) {
1577 warp = fgTimeSecondsUntilSunAngle( cur_time,
1578 longitude->getDoubleValue()
1579 * SGD_DEGREES_TO_RADIANS,
1580 latitude->getDoubleValue()
1581 * SGD_DEGREES_TO_RADIANS,
1583 } else if ( offset_type == "noon" ) {
1584 warp = fgTimeSecondsUntilSunAngle( cur_time,
1585 longitude->getDoubleValue()
1586 * SGD_DEGREES_TO_RADIANS,
1587 latitude->getDoubleValue()
1588 * SGD_DEGREES_TO_RADIANS,
1590 } else if ( offset_type == "afternoon" ) {
1591 warp = fgTimeSecondsUntilSunAngle( cur_time,
1592 longitude->getDoubleValue()
1593 * SGD_DEGREES_TO_RADIANS,
1594 latitude->getDoubleValue()
1595 * SGD_DEGREES_TO_RADIANS,
1597 } else if ( offset_type == "dusk" ) {
1598 warp = fgTimeSecondsUntilSunAngle( cur_time,
1599 longitude->getDoubleValue()
1600 * SGD_DEGREES_TO_RADIANS,
1601 latitude->getDoubleValue()
1602 * SGD_DEGREES_TO_RADIANS,
1604 } else if ( offset_type == "evening" ) {
1605 warp = fgTimeSecondsUntilSunAngle( cur_time,
1606 longitude->getDoubleValue()
1607 * SGD_DEGREES_TO_RADIANS,
1608 latitude->getDoubleValue()
1609 * SGD_DEGREES_TO_RADIANS,
1611 } else if ( offset_type == "midnight" ) {
1612 warp = fgTimeSecondsUntilSunAngle( cur_time,
1613 longitude->getDoubleValue()
1614 * SGD_DEGREES_TO_RADIANS,
1615 latitude->getDoubleValue()
1616 * SGD_DEGREES_TO_RADIANS,
1618 } else if ( offset_type == "system-offset" ) {
1621 } else if ( offset_type == "gmt-offset" ) {
1622 warp = offset - (currGMT - systemLocalTime);
1624 } else if ( offset_type == "latitude-offset" ) {
1625 warp = offset - (aircraftLocalTime - systemLocalTime);
1627 } else if ( offset_type == "system" ) {
1628 warp = offset - (systemLocalTime - currGMT) - cur_time;
1629 } else if ( offset_type == "gmt" ) {
1630 warp = offset - cur_time;
1631 } else if ( offset_type == "latitude" ) {
1632 warp = offset - (aircraftLocalTime - currGMT)- cur_time;
1634 SG_LOG( SG_GENERAL, SG_ALERT,
1635 "FG_TIME::Unsupported offset type " << offset_type );
1638 globals->set_warp( orig_warp + warp );
1639 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1640 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1641 cur_time_override->getLongValue(),
1642 globals->get_warp() );
1644 SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = "
1645 << globals->get_warp() );
1649 // This is the top level init routine which calls all the other
1650 // initialization routines. If you are adding a subsystem to flight
1651 // gear, its initialization call should located in this routine.
1652 // Returns non-zero if a problem encountered.
1653 bool fgInitSubsystems() {
1654 // static const SGPropertyNode *longitude
1655 // = fgGetNode("/sim/presets/longitude-deg");
1656 // static const SGPropertyNode *latitude
1657 // = fgGetNode("/sim/presets/latitude-deg");
1658 // static const SGPropertyNode *altitude
1659 // = fgGetNode("/sim/presets/altitude-ft");
1660 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1661 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1663 ////////////////////////////////////////////////////////////////////
1664 // Initialize the event manager subsystem.
1665 ////////////////////////////////////////////////////////////////////
1667 globals->get_event_mgr()->init();
1668 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1670 ////////////////////////////////////////////////////////////////////
1671 // Initialize the property interpolator subsystem. Put into the INIT
1672 // group because the "nasal" subsystem may need it at GENERAL take-down.
1673 ////////////////////////////////////////////////////////////////////
1674 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1677 ////////////////////////////////////////////////////////////////////
1678 // Add the FlightGear property utilities.
1679 ////////////////////////////////////////////////////////////////////
1680 globals->add_subsystem("properties", new FGProperties);
1682 ////////////////////////////////////////////////////////////////////
1683 // Initialize the material property subsystem.
1684 ////////////////////////////////////////////////////////////////////
1686 SGPath mpath( globals->get_fg_root() );
1687 mpath.append( "materials.xml" );
1688 string season = fgGetString("/sim/startup/season", "summer");
1689 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(), season.c_str(),
1690 globals->get_props()) ) {
1691 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1696 ////////////////////////////////////////////////////////////////////
1697 // Initialize the scenery management subsystem.
1698 ////////////////////////////////////////////////////////////////////
1700 if ( globals->get_tile_mgr()->init() ) {
1701 // Load the local scenery data
1702 double visibility_meters = fgGetDouble("/environment/visibility-m");
1704 globals->get_tile_mgr()->update( visibility_meters );
1706 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1710 globals->get_scenery()->get_scene_graph()
1711 ->addChild(simgear::Particles::getCommonRoot());
1713 ////////////////////////////////////////////////////////////////////
1714 // Initialize the flight model subsystem.
1715 ////////////////////////////////////////////////////////////////////
1719 // allocates structures so must happen before any of the flight
1720 // model or control parameters are set
1721 fgAircraftInit(); // In the future this might not be the case.
1724 ////////////////////////////////////////////////////////////////////
1725 // Initialize the weather subsystem.
1726 ////////////////////////////////////////////////////////////////////
1728 // Initialize the weather modeling subsystem
1729 globals->add_subsystem("environment", new FGEnvironmentMgr);
1732 ////////////////////////////////////////////////////////////////////
1733 // Initialize the aircraft systems and instrumentation (before the
1735 ////////////////////////////////////////////////////////////////////
1737 globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1738 globals->add_subsystem("systems", new FGSystemMgr);
1740 ////////////////////////////////////////////////////////////////////
1741 // Initialize the XML Autopilot subsystem.
1742 ////////////////////////////////////////////////////////////////////
1744 globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1745 globals->add_subsystem( "route-manager", new FGRouteMgr );
1748 ////////////////////////////////////////////////////////////////////
1749 // Initialize the view manager subsystem.
1750 ////////////////////////////////////////////////////////////////////
1754 ////////////////////////////////////////////////////////////////////
1755 // Create and register the logger.
1756 ////////////////////////////////////////////////////////////////////
1758 globals->add_subsystem("logger", new FGLogger);
1760 ////////////////////////////////////////////////////////////////////
1761 // Create and register the XML GUI.
1762 ////////////////////////////////////////////////////////////////////
1764 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1767 ////////////////////////////////////////////////////////////////////
1768 // Initialize the local time subsystem.
1769 ////////////////////////////////////////////////////////////////////
1771 // update the current timezone each 30 minutes
1772 globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1773 &fgUpdateLocalTime, 30*60 );
1774 fgInitTimeOffset(); // the environment subsystem needs this
1777 ////////////////////////////////////////////////////////////////////
1778 // Initialize the lighting subsystem.
1779 ////////////////////////////////////////////////////////////////////
1781 globals->add_subsystem("lighting", new FGLight);
1783 //////////////////////////////////////////////////////////////////////
1784 // Initialize the 2D cloud subsystem.
1785 ////////////////////////////////////////////////////////////////////
1786 fgGetBool("/sim/rendering/bump-mapping", false);
1788 #ifdef ENABLE_AUDIO_SUPPORT
1789 ////////////////////////////////////////////////////////////////////
1790 // Initialize the sound subsystem.
1791 ////////////////////////////////////////////////////////////////////
1793 init_volume = fgGetFloat("/sim/sound/volume");
1794 fgSetFloat("/sim/sound/volume", 0.0f);
1795 globals->set_soundmgr(new SGSoundMgr);
1796 globals->get_soundmgr()->init();
1797 globals->get_soundmgr()->bind();
1800 ////////////////////////////////////////////////////////////////////
1801 // Initialize the sound-effects subsystem.
1802 ////////////////////////////////////////////////////////////////////
1804 globals->add_subsystem("fx", new FGFX);
1805 globals->add_subsystem("voice", new FGVoiceMgr);
1808 ////////////////////////////////////////////////////////////////////
1809 // Initialise the ATC Manager
1810 ////////////////////////////////////////////////////////////////////
1812 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1813 globals->set_ATC_mgr(new FGATCMgr);
1814 globals->get_ATC_mgr()->init();
1816 ////////////////////////////////////////////////////////////////////
1817 // Initialise the AI Manager
1818 ////////////////////////////////////////////////////////////////////
1820 SG_LOG(SG_GENERAL, SG_INFO, " AI Manager");
1821 globals->set_AI_mgr(new FGAIMgr);
1822 globals->get_AI_mgr()->init();
1824 ////////////////////////////////////////////////////////////////////
1825 // Initialise the AI Model Manager
1826 ////////////////////////////////////////////////////////////////////
1827 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1828 globals->add_subsystem("ai_model", new FGAIManager);
1829 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1832 // It's probably a good idea to initialize the top level traffic manager
1833 // After the AI and ATC systems have been initialized properly.
1834 // AI Traffic manager
1835 globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1838 ////////////////////////////////////////////////////////////////////
1839 // Initialize the cockpit subsystem
1840 ////////////////////////////////////////////////////////////////////
1841 if( fgCockpitInit( ¤t_aircraft )) {
1842 // Cockpit initialized ok.
1844 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1849 ////////////////////////////////////////////////////////////////////
1850 // Initialize I/O subsystem.
1851 ////////////////////////////////////////////////////////////////////
1853 globals->get_io()->init();
1854 globals->get_io()->bind();
1857 ////////////////////////////////////////////////////////////////////
1858 // Add a new 2D panel.
1859 ////////////////////////////////////////////////////////////////////
1861 string panel_path = fgGetString("/sim/panel/path",
1862 "Panels/Default/default.xml");
1864 globals->set_current_panel( fgReadPanel(panel_path) );
1865 if (globals->get_current_panel() == 0) {
1866 SG_LOG( SG_INPUT, SG_ALERT,
1867 "Error reading new panel from " << panel_path );
1869 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1870 globals->get_current_panel()->init();
1871 globals->get_current_panel()->bind();
1875 ////////////////////////////////////////////////////////////////////
1876 // Initialize the controls subsystem.
1877 ////////////////////////////////////////////////////////////////////
1879 globals->get_controls()->init();
1880 globals->get_controls()->bind();
1883 ////////////////////////////////////////////////////////////////////
1884 // Initialize the input subsystem.
1885 ////////////////////////////////////////////////////////////////////
1887 globals->add_subsystem("input", new FGInput);
1890 ////////////////////////////////////////////////////////////////////
1891 // Initialize the replay subsystem
1892 ////////////////////////////////////////////////////////////////////
1893 globals->add_subsystem("replay", new FGReplay);
1895 ////////////////////////////////////////////////////////////////////
1896 // Bind and initialize subsystems.
1897 ////////////////////////////////////////////////////////////////////
1899 globals->get_subsystem_mgr()->bind();
1900 globals->get_subsystem_mgr()->init();
1902 ////////////////////////////////////////////////////////////////////
1903 // Initialize multiplayer subsystem
1904 ////////////////////////////////////////////////////////////////////
1906 globals->set_multiplayer_mgr(new FGMultiplayMgr);
1907 globals->get_multiplayer_mgr()->init();
1909 ////////////////////////////////////////////////////////////////////////
1910 // Initialize the Nasal interpreter.
1911 // Do this last, so that the loaded scripts see initialized state
1912 ////////////////////////////////////////////////////////////////////////
1913 FGNasalSys* nasal = new FGNasalSys();
1914 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1917 // initialize methods that depend on other subsystems.
1918 globals->get_subsystem_mgr()->postinit();
1920 ////////////////////////////////////////////////////////////////////////
1921 // End of subsystem initialization.
1922 ////////////////////////////////////////////////////////////////////
1924 SG_LOG( SG_GENERAL, SG_INFO, endl);
1926 // Save the initial state for future
1928 globals->saveInitialState();
1934 void fgReInitSubsystems()
1936 // static const SGPropertyNode *longitude
1937 // = fgGetNode("/sim/presets/longitude-deg");
1938 // static const SGPropertyNode *latitude
1939 // = fgGetNode("/sim/presets/latitude-deg");
1940 static const SGPropertyNode *altitude
1941 = fgGetNode("/sim/presets/altitude-ft");
1942 static const SGPropertyNode *master_freeze
1943 = fgGetNode("/sim/freeze/master");
1945 SG_LOG( SG_GENERAL, SG_INFO,
1946 "fgReInitSubsystems(): /position/altitude = "
1947 << altitude->getDoubleValue() );
1949 bool freeze = master_freeze->getBoolValue();
1951 fgSetBool("/sim/freeze/master", true);
1953 fgSetBool("/sim/crashed", false);
1955 // Force reupdating the positions of the ai 3d models. They are used for
1956 // initializing ground level for the FDM.
1957 globals->get_subsystem("ai_model")->reinit();
1959 // Initialize the FDM
1962 // allocates structures so must happen before any of the flight
1963 // model or control parameters are set
1964 fgAircraftInit(); // In the future this might not be the case.
1966 // reload offsets from config defaults
1967 globals->get_viewmgr()->reinit();
1971 globals->get_controls()->reset_all();
1973 fgUpdateLocalTime();
1975 // re-init to proper time of day setting
1979 fgSetBool("/sim/freeze/master", false);
1981 fgSetBool("/sim/sceneryloaded",false);