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.
30 #include <string.h> // strcmp()
32 #if defined( unix ) || defined( __CYGWIN__ )
33 # include <unistd.h> // for gethostname()
35 #if defined( _MSC_VER) || defined(__MINGW32__)
36 # include <direct.h> // for getcwd()
37 # define getcwd _getcwd
40 // work around a stdc++ lib bug in some versions of linux, but doesn't
41 // seem to hurt to have this here for all versions of Linux.
43 # define _G_NO_EXTERN_TEMPLATES
46 #include <simgear/compiler.h>
50 #include <simgear/constants.h>
51 #include <simgear/debug/logstream.hxx>
52 #include <simgear/structure/exception.hxx>
53 #include <simgear/structure/event_mgr.hxx>
54 #include <simgear/math/point3d.hxx>
55 #include <simgear/math/polar3d.hxx>
56 #include <simgear/math/sg_geodesy.hxx>
57 #include <simgear/misc/sg_path.hxx>
58 #include <simgear/misc/interpolator.hxx>
59 #include <simgear/scene/material/matlib.hxx>
60 #include <simgear/scene/model/particles.hxx>
61 #include <simgear/timing/sg_time.hxx>
62 #include <simgear/timing/lowleveltime.h>
64 #include <Aircraft/aircraft.hxx>
65 #include <Aircraft/controls.hxx>
66 #include <Aircraft/replay.hxx>
67 #include <Airports/apt_loader.hxx>
68 #include <Airports/runways.hxx>
69 #include <Airports/simple.hxx>
70 #include <AIModel/AIManager.hxx>
71 #include <ATCDCL/ATCmgr.hxx>
72 #include <ATCDCL/AIMgr.hxx>
73 #include <Autopilot/route_mgr.hxx>
74 #include <Autopilot/xmlauto.hxx>
75 #include <Cockpit/cockpit.hxx>
76 #include <Cockpit/panel.hxx>
77 #include <Cockpit/panel_io.hxx>
79 #include <FDM/SP/ADA.hxx>
80 #include <FDM/SP/ACMS.hxx>
81 #include <FDM/SP/MagicCarpet.hxx>
82 #include <FDM/SP/Balloon.h>
84 #include <FDM/ExternalNet/ExternalNet.hxx>
85 #include <FDM/ExternalPipe/ExternalPipe.hxx>
86 #include <FDM/JSBSim/JSBSim.hxx>
87 #include <FDM/LaRCsim/LaRCsim.hxx>
88 #include <FDM/UFO.hxx>
89 #include <FDM/NullFDM.hxx>
90 #include <FDM/YASim/YASim.hxx>
91 #include <GUI/new_gui.hxx>
92 #include <Include/general.hxx>
93 #include <Input/input.hxx>
94 #include <Instrumentation/instrument_mgr.hxx>
95 #include <Model/acmodel.hxx>
96 #include <AIModel/submodel.hxx>
97 #include <AIModel/AIManager.hxx>
98 #include <Navaids/navdb.hxx>
99 #include <Navaids/navlist.hxx>
100 #include <Scenery/scenery.hxx>
101 #include <Scenery/tilemgr.hxx>
102 #include <Scripting/NasalSys.hxx>
103 #include <Sound/fg_fx.hxx>
104 #include <Sound/beacon.hxx>
105 #include <Sound/morse.hxx>
106 #include <Sound/voice.hxx>
107 #include <Systems/system_mgr.hxx>
108 #include <Time/light.hxx>
109 #include <Time/sunsolver.hxx>
110 #include <Time/tmp.hxx>
111 #include <Traffic/TrafficMgr.hxx>
112 #include <MultiPlayer/multiplaymgr.hxx>
114 #include <Environment/environment_mgr.hxx>
116 #include "fg_init.hxx"
118 #include "fg_commands.hxx"
119 #include "fg_props.hxx"
120 #include "options.hxx"
121 #include "globals.hxx"
122 #include "logger.hxx"
123 #include "renderer.hxx"
124 #include "viewmgr.hxx"
128 # include <CoreFoundation/CoreFoundation.h>
134 extern const char *default_root;
138 // Scan the command line options for the specified option and return
140 static string fgScanForOption( const string& option, int argc, char **argv ) {
143 if (hostname == NULL)
146 gethostname(_hostname, 256);
147 hostname = strdup(_hostname);
148 free_hostname = true;
151 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
153 int len = option.length();
156 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
158 string arg = argv[i];
159 if ( arg.find( option ) == 0 ) {
160 return arg.substr( len );
170 // Scan the user config files for the specified option and return
172 static string fgScanForOption( const string& option, const string& path ) {
173 sg_gzifstream in( path );
174 if ( !in.is_open() ) {
178 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
180 int len = option.length();
183 while ( ! in.eof() ) {
185 getline( in, line, '\n' );
187 // catch extraneous (DOS) line ending character
188 if ( line[line.length() - 1] < 32 ) {
189 line = line.substr( 0, line.length()-1 );
192 if ( line.find( option ) == 0 ) {
193 return line.substr( len );
202 // Scan the user config files for the specified option and return
204 static string fgScanForOption( const string& option ) {
207 #if defined( unix ) || defined( __CYGWIN__ )
208 // Next check home directory for .fgfsrc.hostname file
210 if ( homedir != NULL ) {
211 SGPath config( homedir );
212 config.append( ".fgfsrc" );
213 config.concat( "." );
214 config.concat( hostname );
215 arg = fgScanForOption( option, config.str() );
220 // Next check home directory for .fgfsrc file
222 if ( homedir != NULL ) {
223 SGPath config( homedir );
224 config.append( ".fgfsrc" );
225 arg = fgScanForOption( option, config.str() );
230 // Check for $fg_root/system.fgfsrc
231 SGPath config( globals->get_fg_root() );
232 config.append( "system.fgfsrc" );
233 arg = fgScanForOption( option, config.str() );
240 // Read in configuration (files and command line options) but only set
242 bool fgInitFGRoot ( int argc, char **argv ) {
245 // First parse command line options looking for --fg-root=, this
246 // will override anything specified in a config file
247 root = fgScanForOption( "--fg-root=", argc, argv);
249 // Check in one of the user configuration files.
251 root = fgScanForOption( "--fg-root=" );
253 // Next check if fg-root is set as an env variable
254 if ( root.empty() ) {
255 char *envp = ::getenv( "FG_ROOT" );
256 if ( envp != NULL ) {
261 // Otherwise, default to a random compiled-in location if we can't
262 // find fg-root any other way.
263 if ( root.empty() ) {
264 #if defined( __CYGWIN__ )
265 root = "/FlightGear";
266 #elif defined( WIN32 )
267 root = "\\FlightGear";
268 #elif defined(__APPLE__)
270 The following code looks for the base package inside the application
271 bundle, in the standard Contents/Resources location.
273 CFURLRef resourcesUrl = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
275 // look for a 'data' subdir
276 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, resourcesUrl, CFSTR("data"), true);
278 // now convert down to a path, and the a c-string
279 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
280 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
282 CFRelease(resourcesUrl);
290 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
291 globals->set_fg_root(root);
297 // Read in configuration (files and command line options) but only set
299 bool fgInitFGAircraft ( int argc, char **argv ) {
302 // First parse command line options looking for --aircraft=, this
303 // will override anything specified in a config file
304 aircraft = fgScanForOption( "--aircraft=", argc, argv );
305 if ( aircraft.empty() ) {
306 // check synonym option
307 aircraft = fgScanForOption( "--vehicle=", argc, argv );
310 // Check in one of the user configuration files.
311 if ( aircraft.empty() ) {
312 aircraft = fgScanForOption( "--aircraft=" );
314 if ( aircraft.empty() ) {
315 aircraft = fgScanForOption( "--vehicle=" );
318 // if an aircraft was specified, set the property name
319 if ( !aircraft.empty() ) {
320 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
321 fgSetString("/sim/aircraft", aircraft.c_str() );
323 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
330 // Return the current base package version
331 string fgBasePackageVersion() {
332 SGPath base_path( globals->get_fg_root() );
333 base_path.append("version");
335 sg_gzifstream in( base_path.str() );
336 if ( !in.is_open() ) {
337 SGPath old_path( globals->get_fg_root() );
338 old_path.append( "Thanks" );
339 sg_gzifstream old( old_path.str() );
340 if ( !old.is_open() ) {
343 return "[old version]";
354 // Initialize the localization
355 SGPropertyNode *fgInitLocale(const char *language) {
356 SGPropertyNode *c_node = NULL, *d_node = NULL;
357 SGPropertyNode *intl = fgGetNode("/sim/intl");
359 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
361 // localization not defined
366 // Select the proper language from the list
368 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
369 for (unsigned int i = 0; i < locale.size(); i++) {
371 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
372 for (unsigned int j = 0; j < lang.size(); j++) {
374 if (!strcmp(lang[j]->getStringValue(), language)) {
383 d_node = intl->getChild("locale");
387 // Check for localized font
388 SGPropertyNode *font_n = c_node->getNode("font", true);
389 if ( !strcmp(font_n->getStringValue(), "") )
390 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
394 // Load the default strings
396 SGPath d_path( globals->get_fg_root() );
398 const char *d_path_str = d_node->getStringValue("strings");
400 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << d_node->getPath() << "/strings.");
404 d_path.append(d_path_str);
405 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << d_path.str());
407 SGPropertyNode *strings = c_node->getNode("strings");
409 readProperties(d_path.str(), strings);
410 } catch (const sg_exception &) {
411 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
416 // Load the language specific strings
418 if (c_node != d_node) {
419 SGPath c_path( globals->get_fg_root() );
421 const char *c_path_str = c_node->getStringValue("strings");
423 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << c_node->getPath() << "/strings");
427 c_path.append(c_path_str);
428 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << c_path.str());
431 readProperties(c_path.str(), strings);
432 } catch (const sg_exception &) {
433 SG_LOG(SG_GENERAL, SG_ALERT,
434 "Unable to read the localized strings from " << c_path.str());
444 // Initialize the localization routines
445 bool fgDetectLanguage() {
446 const char *language = ::getenv("LANG");
448 if (language == NULL) {
449 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
453 SGPropertyNode *locale = fgInitLocale(language);
455 SG_LOG(SG_GENERAL, SG_ALERT,
456 "No internationalization settings specified in preferences.xml" );
461 globals->set_locale( locale );
466 // Attempt to locate and parse the various non-XML config files in order
467 // from least precidence to greatest precidence
469 do_options (int argc, char ** argv)
471 // Check for $fg_root/system.fgfsrc
472 SGPath config( globals->get_fg_root() );
473 config.append( "system.fgfsrc" );
474 fgParseOptions(config.str());
476 #if defined( unix ) || defined( __CYGWIN__ )
477 config.concat( "." );
478 config.concat( hostname );
479 fgParseOptions(config.str());
482 // Check for ~/.fgfsrc
483 if ( homedir != NULL ) {
484 config.set( homedir );
485 config.append( ".fgfsrc" );
486 fgParseOptions(config.str());
489 #if defined( unix ) || defined( __CYGWIN__ )
490 // Check for ~/.fgfsrc.hostname
491 config.concat( "." );
492 config.concat( hostname );
493 fgParseOptions(config.str());
496 // Parse remaining command line options
497 // These will override anything specified in a config file
498 fgParseArgs(argc, argv);
502 static string fgFindAircraftPath( const SGPath &path, const string &aircraft,
503 SGPropertyNode *cache, int depth = 0 )
505 const int MAXDEPTH = 1;
508 ulDir *dirp = ulOpenDir(path.str().c_str());
510 cerr << "Unable to open aircraft directory '" << path.str() << '\'' << endl;
515 while ((dire = ulReadDir(dirp)) != NULL) {
517 if (depth > MAXDEPTH)
520 if (!strcmp("CVS", dire->d_name) || !strcmp(".", dire->d_name)
521 || !strcmp("..", dire->d_name) || !strcmp("AI", dire->d_name))
525 next.append(dire->d_name);
527 result = fgFindAircraftPath( next, aircraft, cache, depth + 1 );
528 if ( ! result.empty() )
532 int len = strlen(dire->d_name);
533 if (len < 9 || strcmp(dire->d_name + len - 8, "-set.xml"))
539 if (!cache->getChild("aircraft", i++, false))
542 SGPropertyNode *n, *entry = cache->getChild("aircraft", --i, true);
544 n = entry->getNode("file", true);
545 n->setStringValue(dire->d_name);
546 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
548 n = entry->getNode("path", true);
549 n->setStringValue(path.str().c_str());
550 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
552 if ( !strcmp(dire->d_name, aircraft.c_str()) ) {
564 // Read in configuration (file and command line)
565 bool fgInitConfig ( int argc, char **argv ) {
567 // First, set some sane default values
570 // Read global preferences from $FG_ROOT/preferences.xml
571 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
572 fgLoadProps("preferences.xml", globals->get_props());
573 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
575 // Detect the required language as early as possible
576 if ( !fgDetectLanguage() ) {
580 SGPropertyNode autosave;
582 char *envp = ::getenv( "APPDATA" );
584 SGPath config( envp );
585 config.append( "flightgear.org" );
587 if ( homedir != NULL ) {
588 SGPath config( homedir );
589 config.append( ".fgfs" );
591 const char *fg_home = getenv("FG_HOME");
595 // Set /sim/fg-home and don't allow malign code to override it until
596 // Nasal security is set up. Use FG_HOME if necessary.
597 SGPropertyNode *home = fgGetNode("/sim", true);
598 home->removeChild("fg-home", 0, false);
599 home = home->getChild("fg-home", 0, true);
600 home->setStringValue(config.c_str());
601 home->setAttribute(SGPropertyNode::WRITE, false);
603 config.append( "autosave.xml" );
604 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << config.str());
606 readProperties(config.str(), &autosave, SGPropertyNode::USERARCHIVE);
608 SG_LOG(SG_INPUT, SG_DEBUG, "First time reading user settings");
610 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Reading user settings");
612 SGPropertyNode *cache_root = autosave.getNode("sim/startup/path-cache", true);
615 // Scan user config files and command line for a specified aircraft.
616 fgInitFGAircraft(argc, argv);
618 string aircraft = fgGetString( "/sim/aircraft", "" );
619 if ( aircraft.size() > 0 ) {
620 SGPath aircraft_search( globals->get_fg_root() );
621 aircraft_search.append( "Aircraft" );
623 string aircraft_set = aircraft + "-set.xml";
626 // check if the *-set.xml file is already in the cache
627 if (globals->get_fg_root() == cache_root->getStringValue("fg-root", "")) {
628 vector<SGPropertyNode_ptr> cache = cache_root->getChildren("aircraft");
629 for (unsigned int i = 0; i < cache.size(); i++) {
630 const char *name = cache[i]->getStringValue("file", "");
631 if (aircraft_set == name) {
632 const char *path = cache[i]->getStringValue("path", "");
642 if (result.empty()) {
643 // prepare cache for rescan
644 SGPropertyNode *n = cache_root->getNode("fg-root", true);
645 n->setStringValue(globals->get_fg_root().c_str());
646 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
647 cache_root->removeChildren("aircraft");
649 result = fgFindAircraftPath( aircraft_search, aircraft_set, cache_root );
652 if ( !result.empty() ) {
653 fgSetString( "/sim/aircraft-dir", result.c_str() );
654 SGPath full_name( result );
655 full_name.append( aircraft_set );
657 SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
658 << " from " << full_name.str());
660 readProperties( full_name.str(), globals->get_props() );
661 } catch ( const sg_exception &e ) {
662 string message = "Error reading default aircraft: ";
663 message += e.getFormattedMessage();
664 SG_LOG(SG_INPUT, SG_ALERT, message);
668 SG_LOG( SG_INPUT, SG_ALERT, "Cannot find specified aircraft: "
674 SG_LOG( SG_INPUT, SG_ALERT, "No default aircraft specified" );
677 copyProperties(&autosave, globals->get_props());
679 // parse options after loading aircraft to ensure any user
680 // overrides of defaults are honored.
681 do_options(argc, argv);
692 // This function is never used, but maybe useful in the future ???
695 // Preset lon/lat given an airport id
696 static bool fgSetPosFromAirportID( const string& id ) {
700 SG_LOG( SG_GENERAL, SG_INFO,
701 "Attempting to set starting position from airport code " << id );
703 if ( fgFindAirportID( id, &a ) ) {
705 fgSetDouble("/sim/presets/longitude-deg", a->longitude );
706 fgSetDouble("/sim/presets/latitude-deg", a->latitude );
708 // other code depends on the actual postition being set so set
710 fgSetDouble("/position/longitude-deg", a->longitude );
711 fgSetDouble("/position/latitude-deg", a->latitude );
713 SG_LOG( SG_GENERAL, SG_INFO,
714 "Position for " << id << " is (" << a->longitude
715 << ", " << a->latitude << ")" );
725 // Set current tower position lon/lat given an airport id
726 static bool fgSetTowerPosFromAirportID( const string& id) {
727 const FGAirport *a = fgFindAirportID( id);
729 SGGeod tower = a->getTowerLocation();
730 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
731 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
732 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
740 struct FGTowerLocationListener : SGPropertyChangeListener {
741 void valueChanged(SGPropertyNode* node) {
742 const string id(node->getStringValue());
743 fgSetTowerPosFromAirportID(id);
747 void fgInitTowerLocationListener() {
748 fgGetNode("/sim/tower/airport-id", true)
749 ->addChangeListener( new FGTowerLocationListener(), true );
752 // Set current_options lon/lat given an airport id and heading (degrees)
753 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
759 // set initial position from runway and heading
760 SG_LOG( SG_GENERAL, SG_INFO,
761 "Attempting to set starting position from airport code "
762 << id << " heading " << tgt_hdg );
764 if ( ! globals->get_runways()->search( id, (int)tgt_hdg, &r ) ) {
765 SG_LOG( SG_GENERAL, SG_ALERT,
766 "Failed to find a good runway for " << id << '\n' );
769 fgSetString("/sim/atc/runway", r._rwy_no.c_str());
771 double lat2, lon2, az2;
772 double heading = r._heading;
773 double azimuth = heading + 180.0;
774 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
776 SG_LOG( SG_GENERAL, SG_INFO,
777 "runway = " << r._lon << ", " << r._lat
778 << " length = " << r._length * SG_FEET_TO_METER
779 << " heading = " << azimuth );
781 geo_direct_wgs_84 ( 0, r._lat, r._lon, azimuth, r._length * SG_FEET_TO_METER * 0.5
782 - fgGetDouble("/sim/airport/runways/start-offset-m", 5.0),
783 &lat2, &lon2, &az2 );
785 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
787 double odist = fgGetDouble("/sim/presets/offset-distance-nm");
788 odist *= SG_NM_TO_METER;
789 double oaz = azimuth;
790 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
791 oaz = fgGetDouble("/sim/presets/offset-azimuth-deg") + 180;
794 while ( oaz >= 360.0 ) { oaz -= 360.0; }
795 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
801 fgSetDouble("/sim/presets/longitude-deg", lon2 );
802 fgSetDouble("/sim/presets/latitude-deg", lat2 );
803 fgSetDouble("/sim/presets/heading-deg", heading );
805 // other code depends on the actual values being set ...
806 fgSetDouble("/position/longitude-deg", lon2 );
807 fgSetDouble("/position/latitude-deg", lat2 );
808 fgSetDouble("/orientation/heading-deg", heading );
810 SG_LOG( SG_GENERAL, SG_INFO,
811 "Position for " << id << " is ("
813 << lat2 << ") new heading is "
819 // Set current_options lon/lat given an airport id and parkig position name
820 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
824 // can't see an easy way around this const_cast at the moment
825 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
827 SG_LOG( SG_GENERAL, SG_ALERT,
828 "Failed to find airport " << id );
831 FGAirportDynamics* dcs = apt->getDynamics();
833 SG_LOG( SG_GENERAL, SG_ALERT,
834 "Failed to find parking position " << parkpos <<
835 " at airport " << id );
839 int park_index = dcs->getNrOfParkings() - 1;
840 while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
841 if (park_index < 0) {
842 SG_LOG( SG_GENERAL, SG_ALERT,
843 "Failed to find parking position " << parkpos <<
844 " at airport " << id );
847 FGParking* parking = dcs->getParking(park_index);
849 double lat = parking->getLatitude();
850 double lon = parking->getLongitude();
851 double hdg = parking->getHeading();
854 fgSetDouble("/sim/presets/longitude-deg", lon );
855 fgSetDouble("/sim/presets/latitude-deg", lat );
856 fgSetDouble("/sim/presets/heading-deg", hdg );
858 // other code depends on the actual values being set ...
859 fgSetDouble("/position/longitude-deg", lon );
860 fgSetDouble("/position/latitude-deg", lat );
861 fgSetDouble("/orientation/heading-deg", hdg );
863 SG_LOG( SG_GENERAL, SG_INFO,
864 "Position for " << id << " is ("
866 << lat << ") new heading is "
873 // Set current_options lon/lat given an airport id and runway number
874 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
880 // set initial position from airport and runway number
881 SG_LOG( SG_GENERAL, SG_INFO,
882 "Attempting to set starting position for "
883 << id << ":" << rwy );
885 if ( ! globals->get_runways()->search( id, rwy, &r ) ) {
886 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
887 "Failed to find runway " << rwy <<
888 " at airport " << id << ". Using default runway." );
891 fgSetString("/sim/atc/runway", r._rwy_no.c_str());
893 double lat2, lon2, az2;
894 double heading = r._heading;
895 double azimuth = heading + 180.0;
896 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
898 SG_LOG( SG_GENERAL, SG_INFO,
899 "runway = " << r._lon << ", " << r._lat
900 << " length = " << r._length * SG_FEET_TO_METER
901 << " heading = " << azimuth );
903 geo_direct_wgs_84 ( 0, r._lat, r._lon, azimuth, r._length * SG_FEET_TO_METER * 0.5
904 - fgGetDouble("/sim/airport/runways/start-offset-m", 5.0),
905 &lat2, &lon2, &az2 );
907 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON )
910 double odist = fgGetDouble("/sim/presets/offset-distance-nm");
911 odist *= SG_NM_TO_METER;
912 double oaz = azimuth;
913 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON )
915 oaz = fgGetDouble("/sim/presets/offset-azimuth-deg") + 180;
916 heading = fgGetDouble("/sim/presets/heading-deg");
918 while ( oaz >= 360.0 ) { oaz -= 360.0; }
919 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
925 fgSetDouble("/sim/presets/longitude-deg", lon2 );
926 fgSetDouble("/sim/presets/latitude-deg", lat2 );
927 fgSetDouble("/sim/presets/heading-deg", heading );
929 // other code depends on the actual values being set ...
930 fgSetDouble("/position/longitude-deg", lon2 );
931 fgSetDouble("/position/latitude-deg", lat2 );
932 fgSetDouble("/orientation/heading-deg", heading );
934 SG_LOG( SG_GENERAL, SG_INFO,
935 "Position for " << id << " is ("
937 << lat2 << ") new heading is "
944 static void fgSetDistOrAltFromGlideSlope() {
945 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
946 string apt_id = fgGetString("/sim/presets/airport-id");
947 double gs = fgGetDouble("/sim/presets/glideslope-deg")
948 * SG_DEGREES_TO_RADIANS ;
949 double od = fgGetDouble("/sim/presets/offset-distance-nm");
950 double alt = fgGetDouble("/sim/presets/altitude-ft");
952 double apt_elev = 0.0;
953 if ( ! apt_id.empty() ) {
954 apt_elev = fgGetAirportElev( apt_id );
955 if ( apt_elev < -9990.0 ) {
962 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
963 // set altitude from glideslope and offset-distance
964 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
965 alt = fabs(od*tan(gs)) + apt_elev;
966 fgSetDouble("/sim/presets/altitude-ft", alt);
967 fgSetBool("/sim/presets/onground", false);
968 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
970 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
971 // set offset-distance from glideslope and altitude
972 od = (alt - apt_elev) / tan(gs);
973 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
974 fgSetDouble("/sim/presets/offset-distance-nm", od);
975 fgSetBool("/sim/presets/onground", false);
976 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
978 } else if( fabs(gs) > 0.01 ) {
979 SG_LOG( SG_GENERAL, SG_ALERT,
980 "Glideslope given but not altitude or offset-distance." );
981 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
982 fgSetDouble("/sim/presets/glideslope-deg", 0);
983 fgSetBool("/sim/presets/onground", true);
988 // Set current_options lon/lat given an airport id and heading (degrees)
989 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
991 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
993 // set initial position from runway and heading
995 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
996 << id << ":" << freq );
998 double lon = nav->get_lon();
999 double lat = nav->get_lat();
1001 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON )
1003 double odist = fgGetDouble("/sim/presets/offset-distance-nm")
1005 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth-deg"))
1007 while ( oaz >= 360.0 ) { oaz -= 360.0; }
1008 double olat, olon, az2;
1009 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
1016 fgSetDouble("/sim/presets/longitude-deg", lon );
1017 fgSetDouble("/sim/presets/latitude-deg", lat );
1019 // other code depends on the actual values being set ...
1020 fgSetDouble("/position/longitude-deg", lon );
1021 fgSetDouble("/position/latitude-deg", lat );
1022 fgSetDouble("/orientation/heading-deg",
1023 fgGetDouble("/sim/presets/heading-deg") );
1025 SG_LOG( SG_GENERAL, SG_INFO,
1026 "Position for " << id << ":" << freq << " is ("
1027 << lon << ", "<< lat << ")" );
1031 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1032 << id << ":" << freq );
1037 // Set current_options lon/lat given an aircraft carrier id
1038 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
1040 // set initial position from runway and heading
1044 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
1045 double lon = geodPos.getLongitudeDeg();
1046 double lat = geodPos.getLatitudeDeg();
1047 double alt = geodPos.getElevationFt();
1049 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1050 << carrier << " at lat = " << lat << ", lon = " << lon
1051 << ", alt = " << alt << ", heading = " << heading);
1053 fgSetDouble("/sim/presets/longitude-deg", lon);
1054 fgSetDouble("/sim/presets/latitude-deg", lat);
1055 fgSetDouble("/sim/presets/altitude-ft", alt);
1056 fgSetDouble("/sim/presets/heading-deg", heading);
1057 fgSetDouble("/position/longitude-deg", lon);
1058 fgSetDouble("/position/latitude-deg", lat);
1059 fgSetDouble("/position/altitude-ft", alt);
1060 fgSetDouble("/orientation/heading-deg", heading);
1062 fgSetString("/sim/presets/speed-set", "UVW");
1063 fgSetDouble("/velocities/uBody-fps", uvw(0));
1064 fgSetDouble("/velocities/vBody-fps", uvw(1));
1065 fgSetDouble("/velocities/wBody-fps", uvw(2));
1066 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
1067 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
1068 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
1070 fgSetBool("/sim/presets/onground", true);
1074 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
1080 // Set current_options lon/lat given an airport id and heading (degrees)
1081 static bool fgSetPosFromFix( const string& id ) {
1084 // set initial position from runway and heading
1085 if ( globals->get_fixlist()->query( id.c_str(), &fix ) ) {
1086 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1089 double lon = fix.get_lon();
1090 double lat = fix.get_lat();
1092 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON )
1094 double odist = fgGetDouble("/sim/presets/offset-distance-nm")
1096 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth-deg"))
1098 while ( oaz >= 360.0 ) { oaz -= 360.0; }
1099 double olat, olon, az2;
1100 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
1107 fgSetDouble("/sim/presets/longitude-deg", lon );
1108 fgSetDouble("/sim/presets/latitude-deg", lat );
1110 // other code depends on the actual values being set ...
1111 fgSetDouble("/position/longitude-deg", lon );
1112 fgSetDouble("/position/latitude-deg", lat );
1113 fgSetDouble("/orientation/heading-deg",
1114 fgGetDouble("/sim/presets/heading-deg") );
1116 SG_LOG( SG_GENERAL, SG_INFO,
1117 "Position for " << id << " is ("
1118 << lon << ", "<< lat << ")" );
1122 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1130 * Initialize vor/ndb/ils/fix list management and query systems (as
1131 * well as simple airport db list)
1136 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
1138 SGPath aptdb( globals->get_fg_root() );
1139 aptdb.append( "Airports/apt.dat" );
1141 SGPath p_metar( globals->get_fg_root() );
1142 p_metar.append( "Airports/metar.dat" );
1144 FGAirportList *airports = new FGAirportList();
1145 globals->set_airports( airports );
1146 FGRunwayList *runways = new FGRunwayList();
1147 globals->set_runways( runways );
1149 fgAirportDBLoad( airports, runways, aptdb.str(), p_metar.str() );
1151 FGNavList *navlist = new FGNavList;
1152 FGNavList *loclist = new FGNavList;
1153 FGNavList *gslist = new FGNavList;
1154 FGNavList *dmelist = new FGNavList;
1155 FGNavList *mkrlist = new FGNavList;
1156 FGNavList *tacanlist = new FGNavList;
1157 FGNavList *carrierlist = new FGNavList;
1158 FGTACANList *channellist = new FGTACANList;
1160 globals->set_navlist( navlist );
1161 globals->set_loclist( loclist );
1162 globals->set_gslist( gslist );
1163 globals->set_dmelist( dmelist );
1164 globals->set_mkrlist( mkrlist );
1165 globals->set_tacanlist( tacanlist );
1166 globals->set_carrierlist( carrierlist );
1167 globals->set_channellist( channellist );
1169 if ( !fgNavDBInit(airports, navlist, loclist, gslist, dmelist, mkrlist, tacanlist, carrierlist, channellist) ) {
1170 SG_LOG( SG_GENERAL, SG_ALERT,
1171 "Problems loading one or more navigational database" );
1174 if ( fgGetBool("/sim/navdb/localizers/auto-align", true) ) {
1175 // align all the localizers with their corresponding runways
1176 // since data sources are good for cockpit navigation
1177 // purposes, but not always to the error tolerances needed to
1178 // exactly place these items.
1180 = fgGetDouble( "/sim/navdb/localizers/auto-align-threshold-deg",
1182 fgNavDBAlignLOCwithRunway( runways, loclist, threshold );
1185 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1186 SGPath p_fix( globals->get_fg_root() );
1187 p_fix.append( "Navaids/fix.dat" );
1188 FGFixList *fixlist = new FGFixList;
1189 fixlist->init( p_fix );
1190 globals->set_fixlist( fixlist );
1192 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
1193 SGPath p_awy( globals->get_fg_root() );
1194 p_awy.append( "Navaids/awy.dat" );
1195 FGAirwayNetwork *awyNet = new FGAirwayNetwork;
1196 //cerr << "Loading Airways" << endl;
1197 awyNet->load (p_awy );
1199 //cerr << "initializing airways" << endl;
1200 globals->set_airwaynet( awyNet );
1206 // Set the initial position based on presets (or defaults)
1207 bool fgInitPosition() {
1208 // cout << "fgInitPosition()" << endl;
1209 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1210 * SG_DEGREES_TO_RADIANS ;
1211 double od = fgGetDouble("/sim/presets/offset-distance-nm");
1212 double alt = fgGetDouble("/sim/presets/altitude-ft");
1214 bool set_pos = false;
1216 // If glideslope is specified, then calculate offset-distance or
1217 // altitude relative to glide slope if either of those was not
1219 if ( fabs( gs ) > 0.01 ) {
1220 fgSetDistOrAltFromGlideSlope();
1224 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1225 // If not, check for an airport-id and use that.
1226 // If not, default to the middle of the KSFO field.
1227 // The default values for lon/lat are deliberately out of range
1228 // so that the airport-id can take effect; valid lon/lat will
1229 // override airport-id, however.
1230 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1231 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1232 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1233 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1238 string apt = fgGetString("/sim/presets/airport-id");
1239 string rwy_no = fgGetString("/sim/presets/runway");
1240 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1241 string vor = fgGetString("/sim/presets/vor-id");
1242 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1243 string ndb = fgGetString("/sim/presets/ndb-id");
1244 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1245 string carrier = fgGetString("/sim/presets/carrier");
1246 string parkpos = fgGetString("/sim/presets/parkpos");
1247 string fix = fgGetString("/sim/presets/fix");
1248 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1249 double hdg = hdg_preset->getDoubleValue();
1251 // save some start parameters, so that we can later say what the
1252 // user really requested. TODO generalize that and move it to options.cxx
1253 static bool start_options_saved = false;
1254 if (!start_options_saved) {
1255 start_options_saved = true;
1256 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1258 opt->setDoubleValue("latitude-deg", lat_deg);
1259 opt->setDoubleValue("longitude-deg", lon_deg);
1260 opt->setDoubleValue("heading-deg", hdg);
1261 opt->setStringValue("airport", apt.c_str());
1262 opt->setStringValue("runway", rwy_no.c_str());
1266 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1268 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1269 // An airport + parking position is requested
1270 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1271 // set tower position
1272 fgSetString("/sim/tower/airport-id", apt.c_str());
1277 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1278 // An airport + runway is requested
1279 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1280 // set tower position (a little off the heading for single
1282 fgSetString("/sim/tower/airport-id", apt.c_str());
1287 if ( !set_pos && !apt.empty() ) {
1288 // An airport is requested (find runway closest to hdg)
1289 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1290 // set tower position (a little off the heading for single
1292 fgSetString("/sim/tower/airport-id", apt.c_str());
1297 if (hdg_preset->getDoubleValue() > 9990.0)
1298 hdg_preset->setDoubleValue(hdg);
1300 if ( !set_pos && !vor.empty() ) {
1301 // a VOR is requested
1302 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1307 if ( !set_pos && !ndb.empty() ) {
1308 // an NDB is requested
1309 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1314 if ( !set_pos && !carrier.empty() ) {
1315 // an aircraft carrier is requested
1316 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1321 if ( !set_pos && !fix.empty() ) {
1322 // a Fix is requested
1323 if ( fgSetPosFromFix( fix ) ) {
1329 // No lon/lat specified, no airport specified, default to
1330 // middle of KSFO field.
1331 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1332 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1335 fgSetDouble( "/position/longitude-deg",
1336 fgGetDouble("/sim/presets/longitude-deg") );
1337 fgSetDouble( "/position/latitude-deg",
1338 fgGetDouble("/sim/presets/latitude-deg") );
1339 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1341 // determine if this should be an on-ground or in-air start
1342 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1343 fgSetBool("/sim/presets/onground", false);
1345 fgSetBool("/sim/presets/onground", true);
1352 // General house keeping initializations
1353 bool fgInitGeneral() {
1356 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1357 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1359 root = globals->get_fg_root();
1360 if ( ! root.length() ) {
1361 // No root path set? Then bail ...
1362 SG_LOG( SG_GENERAL, SG_ALERT,
1363 "Cannot continue without a path to the base package "
1364 << "being defined." );
1367 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1369 globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1371 char buf[512], *cwd = getcwd(buf, 511);
1373 SGPropertyNode *curr = fgGetNode("/sim", true);
1374 curr->removeChild("fg-current", 0, false);
1375 curr = curr->getChild("fg-current", 0, true);
1376 curr->setStringValue(cwd ? cwd : "");
1377 curr->setAttribute(SGPropertyNode::WRITE, false);
1382 // Initialize the flight model subsystem. This just creates the
1383 // object. The actual fdm initialization is delayed until we get a
1384 // proper scenery elevation hit. This is checked for in main.cxx
1388 if ( cur_fdm_state ) {
1389 delete cur_fdm_state;
1393 double dt = 1.0 / fgGetInt("/sim/model-hz");
1394 string model = fgGetString("/sim/flight-model");
1396 if ( model == "larcsim" ) {
1397 cur_fdm_state = new FGLaRCsim( dt );
1398 } else if ( model == "jsb" ) {
1399 cur_fdm_state = new FGJSBsim( dt );
1401 } else if ( model == "ada" ) {
1402 cur_fdm_state = new FGADA( dt );
1403 } else if ( model == "acms" ) {
1404 cur_fdm_state = new FGACMS( dt );
1405 } else if ( model == "balloon" ) {
1406 cur_fdm_state = new FGBalloonSim( dt );
1407 } else if ( model == "magic" ) {
1408 cur_fdm_state = new FGMagicCarpet( dt );
1410 } else if ( model == "ufo" ) {
1411 cur_fdm_state = new FGUFO( dt );
1412 } else if ( model == "external" ) {
1413 // external is a synonym for "--fdm=null" and is
1414 // maintained here for backwards compatibility
1415 cur_fdm_state = new FGNullFDM( dt );
1416 } else if ( model.find("network") == 0 ) {
1417 string host = "localhost";
1421 string net_options = model.substr(8);
1422 string::size_type begin, end;
1425 end = net_options.find( ",", begin );
1426 if ( end != string::npos ) {
1427 host = net_options.substr(begin, end - begin);
1431 end = net_options.find( ",", begin );
1432 if ( end != string::npos ) {
1433 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1437 end = net_options.find( ",", begin );
1438 if ( end != string::npos ) {
1439 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1443 end = net_options.find( ",", begin );
1444 if ( end != string::npos ) {
1445 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1448 cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1449 } else if ( model.find("pipe") == 0 ) {
1450 // /* old */ string pipe_path = model.substr(5);
1451 // /* old */ cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1452 string pipe_path = "";
1453 string pipe_protocol = "";
1454 string pipe_options = model.substr(5);
1455 string::size_type begin, end;
1458 end = pipe_options.find( ",", begin );
1459 if ( end != string::npos ) {
1460 pipe_path = pipe_options.substr(begin, end - begin);
1463 // protocol (last option)
1464 pipe_protocol = pipe_options.substr(begin);
1465 cur_fdm_state = new FGExternalPipe( dt, pipe_path, pipe_protocol );
1466 } else if ( model == "null" ) {
1467 cur_fdm_state = new FGNullFDM( dt );
1468 } else if ( model == "yasim" ) {
1469 cur_fdm_state = new YASim( dt );
1471 throw sg_throwable(string("Unrecognized flight model '") + model
1472 + "', cannot init flight dynamics model.");
1476 // Initialize view parameters
1478 // force update of model so that viewer can get some data...
1479 globals->get_aircraft_model()->update(0);
1480 // run update for current view so that data is current...
1481 globals->get_viewmgr()->update(0);
1485 SGTime *fgInitTime() {
1487 static const SGPropertyNode *longitude
1488 = fgGetNode("/position/longitude-deg");
1489 static const SGPropertyNode *latitude
1490 = fgGetNode("/position/latitude-deg");
1491 static const SGPropertyNode *cur_time_override
1492 = fgGetNode("/sim/time/cur-time-override", true);
1494 SGPath zone( globals->get_fg_root() );
1495 zone.append( "Timezone" );
1496 SGTime *t = new SGTime( longitude->getDoubleValue()
1497 * SGD_DEGREES_TO_RADIANS,
1498 latitude->getDoubleValue()
1499 * SGD_DEGREES_TO_RADIANS,
1501 cur_time_override->getLongValue() );
1503 globals->set_warp_delta( 0 );
1505 t->update( 0.0, 0.0,
1506 cur_time_override->getLongValue(),
1507 globals->get_warp() );
1513 // set up a time offset (aka warp) if one is specified
1514 void fgInitTimeOffset() {
1515 static const SGPropertyNode *longitude
1516 = fgGetNode("/position/longitude-deg");
1517 static const SGPropertyNode *latitude
1518 = fgGetNode("/position/latitude-deg");
1519 static const SGPropertyNode *cur_time_override
1520 = fgGetNode("/sim/time/cur-time-override", true);
1522 // Handle potential user specified time offsets
1523 int orig_warp = globals->get_warp();
1524 SGTime *t = globals->get_time_params();
1525 time_t cur_time = t->get_cur_time();
1526 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1527 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1528 time_t aircraftLocalTime =
1529 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1531 // Okay, we now have several possible scenarios
1532 int offset = fgGetInt("/sim/startup/time-offset");
1533 string offset_type = fgGetString("/sim/startup/time-offset-type");
1536 if ( offset_type == "real" ) {
1538 } else if ( offset_type == "dawn" ) {
1539 warp = fgTimeSecondsUntilSunAngle( cur_time,
1540 longitude->getDoubleValue()
1541 * SGD_DEGREES_TO_RADIANS,
1542 latitude->getDoubleValue()
1543 * SGD_DEGREES_TO_RADIANS,
1545 } else if ( offset_type == "morning" ) {
1546 warp = fgTimeSecondsUntilSunAngle( cur_time,
1547 longitude->getDoubleValue()
1548 * SGD_DEGREES_TO_RADIANS,
1549 latitude->getDoubleValue()
1550 * SGD_DEGREES_TO_RADIANS,
1552 } else if ( offset_type == "noon" ) {
1553 warp = fgTimeSecondsUntilSunAngle( cur_time,
1554 longitude->getDoubleValue()
1555 * SGD_DEGREES_TO_RADIANS,
1556 latitude->getDoubleValue()
1557 * SGD_DEGREES_TO_RADIANS,
1559 } else if ( offset_type == "afternoon" ) {
1560 warp = fgTimeSecondsUntilSunAngle( cur_time,
1561 longitude->getDoubleValue()
1562 * SGD_DEGREES_TO_RADIANS,
1563 latitude->getDoubleValue()
1564 * SGD_DEGREES_TO_RADIANS,
1566 } else if ( offset_type == "dusk" ) {
1567 warp = fgTimeSecondsUntilSunAngle( cur_time,
1568 longitude->getDoubleValue()
1569 * SGD_DEGREES_TO_RADIANS,
1570 latitude->getDoubleValue()
1571 * SGD_DEGREES_TO_RADIANS,
1573 } else if ( offset_type == "evening" ) {
1574 warp = fgTimeSecondsUntilSunAngle( cur_time,
1575 longitude->getDoubleValue()
1576 * SGD_DEGREES_TO_RADIANS,
1577 latitude->getDoubleValue()
1578 * SGD_DEGREES_TO_RADIANS,
1580 } else if ( offset_type == "midnight" ) {
1581 warp = fgTimeSecondsUntilSunAngle( cur_time,
1582 longitude->getDoubleValue()
1583 * SGD_DEGREES_TO_RADIANS,
1584 latitude->getDoubleValue()
1585 * SGD_DEGREES_TO_RADIANS,
1587 } else if ( offset_type == "system-offset" ) {
1590 } else if ( offset_type == "gmt-offset" ) {
1591 warp = offset - (currGMT - systemLocalTime);
1593 } else if ( offset_type == "latitude-offset" ) {
1594 warp = offset - (aircraftLocalTime - systemLocalTime);
1596 } else if ( offset_type == "system" ) {
1597 warp = offset - (systemLocalTime - currGMT) - cur_time;
1598 } else if ( offset_type == "gmt" ) {
1599 warp = offset - cur_time;
1600 } else if ( offset_type == "latitude" ) {
1601 warp = offset - (aircraftLocalTime - currGMT)- cur_time;
1603 SG_LOG( SG_GENERAL, SG_ALERT,
1604 "FG_TIME::Unsupported offset type " << offset_type );
1607 globals->set_warp( orig_warp + warp );
1608 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1609 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1610 cur_time_override->getLongValue(),
1611 globals->get_warp() );
1613 SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = "
1614 << globals->get_warp() );
1618 // This is the top level init routine which calls all the other
1619 // initialization routines. If you are adding a subsystem to flight
1620 // gear, its initialization call should located in this routine.
1621 // Returns non-zero if a problem encountered.
1622 bool fgInitSubsystems() {
1623 // static const SGPropertyNode *longitude
1624 // = fgGetNode("/sim/presets/longitude-deg");
1625 // static const SGPropertyNode *latitude
1626 // = fgGetNode("/sim/presets/latitude-deg");
1627 // static const SGPropertyNode *altitude
1628 // = fgGetNode("/sim/presets/altitude-ft");
1629 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1630 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1632 ////////////////////////////////////////////////////////////////////
1633 // Initialize the event manager subsystem.
1634 ////////////////////////////////////////////////////////////////////
1636 globals->get_event_mgr()->init();
1637 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1639 ////////////////////////////////////////////////////////////////////
1640 // Initialize the property interpolator subsystem. Put into the INIT
1641 // group because the "nasal" subsystem may need it at GENERAL take-down.
1642 ////////////////////////////////////////////////////////////////////
1643 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1646 ////////////////////////////////////////////////////////////////////
1647 // Add the FlightGear property utilities.
1648 ////////////////////////////////////////////////////////////////////
1649 globals->add_subsystem("properties", new FGProperties);
1651 ////////////////////////////////////////////////////////////////////
1652 // Initialize the material property subsystem.
1653 ////////////////////////////////////////////////////////////////////
1655 SGPath mpath( globals->get_fg_root() );
1656 mpath.append( "materials.xml" );
1657 string season = fgGetString("/sim/startup/season", "summer");
1658 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(), season.c_str(),
1659 globals->get_props()) ) {
1660 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1665 ////////////////////////////////////////////////////////////////////
1666 // Initialize the scenery management subsystem.
1667 ////////////////////////////////////////////////////////////////////
1669 if ( globals->get_tile_mgr()->init() ) {
1670 // Load the local scenery data
1671 double visibility_meters = fgGetDouble("/environment/visibility-m");
1673 globals->get_tile_mgr()->update( visibility_meters );
1675 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1679 globals->get_scenery()->get_scene_graph()
1680 ->addChild(simgear::Particles::getCommonRoot());
1682 ////////////////////////////////////////////////////////////////////
1683 // Initialize the flight model subsystem.
1684 ////////////////////////////////////////////////////////////////////
1688 // allocates structures so must happen before any of the flight
1689 // model or control parameters are set
1690 fgAircraftInit(); // In the future this might not be the case.
1693 ////////////////////////////////////////////////////////////////////
1694 // Initialize the weather subsystem.
1695 ////////////////////////////////////////////////////////////////////
1697 // Initialize the weather modeling subsystem
1698 globals->add_subsystem("environment", new FGEnvironmentMgr);
1701 ////////////////////////////////////////////////////////////////////
1702 // Initialize the aircraft systems and instrumentation (before the
1704 ////////////////////////////////////////////////////////////////////
1706 globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1707 globals->add_subsystem("systems", new FGSystemMgr);
1709 ////////////////////////////////////////////////////////////////////
1710 // Initialize the XML Autopilot subsystem.
1711 ////////////////////////////////////////////////////////////////////
1713 globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1714 globals->add_subsystem( "route-manager", new FGRouteMgr );
1717 ////////////////////////////////////////////////////////////////////
1718 // Initialize the view manager subsystem.
1719 ////////////////////////////////////////////////////////////////////
1723 ////////////////////////////////////////////////////////////////////
1724 // Create and register the logger.
1725 ////////////////////////////////////////////////////////////////////
1727 globals->add_subsystem("logger", new FGLogger);
1729 ////////////////////////////////////////////////////////////////////
1730 // Create and register the XML GUI.
1731 ////////////////////////////////////////////////////////////////////
1733 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1736 ////////////////////////////////////////////////////////////////////
1737 // Initialize the local time subsystem.
1738 ////////////////////////////////////////////////////////////////////
1740 // update the current timezone each 30 minutes
1741 globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1742 &fgUpdateLocalTime, 30*60 );
1743 fgInitTimeOffset(); // the environment subsystem needs this
1746 ////////////////////////////////////////////////////////////////////
1747 // Initialize the lighting subsystem.
1748 ////////////////////////////////////////////////////////////////////
1750 globals->add_subsystem("lighting", new FGLight);
1752 //////////////////////////////////////////////////////////////////////
1753 // Initialize the 2D cloud subsystem.
1754 ////////////////////////////////////////////////////////////////////
1755 fgGetBool("/sim/rendering/bump-mapping", false);
1757 #ifdef ENABLE_AUDIO_SUPPORT
1758 ////////////////////////////////////////////////////////////////////
1759 // Initialize the sound subsystem.
1760 ////////////////////////////////////////////////////////////////////
1762 init_volume = fgGetFloat("/sim/sound/volume");
1763 fgSetFloat("/sim/sound/volume", 0.0f);
1764 globals->set_soundmgr(new SGSoundMgr);
1765 globals->get_soundmgr()->init();
1766 globals->get_soundmgr()->bind();
1769 ////////////////////////////////////////////////////////////////////
1770 // Initialize the sound-effects subsystem.
1771 ////////////////////////////////////////////////////////////////////
1773 globals->add_subsystem("fx", new FGFX);
1774 globals->add_subsystem("voice", new FGVoiceMgr);
1777 ////////////////////////////////////////////////////////////////////
1778 // Initialise the ATC Manager
1779 ////////////////////////////////////////////////////////////////////
1781 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1782 globals->set_ATC_mgr(new FGATCMgr);
1783 globals->get_ATC_mgr()->init();
1785 ////////////////////////////////////////////////////////////////////
1786 // Initialise the AI Manager
1787 ////////////////////////////////////////////////////////////////////
1789 SG_LOG(SG_GENERAL, SG_INFO, " AI Manager");
1790 globals->set_AI_mgr(new FGAIMgr);
1791 globals->get_AI_mgr()->init();
1793 ////////////////////////////////////////////////////////////////////
1794 // Initialise the AI Model Manager
1795 ////////////////////////////////////////////////////////////////////
1796 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1797 globals->add_subsystem("ai_model", new FGAIManager);
1798 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1801 // It's probably a good idea to initialize the top level traffic manager
1802 // After the AI and ATC systems have been initialized properly.
1803 // AI Traffic manager
1804 globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1807 ////////////////////////////////////////////////////////////////////
1808 // Initialize the cockpit subsystem
1809 ////////////////////////////////////////////////////////////////////
1810 if( fgCockpitInit( ¤t_aircraft )) {
1811 // Cockpit initialized ok.
1813 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1818 ////////////////////////////////////////////////////////////////////
1819 // Initialize I/O subsystem.
1820 ////////////////////////////////////////////////////////////////////
1822 globals->get_io()->init();
1823 globals->get_io()->bind();
1826 ////////////////////////////////////////////////////////////////////
1827 // Add a new 2D panel.
1828 ////////////////////////////////////////////////////////////////////
1830 string panel_path = fgGetString("/sim/panel/path",
1831 "Panels/Default/default.xml");
1833 globals->set_current_panel( fgReadPanel(panel_path) );
1834 if (globals->get_current_panel() == 0) {
1835 SG_LOG( SG_INPUT, SG_ALERT,
1836 "Error reading new panel from " << panel_path );
1838 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1839 globals->get_current_panel()->init();
1840 globals->get_current_panel()->bind();
1844 ////////////////////////////////////////////////////////////////////
1845 // Initialize the controls subsystem.
1846 ////////////////////////////////////////////////////////////////////
1848 globals->get_controls()->init();
1849 globals->get_controls()->bind();
1852 ////////////////////////////////////////////////////////////////////
1853 // Initialize the input subsystem.
1854 ////////////////////////////////////////////////////////////////////
1856 globals->add_subsystem("input", new FGInput);
1859 ////////////////////////////////////////////////////////////////////
1860 // Initialize the replay subsystem
1861 ////////////////////////////////////////////////////////////////////
1862 globals->add_subsystem("replay", new FGReplay);
1864 ////////////////////////////////////////////////////////////////////
1865 // Bind and initialize subsystems.
1866 ////////////////////////////////////////////////////////////////////
1868 globals->get_subsystem_mgr()->bind();
1869 globals->get_subsystem_mgr()->init();
1871 ////////////////////////////////////////////////////////////////////
1872 // Initialize multiplayer subsystem
1873 ////////////////////////////////////////////////////////////////////
1875 globals->set_multiplayer_mgr(new FGMultiplayMgr);
1876 globals->get_multiplayer_mgr()->init();
1878 ////////////////////////////////////////////////////////////////////////
1879 // Initialize the Nasal interpreter.
1880 // Do this last, so that the loaded scripts see initialized state
1881 ////////////////////////////////////////////////////////////////////////
1882 FGNasalSys* nasal = new FGNasalSys();
1883 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1886 // initialize methods that depend on other subsystems.
1887 globals->get_subsystem_mgr()->postinit();
1889 ////////////////////////////////////////////////////////////////////////
1890 // End of subsystem initialization.
1891 ////////////////////////////////////////////////////////////////////
1893 SG_LOG( SG_GENERAL, SG_INFO, endl);
1895 // Save the initial state for future
1897 globals->saveInitialState();
1903 void fgReInitSubsystems()
1905 // static const SGPropertyNode *longitude
1906 // = fgGetNode("/sim/presets/longitude-deg");
1907 // static const SGPropertyNode *latitude
1908 // = fgGetNode("/sim/presets/latitude-deg");
1909 static const SGPropertyNode *altitude
1910 = fgGetNode("/sim/presets/altitude-ft");
1911 static const SGPropertyNode *master_freeze
1912 = fgGetNode("/sim/freeze/master");
1914 SG_LOG( SG_GENERAL, SG_INFO,
1915 "fgReInitSubsystems(): /position/altitude = "
1916 << altitude->getDoubleValue() );
1918 bool freeze = master_freeze->getBoolValue();
1920 fgSetBool("/sim/freeze/master", true);
1922 fgSetBool("/sim/crashed", false);
1924 // Force reupdating the positions of the ai 3d models. They are used for
1925 // initializing ground level for the FDM.
1926 globals->get_subsystem("ai_model")->reinit();
1928 // Initialize the FDM
1931 // allocates structures so must happen before any of the flight
1932 // model or control parameters are set
1933 fgAircraftInit(); // In the future this might not be the case.
1935 // reload offsets from config defaults
1936 globals->get_viewmgr()->reinit();
1940 globals->get_controls()->reset_all();
1942 fgUpdateLocalTime();
1944 // re-init to proper time of day setting
1948 fgSetBool("/sim/freeze/master", false);
1950 fgSetBool("/sim/sceneryloaded",false);
1954 void reInit(void) // from gui_local.cxx -- TODO merge with fgReInitSubsystems()
1956 static SGPropertyNode_ptr master_freeze = fgGetNode("/sim/freeze/master", true);
1958 bool freeze = master_freeze->getBoolValue();
1960 master_freeze->setBoolValue(true);
1962 fgSetBool("/sim/signals/reinit", true);
1963 cur_fdm_state->unbind();
1965 // in case user has changed window size as
1966 // restoreInitialState() overwrites these
1967 int xsize = fgGetInt("/sim/startup/xsize");
1968 int ysize = fgGetInt("/sim/startup/ysize");
1970 globals->restoreInitialState();
1972 // update our position based on current presets
1975 // We don't know how to resize the window, so keep the last values
1976 // for xsize and ysize, and don't use the one set initially
1977 fgSetInt("/sim/startup/xsize", xsize);
1978 fgSetInt("/sim/startup/ysize", ysize);
1980 SGTime *t = globals->get_time_params();
1983 globals->set_time_params(t);
1985 fgReInitSubsystems();
1987 globals->get_tile_mgr()->update(fgGetDouble("/environment/visibility-m"));
1988 globals->get_renderer()->resize(xsize, ysize);
1989 fgSetBool("/sim/signals/reinit", false);
1992 master_freeze->setBoolValue(false);